1 // Copyright (c) 2013 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.
9 #include "base/at_exit.h"
10 #include "base/basictypes.h"
11 #include "base/bind.h"
12 #include "base/command_line.h"
13 #include "base/file_util.h"
14 #include "base/files/file_enumerator.h"
15 #include "base/files/scoped_temp_dir.h"
16 #include "base/json/json_file_value_serializer.h"
17 #include "base/json/json_reader.h"
18 #include "base/json/json_string_value_serializer.h"
19 #include "base/memory/scoped_ptr.h"
20 #include "base/memory/weak_ptr.h"
21 #include "base/message_loop/message_loop.h"
22 #include "base/prefs/scoped_user_pref_update.h"
23 #include "base/stl_util.h"
24 #include "base/strings/string16.h"
25 #include "base/strings/string_number_conversions.h"
26 #include "base/strings/string_util.h"
27 #include "base/strings/utf_string_conversions.h"
28 #include "base/version.h"
29 #include "chrome/browser/browser_process.h"
30 #include "chrome/browser/chrome_notification_types.h"
31 #include "chrome/browser/extensions/app_sync_data.h"
32 #include "chrome/browser/extensions/blacklist.h"
33 #include "chrome/browser/extensions/chrome_app_sorting.h"
34 #include "chrome/browser/extensions/component_loader.h"
35 #include "chrome/browser/extensions/crx_installer.h"
36 #include "chrome/browser/extensions/default_apps.h"
37 #include "chrome/browser/extensions/extension_creator.h"
38 #include "chrome/browser/extensions/extension_error_reporter.h"
39 #include "chrome/browser/extensions/extension_error_ui.h"
40 #include "chrome/browser/extensions/extension_notification_observer.h"
41 #include "chrome/browser/extensions/extension_service.h"
42 #include "chrome/browser/extensions/extension_service_test_base.h"
43 #include "chrome/browser/extensions/extension_special_storage_policy.h"
44 #include "chrome/browser/extensions/extension_sync_data.h"
45 #include "chrome/browser/extensions/extension_sync_service.h"
46 #include "chrome/browser/extensions/extension_util.h"
47 #include "chrome/browser/extensions/external_install_error.h"
48 #include "chrome/browser/extensions/external_install_manager.h"
49 #include "chrome/browser/extensions/external_policy_loader.h"
50 #include "chrome/browser/extensions/external_pref_loader.h"
51 #include "chrome/browser/extensions/external_provider_impl.h"
52 #include "chrome/browser/extensions/fake_safe_browsing_database_manager.h"
53 #include "chrome/browser/extensions/installed_loader.h"
54 #include "chrome/browser/extensions/pack_extension_job.h"
55 #include "chrome/browser/extensions/pending_extension_info.h"
56 #include "chrome/browser/extensions/pending_extension_manager.h"
57 #include "chrome/browser/extensions/test_blacklist.h"
58 #include "chrome/browser/extensions/test_extension_system.h"
59 #include "chrome/browser/extensions/unpacked_installer.h"
60 #include "chrome/browser/extensions/updater/extension_updater.h"
61 #include "chrome/browser/prefs/pref_service_syncable.h"
62 #include "chrome/browser/supervised_user/supervised_user_service.h"
63 #include "chrome/browser/supervised_user/supervised_user_service_factory.h"
64 #include "chrome/browser/sync/profile_sync_service.h"
65 #include "chrome/browser/sync/profile_sync_service_factory.h"
66 #include "chrome/common/chrome_constants.h"
67 #include "chrome/common/chrome_switches.h"
68 #include "chrome/common/extensions/api/plugins/plugins_handler.h"
69 #include "chrome/common/extensions/manifest_handlers/app_launch_info.h"
70 #include "chrome/common/extensions/manifest_handlers/content_scripts_handler.h"
71 #include "chrome/common/extensions/manifest_url_handler.h"
72 #include "chrome/common/pref_names.h"
73 #include "chrome/common/url_constants.h"
74 #include "chrome/test/base/scoped_browser_locale.h"
75 #include "chrome/test/base/testing_profile.h"
76 #include "components/pref_registry/pref_registry_syncable.h"
77 #include "content/public/browser/dom_storage_context.h"
78 #include "content/public/browser/gpu_data_manager.h"
79 #include "content/public/browser/indexed_db_context.h"
80 #include "content/public/browser/notification_registrar.h"
81 #include "content/public/browser/notification_service.h"
82 #include "content/public/browser/plugin_service.h"
83 #include "content/public/browser/render_process_host.h"
84 #include "content/public/browser/storage_partition.h"
85 #include "content/public/common/content_constants.h"
86 #include "content/public/test/test_utils.h"
87 #include "extensions/browser/extension_registry.h"
88 #include "extensions/browser/extension_system.h"
89 #include "extensions/browser/external_provider_interface.h"
90 #include "extensions/browser/install_flag.h"
91 #include "extensions/browser/management_policy.h"
92 #include "extensions/browser/pref_names.h"
93 #include "extensions/browser/test_management_policy.h"
94 #include "extensions/browser/uninstall_reason.h"
95 #include "extensions/common/constants.h"
96 #include "extensions/common/extension.h"
97 #include "extensions/common/extension_builder.h"
98 #include "extensions/common/extension_l10n_util.h"
99 #include "extensions/common/extension_resource.h"
100 #include "extensions/common/feature_switch.h"
101 #include "extensions/common/manifest_constants.h"
102 #include "extensions/common/manifest_handlers/background_info.h"
103 #include "extensions/common/permissions/permission_set.h"
104 #include "extensions/common/permissions/permissions_data.h"
105 #include "extensions/common/switches.h"
106 #include "extensions/common/url_pattern.h"
107 #include "extensions/common/value_builder.h"
108 #include "gpu/config/gpu_info.h"
109 #include "grit/browser_resources.h"
110 #include "net/cookies/canonical_cookie.h"
111 #include "net/cookies/cookie_monster.h"
112 #include "net/cookies/cookie_options.h"
113 #include "net/url_request/url_request_context.h"
114 #include "net/url_request/url_request_context_getter.h"
115 #include "sync/api/fake_sync_change_processor.h"
116 #include "sync/api/string_ordinal.h"
117 #include "sync/api/sync_data.h"
118 #include "sync/api/sync_error_factory.h"
119 #include "sync/api/sync_error_factory_mock.h"
120 #include "sync/api/syncable_service.h"
121 #include "sync/protocol/app_specifics.pb.h"
122 #include "sync/protocol/extension_specifics.pb.h"
123 #include "sync/protocol/sync.pb.h"
124 #include "testing/gtest/include/gtest/gtest.h"
125 #include "testing/platform_test.h"
126 #include "url/gurl.h"
127 #include "webkit/browser/database/database_tracker.h"
128 #include "webkit/browser/quota/quota_manager.h"
129 #include "webkit/common/database/database_identifier.h"
131 #if defined(OS_CHROMEOS)
132 #include "chrome/browser/chromeos/login/users/scoped_test_user_manager.h"
133 #include "chrome/browser/chromeos/settings/cros_settings.h"
134 #include "chrome/browser/chromeos/settings/device_settings_service.h"
137 // The blacklist tests rely on safe browsing.
138 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
139 #define ENABLE_BLACKLIST_TESTS
142 using base::DictionaryValue;
143 using base::ListValue;
145 using content::BrowserContext;
146 using content::BrowserThread;
147 using content::DOMStorageContext;
148 using content::IndexedDBContext;
149 using content::PluginService;
150 using extensions::APIPermission;
151 using extensions::APIPermissionSet;
152 using extensions::AppSorting;
153 using extensions::Blacklist;
154 using extensions::CrxInstaller;
155 using extensions::Extension;
156 using extensions::ExtensionCreator;
157 using extensions::ExtensionPrefs;
158 using extensions::ExtensionRegistry;
159 using extensions::ExtensionResource;
160 using extensions::ExtensionSystem;
161 using extensions::FakeSafeBrowsingDatabaseManager;
162 using extensions::FeatureSwitch;
163 using extensions::Manifest;
164 using extensions::PermissionSet;
165 using extensions::TestExtensionSystem;
166 using extensions::UnloadedExtensionInfo;
167 using extensions::URLPatternSet;
169 namespace keys = extensions::manifest_keys;
173 // Extension ids used during testing.
174 const char good0[] = "behllobkkfkfnphdnhnkndlbkcpglgmj";
175 const char good1[] = "hpiknbiabeeppbpihjehijgoemciehgk";
176 const char good2[] = "bjafgdebaacbbbecmhlhpofkepfkgcpa";
177 const char all_zero[] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
178 const char good2048[] = "nmgjhmhbleinmjpbdhgajfjkbijcmgbh";
179 const char good_crx[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
180 const char hosted_app[] = "kbmnembihfiondgfjekmnmcbddelicoi";
181 const char page_action[] = "obcimlgaoabeegjmmpldobjndiealpln";
182 const char theme_crx[] = "iamefpfkojoapidjnbafmgkgncegbkad";
183 const char theme2_crx[] = "pjpgmfcmabopnnfonnhmdjglfpjjfkbf";
184 const char permissions_crx[] = "eagpmdpfmaekmmcejjbmjoecnejeiiin";
185 const char unpacked[] = "cbcdidchbppangcjoddlpdjlenngjldk";
186 const char updates_from_webstore[] = "akjooamlhcgeopfifcmlggaebeocgokj";
188 struct ExtensionsOrder {
189 bool operator()(const scoped_refptr<const Extension>& a,
190 const scoped_refptr<const Extension>& b) {
191 return a->name() < b->name();
195 static std::vector<base::string16> GetErrors() {
196 const std::vector<base::string16>* errors =
197 ExtensionErrorReporter::GetInstance()->GetErrors();
198 std::vector<base::string16> ret_val;
200 for (std::vector<base::string16>::const_iterator iter = errors->begin();
201 iter != errors->end(); ++iter) {
202 std::string utf8_error = base::UTF16ToUTF8(*iter);
203 if (utf8_error.find(".svn") == std::string::npos) {
204 ret_val.push_back(*iter);
208 // The tests rely on the errors being in a certain order, which can vary
209 // depending on how filesystem iteration works.
210 std::stable_sort(ret_val.begin(), ret_val.end());
215 static void AddPattern(URLPatternSet* extent, const std::string& pattern) {
216 int schemes = URLPattern::SCHEME_ALL;
217 extent->AddPattern(URLPattern(schemes, pattern));
220 base::FilePath GetTemporaryFile() {
221 base::FilePath temp_file;
222 CHECK(base::CreateTemporaryFile(&temp_file));
226 bool WaitForCountNotificationsCallback(int *count) {
227 return --(*count) == 0;
232 class MockExtensionProvider : public extensions::ExternalProviderInterface {
234 MockExtensionProvider(
235 VisitorInterface* visitor,
236 Manifest::Location location)
237 : location_(location), visitor_(visitor), visit_count_(0) {
240 virtual ~MockExtensionProvider() {}
242 void UpdateOrAddExtension(const std::string& id,
243 const std::string& version,
244 const base::FilePath& path) {
245 extension_map_[id] = std::make_pair(version, path);
248 void RemoveExtension(const std::string& id) {
249 extension_map_.erase(id);
252 // ExternalProvider implementation:
253 virtual void VisitRegisteredExtension() OVERRIDE {
255 for (DataMap::const_iterator i = extension_map_.begin();
256 i != extension_map_.end(); ++i) {
257 Version version(i->second.first);
259 visitor_->OnExternalExtensionFileFound(
260 i->first, &version, i->second.second, location_,
261 Extension::NO_FLAGS, false);
263 visitor_->OnExternalProviderReady(this);
266 virtual bool HasExtension(const std::string& id) const OVERRIDE {
267 return extension_map_.find(id) != extension_map_.end();
270 virtual bool GetExtensionDetails(
271 const std::string& id,
272 Manifest::Location* location,
273 scoped_ptr<Version>* version) const OVERRIDE {
274 DataMap::const_iterator it = extension_map_.find(id);
275 if (it == extension_map_.end())
279 version->reset(new Version(it->second.first));
282 *location = location_;
287 virtual bool IsReady() const OVERRIDE {
291 virtual void ServiceShutdown() OVERRIDE {
294 int visit_count() const { return visit_count_; }
295 void set_visit_count(int visit_count) {
296 visit_count_ = visit_count;
300 typedef std::map< std::string, std::pair<std::string, base::FilePath> >
302 DataMap extension_map_;
303 Manifest::Location location_;
304 VisitorInterface* visitor_;
306 // visit_count_ tracks the number of calls to VisitRegisteredExtension().
307 // Mutable because it must be incremented on each call to
308 // VisitRegisteredExtension(), which must be a const method to inherit
309 // from the class being mocked.
310 mutable int visit_count_;
312 DISALLOW_COPY_AND_ASSIGN(MockExtensionProvider);
315 class MockProviderVisitor
316 : public extensions::ExternalProviderInterface::VisitorInterface {
318 // The provider will return |fake_base_path| from
319 // GetBaseCrxFilePath(). User can test the behavior with
320 // and without an empty path using this parameter.
321 explicit MockProviderVisitor(base::FilePath fake_base_path)
323 fake_base_path_(fake_base_path),
324 expected_creation_flags_(Extension::NO_FLAGS) {
325 profile_.reset(new TestingProfile);
328 MockProviderVisitor(base::FilePath fake_base_path,
329 int expected_creation_flags)
331 fake_base_path_(fake_base_path),
332 expected_creation_flags_(expected_creation_flags) {
335 int Visit(const std::string& json_data) {
336 // Give the test json file to the provider for parsing.
337 provider_.reset(new extensions::ExternalProviderImpl(
339 new extensions::ExternalTestingLoader(json_data, fake_base_path_),
341 Manifest::EXTERNAL_PREF,
342 Manifest::EXTERNAL_PREF_DOWNLOAD,
343 Extension::NO_FLAGS));
345 // We also parse the file into a dictionary to compare what we get back
346 // from the provider.
347 JSONStringValueSerializer serializer(json_data);
348 base::Value* json_value = serializer.Deserialize(NULL, NULL);
350 if (!json_value || !json_value->IsType(base::Value::TYPE_DICTIONARY)) {
351 NOTREACHED() << "Unable to deserialize json data";
354 base::DictionaryValue* external_extensions =
355 static_cast<base::DictionaryValue*>(json_value);
356 prefs_.reset(external_extensions);
359 // Reset our counter.
361 // Ask the provider to look up all extensions and return them.
362 provider_->VisitRegisteredExtension();
367 virtual bool OnExternalExtensionFileFound(const std::string& id,
368 const Version* version,
369 const base::FilePath& path,
370 Manifest::Location unused,
372 bool mark_acknowledged) OVERRIDE {
373 EXPECT_EQ(expected_creation_flags_, creation_flags);
376 base::DictionaryValue* pref;
377 // This tests is to make sure that the provider only notifies us of the
378 // values we gave it. So if the id we doesn't exist in our internal
379 // dictionary then something is wrong.
380 EXPECT_TRUE(prefs_->GetDictionary(id, &pref))
381 << "Got back ID (" << id.c_str() << ") we weren't expecting";
383 EXPECT_TRUE(path.IsAbsolute());
384 if (!fake_base_path_.empty())
385 EXPECT_TRUE(fake_base_path_.IsParent(path));
388 EXPECT_TRUE(provider_->HasExtension(id));
390 // Ask provider if the extension we got back is registered.
391 Manifest::Location location = Manifest::INVALID_LOCATION;
392 scoped_ptr<Version> v1;
393 base::FilePath crx_path;
395 EXPECT_TRUE(provider_->GetExtensionDetails(id, NULL, &v1));
396 EXPECT_STREQ(version->GetString().c_str(), v1->GetString().c_str());
398 scoped_ptr<Version> v2;
399 EXPECT_TRUE(provider_->GetExtensionDetails(id, &location, &v2));
400 EXPECT_STREQ(version->GetString().c_str(), v1->GetString().c_str());
401 EXPECT_STREQ(version->GetString().c_str(), v2->GetString().c_str());
402 EXPECT_EQ(Manifest::EXTERNAL_PREF, location);
404 // Remove it so we won't count it ever again.
405 prefs_->Remove(id, NULL);
410 virtual bool OnExternalExtensionUpdateUrlFound(
411 const std::string& id,
412 const std::string& install_parameter,
413 const GURL& update_url,
414 Manifest::Location location,
416 bool mark_acknowledged) OVERRIDE {
418 base::DictionaryValue* pref;
419 // This tests is to make sure that the provider only notifies us of the
420 // values we gave it. So if the id we doesn't exist in our internal
421 // dictionary then something is wrong.
422 EXPECT_TRUE(prefs_->GetDictionary(id, &pref))
423 << L"Got back ID (" << id.c_str() << ") we weren't expecting";
424 EXPECT_EQ(Manifest::EXTERNAL_PREF_DOWNLOAD, location);
427 EXPECT_TRUE(provider_->HasExtension(id));
429 // External extensions with update URLs do not have versions.
430 scoped_ptr<Version> v1;
431 Manifest::Location location1 = Manifest::INVALID_LOCATION;
432 EXPECT_TRUE(provider_->GetExtensionDetails(id, &location1, &v1));
433 EXPECT_FALSE(v1.get());
434 EXPECT_EQ(Manifest::EXTERNAL_PREF_DOWNLOAD, location1);
436 std::string parsed_install_parameter;
437 pref->GetString("install_parameter", &parsed_install_parameter);
438 EXPECT_EQ(parsed_install_parameter, install_parameter);
440 // Remove it so we won't count it again.
441 prefs_->Remove(id, NULL);
446 virtual void OnExternalProviderReady(
447 const extensions::ExternalProviderInterface* provider) OVERRIDE {
448 EXPECT_EQ(provider, provider_.get());
449 EXPECT_TRUE(provider->IsReady());
454 base::FilePath fake_base_path_;
455 int expected_creation_flags_;
456 scoped_ptr<extensions::ExternalProviderImpl> provider_;
457 scoped_ptr<base::DictionaryValue> prefs_;
458 scoped_ptr<TestingProfile> profile_;
460 DISALLOW_COPY_AND_ASSIGN(MockProviderVisitor);
463 class ExtensionServiceTest : public extensions::ExtensionServiceTestBase,
464 public content::NotificationObserver {
466 ExtensionServiceTest()
467 : unloaded_reason_(UnloadedExtensionInfo::REASON_UNDEFINED),
470 override_external_install_prompt_(
471 FeatureSwitch::prompt_for_external_extensions(),
473 expected_extensions_count_(0) {
475 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
476 content::NotificationService::AllSources());
478 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
479 content::NotificationService::AllSources());
482 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
483 content::NotificationService::AllSources());
486 virtual void Observe(int type,
487 const content::NotificationSource& source,
488 const content::NotificationDetails& details) OVERRIDE {
490 case extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED: {
491 const Extension* extension =
492 content::Details<const Extension>(details).ptr();
493 loaded_.push_back(make_scoped_refptr(extension));
494 // The tests rely on the errors being in a certain order, which can vary
495 // depending on how filesystem iteration works.
496 std::stable_sort(loaded_.begin(), loaded_.end(), ExtensionsOrder());
500 case extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED: {
501 UnloadedExtensionInfo* unloaded_info =
502 content::Details<UnloadedExtensionInfo>(details).ptr();
503 const Extension* e = unloaded_info->extension;
504 unloaded_id_ = e->id();
505 unloaded_reason_ = unloaded_info->reason;
506 extensions::ExtensionList::iterator i =
507 std::find(loaded_.begin(), loaded_.end(), e);
508 // TODO(erikkay) fix so this can be an assert. Right now the tests
509 // are manually calling clear() on loaded_, so this isn't doable.
510 if (i == loaded_.end())
515 case extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED: {
516 const extensions::InstalledExtensionInfo* installed_info =
517 content::Details<const extensions::InstalledExtensionInfo>(details)
519 installed_ = installed_info->extension;
520 was_update_ = installed_info->is_update;
521 old_name_ = installed_info->old_name;
530 void AddMockExternalProvider(
531 extensions::ExternalProviderInterface* provider) {
532 service()->AddProviderForTesting(provider);
535 void MockSyncStartFlare(bool* was_called,
536 syncer::ModelType* model_type_passed_in,
537 syncer::ModelType model_type) {
539 *model_type_passed_in = model_type;
543 // Paths to some of the fake extensions.
544 base::FilePath good0_path() {
547 .AppendASCII("Extensions")
549 .AppendASCII("1.0.0.0");
552 base::FilePath good1_path() {
555 .AppendASCII("Extensions")
560 base::FilePath good2_path() {
563 .AppendASCII("Extensions")
568 void TestExternalProvider(MockExtensionProvider* provider,
569 Manifest::Location location);
571 void PackCRX(const base::FilePath& dir_path,
572 const base::FilePath& pem_path,
573 const base::FilePath& crx_path) {
574 // Use the existing pem key, if provided.
575 base::FilePath pem_output_path;
576 if (pem_path.value().empty()) {
577 pem_output_path = crx_path.DirName().AppendASCII("temp.pem");
579 ASSERT_TRUE(base::PathExists(pem_path));
582 ASSERT_TRUE(base::DeleteFile(crx_path, false));
584 scoped_ptr<ExtensionCreator> creator(new ExtensionCreator());
585 ASSERT_TRUE(creator->Run(dir_path,
589 ExtensionCreator::kOverwriteCRX));
591 ASSERT_TRUE(base::PathExists(crx_path));
598 INSTALL_WITHOUT_LOAD,
601 const Extension* PackAndInstallCRX(const base::FilePath& dir_path,
602 const base::FilePath& pem_path,
603 InstallState install_state,
604 int creation_flags) {
605 base::FilePath crx_path;
606 base::ScopedTempDir temp_dir;
607 EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
608 crx_path = temp_dir.path().AppendASCII("temp.crx");
610 PackCRX(dir_path, pem_path, crx_path);
611 return InstallCRX(crx_path, install_state, creation_flags);
614 const Extension* PackAndInstallCRX(const base::FilePath& dir_path,
615 const base::FilePath& pem_path,
616 InstallState install_state) {
617 return PackAndInstallCRX(dir_path, pem_path, install_state,
618 Extension::NO_FLAGS);
621 const Extension* PackAndInstallCRX(const base::FilePath& dir_path,
622 InstallState install_state) {
623 return PackAndInstallCRX(dir_path, base::FilePath(), install_state,
624 Extension::NO_FLAGS);
627 // Attempts to install an extension. Use INSTALL_FAILED if the installation
628 // is expected to fail.
629 // If |install_state| is INSTALL_UPDATED, and |expected_old_name| is
630 // non-empty, expects that the existing extension's title was
631 // |expected_old_name|.
632 const Extension* InstallCRX(const base::FilePath& path,
633 InstallState install_state,
635 const std::string& expected_old_name) {
636 InstallCRXInternal(path, creation_flags);
637 return VerifyCrxInstall(path, install_state, expected_old_name);
640 // Attempts to install an extension. Use INSTALL_FAILED if the installation
641 // is expected to fail.
642 const Extension* InstallCRX(const base::FilePath& path,
643 InstallState install_state,
644 int creation_flags) {
645 return InstallCRX(path, install_state, creation_flags, std::string());
648 // Attempts to install an extension. Use INSTALL_FAILED if the installation
649 // is expected to fail.
650 const Extension* InstallCRX(const base::FilePath& path,
651 InstallState install_state) {
652 return InstallCRX(path, install_state, Extension::NO_FLAGS);
655 const Extension* InstallCRXFromWebStore(const base::FilePath& path,
656 InstallState install_state) {
657 InstallCRXInternal(path, Extension::FROM_WEBSTORE);
658 return VerifyCrxInstall(path, install_state);
661 const Extension* InstallCRXWithLocation(const base::FilePath& crx_path,
662 Manifest::Location install_location,
663 InstallState install_state) {
664 EXPECT_TRUE(base::PathExists(crx_path))
665 << "Path does not exist: "<< crx_path.value().c_str();
666 // no client (silent install)
667 scoped_refptr<CrxInstaller> installer(
668 CrxInstaller::CreateSilent(service()));
669 installer->set_install_source(install_location);
671 content::WindowedNotificationObserver observer(
672 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
673 content::NotificationService::AllSources());
674 installer->InstallCrx(crx_path);
677 return VerifyCrxInstall(crx_path, install_state);
680 // Verifies the result of a CRX installation. Used by InstallCRX. Set the
681 // |install_state| to INSTALL_FAILED if the installation is expected to fail.
682 // Returns an Extension pointer if the install succeeded, NULL otherwise.
683 const Extension* VerifyCrxInstall(const base::FilePath& path,
684 InstallState install_state) {
685 return VerifyCrxInstall(path, install_state, std::string());
688 // Verifies the result of a CRX installation. Used by InstallCRX. Set the
689 // |install_state| to INSTALL_FAILED if the installation is expected to fail.
690 // If |install_state| is INSTALL_UPDATED, and |expected_old_name| is
691 // non-empty, expects that the existing extension's title was
692 // |expected_old_name|.
693 // Returns an Extension pointer if the install succeeded, NULL otherwise.
694 const Extension* VerifyCrxInstall(const base::FilePath& path,
695 InstallState install_state,
696 const std::string& expected_old_name) {
697 std::vector<base::string16> errors = GetErrors();
698 const Extension* extension = NULL;
699 if (install_state != INSTALL_FAILED) {
700 if (install_state == INSTALL_NEW)
701 ++expected_extensions_count_;
703 EXPECT_TRUE(installed_) << path.value();
704 // If and only if INSTALL_UPDATED, it should have the is_update flag.
705 EXPECT_EQ(install_state == INSTALL_UPDATED, was_update_)
707 // If INSTALL_UPDATED, old_name_ should match the given string.
708 if (install_state == INSTALL_UPDATED && !expected_old_name.empty())
709 EXPECT_EQ(expected_old_name, old_name_);
710 EXPECT_EQ(0u, errors.size()) << path.value();
712 if (install_state == INSTALL_WITHOUT_LOAD) {
713 EXPECT_EQ(0u, loaded_.size()) << path.value();
715 EXPECT_EQ(1u, loaded_.size()) << path.value();
716 size_t actual_extension_count =
717 registry()->enabled_extensions().size() +
718 registry()->disabled_extensions().size();
719 EXPECT_EQ(expected_extensions_count_, actual_extension_count) <<
721 extension = loaded_[0].get();
722 EXPECT_TRUE(service()->GetExtensionById(extension->id(), false))
726 for (std::vector<base::string16>::iterator err = errors.begin();
727 err != errors.end(); ++err) {
731 EXPECT_FALSE(installed_) << path.value();
732 EXPECT_EQ(0u, loaded_.size()) << path.value();
733 EXPECT_EQ(1u, errors.size()) << path.value();
740 ExtensionErrorReporter::GetInstance()->ClearErrors();
753 void BlackListWebGL() {
754 static const std::string json_blacklist =
756 " \"name\": \"gpu blacklist\",\n"
757 " \"version\": \"1.0\",\n"
761 " \"features\": [\"webgl\"]\n"
765 gpu::GPUInfo gpu_info;
766 content::GpuDataManager::GetInstance()->InitializeForTesting(
767 json_blacklist, gpu_info);
770 // Helper method to set up a WindowedNotificationObserver to wait for a
771 // specific CrxInstaller to finish if we don't know the value of the
773 static bool IsCrxInstallerDone(extensions::CrxInstaller** installer,
774 const content::NotificationSource& source,
775 const content::NotificationDetails& details) {
776 return content::Source<extensions::CrxInstaller>(source).ptr() ==
780 void PackCRXAndUpdateExtension(const std::string& id,
781 const base::FilePath& dir_path,
782 const base::FilePath& pem_path,
783 UpdateState expected_state) {
784 base::ScopedTempDir temp_dir;
785 EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
786 base::FilePath crx_path = temp_dir.path().AppendASCII("temp.crx");
788 PackCRX(dir_path, pem_path, crx_path);
789 UpdateExtension(id, crx_path, expected_state);
792 void UpdateExtension(const std::string& id,
793 const base::FilePath& in_path,
794 UpdateState expected_state) {
795 ASSERT_TRUE(base::PathExists(in_path));
797 // We need to copy this to a temporary location because Update() will delete
799 base::FilePath path = temp_dir().path();
800 path = path.Append(in_path.BaseName());
801 ASSERT_TRUE(base::CopyFile(in_path, path));
803 int previous_enabled_extension_count =
804 registry()->enabled_extensions().size();
805 int previous_installed_extension_count =
806 previous_enabled_extension_count +
807 registry()->disabled_extensions().size();
809 extensions::CrxInstaller* installer = NULL;
810 content::WindowedNotificationObserver observer(
811 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
812 base::Bind(&IsCrxInstallerDone, &installer));
813 service()->UpdateExtension(id, path, true, &installer);
818 base::RunLoop().RunUntilIdle();
820 std::vector<base::string16> errors = GetErrors();
821 int error_count = errors.size();
822 int enabled_extension_count = registry()->enabled_extensions().size();
823 int installed_extension_count =
824 enabled_extension_count + registry()->disabled_extensions().size();
826 int expected_error_count = (expected_state == FAILED) ? 1 : 0;
827 EXPECT_EQ(expected_error_count, error_count) << path.value();
829 if (expected_state <= FAILED) {
830 EXPECT_EQ(previous_enabled_extension_count,
831 enabled_extension_count);
832 EXPECT_EQ(previous_installed_extension_count,
833 installed_extension_count);
835 int expected_installed_extension_count =
836 (expected_state >= INSTALLED) ? 1 : 0;
837 int expected_enabled_extension_count =
838 (expected_state >= ENABLED) ? 1 : 0;
839 EXPECT_EQ(expected_installed_extension_count,
840 installed_extension_count);
841 EXPECT_EQ(expected_enabled_extension_count,
842 enabled_extension_count);
845 // Update() should the temporary input file.
846 EXPECT_FALSE(base::PathExists(path));
849 void TerminateExtension(const std::string& id) {
850 const Extension* extension = service()->GetInstalledExtension(id);
855 service()->TrackTerminatedExtensionForTest(extension);
858 size_t GetPrefKeyCount() {
859 const base::DictionaryValue* dict =
860 profile()->GetPrefs()->GetDictionary("extensions.settings");
868 void UninstallExtension(const std::string& id, bool use_helper) {
869 // Verify that the extension is installed.
870 base::FilePath extension_path = extensions_install_dir().AppendASCII(id);
871 EXPECT_TRUE(base::PathExists(extension_path));
872 size_t pref_key_count = GetPrefKeyCount();
873 EXPECT_GT(pref_key_count, 0u);
874 ValidateIntegerPref(id, "state", Extension::ENABLED);
878 EXPECT_TRUE(ExtensionService::UninstallExtensionHelper(
879 service(), id, extensions::UNINSTALL_REASON_FOR_TESTING));
881 EXPECT_TRUE(service()->UninstallExtension(
883 extensions::UNINSTALL_REASON_FOR_TESTING,
884 base::Bind(&base::DoNothing),
887 --expected_extensions_count_;
889 // We should get an unload notification.
890 EXPECT_FALSE(unloaded_id_.empty());
891 EXPECT_EQ(id, unloaded_id_);
893 // Verify uninstalled state.
894 size_t new_pref_key_count = GetPrefKeyCount();
895 if (new_pref_key_count == pref_key_count) {
896 ValidateIntegerPref(id, "location",
897 Extension::EXTERNAL_EXTENSION_UNINSTALLED);
899 EXPECT_EQ(new_pref_key_count, pref_key_count - 1);
902 // The extension should not be in the service anymore.
903 EXPECT_FALSE(service()->GetInstalledExtension(id));
904 base::RunLoop().RunUntilIdle();
906 // The directory should be gone.
907 EXPECT_FALSE(base::PathExists(extension_path));
910 void ValidatePrefKeyCount(size_t count) {
911 EXPECT_EQ(count, GetPrefKeyCount());
914 testing::AssertionResult ValidateBooleanPref(
915 const std::string& extension_id,
916 const std::string& pref_path,
918 std::string msg = "while checking: ";
923 msg += expected_val ? "true" : "false";
925 PrefService* prefs = profile()->GetPrefs();
926 const base::DictionaryValue* dict =
927 prefs->GetDictionary("extensions.settings");
929 return testing::AssertionFailure()
930 << "extension.settings does not exist " << msg;
933 const base::DictionaryValue* pref = NULL;
934 if (!dict->GetDictionary(extension_id, &pref)) {
935 return testing::AssertionFailure()
936 << "extension pref does not exist " << msg;
940 if (!pref->GetBoolean(pref_path, &val)) {
941 return testing::AssertionFailure()
942 << pref_path << " pref not found " << msg;
945 return expected_val == val
946 ? testing::AssertionSuccess()
947 : testing::AssertionFailure() << "base::Value is incorrect " << msg;
950 bool IsPrefExist(const std::string& extension_id,
951 const std::string& pref_path) {
952 const base::DictionaryValue* dict =
953 profile()->GetPrefs()->GetDictionary("extensions.settings");
954 if (dict == NULL) return false;
955 const base::DictionaryValue* pref = NULL;
956 if (!dict->GetDictionary(extension_id, &pref)) {
963 if (!pref->GetBoolean(pref_path, &val)) {
969 void ValidateIntegerPref(const std::string& extension_id,
970 const std::string& pref_path,
972 std::string msg = " while checking: ";
977 msg += base::IntToString(expected_val);
979 PrefService* prefs = profile()->GetPrefs();
980 const base::DictionaryValue* dict =
981 prefs->GetDictionary("extensions.settings");
982 ASSERT_TRUE(dict != NULL) << msg;
983 const base::DictionaryValue* pref = NULL;
984 ASSERT_TRUE(dict->GetDictionary(extension_id, &pref)) << msg;
985 EXPECT_TRUE(pref != NULL) << msg;
987 ASSERT_TRUE(pref->GetInteger(pref_path, &val)) << msg;
988 EXPECT_EQ(expected_val, val) << msg;
991 void ValidateStringPref(const std::string& extension_id,
992 const std::string& pref_path,
993 const std::string& expected_val) {
994 std::string msg = " while checking: ";
1001 const base::DictionaryValue* dict =
1002 profile()->GetPrefs()->GetDictionary("extensions.settings");
1003 ASSERT_TRUE(dict != NULL) << msg;
1004 const base::DictionaryValue* pref = NULL;
1005 std::string manifest_path = extension_id + ".manifest";
1006 ASSERT_TRUE(dict->GetDictionary(manifest_path, &pref)) << msg;
1007 EXPECT_TRUE(pref != NULL) << msg;
1009 ASSERT_TRUE(pref->GetString(pref_path, &val)) << msg;
1010 EXPECT_EQ(expected_val, val) << msg;
1013 void SetPref(const std::string& extension_id,
1014 const std::string& pref_path,
1016 const std::string& msg) {
1017 DictionaryPrefUpdate update(profile()->GetPrefs(), "extensions.settings");
1018 base::DictionaryValue* dict = update.Get();
1019 ASSERT_TRUE(dict != NULL) << msg;
1020 base::DictionaryValue* pref = NULL;
1021 ASSERT_TRUE(dict->GetDictionary(extension_id, &pref)) << msg;
1022 EXPECT_TRUE(pref != NULL) << msg;
1023 pref->Set(pref_path, value);
1026 void SetPrefInteg(const std::string& extension_id,
1027 const std::string& pref_path,
1029 std::string msg = " while setting: ";
1030 msg += extension_id;
1034 msg += base::IntToString(value);
1036 SetPref(extension_id, pref_path, new base::FundamentalValue(value), msg);
1039 void SetPrefBool(const std::string& extension_id,
1040 const std::string& pref_path,
1042 std::string msg = " while setting: ";
1043 msg += extension_id + " " + pref_path;
1045 msg += (value ? "true" : "false");
1047 SetPref(extension_id, pref_path, new base::FundamentalValue(value), msg);
1050 void ClearPref(const std::string& extension_id,
1051 const std::string& pref_path) {
1052 std::string msg = " while clearing: ";
1053 msg += extension_id + " " + pref_path;
1055 DictionaryPrefUpdate update(profile()->GetPrefs(), "extensions.settings");
1056 base::DictionaryValue* dict = update.Get();
1057 ASSERT_TRUE(dict != NULL) << msg;
1058 base::DictionaryValue* pref = NULL;
1059 ASSERT_TRUE(dict->GetDictionary(extension_id, &pref)) << msg;
1060 EXPECT_TRUE(pref != NULL) << msg;
1061 pref->Remove(pref_path, NULL);
1064 void SetPrefStringSet(const std::string& extension_id,
1065 const std::string& pref_path,
1066 const std::set<std::string>& value) {
1067 std::string msg = " while setting: ";
1068 msg += extension_id + " " + pref_path;
1070 base::ListValue* list_value = new base::ListValue();
1071 for (std::set<std::string>::const_iterator iter = value.begin();
1072 iter != value.end(); ++iter)
1073 list_value->Append(new base::StringValue(*iter));
1075 SetPref(extension_id, pref_path, list_value, msg);
1078 void InitPluginService() {
1079 #if defined(ENABLE_PLUGINS)
1080 PluginService::GetInstance()->Init();
1084 void InitializeExtensionSyncService() {
1085 extension_sync_service_.reset(new ExtensionSyncService(
1086 profile(), ExtensionPrefs::Get(browser_context()), service()));
1089 extensions::ManagementPolicy* GetManagementPolicy() {
1090 return ExtensionSystem::Get(browser_context())->management_policy();
1093 ExtensionSyncService* extension_sync_service() {
1094 return extension_sync_service_.get();
1098 scoped_ptr<ExtensionSyncService> extension_sync_service_;
1099 extensions::ExtensionList loaded_;
1100 std::string unloaded_id_;
1101 UnloadedExtensionInfo::Reason unloaded_reason_;
1102 const Extension* installed_;
1104 std::string old_name_;
1105 FeatureSwitch::ScopedOverride override_external_install_prompt_;
1108 // Create a CrxInstaller and install the CRX file.
1109 // Instead of calling this method yourself, use InstallCRX(), which does extra
1111 void InstallCRXInternal(const base::FilePath& crx_path) {
1112 InstallCRXInternal(crx_path, Extension::NO_FLAGS);
1115 void InstallCRXInternal(const base::FilePath& crx_path, int creation_flags) {
1116 ASSERT_TRUE(base::PathExists(crx_path))
1117 << "Path does not exist: "<< crx_path.value().c_str();
1118 scoped_refptr<CrxInstaller> installer(
1119 CrxInstaller::CreateSilent(service()));
1120 installer->set_creation_flags(creation_flags);
1121 if (!(creation_flags & Extension::WAS_INSTALLED_BY_DEFAULT))
1122 installer->set_allow_silent_install(true);
1124 content::WindowedNotificationObserver observer(
1125 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
1126 content::Source<extensions::CrxInstaller>(installer));
1128 installer->InstallCrx(crx_path);
1133 size_t expected_extensions_count_;
1134 content::NotificationRegistrar registrar_;
1137 // Receives notifications from a PackExtensionJob, indicating either that
1138 // packing succeeded or that there was some error.
1139 class PackExtensionTestClient : public extensions::PackExtensionJob::Client {
1141 PackExtensionTestClient(const base::FilePath& expected_crx_path,
1142 const base::FilePath& expected_private_key_path);
1143 virtual void OnPackSuccess(const base::FilePath& crx_path,
1144 const base::FilePath& private_key_path) OVERRIDE;
1145 virtual void OnPackFailure(const std::string& error_message,
1146 ExtensionCreator::ErrorType type) OVERRIDE;
1149 const base::FilePath expected_crx_path_;
1150 const base::FilePath expected_private_key_path_;
1151 DISALLOW_COPY_AND_ASSIGN(PackExtensionTestClient);
1154 PackExtensionTestClient::PackExtensionTestClient(
1155 const base::FilePath& expected_crx_path,
1156 const base::FilePath& expected_private_key_path)
1157 : expected_crx_path_(expected_crx_path),
1158 expected_private_key_path_(expected_private_key_path) {}
1160 // If packing succeeded, we make sure that the package names match our
1162 void PackExtensionTestClient::OnPackSuccess(
1163 const base::FilePath& crx_path,
1164 const base::FilePath& private_key_path) {
1165 // We got the notification and processed it; we don't expect any further tasks
1166 // to be posted to the current thread, so we should stop blocking and continue
1167 // on with the rest of the test.
1168 // This call to |Quit()| matches the call to |Run()| in the
1169 // |PackPunctuatedExtension| test.
1170 base::MessageLoop::current()->Quit();
1171 EXPECT_EQ(expected_crx_path_.value(), crx_path.value());
1172 EXPECT_EQ(expected_private_key_path_.value(), private_key_path.value());
1173 ASSERT_TRUE(base::PathExists(private_key_path));
1176 // The tests are designed so that we never expect to see a packing error.
1177 void PackExtensionTestClient::OnPackFailure(const std::string& error_message,
1178 ExtensionCreator::ErrorType type) {
1179 if (type == ExtensionCreator::kCRXExists)
1180 FAIL() << "Packing should not fail.";
1182 FAIL() << "Existing CRX should have been overwritten.";
1185 // Test loading good extensions from the profile directory.
1186 TEST_F(ExtensionServiceTest, LoadAllExtensionsFromDirectorySuccess) {
1187 InitPluginService();
1188 InitializeGoodInstalledExtensionService();
1191 uint32 expected_num_extensions = 3u;
1192 ASSERT_EQ(expected_num_extensions, loaded_.size());
1194 EXPECT_EQ(std::string(good0), loaded_[0]->id());
1195 EXPECT_EQ(std::string("My extension 1"),
1196 loaded_[0]->name());
1197 EXPECT_EQ(std::string("The first extension that I made."),
1198 loaded_[0]->description());
1199 EXPECT_EQ(Manifest::INTERNAL, loaded_[0]->location());
1200 EXPECT_TRUE(service()->GetExtensionById(loaded_[0]->id(), false));
1201 EXPECT_EQ(expected_num_extensions, registry()->enabled_extensions().size());
1203 ValidatePrefKeyCount(3);
1204 ValidateIntegerPref(good0, "state", Extension::ENABLED);
1205 ValidateIntegerPref(good0, "location", Manifest::INTERNAL);
1206 ValidateIntegerPref(good1, "state", Extension::ENABLED);
1207 ValidateIntegerPref(good1, "location", Manifest::INTERNAL);
1208 ValidateIntegerPref(good2, "state", Extension::ENABLED);
1209 ValidateIntegerPref(good2, "location", Manifest::INTERNAL);
1211 URLPatternSet expected_patterns;
1212 AddPattern(&expected_patterns, "file:///*");
1213 AddPattern(&expected_patterns, "http://*.google.com/*");
1214 AddPattern(&expected_patterns, "https://*.google.com/*");
1215 const Extension* extension = loaded_[0].get();
1216 const extensions::UserScriptList& scripts =
1217 extensions::ContentScriptsInfo::GetContentScripts(extension);
1218 ASSERT_EQ(2u, scripts.size());
1219 EXPECT_EQ(expected_patterns, scripts[0].url_patterns());
1220 EXPECT_EQ(2u, scripts[0].js_scripts().size());
1221 ExtensionResource resource00(extension->id(),
1222 scripts[0].js_scripts()[0].extension_root(),
1223 scripts[0].js_scripts()[0].relative_path());
1224 base::FilePath expected_path =
1225 base::MakeAbsoluteFilePath(extension->path().AppendASCII("script1.js"));
1226 EXPECT_TRUE(resource00.ComparePathWithDefault(expected_path));
1227 ExtensionResource resource01(extension->id(),
1228 scripts[0].js_scripts()[1].extension_root(),
1229 scripts[0].js_scripts()[1].relative_path());
1231 base::MakeAbsoluteFilePath(extension->path().AppendASCII("script2.js"));
1232 EXPECT_TRUE(resource01.ComparePathWithDefault(expected_path));
1233 EXPECT_TRUE(!extensions::PluginInfo::HasPlugins(extension));
1234 EXPECT_EQ(1u, scripts[1].url_patterns().patterns().size());
1235 EXPECT_EQ("http://*.news.com/*",
1236 scripts[1].url_patterns().begin()->GetAsString());
1237 ExtensionResource resource10(extension->id(),
1238 scripts[1].js_scripts()[0].extension_root(),
1239 scripts[1].js_scripts()[0].relative_path());
1241 extension->path().AppendASCII("js_files").AppendASCII("script3.js");
1242 expected_path = base::MakeAbsoluteFilePath(expected_path);
1243 EXPECT_TRUE(resource10.ComparePathWithDefault(expected_path));
1245 expected_patterns.ClearPatterns();
1246 AddPattern(&expected_patterns, "http://*.google.com/*");
1247 AddPattern(&expected_patterns, "https://*.google.com/*");
1250 extension->permissions_data()->active_permissions()->explicit_hosts());
1252 EXPECT_EQ(std::string(good1), loaded_[1]->id());
1253 EXPECT_EQ(std::string("My extension 2"), loaded_[1]->name());
1254 EXPECT_EQ(std::string(), loaded_[1]->description());
1255 EXPECT_EQ(loaded_[1]->GetResourceURL("background.html"),
1256 extensions::BackgroundInfo::GetBackgroundURL(loaded_[1].get()));
1258 extensions::ContentScriptsInfo::GetContentScripts(loaded_[1].get())
1261 // We don't parse the plugins section on Chrome OS.
1262 #if defined(OS_CHROMEOS)
1263 EXPECT_TRUE(!extensions::PluginInfo::HasPlugins(loaded_[1].get()));
1265 ASSERT_TRUE(extensions::PluginInfo::HasPlugins(loaded_[1].get()));
1266 const std::vector<extensions::PluginInfo>* plugins =
1267 extensions::PluginInfo::GetPlugins(loaded_[1].get());
1268 ASSERT_TRUE(plugins);
1269 ASSERT_EQ(2u, plugins->size());
1270 EXPECT_EQ(loaded_[1]->path().AppendASCII("content_plugin.dll").value(),
1271 plugins->at(0).path.value());
1272 EXPECT_TRUE(plugins->at(0).is_public);
1273 EXPECT_EQ(loaded_[1]->path().AppendASCII("extension_plugin.dll").value(),
1274 plugins->at(1).path.value());
1275 EXPECT_FALSE(plugins->at(1).is_public);
1278 EXPECT_EQ(Manifest::INTERNAL, loaded_[1]->location());
1280 int index = expected_num_extensions - 1;
1281 EXPECT_EQ(std::string(good2), loaded_[index]->id());
1282 EXPECT_EQ(std::string("My extension 3"), loaded_[index]->name());
1283 EXPECT_EQ(std::string(), loaded_[index]->description());
1285 extensions::ContentScriptsInfo::GetContentScripts(
1286 loaded_[index].get()).size());
1287 EXPECT_EQ(Manifest::INTERNAL, loaded_[index]->location());
1290 // Test loading bad extensions from the profile directory.
1291 TEST_F(ExtensionServiceTest, LoadAllExtensionsFromDirectoryFail) {
1292 // Initialize the test dir with a bad Preferences/extensions.
1293 base::FilePath source_install_dir =
1294 data_dir().AppendASCII("bad").AppendASCII("Extensions");
1295 base::FilePath pref_path =
1296 source_install_dir.DirName().Append(chrome::kPreferencesFilename);
1298 InitializeInstalledExtensionService(pref_path, source_install_dir);
1302 ASSERT_EQ(4u, GetErrors().size());
1303 ASSERT_EQ(0u, loaded_.size());
1305 EXPECT_TRUE(MatchPattern(base::UTF16ToUTF8(GetErrors()[0]),
1306 std::string("Could not load extension from '*'. ") +
1307 extensions::manifest_errors::kManifestUnreadable)) <<
1308 base::UTF16ToUTF8(GetErrors()[0]);
1310 EXPECT_TRUE(MatchPattern(base::UTF16ToUTF8(GetErrors()[1]),
1311 std::string("Could not load extension from '*'. ") +
1312 extensions::manifest_errors::kManifestUnreadable)) <<
1313 base::UTF16ToUTF8(GetErrors()[1]);
1315 EXPECT_TRUE(MatchPattern(base::UTF16ToUTF8(GetErrors()[2]),
1316 std::string("Could not load extension from '*'. ") +
1317 extensions::manifest_errors::kMissingFile)) <<
1318 base::UTF16ToUTF8(GetErrors()[2]);
1320 EXPECT_TRUE(MatchPattern(base::UTF16ToUTF8(GetErrors()[3]),
1321 std::string("Could not load extension from '*'. ") +
1322 extensions::manifest_errors::kManifestUnreadable)) <<
1323 base::UTF16ToUTF8(GetErrors()[3]);
1326 // Test various cases for delayed install because of missing imports.
1327 TEST_F(ExtensionServiceTest, PendingImports) {
1328 InitPluginService();
1330 base::FilePath source_install_dir =
1331 data_dir().AppendASCII("pending_updates_with_imports").AppendASCII(
1333 base::FilePath pref_path =
1334 source_install_dir.DirName().Append(chrome::kPreferencesFilename);
1336 InitializeInstalledExtensionService(pref_path, source_install_dir);
1338 // Verify there are no pending extensions initially.
1339 EXPECT_FALSE(service()->pending_extension_manager()->HasPendingExtensions());
1342 // Wait for GarbageCollectExtensions task to complete.
1343 base::RunLoop().RunUntilIdle();
1345 // These extensions are used by the extensions we test below, they must be
1347 EXPECT_TRUE(base::PathExists(extensions_install_dir().AppendASCII(
1348 "bjafgdebaacbbbecmhlhpofkepfkgcpa/1.0")));
1349 EXPECT_TRUE(base::PathExists(extensions_install_dir().AppendASCII(
1350 "hpiknbiabeeppbpihjehijgoemciehgk/2")));
1352 // Each of these extensions should have been rejected because of dependencies
1353 // that cannot be satisfied.
1354 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
1356 prefs->GetDelayedInstallInfo("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
1358 prefs->GetInstalledExtensionInfo("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
1360 prefs->GetDelayedInstallInfo("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"));
1362 prefs->GetInstalledExtensionInfo("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"));
1364 prefs->GetDelayedInstallInfo("cccccccccccccccccccccccccccccccc"));
1366 prefs->GetInstalledExtensionInfo("cccccccccccccccccccccccccccccccc"));
1368 // Make sure the import started for the extension with a dependency.
1370 prefs->GetDelayedInstallInfo("behllobkkfkfnphdnhnkndlbkcpglgmj"));
1371 EXPECT_EQ(ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS,
1372 prefs->GetDelayedInstallReason("behllobkkfkfnphdnhnkndlbkcpglgmj"));
1374 EXPECT_FALSE(base::PathExists(extensions_install_dir().AppendASCII(
1375 "behllobkkfkfnphdnhnkndlbkcpglgmj/1.0.0.0")));
1377 EXPECT_TRUE(service()->pending_extension_manager()->HasPendingExtensions());
1378 std::string pending_id("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
1379 EXPECT_TRUE(service()->pending_extension_manager()->IsIdPending(pending_id));
1380 // Remove it because we are not testing the pending extension manager's
1381 // ability to download and install extensions.
1382 EXPECT_TRUE(service()->pending_extension_manager()->Remove(pending_id));
1385 // Test installing extensions. This test tries to install few extensions using
1386 // crx files. If you need to change those crx files, feel free to repackage
1387 // them, throw away the key used and change the id's above.
1388 TEST_F(ExtensionServiceTest, InstallExtension) {
1389 InitializeEmptyExtensionService();
1391 // Extensions not enabled.
1392 service()->set_extensions_enabled(false);
1393 base::FilePath path = data_dir().AppendASCII("good.crx");
1394 InstallCRX(path, INSTALL_FAILED);
1395 service()->set_extensions_enabled(true);
1397 ValidatePrefKeyCount(0);
1399 // A simple extension that should install without error.
1400 path = data_dir().AppendASCII("good.crx");
1401 InstallCRX(path, INSTALL_NEW);
1402 // TODO(erikkay): verify the contents of the installed extension.
1405 ValidatePrefKeyCount(++pref_count);
1406 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
1407 ValidateIntegerPref(good_crx, "location", Manifest::INTERNAL);
1409 // An extension with page actions.
1410 path = data_dir().AppendASCII("page_action.crx");
1411 InstallCRX(path, INSTALL_NEW);
1412 ValidatePrefKeyCount(++pref_count);
1413 ValidateIntegerPref(page_action, "state", Extension::ENABLED);
1414 ValidateIntegerPref(page_action, "location", Manifest::INTERNAL);
1417 path = data_dir().AppendASCII("bad_signature.crx");
1418 InstallCRX(path, INSTALL_FAILED);
1419 ValidatePrefKeyCount(pref_count);
1421 // 0-length extension file.
1422 path = data_dir().AppendASCII("not_an_extension.crx");
1423 InstallCRX(path, INSTALL_FAILED);
1424 ValidatePrefKeyCount(pref_count);
1426 // Bad magic number.
1427 path = data_dir().AppendASCII("bad_magic.crx");
1428 InstallCRX(path, INSTALL_FAILED);
1429 ValidatePrefKeyCount(pref_count);
1431 // Packed extensions may have folders or files that have underscores.
1432 // This will only cause a warning, rather than a fatal error.
1433 path = data_dir().AppendASCII("bad_underscore.crx");
1434 InstallCRX(path, INSTALL_NEW);
1435 ValidatePrefKeyCount(++pref_count);
1437 // A test for an extension with a 2048-bit public key.
1438 path = data_dir().AppendASCII("good2048.crx");
1439 InstallCRX(path, INSTALL_NEW);
1440 ValidatePrefKeyCount(++pref_count);
1441 ValidateIntegerPref(good2048, "state", Extension::ENABLED);
1442 ValidateIntegerPref(good2048, "location", Manifest::INTERNAL);
1444 // TODO(erikkay): add more tests for many of the failure cases.
1445 // TODO(erikkay): add tests for upgrade cases.
1448 struct MockExtensionRegistryObserver
1449 : public extensions::ExtensionRegistryObserver {
1450 virtual void OnExtensionWillBeInstalled(
1451 content::BrowserContext* browser_context,
1452 const Extension* extension,
1454 bool from_ephemeral,
1455 const std::string& old_name) OVERRIDE {
1456 last_extension_installed = extension->id();
1459 virtual void OnExtensionUninstalled(
1460 content::BrowserContext* browser_context,
1461 const Extension* extension,
1462 extensions::UninstallReason reason) OVERRIDE {
1463 last_extension_uninstalled = extension->id();
1466 std::string last_extension_installed;
1467 std::string last_extension_uninstalled;
1470 // Test that correct notifications are sent to ExtensionRegistryObserver on
1471 // extension install and uninstall.
1472 TEST_F(ExtensionServiceTest, InstallObserverNotified) {
1473 InitializeEmptyExtensionService();
1475 extensions::ExtensionRegistry* registry(
1476 extensions::ExtensionRegistry::Get(profile()));
1477 MockExtensionRegistryObserver observer;
1478 registry->AddObserver(&observer);
1480 // A simple extension that should install without error.
1481 ASSERT_TRUE(observer.last_extension_installed.empty());
1482 base::FilePath path = data_dir().AppendASCII("good.crx");
1483 InstallCRX(path, INSTALL_NEW);
1484 ASSERT_EQ(good_crx, observer.last_extension_installed);
1486 // Uninstall the extension.
1487 ASSERT_TRUE(observer.last_extension_uninstalled.empty());
1488 UninstallExtension(good_crx, false);
1489 ASSERT_EQ(good_crx, observer.last_extension_uninstalled);
1491 registry->RemoveObserver(&observer);
1494 // Tests that flags passed to OnExternalExtensionFileFound() make it to the
1495 // extension object.
1496 TEST_F(ExtensionServiceTest, InstallingExternalExtensionWithFlags) {
1497 const char kPrefFromBookmark[] = "from_bookmark";
1499 InitializeEmptyExtensionService();
1501 base::FilePath path = data_dir().AppendASCII("good.crx");
1502 service()->set_extensions_enabled(true);
1504 // Register and install an external extension.
1505 Version version("1.0.0.0");
1506 content::WindowedNotificationObserver observer(
1507 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
1508 content::NotificationService::AllSources());
1509 if (service()->OnExternalExtensionFileFound(good_crx,
1512 Manifest::EXTERNAL_PREF,
1513 Extension::FROM_BOOKMARK,
1514 false /* mark_acknowledged */)) {
1518 const Extension* extension = service()->GetExtensionById(good_crx, false);
1519 ASSERT_TRUE(extension);
1520 ASSERT_TRUE(extension->from_bookmark());
1521 ASSERT_TRUE(ValidateBooleanPref(good_crx, kPrefFromBookmark, true));
1523 // Upgrade to version 2.0, the flag should be preserved.
1524 path = data_dir().AppendASCII("good2.crx");
1525 UpdateExtension(good_crx, path, ENABLED);
1526 ASSERT_TRUE(ValidateBooleanPref(good_crx, kPrefFromBookmark, true));
1527 extension = service()->GetExtensionById(good_crx, false);
1528 ASSERT_TRUE(extension);
1529 ASSERT_TRUE(extension->from_bookmark());
1532 // Test the handling of Extension::EXTERNAL_EXTENSION_UNINSTALLED
1533 TEST_F(ExtensionServiceTest, UninstallingExternalExtensions) {
1534 InitializeEmptyExtensionService();
1536 base::FilePath path = data_dir().AppendASCII("good.crx");
1537 service()->set_extensions_enabled(true);
1539 // Install an external extension.
1540 Version version("1.0.0.0");
1541 content::WindowedNotificationObserver observer(
1542 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
1543 content::NotificationService::AllSources());
1544 if (service()->OnExternalExtensionFileFound(good_crx,
1547 Manifest::EXTERNAL_PREF,
1548 Extension::NO_FLAGS,
1553 ASSERT_TRUE(service()->GetExtensionById(good_crx, false));
1555 // Uninstall it and check that its killbit gets set.
1556 UninstallExtension(good_crx, false);
1557 ValidateIntegerPref(good_crx, "location",
1558 Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1560 // Try to re-install it externally. This should fail because of the killbit.
1561 service()->OnExternalExtensionFileFound(good_crx,
1564 Manifest::EXTERNAL_PREF,
1565 Extension::NO_FLAGS,
1567 base::RunLoop().RunUntilIdle();
1568 ASSERT_TRUE(NULL == service()->GetExtensionById(good_crx, false));
1569 ValidateIntegerPref(good_crx, "location",
1570 Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1572 version = Version("1.0.0.1");
1573 // Repeat the same thing with a newer version of the extension.
1574 path = data_dir().AppendASCII("good2.crx");
1575 service()->OnExternalExtensionFileFound(good_crx,
1578 Manifest::EXTERNAL_PREF,
1579 Extension::NO_FLAGS,
1581 base::RunLoop().RunUntilIdle();
1582 ASSERT_TRUE(NULL == service()->GetExtensionById(good_crx, false));
1583 ValidateIntegerPref(good_crx, "location",
1584 Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1586 // Try adding the same extension from an external update URL.
1587 ASSERT_FALSE(service()->pending_extension_manager()->AddFromExternalUpdateUrl(
1590 GURL("http:://fake.update/url"),
1591 Manifest::EXTERNAL_PREF_DOWNLOAD,
1592 Extension::NO_FLAGS,
1595 ASSERT_FALSE(service()->pending_extension_manager()->IsIdPending(good_crx));
1598 // Test that uninstalling an external extension does not crash when
1599 // the extension could not be loaded.
1600 // This extension shown in preferences file requires an experimental permission.
1601 // It could not be loaded without such permission.
1602 TEST_F(ExtensionServiceTest, UninstallingNotLoadedExtension) {
1603 base::FilePath source_install_dir =
1604 data_dir().AppendASCII("good").AppendASCII("Extensions");
1605 // The preference contains an external extension
1606 // that requires 'experimental' permission.
1607 base::FilePath pref_path = source_install_dir
1609 .AppendASCII("PreferencesExperimental");
1611 // Aforementioned extension will not be loaded if
1612 // there is no '--enable-experimental-extension-apis' command line flag.
1613 InitializeInstalledExtensionService(pref_path, source_install_dir);
1617 // Check and try to uninstall it.
1618 // If we don't check whether the extension is loaded before we uninstall it
1619 // in CheckExternalUninstall, a crash will happen here because we will get or
1620 // dereference a NULL pointer (extension) inside UninstallExtension.
1621 MockExtensionProvider provider(NULL, Manifest::EXTERNAL_REGISTRY);
1622 service()->OnExternalProviderReady(&provider);
1625 // Test that external extensions with incorrect IDs are not installed.
1626 TEST_F(ExtensionServiceTest, FailOnWrongId) {
1627 InitializeEmptyExtensionService();
1628 base::FilePath path = data_dir().AppendASCII("good.crx");
1629 service()->set_extensions_enabled(true);
1631 Version version("1.0.0.0");
1633 const std::string wrong_id = all_zero;
1634 const std::string correct_id = good_crx;
1635 ASSERT_NE(correct_id, wrong_id);
1637 // Install an external extension with an ID from the external
1638 // source that is not equal to the ID in the extension manifest.
1639 content::WindowedNotificationObserver observer(
1640 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
1641 content::NotificationService::AllSources());
1642 service()->OnExternalExtensionFileFound(wrong_id,
1645 Manifest::EXTERNAL_PREF,
1646 Extension::NO_FLAGS,
1650 ASSERT_FALSE(service()->GetExtensionById(good_crx, false));
1652 // Try again with the right ID. Expect success.
1653 content::WindowedNotificationObserver observer2(
1654 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
1655 content::NotificationService::AllSources());
1656 if (service()->OnExternalExtensionFileFound(correct_id,
1659 Manifest::EXTERNAL_PREF,
1660 Extension::NO_FLAGS,
1664 ASSERT_TRUE(service()->GetExtensionById(good_crx, false));
1667 // Test that external extensions with incorrect versions are not installed.
1668 TEST_F(ExtensionServiceTest, FailOnWrongVersion) {
1669 InitializeEmptyExtensionService();
1670 base::FilePath path = data_dir().AppendASCII("good.crx");
1671 service()->set_extensions_enabled(true);
1673 // Install an external extension with a version from the external
1674 // source that is not equal to the version in the extension manifest.
1675 Version wrong_version("1.2.3.4");
1676 content::WindowedNotificationObserver observer(
1677 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
1678 content::NotificationService::AllSources());
1679 service()->OnExternalExtensionFileFound(good_crx,
1682 Manifest::EXTERNAL_PREF,
1683 Extension::NO_FLAGS,
1687 ASSERT_FALSE(service()->GetExtensionById(good_crx, false));
1689 // Try again with the right version. Expect success.
1690 service()->pending_extension_manager()->Remove(good_crx);
1691 Version correct_version("1.0.0.0");
1692 content::WindowedNotificationObserver observer2(
1693 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
1694 content::NotificationService::AllSources());
1695 if (service()->OnExternalExtensionFileFound(good_crx,
1698 Manifest::EXTERNAL_PREF,
1699 Extension::NO_FLAGS,
1703 ASSERT_TRUE(service()->GetExtensionById(good_crx, false));
1706 // Install a user script (they get converted automatically to an extension)
1707 TEST_F(ExtensionServiceTest, InstallUserScript) {
1708 // The details of script conversion are tested elsewhere, this just tests
1709 // integration with ExtensionService.
1710 InitializeEmptyExtensionService();
1712 base::FilePath path = data_dir().AppendASCII("user_script_basic.user.js");
1714 ASSERT_TRUE(base::PathExists(path));
1715 scoped_refptr<CrxInstaller> installer(CrxInstaller::CreateSilent(service()));
1716 installer->set_allow_silent_install(true);
1717 installer->InstallUserScript(
1719 GURL("http://www.aaronboodman.com/scripts/user_script_basic.user.js"));
1721 base::RunLoop().RunUntilIdle();
1722 std::vector<base::string16> errors = GetErrors();
1723 EXPECT_TRUE(installed_) << "Nothing was installed.";
1724 EXPECT_FALSE(was_update_) << path.value();
1725 ASSERT_EQ(1u, loaded_.size()) << "Nothing was loaded.";
1726 EXPECT_EQ(0u, errors.size()) << "There were errors: "
1727 << JoinString(errors, ',');
1728 EXPECT_TRUE(service()->GetExtensionById(loaded_[0]->id(), false))
1732 was_update_ = false;
1734 ExtensionErrorReporter::GetInstance()->ClearErrors();
1737 // Extensions don't install during shutdown.
1738 TEST_F(ExtensionServiceTest, InstallExtensionDuringShutdown) {
1739 InitializeEmptyExtensionService();
1741 // Simulate shutdown.
1742 service()->set_browser_terminating_for_test(true);
1744 base::FilePath path = data_dir().AppendASCII("good.crx");
1745 scoped_refptr<CrxInstaller> installer(CrxInstaller::CreateSilent(service()));
1746 installer->set_allow_silent_install(true);
1747 installer->InstallCrx(path);
1748 base::RunLoop().RunUntilIdle();
1750 EXPECT_FALSE(installed_) << "Extension installed during shutdown.";
1751 ASSERT_EQ(0u, loaded_.size()) << "Extension loaded during shutdown.";
1754 // This tests that the granted permissions preferences are correctly set when
1755 // installing an extension.
1756 TEST_F(ExtensionServiceTest, GrantedPermissions) {
1757 InitializeEmptyExtensionService();
1758 base::FilePath path = data_dir().AppendASCII("permissions");
1760 base::FilePath pem_path = path.AppendASCII("unknown.pem");
1761 path = path.AppendASCII("unknown");
1763 ASSERT_TRUE(base::PathExists(pem_path));
1764 ASSERT_TRUE(base::PathExists(path));
1766 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
1768 APIPermissionSet expected_api_perms;
1769 URLPatternSet expected_host_perms;
1771 // Make sure there aren't any granted permissions before the
1772 // extension is installed.
1773 scoped_refptr<PermissionSet> known_perms(
1774 prefs->GetGrantedPermissions(permissions_crx));
1775 EXPECT_FALSE(known_perms.get());
1777 const Extension* extension = PackAndInstallCRX(path, pem_path, INSTALL_NEW);
1779 EXPECT_EQ(0u, GetErrors().size());
1780 ASSERT_EQ(1u, registry()->enabled_extensions().size());
1781 EXPECT_EQ(permissions_crx, extension->id());
1783 // Verify that the valid API permissions have been recognized.
1784 expected_api_perms.insert(APIPermission::kTab);
1786 AddPattern(&expected_host_perms, "http://*.google.com/*");
1787 AddPattern(&expected_host_perms, "https://*.google.com/*");
1788 AddPattern(&expected_host_perms, "http://*.google.com.hk/*");
1789 AddPattern(&expected_host_perms, "http://www.example.com/*");
1791 known_perms = prefs->GetGrantedPermissions(extension->id());
1792 EXPECT_TRUE(known_perms.get());
1793 EXPECT_FALSE(known_perms->IsEmpty());
1794 EXPECT_EQ(expected_api_perms, known_perms->apis());
1795 EXPECT_FALSE(known_perms->HasEffectiveFullAccess());
1796 EXPECT_EQ(expected_host_perms, known_perms->effective_hosts());
1800 #if !defined(OS_CHROMEOS)
1801 // This tests that the granted permissions preferences are correctly set for
1803 TEST_F(ExtensionServiceTest, DefaultAppsGrantedPermissions) {
1804 InitializeEmptyExtensionService();
1805 base::FilePath path = data_dir().AppendASCII("permissions");
1807 base::FilePath pem_path = path.AppendASCII("unknown.pem");
1808 path = path.AppendASCII("unknown");
1810 ASSERT_TRUE(base::PathExists(pem_path));
1811 ASSERT_TRUE(base::PathExists(path));
1813 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
1815 APIPermissionSet expected_api_perms;
1816 URLPatternSet expected_host_perms;
1818 // Make sure there aren't any granted permissions before the
1819 // extension is installed.
1820 scoped_refptr<PermissionSet> known_perms(
1821 prefs->GetGrantedPermissions(permissions_crx));
1822 EXPECT_FALSE(known_perms.get());
1824 const Extension* extension = PackAndInstallCRX(
1825 path, pem_path, INSTALL_NEW, Extension::WAS_INSTALLED_BY_DEFAULT);
1827 EXPECT_EQ(0u, GetErrors().size());
1828 ASSERT_EQ(1u, registry()->enabled_extensions().size());
1829 EXPECT_EQ(permissions_crx, extension->id());
1831 // Verify that the valid API permissions have been recognized.
1832 expected_api_perms.insert(APIPermission::kTab);
1834 known_perms = prefs->GetGrantedPermissions(extension->id());
1835 EXPECT_TRUE(known_perms.get());
1836 EXPECT_FALSE(known_perms->IsEmpty());
1837 EXPECT_EQ(expected_api_perms, known_perms->apis());
1838 EXPECT_FALSE(known_perms->HasEffectiveFullAccess());
1842 #if !defined(OS_POSIX) || defined(OS_MACOSX)
1843 // Tests that the granted permissions full_access bit gets set correctly when
1844 // an extension contains an NPAPI plugin.
1845 // Only run this on platforms that support NPAPI plugins.
1846 TEST_F(ExtensionServiceTest, GrantedFullAccessPermissions) {
1847 InitPluginService();
1849 InitializeEmptyExtensionService();
1851 ASSERT_TRUE(base::PathExists(good1_path()));
1852 const Extension* extension = PackAndInstallCRX(good1_path(), INSTALL_NEW);
1853 EXPECT_EQ(0u, GetErrors().size());
1854 EXPECT_EQ(1u, registry()->enabled_extensions().size());
1855 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
1857 scoped_refptr<PermissionSet> permissions(
1858 prefs->GetGrantedPermissions(extension->id()));
1859 EXPECT_FALSE(permissions->IsEmpty());
1860 EXPECT_TRUE(permissions->HasEffectiveFullAccess());
1861 EXPECT_FALSE(permissions->apis().empty());
1862 EXPECT_TRUE(permissions->HasAPIPermission(APIPermission::kPlugin));
1864 // Full access implies full host access too...
1865 EXPECT_TRUE(permissions->HasEffectiveAccessToAllHosts());
1869 // Tests that the extension is disabled when permissions are missing from
1870 // the extension's granted permissions preferences. (This simulates updating
1871 // the browser to a version which recognizes more permissions).
1872 TEST_F(ExtensionServiceTest, GrantedAPIAndHostPermissions) {
1873 InitializeEmptyExtensionService();
1875 base::FilePath path =
1876 data_dir().AppendASCII("permissions").AppendASCII("unknown");
1878 ASSERT_TRUE(base::PathExists(path));
1880 const Extension* extension = PackAndInstallCRX(path, INSTALL_NEW);
1882 EXPECT_EQ(0u, GetErrors().size());
1883 EXPECT_EQ(1u, registry()->enabled_extensions().size());
1884 std::string extension_id = extension->id();
1886 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
1888 APIPermissionSet expected_api_permissions;
1889 URLPatternSet expected_host_permissions;
1891 expected_api_permissions.insert(APIPermission::kTab);
1892 AddPattern(&expected_host_permissions, "http://*.google.com/*");
1893 AddPattern(&expected_host_permissions, "https://*.google.com/*");
1894 AddPattern(&expected_host_permissions, "http://*.google.com.hk/*");
1895 AddPattern(&expected_host_permissions, "http://www.example.com/*");
1897 std::set<std::string> host_permissions;
1899 // Test that the extension is disabled when an API permission is missing from
1900 // the extension's granted api permissions preference. (This simulates
1901 // updating the browser to a version which recognizes a new API permission).
1902 SetPref(extension_id, "granted_permissions.api",
1903 new base::ListValue(), "granted_permissions.api");
1904 service()->ReloadExtensionsForTest();
1906 EXPECT_EQ(1u, registry()->disabled_extensions().size());
1907 extension = registry()->disabled_extensions().begin()->get();
1909 ASSERT_TRUE(prefs->IsExtensionDisabled(extension_id));
1910 ASSERT_FALSE(service()->IsExtensionEnabled(extension_id));
1911 ASSERT_TRUE(prefs->DidExtensionEscalatePermissions(extension_id));
1913 // Now grant and re-enable the extension, making sure the prefs are updated.
1914 service()->GrantPermissionsAndEnableExtension(extension);
1916 ASSERT_FALSE(prefs->IsExtensionDisabled(extension_id));
1917 ASSERT_TRUE(service()->IsExtensionEnabled(extension_id));
1918 ASSERT_FALSE(prefs->DidExtensionEscalatePermissions(extension_id));
1920 scoped_refptr<PermissionSet> current_perms(
1921 prefs->GetGrantedPermissions(extension_id));
1922 ASSERT_TRUE(current_perms.get());
1923 ASSERT_FALSE(current_perms->IsEmpty());
1924 ASSERT_FALSE(current_perms->HasEffectiveFullAccess());
1925 ASSERT_EQ(expected_api_permissions, current_perms->apis());
1926 ASSERT_EQ(expected_host_permissions, current_perms->effective_hosts());
1928 // Tests that the extension is disabled when a host permission is missing from
1929 // the extension's granted host permissions preference. (This simulates
1930 // updating the browser to a version which recognizes additional host
1932 host_permissions.clear();
1933 current_perms = NULL;
1935 host_permissions.insert("http://*.google.com/*");
1936 host_permissions.insert("https://*.google.com/*");
1937 host_permissions.insert("http://*.google.com.hk/*");
1939 base::ListValue* api_permissions = new base::ListValue();
1940 api_permissions->Append(
1941 new base::StringValue("tabs"));
1942 SetPref(extension_id, "granted_permissions.api",
1943 api_permissions, "granted_permissions.api");
1945 extension_id, "granted_permissions.scriptable_host", host_permissions);
1947 service()->ReloadExtensionsForTest();
1949 EXPECT_EQ(1u, registry()->disabled_extensions().size());
1950 extension = registry()->disabled_extensions().begin()->get();
1952 ASSERT_TRUE(prefs->IsExtensionDisabled(extension_id));
1953 ASSERT_FALSE(service()->IsExtensionEnabled(extension_id));
1954 ASSERT_TRUE(prefs->DidExtensionEscalatePermissions(extension_id));
1956 // Now grant and re-enable the extension, making sure the prefs are updated.
1957 service()->GrantPermissionsAndEnableExtension(extension);
1959 ASSERT_TRUE(service()->IsExtensionEnabled(extension_id));
1960 ASSERT_FALSE(prefs->DidExtensionEscalatePermissions(extension_id));
1962 current_perms = prefs->GetGrantedPermissions(extension_id);
1963 ASSERT_TRUE(current_perms.get());
1964 ASSERT_FALSE(current_perms->IsEmpty());
1965 ASSERT_FALSE(current_perms->HasEffectiveFullAccess());
1966 ASSERT_EQ(expected_api_permissions, current_perms->apis());
1967 ASSERT_EQ(expected_host_permissions, current_perms->effective_hosts());
1970 // Test Packaging and installing an extension.
1971 TEST_F(ExtensionServiceTest, PackExtension) {
1972 InitializeEmptyExtensionService();
1973 base::FilePath input_directory =
1975 .AppendASCII("good")
1976 .AppendASCII("Extensions")
1977 .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
1978 .AppendASCII("1.0.0.0");
1980 base::ScopedTempDir temp_dir;
1981 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
1982 base::FilePath output_directory = temp_dir.path();
1984 base::FilePath crx_path(output_directory.AppendASCII("ex1.crx"));
1985 base::FilePath privkey_path(output_directory.AppendASCII("privkey.pem"));
1987 scoped_ptr<ExtensionCreator> creator(new ExtensionCreator());
1988 ASSERT_TRUE(creator->Run(input_directory, crx_path, base::FilePath(),
1989 privkey_path, ExtensionCreator::kNoRunFlags));
1990 ASSERT_TRUE(base::PathExists(crx_path));
1991 ASSERT_TRUE(base::PathExists(privkey_path));
1993 // Repeat the run with the pem file gone, and no special flags
1994 // Should refuse to overwrite the existing crx.
1995 base::DeleteFile(privkey_path, false);
1996 ASSERT_FALSE(creator->Run(input_directory, crx_path, base::FilePath(),
1997 privkey_path, ExtensionCreator::kNoRunFlags));
1999 // OK, now try it with a flag to overwrite existing crx. Should work.
2000 ASSERT_TRUE(creator->Run(input_directory, crx_path, base::FilePath(),
2001 privkey_path, ExtensionCreator::kOverwriteCRX));
2003 // Repeat the run allowing existing crx, but the existing pem is still
2004 // an error. Should fail.
2005 ASSERT_FALSE(creator->Run(input_directory, crx_path, base::FilePath(),
2006 privkey_path, ExtensionCreator::kOverwriteCRX));
2008 ASSERT_TRUE(base::PathExists(privkey_path));
2009 InstallCRX(crx_path, INSTALL_NEW);
2011 // Try packing with invalid paths.
2012 creator.reset(new ExtensionCreator());
2014 creator->Run(base::FilePath(), base::FilePath(), base::FilePath(),
2015 base::FilePath(), ExtensionCreator::kOverwriteCRX));
2017 // Try packing an empty directory. Should fail because an empty directory is
2018 // not a valid extension.
2019 base::ScopedTempDir temp_dir2;
2020 ASSERT_TRUE(temp_dir2.CreateUniqueTempDir());
2021 creator.reset(new ExtensionCreator());
2022 ASSERT_FALSE(creator->Run(temp_dir2.path(), crx_path, privkey_path,
2023 base::FilePath(), ExtensionCreator::kOverwriteCRX));
2025 // Try packing with an invalid manifest.
2026 std::string invalid_manifest_content = "I am not a manifest.";
2027 ASSERT_TRUE(base::WriteFile(
2028 temp_dir2.path().Append(extensions::kManifestFilename),
2029 invalid_manifest_content.c_str(), invalid_manifest_content.size()));
2030 creator.reset(new ExtensionCreator());
2031 ASSERT_FALSE(creator->Run(temp_dir2.path(), crx_path, privkey_path,
2032 base::FilePath(), ExtensionCreator::kOverwriteCRX));
2034 // Try packing with a private key that is a valid key, but invalid for the
2036 base::FilePath bad_private_key_dir =
2037 data_dir().AppendASCII("bad_private_key");
2038 crx_path = output_directory.AppendASCII("bad_private_key.crx");
2039 privkey_path = data_dir().AppendASCII("bad_private_key.pem");
2040 ASSERT_FALSE(creator->Run(bad_private_key_dir, crx_path, base::FilePath(),
2041 privkey_path, ExtensionCreator::kOverwriteCRX));
2044 // Test Packaging and installing an extension whose name contains punctuation.
2045 TEST_F(ExtensionServiceTest, PackPunctuatedExtension) {
2046 InitializeEmptyExtensionService();
2047 base::FilePath input_directory = data_dir()
2048 .AppendASCII("good")
2049 .AppendASCII("Extensions")
2051 .AppendASCII("1.0.0.0");
2053 base::ScopedTempDir temp_dir;
2054 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
2056 // Extension names containing punctuation, and the expected names for the
2057 // packed extensions.
2058 const base::FilePath punctuated_names[] = {
2059 base::FilePath(FILE_PATH_LITERAL("this.extensions.name.has.periods")),
2060 base::FilePath(FILE_PATH_LITERAL(".thisextensionsnamestartswithaperiod")),
2061 base::FilePath(FILE_PATH_LITERAL("thisextensionhasaslashinitsname/")).
2062 NormalizePathSeparators(),
2064 const base::FilePath expected_crx_names[] = {
2065 base::FilePath(FILE_PATH_LITERAL("this.extensions.name.has.periods.crx")),
2067 FILE_PATH_LITERAL(".thisextensionsnamestartswithaperiod.crx")),
2068 base::FilePath(FILE_PATH_LITERAL("thisextensionhasaslashinitsname.crx")),
2070 const base::FilePath expected_private_key_names[] = {
2071 base::FilePath(FILE_PATH_LITERAL("this.extensions.name.has.periods.pem")),
2073 FILE_PATH_LITERAL(".thisextensionsnamestartswithaperiod.pem")),
2074 base::FilePath(FILE_PATH_LITERAL("thisextensionhasaslashinitsname.pem")),
2077 for (size_t i = 0; i < arraysize(punctuated_names); ++i) {
2078 SCOPED_TRACE(punctuated_names[i].value().c_str());
2079 base::FilePath output_dir = temp_dir.path().Append(punctuated_names[i]);
2081 // Copy the extension into the output directory, as PackExtensionJob doesn't
2082 // let us choose where to output the packed extension.
2083 ASSERT_TRUE(base::CopyDirectory(input_directory, output_dir, true));
2085 base::FilePath expected_crx_path =
2086 temp_dir.path().Append(expected_crx_names[i]);
2087 base::FilePath expected_private_key_path =
2088 temp_dir.path().Append(expected_private_key_names[i]);
2089 PackExtensionTestClient pack_client(expected_crx_path,
2090 expected_private_key_path);
2091 scoped_refptr<extensions::PackExtensionJob> packer(
2092 new extensions::PackExtensionJob(&pack_client, output_dir,
2094 ExtensionCreator::kOverwriteCRX));
2097 // The packer will post a notification task to the current thread's message
2098 // loop when it is finished. We manually run the loop here so that we
2099 // block and catch the notification; otherwise, the process would exit.
2100 // This call to |Run()| is matched by a call to |Quit()| in the
2101 // |PackExtensionTestClient|'s notification handling code.
2102 base::MessageLoop::current()->Run();
2104 if (HasFatalFailure())
2107 InstallCRX(expected_crx_path, INSTALL_NEW);
2111 TEST_F(ExtensionServiceTest, PackExtensionContainingKeyFails) {
2112 InitializeEmptyExtensionService();
2114 base::ScopedTempDir extension_temp_dir;
2115 ASSERT_TRUE(extension_temp_dir.CreateUniqueTempDir());
2116 base::FilePath input_directory = extension_temp_dir.path().AppendASCII("ext");
2118 base::CopyDirectory(data_dir()
2119 .AppendASCII("good")
2120 .AppendASCII("Extensions")
2121 .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
2122 .AppendASCII("1.0.0.0"),
2124 /*recursive=*/true));
2126 base::ScopedTempDir output_temp_dir;
2127 ASSERT_TRUE(output_temp_dir.CreateUniqueTempDir());
2128 base::FilePath output_directory = output_temp_dir.path();
2130 base::FilePath crx_path(output_directory.AppendASCII("ex1.crx"));
2131 base::FilePath privkey_path(output_directory.AppendASCII("privkey.pem"));
2133 // Pack the extension once to get a private key.
2134 scoped_ptr<ExtensionCreator> creator(new ExtensionCreator());
2135 ASSERT_TRUE(creator->Run(input_directory, crx_path, base::FilePath(),
2136 privkey_path, ExtensionCreator::kNoRunFlags))
2137 << creator->error_message();
2138 ASSERT_TRUE(base::PathExists(crx_path));
2139 ASSERT_TRUE(base::PathExists(privkey_path));
2141 base::DeleteFile(crx_path, false);
2142 // Move the pem file into the extension.
2143 base::Move(privkey_path,
2144 input_directory.AppendASCII("privkey.pem"));
2146 // This pack should fail because of the contained private key.
2147 EXPECT_FALSE(creator->Run(input_directory, crx_path, base::FilePath(),
2148 privkey_path, ExtensionCreator::kNoRunFlags));
2149 EXPECT_THAT(creator->error_message(),
2150 testing::ContainsRegex(
2151 "extension includes the key file.*privkey.pem"));
2154 // Test Packaging and installing an extension using an openssl generated key.
2155 // The openssl is generated with the following:
2156 // > openssl genrsa -out privkey.pem 1024
2157 // > openssl pkcs8 -topk8 -nocrypt -in privkey.pem -out privkey_asn1.pem
2158 // The privkey.pem is a PrivateKey, and the pcks8 -topk8 creates a
2159 // PrivateKeyInfo ASN.1 structure, we our RSAPrivateKey expects.
2160 TEST_F(ExtensionServiceTest, PackExtensionOpenSSLKey) {
2161 InitializeEmptyExtensionService();
2162 base::FilePath input_directory =
2164 .AppendASCII("good")
2165 .AppendASCII("Extensions")
2166 .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
2167 .AppendASCII("1.0.0.0");
2168 base::FilePath privkey_path(
2169 data_dir().AppendASCII("openssl_privkey_asn1.pem"));
2170 ASSERT_TRUE(base::PathExists(privkey_path));
2172 base::ScopedTempDir temp_dir;
2173 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
2174 base::FilePath output_directory = temp_dir.path();
2176 base::FilePath crx_path(output_directory.AppendASCII("ex1.crx"));
2178 scoped_ptr<ExtensionCreator> creator(new ExtensionCreator());
2179 ASSERT_TRUE(creator->Run(input_directory, crx_path, privkey_path,
2180 base::FilePath(), ExtensionCreator::kOverwriteCRX));
2182 InstallCRX(crx_path, INSTALL_NEW);
2185 #if defined(THREAD_SANITIZER)
2186 // Flaky under Tsan. http://crbug.com/377702
2187 #define MAYBE_InstallTheme DISABLED_InstallTheme
2189 #define MAYBE_InstallTheme InstallTheme
2192 TEST_F(ExtensionServiceTest, MAYBE_InstallTheme) {
2193 InitializeEmptyExtensionService();
2197 base::FilePath path = data_dir().AppendASCII("theme.crx");
2198 InstallCRX(path, INSTALL_NEW);
2200 ValidatePrefKeyCount(++pref_count);
2201 ValidateIntegerPref(theme_crx, "state", Extension::ENABLED);
2202 ValidateIntegerPref(theme_crx, "location", Manifest::INTERNAL);
2204 // A theme when extensions are disabled. Themes can be installed, even when
2205 // extensions are disabled.
2206 service()->set_extensions_enabled(false);
2207 path = data_dir().AppendASCII("theme2.crx");
2208 InstallCRX(path, INSTALL_NEW);
2209 ValidatePrefKeyCount(++pref_count);
2210 ValidateIntegerPref(theme2_crx, "state", Extension::ENABLED);
2211 ValidateIntegerPref(theme2_crx, "location", Manifest::INTERNAL);
2213 // A theme with extension elements. Themes cannot have extension elements,
2214 // so any such elements (like content scripts) should be ignored.
2215 service()->set_extensions_enabled(true);
2217 path = data_dir().AppendASCII("theme_with_extension.crx");
2218 const Extension* extension = InstallCRX(path, INSTALL_NEW);
2219 ValidatePrefKeyCount(++pref_count);
2220 ASSERT_TRUE(extension);
2221 EXPECT_TRUE(extension->is_theme());
2224 extensions::ContentScriptsInfo::GetContentScripts(extension).size());
2227 // A theme with image resources missing (misspelt path).
2228 path = data_dir().AppendASCII("theme_missing_image.crx");
2229 InstallCRX(path, INSTALL_FAILED);
2230 ValidatePrefKeyCount(pref_count);
2233 TEST_F(ExtensionServiceTest, LoadLocalizedTheme) {
2235 InitializeEmptyExtensionService();
2238 base::FilePath extension_path = data_dir().AppendASCII("theme_i18n");
2240 extensions::UnpackedInstaller::Create(service())->Load(extension_path);
2241 base::RunLoop().RunUntilIdle();
2242 EXPECT_EQ(0u, GetErrors().size());
2243 ASSERT_EQ(1u, loaded_.size());
2244 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2245 const Extension* theme = registry()->enabled_extensions().begin()->get();
2246 EXPECT_EQ("name", theme->name());
2247 EXPECT_EQ("description", theme->description());
2249 // Cleanup the "Cached Theme.pak" file. Ideally, this would be installed in a
2250 // temporary directory, but it automatically installs to the extension's
2251 // directory, and we don't want to copy the whole extension for a unittest.
2252 base::FilePath theme_file = extension_path.Append(chrome::kThemePackFilename);
2253 ASSERT_TRUE(base::PathExists(theme_file));
2254 ASSERT_TRUE(base::DeleteFile(theme_file, false)); // Not recursive.
2257 // Tests that we can change the ID of an unpacked extension by adding a key
2259 TEST_F(ExtensionServiceTest, UnpackedExtensionCanChangeID) {
2260 InitializeEmptyExtensionService();
2262 base::ScopedTempDir temp;
2263 ASSERT_TRUE(temp.CreateUniqueTempDir());
2265 base::FilePath extension_path = temp.path();
2266 base::FilePath manifest_path =
2267 extension_path.Append(extensions::kManifestFilename);
2268 base::FilePath manifest_no_key =
2269 data_dir().AppendASCII("unpacked").AppendASCII("manifest_no_key.json");
2271 base::FilePath manifest_with_key =
2272 data_dir().AppendASCII("unpacked").AppendASCII("manifest_with_key.json");
2274 ASSERT_TRUE(base::PathExists(manifest_no_key));
2275 ASSERT_TRUE(base::PathExists(manifest_with_key));
2277 // Load the unpacked extension with no key.
2278 base::CopyFile(manifest_no_key, manifest_path);
2279 extensions::UnpackedInstaller::Create(service())->Load(extension_path);
2281 base::RunLoop().RunUntilIdle();
2282 EXPECT_EQ(0u, GetErrors().size());
2283 ASSERT_EQ(1u, loaded_.size());
2284 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2286 // Add the key to the manifest.
2287 base::CopyFile(manifest_with_key, manifest_path);
2290 // Reload the extensions.
2291 service()->ReloadExtensionsForTest();
2292 const Extension* extension = service()->GetExtensionById(unpacked, false);
2293 EXPECT_EQ(unpacked, extension->id());
2294 ASSERT_EQ(1u, loaded_.size());
2296 // TODO(jstritar): Right now this just makes sure we don't crash and burn, but
2297 // we should also test that preferences are preserved.
2300 #if defined(OS_POSIX)
2301 TEST_F(ExtensionServiceTest, UnpackedExtensionMayContainSymlinkedFiles) {
2302 base::FilePath source_data_dir =
2303 data_dir().AppendASCII("unpacked").AppendASCII("symlinks_allowed");
2305 // Paths to test data files.
2306 base::FilePath source_manifest = source_data_dir.AppendASCII("manifest.json");
2307 ASSERT_TRUE(base::PathExists(source_manifest));
2308 base::FilePath source_icon = source_data_dir.AppendASCII("icon.png");
2309 ASSERT_TRUE(base::PathExists(source_icon));
2311 // Set up the temporary extension directory.
2312 base::ScopedTempDir temp;
2313 ASSERT_TRUE(temp.CreateUniqueTempDir());
2314 base::FilePath extension_path = temp.path();
2315 base::FilePath manifest = extension_path.Append(
2316 extensions::kManifestFilename);
2317 base::FilePath icon_symlink = extension_path.AppendASCII("icon.png");
2318 base::CopyFile(source_manifest, manifest);
2319 base::CreateSymbolicLink(source_icon, icon_symlink);
2322 InitializeEmptyExtensionService();
2323 extensions::UnpackedInstaller::Create(service())->Load(extension_path);
2324 base::RunLoop().RunUntilIdle();
2326 EXPECT_TRUE(GetErrors().empty());
2327 ASSERT_EQ(1u, loaded_.size());
2328 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2332 TEST_F(ExtensionServiceTest, UnpackedExtensionMayNotHaveUnderscore) {
2333 InitializeEmptyExtensionService();
2334 base::FilePath extension_path = data_dir().AppendASCII("underscore_name");
2335 extensions::UnpackedInstaller::Create(service())->Load(extension_path);
2336 base::RunLoop().RunUntilIdle();
2337 EXPECT_EQ(1u, GetErrors().size());
2338 EXPECT_EQ(0u, registry()->enabled_extensions().size());
2341 TEST_F(ExtensionServiceTest, InstallLocalizedTheme) {
2342 InitializeEmptyExtensionService();
2345 base::FilePath theme_path = data_dir().AppendASCII("theme_i18n");
2347 const Extension* theme = PackAndInstallCRX(theme_path, INSTALL_NEW);
2349 EXPECT_EQ(0u, GetErrors().size());
2350 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2351 EXPECT_EQ("name", theme->name());
2352 EXPECT_EQ("description", theme->description());
2355 TEST_F(ExtensionServiceTest, InstallApps) {
2356 InitializeEmptyExtensionService();
2359 const Extension* app =
2360 PackAndInstallCRX(data_dir().AppendASCII("app1"), INSTALL_NEW);
2362 ValidatePrefKeyCount(++pref_count);
2363 ASSERT_EQ(1u, registry()->enabled_extensions().size());
2364 ValidateIntegerPref(app->id(), "state", Extension::ENABLED);
2365 ValidateIntegerPref(app->id(), "location", Manifest::INTERNAL);
2367 // Another app with non-overlapping extent. Should succeed.
2368 PackAndInstallCRX(data_dir().AppendASCII("app2"), INSTALL_NEW);
2369 ValidatePrefKeyCount(++pref_count);
2371 // A third app whose extent overlaps the first. Should fail.
2372 PackAndInstallCRX(data_dir().AppendASCII("app3"), INSTALL_FAILED);
2373 ValidatePrefKeyCount(pref_count);
2376 // Tests that file access is OFF by default.
2377 TEST_F(ExtensionServiceTest, DefaultFileAccess) {
2378 InitializeEmptyExtensionService();
2379 const Extension* extension = PackAndInstallCRX(
2380 data_dir().AppendASCII("permissions").AppendASCII("files"), INSTALL_NEW);
2381 EXPECT_EQ(0u, GetErrors().size());
2382 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2384 ExtensionPrefs::Get(profile())->AllowFileAccess(extension->id()));
2387 TEST_F(ExtensionServiceTest, UpdateApps) {
2388 InitializeEmptyExtensionService();
2389 base::FilePath extensions_path = data_dir().AppendASCII("app_update");
2391 // First install v1 of a hosted app.
2392 const Extension* extension =
2393 InstallCRX(extensions_path.AppendASCII("v1.crx"), INSTALL_NEW);
2394 ASSERT_EQ(1u, registry()->enabled_extensions().size());
2395 std::string id = extension->id();
2396 ASSERT_EQ(std::string("1"), extension->version()->GetString());
2398 // Now try updating to v2.
2400 extensions_path.AppendASCII("v2.crx"),
2402 ASSERT_EQ(std::string("2"),
2403 service()->GetExtensionById(id, false)->version()->GetString());
2406 // Verifies that the NTP page and launch ordinals are kept when updating apps.
2407 TEST_F(ExtensionServiceTest, UpdateAppsRetainOrdinals) {
2408 InitializeEmptyExtensionService();
2409 AppSorting* sorting = ExtensionPrefs::Get(profile())->app_sorting();
2410 base::FilePath extensions_path = data_dir().AppendASCII("app_update");
2412 // First install v1 of a hosted app.
2413 const Extension* extension =
2414 InstallCRX(extensions_path.AppendASCII("v1.crx"), INSTALL_NEW);
2415 ASSERT_EQ(1u, registry()->enabled_extensions().size());
2416 std::string id = extension->id();
2417 ASSERT_EQ(std::string("1"), extension->version()->GetString());
2419 // Modify the ordinals so we can distinguish them from the defaults.
2420 syncer::StringOrdinal new_page_ordinal =
2421 sorting->GetPageOrdinal(id).CreateAfter();
2422 syncer::StringOrdinal new_launch_ordinal =
2423 sorting->GetAppLaunchOrdinal(id).CreateBefore();
2425 sorting->SetPageOrdinal(id, new_page_ordinal);
2426 sorting->SetAppLaunchOrdinal(id, new_launch_ordinal);
2428 // Now try updating to v2.
2429 UpdateExtension(id, extensions_path.AppendASCII("v2.crx"), ENABLED);
2430 ASSERT_EQ(std::string("2"),
2431 service()->GetExtensionById(id, false)->version()->GetString());
2433 // Verify that the ordinals match.
2434 ASSERT_TRUE(new_page_ordinal.Equals(sorting->GetPageOrdinal(id)));
2435 ASSERT_TRUE(new_launch_ordinal.Equals(sorting->GetAppLaunchOrdinal(id)));
2438 // Ensures that the CWS has properly initialized ordinals.
2439 TEST_F(ExtensionServiceTest, EnsureCWSOrdinalsInitialized) {
2440 InitializeEmptyExtensionService();
2441 service()->component_loader()->Add(
2442 IDR_WEBSTORE_MANIFEST, base::FilePath(FILE_PATH_LITERAL("web_store")));
2445 AppSorting* sorting = ExtensionPrefs::Get(profile())->app_sorting();
2447 sorting->GetPageOrdinal(extension_misc::kWebStoreAppId).IsValid());
2449 sorting->GetAppLaunchOrdinal(extension_misc::kWebStoreAppId).IsValid());
2452 TEST_F(ExtensionServiceTest, InstallAppsWithUnlimitedStorage) {
2453 InitializeEmptyExtensionService();
2454 EXPECT_TRUE(registry()->enabled_extensions().is_empty());
2458 // Install app1 with unlimited storage.
2459 const Extension* extension =
2460 PackAndInstallCRX(data_dir().AppendASCII("app1"), INSTALL_NEW);
2461 ValidatePrefKeyCount(++pref_count);
2462 ASSERT_EQ(1u, registry()->enabled_extensions().size());
2463 const std::string id1 = extension->id();
2464 EXPECT_TRUE(extension->permissions_data()->HasAPIPermission(
2465 APIPermission::kUnlimitedStorage));
2466 EXPECT_TRUE(extension->web_extent().MatchesURL(
2467 extensions::AppLaunchInfo::GetFullLaunchURL(extension)));
2469 extensions::AppLaunchInfo::GetFullLaunchURL(extension).GetOrigin());
2470 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
2473 // Install app2 from the same origin with unlimited storage.
2474 extension = PackAndInstallCRX(data_dir().AppendASCII("app2"), INSTALL_NEW);
2475 ValidatePrefKeyCount(++pref_count);
2476 ASSERT_EQ(2u, registry()->enabled_extensions().size());
2477 const std::string id2 = extension->id();
2478 EXPECT_TRUE(extension->permissions_data()->HasAPIPermission(
2479 APIPermission::kUnlimitedStorage));
2480 EXPECT_TRUE(extension->web_extent().MatchesURL(
2481 extensions::AppLaunchInfo::GetFullLaunchURL(extension)));
2483 extensions::AppLaunchInfo::GetFullLaunchURL(extension).GetOrigin());
2484 EXPECT_EQ(origin1, origin2);
2485 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
2488 // Uninstall one of them, unlimited storage should still be granted
2490 UninstallExtension(id1, false);
2491 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2492 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
2495 // Uninstall the other, unlimited storage should be revoked.
2496 UninstallExtension(id2, false);
2497 EXPECT_EQ(0u, registry()->enabled_extensions().size());
2499 profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
2503 TEST_F(ExtensionServiceTest, InstallAppsAndCheckStorageProtection) {
2504 InitializeEmptyExtensionService();
2505 EXPECT_TRUE(registry()->enabled_extensions().is_empty());
2509 const Extension* extension =
2510 PackAndInstallCRX(data_dir().AppendASCII("app1"), INSTALL_NEW);
2511 ValidatePrefKeyCount(++pref_count);
2512 ASSERT_EQ(1u, registry()->enabled_extensions().size());
2513 EXPECT_TRUE(extension->is_app());
2514 const std::string id1 = extension->id();
2516 extensions::AppLaunchInfo::GetFullLaunchURL(extension).GetOrigin());
2517 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageProtected(
2520 // App 4 has a different origin (maps.google.com).
2521 extension = PackAndInstallCRX(data_dir().AppendASCII("app4"), INSTALL_NEW);
2522 ValidatePrefKeyCount(++pref_count);
2523 ASSERT_EQ(2u, registry()->enabled_extensions().size());
2524 const std::string id2 = extension->id();
2526 extensions::AppLaunchInfo::GetFullLaunchURL(extension).GetOrigin());
2527 ASSERT_NE(origin1, origin2);
2528 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageProtected(
2531 UninstallExtension(id1, false);
2532 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2534 UninstallExtension(id2, false);
2536 EXPECT_TRUE(registry()->enabled_extensions().is_empty());
2538 profile()->GetExtensionSpecialStoragePolicy()->IsStorageProtected(
2541 profile()->GetExtensionSpecialStoragePolicy()->IsStorageProtected(
2545 // Test that when an extension version is reinstalled, nothing happens.
2546 TEST_F(ExtensionServiceTest, Reinstall) {
2547 InitializeEmptyExtensionService();
2549 // A simple extension that should install without error.
2550 base::FilePath path = data_dir().AppendASCII("good.crx");
2551 InstallCRX(path, INSTALL_NEW);
2553 ValidatePrefKeyCount(1);
2554 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
2555 ValidateIntegerPref(good_crx, "location", Manifest::INTERNAL);
2557 // Reinstall the same version, it should overwrite the previous one.
2558 InstallCRX(path, INSTALL_UPDATED);
2560 ValidatePrefKeyCount(1);
2561 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
2562 ValidateIntegerPref(good_crx, "location", Manifest::INTERNAL);
2565 // Test that we can determine if extensions came from the
2566 // Chrome web store.
2567 TEST_F(ExtensionServiceTest, FromWebStore) {
2568 InitializeEmptyExtensionService();
2570 // A simple extension that should install without error.
2571 base::FilePath path = data_dir().AppendASCII("good.crx");
2572 // Not from web store.
2573 const Extension* extension = InstallCRX(path, INSTALL_NEW);
2574 std::string id = extension->id();
2576 ValidatePrefKeyCount(1);
2577 ASSERT_TRUE(ValidateBooleanPref(good_crx, "from_webstore", false));
2578 ASSERT_FALSE(extension->from_webstore());
2580 // Test install from web store.
2581 InstallCRXFromWebStore(path, INSTALL_UPDATED); // From web store.
2583 ValidatePrefKeyCount(1);
2584 ASSERT_TRUE(ValidateBooleanPref(good_crx, "from_webstore", true));
2586 // Reload so extension gets reinitialized with new value.
2587 service()->ReloadExtensionsForTest();
2588 extension = service()->GetExtensionById(id, false);
2589 ASSERT_TRUE(extension->from_webstore());
2591 // Upgrade to version 2.0
2592 path = data_dir().AppendASCII("good2.crx");
2593 UpdateExtension(good_crx, path, ENABLED);
2594 ValidatePrefKeyCount(1);
2595 ASSERT_TRUE(ValidateBooleanPref(good_crx, "from_webstore", true));
2598 // Test upgrading a signed extension.
2599 TEST_F(ExtensionServiceTest, UpgradeSignedGood) {
2600 InitializeEmptyExtensionService();
2602 base::FilePath path = data_dir().AppendASCII("good.crx");
2603 const Extension* extension = InstallCRX(path, INSTALL_NEW);
2604 std::string id = extension->id();
2606 ASSERT_EQ("1.0.0.0", extension->version()->GetString());
2607 ASSERT_EQ(0u, GetErrors().size());
2609 // Upgrade to version 1.0.0.1.
2610 // Also test that the extension's old and new title are correctly retrieved.
2611 path = data_dir().AppendASCII("good2.crx");
2612 InstallCRX(path, INSTALL_UPDATED, Extension::NO_FLAGS, "My extension 1");
2613 extension = service()->GetExtensionById(id, false);
2615 ASSERT_EQ("1.0.0.1", extension->version()->GetString());
2616 ASSERT_EQ("My updated extension 1", extension->name());
2617 ASSERT_EQ(0u, GetErrors().size());
2620 // Test upgrading a signed extension with a bad signature.
2621 TEST_F(ExtensionServiceTest, UpgradeSignedBad) {
2622 InitializeEmptyExtensionService();
2624 base::FilePath path = data_dir().AppendASCII("good.crx");
2625 InstallCRX(path, INSTALL_NEW);
2627 // Try upgrading with a bad signature. This should fail during the unpack,
2628 // because the key will not match the signature.
2629 path = data_dir().AppendASCII("bad_signature.crx");
2630 InstallCRX(path, INSTALL_FAILED);
2633 // Test a normal update via the UpdateExtension API
2634 TEST_F(ExtensionServiceTest, UpdateExtension) {
2635 InitializeEmptyExtensionService();
2637 base::FilePath path = data_dir().AppendASCII("good.crx");
2639 const Extension* good = InstallCRX(path, INSTALL_NEW);
2640 ASSERT_EQ("1.0.0.0", good->VersionString());
2641 ASSERT_EQ(good_crx, good->id());
2643 path = data_dir().AppendASCII("good2.crx");
2644 UpdateExtension(good_crx, path, ENABLED);
2647 service()->GetExtensionById(good_crx, false)->version()->GetString());
2650 // Extensions should not be updated during browser shutdown.
2651 TEST_F(ExtensionServiceTest, UpdateExtensionDuringShutdown) {
2652 InitializeEmptyExtensionService();
2654 // Install an extension.
2655 base::FilePath path = data_dir().AppendASCII("good.crx");
2656 const Extension* good = InstallCRX(path, INSTALL_NEW);
2657 ASSERT_EQ(good_crx, good->id());
2659 // Simulate shutdown.
2660 service()->set_browser_terminating_for_test(true);
2662 // Update should fail and extension should not be updated.
2663 path = data_dir().AppendASCII("good2.crx");
2664 bool updated = service()->UpdateExtension(good_crx, path, true, NULL);
2665 ASSERT_FALSE(updated);
2668 service()->GetExtensionById(good_crx, false)->version()->GetString());
2671 // Test updating a not-already-installed extension - this should fail
2672 TEST_F(ExtensionServiceTest, UpdateNotInstalledExtension) {
2673 InitializeEmptyExtensionService();
2675 base::FilePath path = data_dir().AppendASCII("good.crx");
2676 UpdateExtension(good_crx, path, UPDATED);
2677 base::RunLoop().RunUntilIdle();
2679 ASSERT_EQ(0u, registry()->enabled_extensions().size());
2680 ASSERT_FALSE(installed_);
2681 ASSERT_EQ(0u, loaded_.size());
2684 // Makes sure you can't downgrade an extension via UpdateExtension
2685 TEST_F(ExtensionServiceTest, UpdateWillNotDowngrade) {
2686 InitializeEmptyExtensionService();
2688 base::FilePath path = data_dir().AppendASCII("good2.crx");
2690 const Extension* good = InstallCRX(path, INSTALL_NEW);
2691 ASSERT_EQ("1.0.0.1", good->VersionString());
2692 ASSERT_EQ(good_crx, good->id());
2694 // Change path from good2.crx -> good.crx
2695 path = data_dir().AppendASCII("good.crx");
2696 UpdateExtension(good_crx, path, FAILED);
2699 service()->GetExtensionById(good_crx, false)->version()->GetString());
2702 // Make sure calling update with an identical version does nothing
2703 TEST_F(ExtensionServiceTest, UpdateToSameVersionIsNoop) {
2704 InitializeEmptyExtensionService();
2706 base::FilePath path = data_dir().AppendASCII("good.crx");
2708 const Extension* good = InstallCRX(path, INSTALL_NEW);
2709 ASSERT_EQ(good_crx, good->id());
2710 UpdateExtension(good_crx, path, FAILED_SILENTLY);
2713 // Tests that updating an extension does not clobber old state.
2714 TEST_F(ExtensionServiceTest, UpdateExtensionPreservesState) {
2715 InitializeEmptyExtensionService();
2717 base::FilePath path = data_dir().AppendASCII("good.crx");
2719 const Extension* good = InstallCRX(path, INSTALL_NEW);
2720 ASSERT_EQ("1.0.0.0", good->VersionString());
2721 ASSERT_EQ(good_crx, good->id());
2723 // Disable it and allow it to run in incognito. These settings should carry
2724 // over to the updated version.
2725 service()->DisableExtension(good->id(), Extension::DISABLE_USER_ACTION);
2726 extensions::util::SetIsIncognitoEnabled(good->id(), profile(), true);
2727 ExtensionPrefs::Get(profile())
2728 ->SetDidExtensionEscalatePermissions(good, true);
2730 path = data_dir().AppendASCII("good2.crx");
2731 UpdateExtension(good_crx, path, INSTALLED);
2732 ASSERT_EQ(1u, registry()->disabled_extensions().size());
2733 const Extension* good2 = service()->GetExtensionById(good_crx, true);
2734 ASSERT_EQ("1.0.0.1", good2->version()->GetString());
2735 EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good2->id(), profile()));
2736 EXPECT_TRUE(ExtensionPrefs::Get(profile())
2737 ->DidExtensionEscalatePermissions(good2->id()));
2740 // Tests that updating preserves extension location.
2741 TEST_F(ExtensionServiceTest, UpdateExtensionPreservesLocation) {
2742 InitializeEmptyExtensionService();
2744 base::FilePath path = data_dir().AppendASCII("good.crx");
2746 const Extension* good =
2747 InstallCRXWithLocation(path, Manifest::EXTERNAL_PREF, INSTALL_NEW);
2749 ASSERT_EQ("1.0.0.0", good->VersionString());
2750 ASSERT_EQ(good_crx, good->id());
2752 path = data_dir().AppendASCII("good2.crx");
2753 UpdateExtension(good_crx, path, ENABLED);
2754 const Extension* good2 = service()->GetExtensionById(good_crx, false);
2755 ASSERT_EQ("1.0.0.1", good2->version()->GetString());
2756 EXPECT_EQ(good2->location(), Manifest::EXTERNAL_PREF);
2759 // Makes sure that LOAD extension types can downgrade.
2760 TEST_F(ExtensionServiceTest, LoadExtensionsCanDowngrade) {
2761 InitializeEmptyExtensionService();
2763 base::ScopedTempDir temp;
2764 ASSERT_TRUE(temp.CreateUniqueTempDir());
2766 // We'll write the extension manifest dynamically to a temporary path
2767 // to make it easier to change the version number.
2768 base::FilePath extension_path = temp.path();
2769 base::FilePath manifest_path =
2770 extension_path.Append(extensions::kManifestFilename);
2771 ASSERT_FALSE(base::PathExists(manifest_path));
2773 // Start with version 2.0.
2774 base::DictionaryValue manifest;
2775 manifest.SetString("version", "2.0");
2776 manifest.SetString("name", "LOAD Downgrade Test");
2777 manifest.SetInteger("manifest_version", 2);
2779 JSONFileValueSerializer serializer(manifest_path);
2780 ASSERT_TRUE(serializer.Serialize(manifest));
2782 extensions::UnpackedInstaller::Create(service())->Load(extension_path);
2783 base::RunLoop().RunUntilIdle();
2785 EXPECT_EQ(0u, GetErrors().size());
2786 ASSERT_EQ(1u, loaded_.size());
2787 EXPECT_EQ(Manifest::UNPACKED, loaded_[0]->location());
2788 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2789 EXPECT_EQ("2.0", loaded_[0]->VersionString());
2791 // Now set the version number to 1.0, reload the extensions and verify that
2792 // the downgrade was accepted.
2793 manifest.SetString("version", "1.0");
2794 ASSERT_TRUE(serializer.Serialize(manifest));
2796 extensions::UnpackedInstaller::Create(service())->Load(extension_path);
2797 base::RunLoop().RunUntilIdle();
2799 EXPECT_EQ(0u, GetErrors().size());
2800 ASSERT_EQ(1u, loaded_.size());
2801 EXPECT_EQ(Manifest::UNPACKED, loaded_[0]->location());
2802 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2803 EXPECT_EQ("1.0", loaded_[0]->VersionString());
2806 #if !defined(OS_POSIX) || defined(OS_MACOSX)
2807 // LOAD extensions with plugins require approval.
2808 // Only run this on platforms that support NPAPI plugins.
2809 TEST_F(ExtensionServiceTest, LoadExtensionsWithPlugins) {
2810 base::FilePath extension_with_plugin_path = good1_path();
2811 base::FilePath extension_no_plugin_path = good2_path();
2813 InitPluginService();
2814 InitializeEmptyExtensionService();
2815 InitializeProcessManager();
2816 service()->set_show_extensions_prompts(true);
2818 // Start by canceling any install prompts.
2819 ExtensionInstallPrompt::g_auto_confirm_for_tests =
2820 ExtensionInstallPrompt::CANCEL;
2822 // The extension that has a plugin should not install.
2823 extensions::UnpackedInstaller::Create(service())
2824 ->Load(extension_with_plugin_path);
2825 base::RunLoop().RunUntilIdle();
2826 EXPECT_EQ(0u, GetErrors().size());
2827 EXPECT_EQ(0u, loaded_.size());
2828 EXPECT_EQ(0u, registry()->enabled_extensions().size());
2829 EXPECT_EQ(0u, registry()->disabled_extensions().size());
2831 // But the extension with no plugin should since there's no prompt.
2832 ExtensionErrorReporter::GetInstance()->ClearErrors();
2833 extensions::UnpackedInstaller::Create(service())
2834 ->Load(extension_no_plugin_path);
2835 base::RunLoop().RunUntilIdle();
2836 EXPECT_EQ(0u, GetErrors().size());
2837 EXPECT_EQ(1u, loaded_.size());
2838 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2839 EXPECT_EQ(0u, registry()->disabled_extensions().size());
2840 EXPECT_TRUE(registry()->enabled_extensions().Contains(good2));
2842 // The plugin extension should install if we accept the dialog.
2843 ExtensionInstallPrompt::g_auto_confirm_for_tests =
2844 ExtensionInstallPrompt::ACCEPT;
2846 ExtensionErrorReporter::GetInstance()->ClearErrors();
2847 extensions::UnpackedInstaller::Create(service())
2848 ->Load(extension_with_plugin_path);
2849 base::RunLoop().RunUntilIdle();
2850 EXPECT_EQ(0u, GetErrors().size());
2851 EXPECT_EQ(2u, loaded_.size());
2852 EXPECT_EQ(2u, registry()->enabled_extensions().size());
2853 EXPECT_EQ(0u, registry()->disabled_extensions().size());
2854 EXPECT_TRUE(registry()->enabled_extensions().Contains(good1));
2855 EXPECT_TRUE(registry()->enabled_extensions().Contains(good2));
2857 // Make sure the granted permissions have been setup.
2858 scoped_refptr<PermissionSet> permissions(
2859 ExtensionPrefs::Get(profile())->GetGrantedPermissions(good1));
2860 EXPECT_FALSE(permissions->IsEmpty());
2861 EXPECT_TRUE(permissions->HasEffectiveFullAccess());
2862 EXPECT_FALSE(permissions->apis().empty());
2863 EXPECT_TRUE(permissions->HasAPIPermission(APIPermission::kPlugin));
2865 // We should be able to reload the extension without getting another prompt.
2867 ExtensionInstallPrompt::g_auto_confirm_for_tests =
2868 ExtensionInstallPrompt::CANCEL;
2870 service()->ReloadExtension(good1);
2871 base::RunLoop().RunUntilIdle();
2872 EXPECT_EQ(1u, loaded_.size());
2873 EXPECT_EQ(2u, registry()->enabled_extensions().size());
2874 EXPECT_EQ(0u, registry()->disabled_extensions().size());
2876 #endif // !defined(OS_POSIX) || defined(OS_MACOSX)
2880 bool IsExtension(const Extension* extension) {
2881 return extension->GetType() == Manifest::TYPE_EXTENSION;
2884 #if defined(ENABLE_BLACKLIST_TESTS)
2885 std::set<std::string> StringSet(const std::string& s) {
2886 std::set<std::string> set;
2890 std::set<std::string> StringSet(const std::string& s1, const std::string& s2) {
2891 std::set<std::string> set = StringSet(s1);
2895 #endif // defined(ENABLE_BLACKLIST_TESTS)
2899 // Test adding a pending extension.
2900 TEST_F(ExtensionServiceTest, AddPendingExtensionFromSync) {
2901 InitializeEmptyExtensionService();
2903 const std::string kFakeId(all_zero);
2904 const GURL kFakeUpdateURL("http:://fake.update/url");
2905 const bool kFakeInstallSilently(true);
2906 const bool kFakeRemoteInstall(false);
2907 const bool kFakeInstalledByCustodian(false);
2910 service()->pending_extension_manager()->AddFromSync(
2914 kFakeInstallSilently,
2916 kFakeInstalledByCustodian));
2918 const extensions::PendingExtensionInfo* pending_extension_info;
2919 ASSERT_TRUE((pending_extension_info =
2920 service()->pending_extension_manager()->GetById(kFakeId)));
2921 EXPECT_EQ(kFakeUpdateURL, pending_extension_info->update_url());
2922 EXPECT_EQ(&IsExtension, pending_extension_info->should_allow_install_);
2923 EXPECT_EQ(kFakeInstallSilently, pending_extension_info->install_silently());
2925 // EXPECT_TRUE(kFakeRemoteInstall == pending_extension_info->remote_install())
2927 // EXPECT_EQ(kFakeRemoteInstall, pending_extension_info->remote_install())
2928 // as gcc 4.7 issues the following warning on EXPECT_EQ(false, x), which is
2929 // turned into an error with -Werror=conversion-null:
2930 // converting 'false' to pointer type for argument 1 of
2931 // 'char testing::internal::IsNullLiteralHelper(testing::internal::Secret*)'
2932 // https://code.google.com/p/googletest/issues/detail?id=458
2933 EXPECT_TRUE(kFakeRemoteInstall == pending_extension_info->remote_install());
2937 const char kGoodId[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
2938 const char kGoodUpdateURL[] = "http://good.update/url";
2939 const bool kGoodIsFromSync = true;
2940 const bool kGoodInstallSilently = true;
2941 const bool kGoodRemoteInstall = false;
2942 const bool kGoodInstalledByCustodian = false;
2945 // Test updating a pending extension.
2946 TEST_F(ExtensionServiceTest, UpdatePendingExtension) {
2947 InitializeEmptyExtensionService();
2949 service()->pending_extension_manager()->AddFromSync(
2951 GURL(kGoodUpdateURL),
2953 kGoodInstallSilently,
2955 kGoodInstalledByCustodian));
2956 EXPECT_TRUE(service()->pending_extension_manager()->IsIdPending(kGoodId));
2958 base::FilePath path = data_dir().AppendASCII("good.crx");
2959 UpdateExtension(kGoodId, path, ENABLED);
2961 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(kGoodId));
2963 const Extension* extension = service()->GetExtensionById(kGoodId, true);
2964 ASSERT_TRUE(extension);
2969 bool IsTheme(const Extension* extension) {
2970 return extension->is_theme();
2975 // Test updating a pending theme.
2976 // Disabled due to ASAN failure. http://crbug.com/108320
2977 TEST_F(ExtensionServiceTest, DISABLED_UpdatePendingTheme) {
2978 InitializeEmptyExtensionService();
2979 EXPECT_TRUE(service()->pending_extension_manager()->AddFromSync(
2980 theme_crx, GURL(), &IsTheme, false, false, false));
2981 EXPECT_TRUE(service()->pending_extension_manager()->IsIdPending(theme_crx));
2983 base::FilePath path = data_dir().AppendASCII("theme.crx");
2984 UpdateExtension(theme_crx, path, ENABLED);
2986 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(theme_crx));
2988 const Extension* extension = service()->GetExtensionById(theme_crx, true);
2989 ASSERT_TRUE(extension);
2992 ExtensionPrefs::Get(profile())->IsExtensionDisabled(extension->id()));
2993 EXPECT_TRUE(service()->IsExtensionEnabled(theme_crx));
2996 #if defined(OS_CHROMEOS)
2997 // Always fails on ChromeOS: http://crbug.com/79737
2998 #define MAYBE_UpdatePendingExternalCrx DISABLED_UpdatePendingExternalCrx
3000 #define MAYBE_UpdatePendingExternalCrx UpdatePendingExternalCrx
3002 // Test updating a pending CRX as if the source is an external extension
3003 // with an update URL. In this case we don't know if the CRX is a theme
3005 TEST_F(ExtensionServiceTest, MAYBE_UpdatePendingExternalCrx) {
3006 InitializeEmptyExtensionService();
3007 EXPECT_TRUE(service()->pending_extension_manager()->AddFromExternalUpdateUrl(
3011 Manifest::EXTERNAL_PREF_DOWNLOAD,
3012 Extension::NO_FLAGS,
3015 EXPECT_TRUE(service()->pending_extension_manager()->IsIdPending(theme_crx));
3017 base::FilePath path = data_dir().AppendASCII("theme.crx");
3018 UpdateExtension(theme_crx, path, ENABLED);
3020 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(theme_crx));
3022 const Extension* extension = service()->GetExtensionById(theme_crx, true);
3023 ASSERT_TRUE(extension);
3026 ExtensionPrefs::Get(profile())->IsExtensionDisabled(extension->id()));
3027 EXPECT_TRUE(service()->IsExtensionEnabled(extension->id()));
3029 extensions::util::IsIncognitoEnabled(extension->id(), profile()));
3032 // Test updating a pending CRX as if the source is an external extension
3033 // with an update URL. The external update should overwrite a sync update,
3034 // but a sync update should not overwrite a non-sync update.
3035 TEST_F(ExtensionServiceTest, UpdatePendingExternalCrxWinsOverSync) {
3036 InitializeEmptyExtensionService();
3038 // Add a crx to be installed from the update mechanism.
3040 service()->pending_extension_manager()->AddFromSync(
3042 GURL(kGoodUpdateURL),
3044 kGoodInstallSilently,
3046 kGoodInstalledByCustodian));
3048 // Check that there is a pending crx, with is_from_sync set to true.
3049 const extensions::PendingExtensionInfo* pending_extension_info;
3050 ASSERT_TRUE((pending_extension_info =
3051 service()->pending_extension_manager()->GetById(kGoodId)));
3052 EXPECT_TRUE(pending_extension_info->is_from_sync());
3054 // Add a crx to be updated, with the same ID, from a non-sync source.
3055 EXPECT_TRUE(service()->pending_extension_manager()->AddFromExternalUpdateUrl(
3058 GURL(kGoodUpdateURL),
3059 Manifest::EXTERNAL_PREF_DOWNLOAD,
3060 Extension::NO_FLAGS,
3063 // Check that there is a pending crx, with is_from_sync set to false.
3064 ASSERT_TRUE((pending_extension_info =
3065 service()->pending_extension_manager()->GetById(kGoodId)));
3066 EXPECT_FALSE(pending_extension_info->is_from_sync());
3067 EXPECT_EQ(Manifest::EXTERNAL_PREF_DOWNLOAD,
3068 pending_extension_info->install_source());
3070 // Add a crx to be installed from the update mechanism.
3072 service()->pending_extension_manager()->AddFromSync(
3074 GURL(kGoodUpdateURL),
3076 kGoodInstallSilently,
3078 kGoodInstalledByCustodian));
3080 // Check that the external, non-sync update was not overridden.
3081 ASSERT_TRUE((pending_extension_info =
3082 service()->pending_extension_manager()->GetById(kGoodId)));
3083 EXPECT_FALSE(pending_extension_info->is_from_sync());
3084 EXPECT_EQ(Manifest::EXTERNAL_PREF_DOWNLOAD,
3085 pending_extension_info->install_source());
3088 // Updating a theme should fail if the updater is explicitly told that
3089 // the CRX is not a theme.
3090 TEST_F(ExtensionServiceTest, UpdatePendingCrxThemeMismatch) {
3091 InitializeEmptyExtensionService();
3092 EXPECT_TRUE(service()->pending_extension_manager()->AddFromSync(
3093 theme_crx, GURL(), &IsExtension, true, false, false));
3095 EXPECT_TRUE(service()->pending_extension_manager()->IsIdPending(theme_crx));
3097 base::FilePath path = data_dir().AppendASCII("theme.crx");
3098 UpdateExtension(theme_crx, path, FAILED_SILENTLY);
3100 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(theme_crx));
3102 const Extension* extension = service()->GetExtensionById(theme_crx, true);
3103 ASSERT_FALSE(extension);
3106 // TODO(akalin): Test updating a pending extension non-silently once
3107 // we can mock out ExtensionInstallUI and inject our version into
3108 // UpdateExtension().
3110 // Test updating a pending extension which fails the should-install test.
3111 TEST_F(ExtensionServiceTest, UpdatePendingExtensionFailedShouldInstallTest) {
3112 InitializeEmptyExtensionService();
3113 // Add pending extension with a flipped is_theme.
3115 service()->pending_extension_manager()->AddFromSync(
3117 GURL(kGoodUpdateURL),
3119 kGoodInstallSilently,
3121 kGoodInstalledByCustodian));
3122 EXPECT_TRUE(service()->pending_extension_manager()->IsIdPending(kGoodId));
3124 base::FilePath path = data_dir().AppendASCII("good.crx");
3125 UpdateExtension(kGoodId, path, UPDATED);
3127 // TODO(akalin): Figure out how to check that the extensions
3128 // directory is cleaned up properly in OnExtensionInstalled().
3130 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(kGoodId));
3133 // TODO(akalin): Figure out how to test that installs of pending
3134 // unsyncable extensions are blocked.
3136 // Test updating a pending extension for one that is not pending.
3137 TEST_F(ExtensionServiceTest, UpdatePendingExtensionNotPending) {
3138 InitializeEmptyExtensionService();
3140 base::FilePath path = data_dir().AppendASCII("good.crx");
3141 UpdateExtension(kGoodId, path, UPDATED);
3143 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(kGoodId));
3146 // Test updating a pending extension for one that is already
3148 TEST_F(ExtensionServiceTest, UpdatePendingExtensionAlreadyInstalled) {
3149 InitializeEmptyExtensionService();
3151 base::FilePath path = data_dir().AppendASCII("good.crx");
3152 const Extension* good = InstallCRX(path, INSTALL_NEW);
3153 ASSERT_EQ(1u, registry()->enabled_extensions().size());
3155 EXPECT_FALSE(good->is_theme());
3157 // Use AddExtensionImpl() as AddFrom*() would balk.
3158 service()->pending_extension_manager()->AddExtensionImpl(
3161 extensions::ManifestURL::GetUpdateURL(good),
3165 kGoodInstallSilently,
3167 Extension::NO_FLAGS,
3169 kGoodRemoteInstall);
3170 UpdateExtension(good->id(), path, ENABLED);
3172 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(kGoodId));
3175 #if defined(ENABLE_BLACKLIST_TESTS)
3176 // Tests blacklisting then unblacklisting extensions after the service has been
3178 TEST_F(ExtensionServiceTest, SetUnsetBlacklistInPrefs) {
3179 extensions::TestBlacklist test_blacklist;
3180 // A profile with 3 extensions installed: good0, good1, and good2.
3181 InitializeGoodInstalledExtensionService();
3182 test_blacklist.Attach(service()->blacklist_);
3185 const extensions::ExtensionSet& enabled_extensions =
3186 registry()->enabled_extensions();
3187 const extensions::ExtensionSet& blacklisted_extensions =
3188 registry()->blacklisted_extensions();
3190 EXPECT_TRUE(enabled_extensions.Contains(good0) &&
3191 !blacklisted_extensions.Contains(good0));
3192 EXPECT_TRUE(enabled_extensions.Contains(good1) &&
3193 !blacklisted_extensions.Contains(good1));
3194 EXPECT_TRUE(enabled_extensions.Contains(good2) &&
3195 !blacklisted_extensions.Contains(good2));
3197 EXPECT_FALSE(IsPrefExist(good0, "blacklist"));
3198 EXPECT_FALSE(IsPrefExist(good1, "blacklist"));
3199 EXPECT_FALSE(IsPrefExist(good2, "blacklist"));
3200 EXPECT_FALSE(IsPrefExist("invalid_id", "blacklist"));
3202 // Blacklist good0 and good1 (and an invalid extension ID).
3203 test_blacklist.SetBlacklistState(
3204 good0, extensions::BLACKLISTED_MALWARE, true);
3205 test_blacklist.SetBlacklistState(
3206 good1, extensions::BLACKLISTED_MALWARE, true);
3207 test_blacklist.SetBlacklistState(
3208 "invalid_id", extensions::BLACKLISTED_MALWARE, true);
3209 base::RunLoop().RunUntilIdle();
3211 EXPECT_TRUE(!enabled_extensions.Contains(good0) &&
3212 blacklisted_extensions.Contains(good0));
3213 EXPECT_TRUE(!enabled_extensions.Contains(good1) &&
3214 blacklisted_extensions.Contains(good1));
3215 EXPECT_TRUE(enabled_extensions.Contains(good2) &&
3216 !blacklisted_extensions.Contains(good2));
3218 EXPECT_TRUE(ValidateBooleanPref(good0, "blacklist", true));
3219 EXPECT_TRUE(ValidateBooleanPref(good1, "blacklist", true));
3220 EXPECT_FALSE(IsPrefExist(good2, "blacklist"));
3221 EXPECT_FALSE(IsPrefExist("invalid_id", "blacklist"));
3223 // Un-blacklist good1 and blacklist good2.
3224 test_blacklist.Clear(false);
3225 test_blacklist.SetBlacklistState(
3226 good0, extensions::BLACKLISTED_MALWARE, true);
3227 test_blacklist.SetBlacklistState(
3228 good2, extensions::BLACKLISTED_MALWARE, true);
3229 test_blacklist.SetBlacklistState(
3230 "invalid_id", extensions::BLACKLISTED_MALWARE, true);
3231 base::RunLoop().RunUntilIdle();
3233 EXPECT_TRUE(!enabled_extensions.Contains(good0) &&
3234 blacklisted_extensions.Contains(good0));
3235 EXPECT_TRUE(enabled_extensions.Contains(good1) &&
3236 !blacklisted_extensions.Contains(good1));
3237 EXPECT_TRUE(!enabled_extensions.Contains(good2) &&
3238 blacklisted_extensions.Contains(good2));
3240 EXPECT_TRUE(ValidateBooleanPref(good0, "blacklist", true));
3241 EXPECT_FALSE(IsPrefExist(good1, "blacklist"));
3242 EXPECT_TRUE(ValidateBooleanPref(good2, "blacklist", true));
3243 EXPECT_FALSE(IsPrefExist("invalid_id", "blacklist"));
3245 #endif // defined(ENABLE_BLACKLIST_TESTS)
3247 #if defined(ENABLE_BLACKLIST_TESTS)
3248 // Tests trying to install a blacklisted extension.
3249 TEST_F(ExtensionServiceTest, BlacklistedExtensionWillNotInstall) {
3250 scoped_refptr<FakeSafeBrowsingDatabaseManager> blacklist_db(
3251 new FakeSafeBrowsingDatabaseManager(true));
3252 Blacklist::ScopedDatabaseManagerForTest scoped_blacklist_db(blacklist_db);
3254 InitializeEmptyExtensionService();
3257 // After blacklisting good_crx, we cannot install it.
3258 blacklist_db->SetUnsafe(good_crx).NotifyUpdate();
3259 base::RunLoop().RunUntilIdle();
3261 base::FilePath path = data_dir().AppendASCII("good.crx");
3262 // HACK: specify WAS_INSTALLED_BY_DEFAULT so that test machinery doesn't
3263 // decide to install this silently. Somebody should fix these tests, all
3264 // 6,000 lines of them. Hah!
3265 InstallCRX(path, INSTALL_FAILED, Extension::WAS_INSTALLED_BY_DEFAULT);
3266 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3268 #endif // defined(ENABLE_BLACKLIST_TESTS)
3270 #if defined(ENABLE_BLACKLIST_TESTS)
3271 // Unload blacklisted extension on policy change.
3272 TEST_F(ExtensionServiceTest, UnloadBlacklistedExtensionPolicy) {
3273 extensions::TestBlacklist test_blacklist;
3275 // A profile with no extensions installed.
3276 InitializeEmptyExtensionService();
3277 test_blacklist.Attach(service()->blacklist_);
3279 base::FilePath path = data_dir().AppendASCII("good.crx");
3281 const Extension* good = InstallCRX(path, INSTALL_NEW);
3282 EXPECT_EQ(good_crx, good->id());
3283 UpdateExtension(good_crx, path, FAILED_SILENTLY);
3284 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3286 base::ListValue whitelist;
3287 PrefService* prefs = ExtensionPrefs::Get(profile())->pref_service();
3288 whitelist.Append(new base::StringValue(good_crx));
3289 prefs->Set(extensions::pref_names::kInstallAllowList, whitelist);
3291 test_blacklist.SetBlacklistState(
3292 good_crx, extensions::BLACKLISTED_MALWARE, true);
3293 base::RunLoop().RunUntilIdle();
3295 // The good_crx is blacklisted and the whitelist doesn't negate it.
3296 ASSERT_TRUE(ValidateBooleanPref(good_crx, "blacklist", true));
3297 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3299 #endif // defined(ENABLE_BLACKLIST_TESTS)
3301 #if defined(ENABLE_BLACKLIST_TESTS)
3302 // Tests that a blacklisted extension is eventually unloaded on startup, if it
3304 TEST_F(ExtensionServiceTest, WillNotLoadBlacklistedExtensionsFromDirectory) {
3305 extensions::TestBlacklist test_blacklist;
3307 // A profile with 3 extensions installed: good0, good1, and good2.
3308 InitializeGoodInstalledExtensionService();
3309 test_blacklist.Attach(service()->blacklist_);
3311 // Blacklist good1 before the service initializes.
3312 test_blacklist.SetBlacklistState(
3313 good1, extensions::BLACKLISTED_MALWARE, false);
3317 ASSERT_EQ(3u, loaded_.size()); // hasn't had time to blacklist yet
3319 base::RunLoop().RunUntilIdle();
3321 ASSERT_EQ(1u, registry()->blacklisted_extensions().size());
3322 ASSERT_EQ(2u, registry()->enabled_extensions().size());
3324 ASSERT_TRUE(registry()->enabled_extensions().Contains(good0));
3325 ASSERT_TRUE(registry()->blacklisted_extensions().Contains(good1));
3326 ASSERT_TRUE(registry()->enabled_extensions().Contains(good2));
3328 #endif // defined(ENABLE_BLACKLIST_TESTS)
3330 #if defined(ENABLE_BLACKLIST_TESTS)
3331 // Tests extensions blacklisted in prefs on startup; one still blacklisted by
3332 // safe browsing, the other not. The not-blacklisted one should recover.
3333 TEST_F(ExtensionServiceTest, BlacklistedInPrefsFromStartup) {
3334 extensions::TestBlacklist test_blacklist;
3336 InitializeGoodInstalledExtensionService();
3337 test_blacklist.Attach(service()->blacklist_);
3338 ExtensionPrefs::Get(profile())->SetExtensionBlacklisted(good0, true);
3339 ExtensionPrefs::Get(profile())->SetExtensionBlacklisted(good1, true);
3341 test_blacklist.SetBlacklistState(
3342 good1, extensions::BLACKLISTED_MALWARE, false);
3344 // Extension service hasn't loaded yet, but IsExtensionEnabled reads out of
3345 // prefs. Ensure it takes into account the blacklist state (crbug.com/373842).
3346 EXPECT_FALSE(service()->IsExtensionEnabled(good0));
3347 EXPECT_FALSE(service()->IsExtensionEnabled(good1));
3348 EXPECT_TRUE(service()->IsExtensionEnabled(good2));
3352 EXPECT_EQ(2u, registry()->blacklisted_extensions().size());
3353 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3355 EXPECT_TRUE(registry()->blacklisted_extensions().Contains(good0));
3356 EXPECT_TRUE(registry()->blacklisted_extensions().Contains(good1));
3357 EXPECT_TRUE(registry()->enabled_extensions().Contains(good2));
3359 // Give time for the blacklist to update.
3360 base::RunLoop().RunUntilIdle();
3362 EXPECT_EQ(1u, registry()->blacklisted_extensions().size());
3363 EXPECT_EQ(2u, registry()->enabled_extensions().size());
3365 EXPECT_TRUE(registry()->enabled_extensions().Contains(good0));
3366 EXPECT_TRUE(registry()->blacklisted_extensions().Contains(good1));
3367 EXPECT_TRUE(registry()->enabled_extensions().Contains(good2));
3369 #endif // defined(ENABLE_BLACKLIST_TESTS)
3371 #if defined(ENABLE_BLACKLIST_TESTS)
3372 // Extension is added to blacklist with BLACKLISTED_POTENTIALLY_UNWANTED state
3373 // after it is installed. It is then successfully re-enabled by the user.
3374 TEST_F(ExtensionServiceTest, GreylistedExtensionDisabled) {
3375 extensions::TestBlacklist test_blacklist;
3376 // A profile with 3 extensions installed: good0, good1, and good2.
3377 InitializeGoodInstalledExtensionService();
3378 test_blacklist.Attach(service()->blacklist_);
3381 const extensions::ExtensionSet& enabled_extensions =
3382 registry()->enabled_extensions();
3383 const extensions::ExtensionSet& disabled_extensions =
3384 registry()->disabled_extensions();
3386 EXPECT_TRUE(enabled_extensions.Contains(good0));
3387 EXPECT_TRUE(enabled_extensions.Contains(good1));
3388 EXPECT_TRUE(enabled_extensions.Contains(good2));
3390 // Blacklist good0 and good1 (and an invalid extension ID).
3391 test_blacklist.SetBlacklistState(
3392 good0, extensions::BLACKLISTED_CWS_POLICY_VIOLATION, true);
3393 test_blacklist.SetBlacklistState(
3394 good1, extensions::BLACKLISTED_POTENTIALLY_UNWANTED, true);
3395 test_blacklist.SetBlacklistState(
3396 "invalid_id", extensions::BLACKLISTED_MALWARE, true);
3397 base::RunLoop().RunUntilIdle();
3399 EXPECT_FALSE(enabled_extensions.Contains(good0));
3400 EXPECT_TRUE(disabled_extensions.Contains(good0));
3401 EXPECT_FALSE(enabled_extensions.Contains(good1));
3402 EXPECT_TRUE(disabled_extensions.Contains(good1));
3403 EXPECT_TRUE(enabled_extensions.Contains(good2));
3404 EXPECT_FALSE(disabled_extensions.Contains(good2));
3406 ValidateIntegerPref(
3407 good0, "blacklist_state", extensions::BLACKLISTED_CWS_POLICY_VIOLATION);
3408 ValidateIntegerPref(
3409 good1, "blacklist_state", extensions::BLACKLISTED_POTENTIALLY_UNWANTED);
3411 // Now user enables good0.
3412 service()->EnableExtension(good0);
3414 EXPECT_TRUE(enabled_extensions.Contains(good0));
3415 EXPECT_FALSE(disabled_extensions.Contains(good0));
3416 EXPECT_FALSE(enabled_extensions.Contains(good1));
3417 EXPECT_TRUE(disabled_extensions.Contains(good1));
3419 // Remove extensions from blacklist.
3420 test_blacklist.SetBlacklistState(
3421 good0, extensions::NOT_BLACKLISTED, true);
3422 test_blacklist.SetBlacklistState(
3423 good1, extensions::NOT_BLACKLISTED, true);
3424 base::RunLoop().RunUntilIdle();
3426 // All extensions are enabled.
3427 EXPECT_TRUE(enabled_extensions.Contains(good0));
3428 EXPECT_FALSE(disabled_extensions.Contains(good0));
3429 EXPECT_TRUE(enabled_extensions.Contains(good1));
3430 EXPECT_FALSE(disabled_extensions.Contains(good1));
3431 EXPECT_TRUE(enabled_extensions.Contains(good2));
3432 EXPECT_FALSE(disabled_extensions.Contains(good2));
3434 #endif // defined(ENABLE_BLACKLIST_TESTS)
3436 #if defined(ENABLE_BLACKLIST_TESTS)
3437 // When extension is removed from greylist, do not re-enable it if it is
3438 // disabled by user.
3439 TEST_F(ExtensionServiceTest, GreylistDontEnableManuallyDisabled) {
3440 extensions::TestBlacklist test_blacklist;
3441 // A profile with 3 extensions installed: good0, good1, and good2.
3442 InitializeGoodInstalledExtensionService();
3443 test_blacklist.Attach(service()->blacklist_);
3446 const extensions::ExtensionSet& enabled_extensions =
3447 registry()->enabled_extensions();
3448 const extensions::ExtensionSet& disabled_extensions =
3449 registry()->disabled_extensions();
3451 // Manually disable.
3452 service()->DisableExtension(good0,
3453 extensions::Extension::DISABLE_USER_ACTION);
3455 test_blacklist.SetBlacklistState(
3456 good0, extensions::BLACKLISTED_CWS_POLICY_VIOLATION, true);
3457 test_blacklist.SetBlacklistState(
3458 good1, extensions::BLACKLISTED_POTENTIALLY_UNWANTED, true);
3459 test_blacklist.SetBlacklistState(
3460 good2, extensions::BLACKLISTED_SECURITY_VULNERABILITY, true);
3461 base::RunLoop().RunUntilIdle();
3463 // All extensions disabled.
3464 EXPECT_FALSE(enabled_extensions.Contains(good0));
3465 EXPECT_TRUE(disabled_extensions.Contains(good0));
3466 EXPECT_FALSE(enabled_extensions.Contains(good1));
3467 EXPECT_TRUE(disabled_extensions.Contains(good1));
3468 EXPECT_FALSE(enabled_extensions.Contains(good2));
3469 EXPECT_TRUE(disabled_extensions.Contains(good2));
3471 // Greylisted extension can be enabled.
3472 service()->EnableExtension(good1);
3473 EXPECT_TRUE(enabled_extensions.Contains(good1));
3474 EXPECT_FALSE(disabled_extensions.Contains(good1));
3476 // good1 is now manually disabled.
3477 service()->DisableExtension(good1,
3478 extensions::Extension::DISABLE_USER_ACTION);
3479 EXPECT_FALSE(enabled_extensions.Contains(good1));
3480 EXPECT_TRUE(disabled_extensions.Contains(good1));
3482 // Remove extensions from blacklist.
3483 test_blacklist.SetBlacklistState(
3484 good0, extensions::NOT_BLACKLISTED, true);
3485 test_blacklist.SetBlacklistState(
3486 good1, extensions::NOT_BLACKLISTED, true);
3487 test_blacklist.SetBlacklistState(
3488 good2, extensions::NOT_BLACKLISTED, true);
3489 base::RunLoop().RunUntilIdle();
3491 // good0 and good1 remain disabled.
3492 EXPECT_FALSE(enabled_extensions.Contains(good0));
3493 EXPECT_TRUE(disabled_extensions.Contains(good0));
3494 EXPECT_FALSE(enabled_extensions.Contains(good1));
3495 EXPECT_TRUE(disabled_extensions.Contains(good1));
3496 EXPECT_TRUE(enabled_extensions.Contains(good2));
3497 EXPECT_FALSE(disabled_extensions.Contains(good2));
3499 #endif // defined(ENABLE_BLACKLIST_TESTS)
3501 #if defined(ENABLE_BLACKLIST_TESTS)
3502 // Blacklisted extension with unknown state are not enabled/disabled.
3503 TEST_F(ExtensionServiceTest, GreylistUnknownDontChange) {
3504 extensions::TestBlacklist test_blacklist;
3505 // A profile with 3 extensions installed: good0, good1, and good2.
3506 InitializeGoodInstalledExtensionService();
3507 test_blacklist.Attach(service()->blacklist_);
3510 const extensions::ExtensionSet& enabled_extensions =
3511 registry()->enabled_extensions();
3512 const extensions::ExtensionSet& disabled_extensions =
3513 registry()->disabled_extensions();
3515 test_blacklist.SetBlacklistState(
3516 good0, extensions::BLACKLISTED_CWS_POLICY_VIOLATION, true);
3517 test_blacklist.SetBlacklistState(
3518 good1, extensions::BLACKLISTED_POTENTIALLY_UNWANTED, true);
3519 base::RunLoop().RunUntilIdle();
3521 EXPECT_FALSE(enabled_extensions.Contains(good0));
3522 EXPECT_TRUE(disabled_extensions.Contains(good0));
3523 EXPECT_FALSE(enabled_extensions.Contains(good1));
3524 EXPECT_TRUE(disabled_extensions.Contains(good1));
3525 EXPECT_TRUE(enabled_extensions.Contains(good2));
3526 EXPECT_FALSE(disabled_extensions.Contains(good2));
3528 test_blacklist.SetBlacklistState(
3529 good0, extensions::NOT_BLACKLISTED, true);
3530 test_blacklist.SetBlacklistState(
3531 good1, extensions::BLACKLISTED_UNKNOWN, true);
3532 test_blacklist.SetBlacklistState(
3533 good2, extensions::BLACKLISTED_UNKNOWN, true);
3534 base::RunLoop().RunUntilIdle();
3536 // good0 re-enabled, other remain as they were.
3537 EXPECT_TRUE(enabled_extensions.Contains(good0));
3538 EXPECT_FALSE(disabled_extensions.Contains(good0));
3539 EXPECT_FALSE(enabled_extensions.Contains(good1));
3540 EXPECT_TRUE(disabled_extensions.Contains(good1));
3541 EXPECT_TRUE(enabled_extensions.Contains(good2));
3542 EXPECT_FALSE(disabled_extensions.Contains(good2));
3545 // Tests that blacklisted extensions cannot be reloaded, both those loaded
3546 // before and after extension service startup.
3547 TEST_F(ExtensionServiceTest, ReloadBlacklistedExtension) {
3548 extensions::TestBlacklist test_blacklist;
3550 InitializeGoodInstalledExtensionService();
3551 test_blacklist.Attach(service()->blacklist_);
3553 test_blacklist.SetBlacklistState(
3554 good1, extensions::BLACKLISTED_MALWARE, false);
3556 test_blacklist.SetBlacklistState(
3557 good2, extensions::BLACKLISTED_MALWARE, false);
3558 base::RunLoop().RunUntilIdle();
3560 EXPECT_EQ(StringSet(good0), registry()->enabled_extensions().GetIDs());
3561 EXPECT_EQ(StringSet(good1, good2),
3562 registry()->blacklisted_extensions().GetIDs());
3564 service()->ReloadExtension(good1);
3565 service()->ReloadExtension(good2);
3566 base::RunLoop().RunUntilIdle();
3568 EXPECT_EQ(StringSet(good0), registry()->enabled_extensions().GetIDs());
3569 EXPECT_EQ(StringSet(good1, good2),
3570 registry()->blacklisted_extensions().GetIDs());
3573 #endif // defined(ENABLE_BLACKLIST_TESTS)
3575 // Will not install extension blacklisted by policy.
3576 TEST_F(ExtensionServiceTest, BlacklistedByPolicyWillNotInstall) {
3577 InitializeEmptyExtensionService();
3579 // Blacklist everything.
3581 ListPrefUpdate update(profile()->GetPrefs(),
3582 extensions::pref_names::kInstallDenyList);
3583 base::ListValue* blacklist = update.Get();
3584 blacklist->Append(new base::StringValue("*"));
3587 // Blacklist prevents us from installing good_crx.
3588 base::FilePath path = data_dir().AppendASCII("good.crx");
3589 InstallCRX(path, INSTALL_FAILED);
3590 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3592 // Now whitelist this particular extension.
3594 ListPrefUpdate update(profile()->GetPrefs(),
3595 extensions::pref_names::kInstallAllowList);
3596 base::ListValue* whitelist = update.Get();
3597 whitelist->Append(new base::StringValue(good_crx));
3600 // Ensure we can now install good_crx.
3601 InstallCRX(path, INSTALL_NEW);
3602 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3605 // Extension blacklisted by policy get unloaded after installing.
3606 TEST_F(ExtensionServiceTest, BlacklistedByPolicyRemovedIfRunning) {
3607 InitializeEmptyExtensionService();
3609 // Install good_crx.
3610 base::FilePath path = data_dir().AppendASCII("good.crx");
3611 InstallCRX(path, INSTALL_NEW);
3612 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3614 { // Scope for pref update notification.
3615 PrefService* prefs = profile()->GetPrefs();
3616 ListPrefUpdate update(prefs, extensions::pref_names::kInstallDenyList);
3617 base::ListValue* blacklist = update.Get();
3618 ASSERT_TRUE(blacklist != NULL);
3620 // Blacklist this extension.
3621 blacklist->Append(new base::StringValue(good_crx));
3624 // Extension should not be running now.
3625 base::RunLoop().RunUntilIdle();
3626 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3629 // Tests that component extensions are not blacklisted by policy.
3630 TEST_F(ExtensionServiceTest, ComponentExtensionWhitelisted) {
3631 InitializeEmptyExtensionService();
3633 // Blacklist everything.
3635 ListPrefUpdate update(profile()->GetPrefs(),
3636 extensions::pref_names::kInstallDenyList);
3637 base::ListValue* blacklist = update.Get();
3638 blacklist->Append(new base::StringValue("*"));
3641 // Install a component extension.
3642 base::FilePath path = data_dir()
3643 .AppendASCII("good")
3644 .AppendASCII("Extensions")
3646 .AppendASCII("1.0.0.0");
3647 std::string manifest;
3648 ASSERT_TRUE(base::ReadFileToString(
3649 path.Append(extensions::kManifestFilename), &manifest));
3650 service()->component_loader()->Add(manifest, path);
3653 // Extension should be installed despite blacklist.
3654 ASSERT_EQ(1u, registry()->enabled_extensions().size());
3655 EXPECT_TRUE(service()->GetExtensionById(good0, false));
3657 // Poke external providers and make sure the extension is still present.
3658 service()->CheckForExternalUpdates();
3659 ASSERT_EQ(1u, registry()->enabled_extensions().size());
3660 EXPECT_TRUE(service()->GetExtensionById(good0, false));
3662 // Extension should not be uninstalled on blacklist changes.
3664 ListPrefUpdate update(profile()->GetPrefs(),
3665 extensions::pref_names::kInstallDenyList);
3666 base::ListValue* blacklist = update.Get();
3667 blacklist->Append(new base::StringValue(good0));
3669 base::RunLoop().RunUntilIdle();
3670 ASSERT_EQ(1u, registry()->enabled_extensions().size());
3671 EXPECT_TRUE(service()->GetExtensionById(good0, false));
3674 // Tests that policy-installed extensions are not blacklisted by policy.
3675 TEST_F(ExtensionServiceTest, PolicyInstalledExtensionsWhitelisted) {
3676 InitializeEmptyExtensionService();
3679 // Blacklist everything.
3680 ListPrefUpdate blacklist_update(profile()->GetPrefs(),
3681 extensions::pref_names::kInstallDenyList);
3682 base::ListValue* blacklist = blacklist_update.Get();
3683 blacklist->AppendString("*");
3685 // Mark good.crx for force-installation.
3686 DictionaryPrefUpdate forcelist_update(
3687 profile()->GetPrefs(), extensions::pref_names::kInstallForceList);
3688 extensions::ExternalPolicyLoader::AddExtension(
3689 forcelist_update.Get(), good_crx, "http://example.com/update_url");
3692 // Have policy force-install an extension.
3693 MockExtensionProvider* provider =
3694 new MockExtensionProvider(service(), Manifest::EXTERNAL_POLICY_DOWNLOAD);
3695 AddMockExternalProvider(provider);
3696 provider->UpdateOrAddExtension(
3697 good_crx, "1.0.0.0", data_dir().AppendASCII("good.crx"));
3699 // Reloading extensions should find our externally registered extension
3701 content::WindowedNotificationObserver observer(
3702 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
3703 content::NotificationService::AllSources());
3704 service()->CheckForExternalUpdates();
3707 // Extension should be installed despite blacklist.
3708 ASSERT_EQ(1u, registry()->enabled_extensions().size());
3709 EXPECT_TRUE(service()->GetExtensionById(good_crx, false));
3711 // Blacklist update should not uninstall the extension.
3713 ListPrefUpdate update(profile()->GetPrefs(),
3714 extensions::pref_names::kInstallDenyList);
3715 base::ListValue* blacklist = update.Get();
3716 blacklist->Append(new base::StringValue(good0));
3718 base::RunLoop().RunUntilIdle();
3719 ASSERT_EQ(1u, registry()->enabled_extensions().size());
3720 EXPECT_TRUE(service()->GetExtensionById(good_crx, false));
3723 // Tests that extensions cannot be installed if the policy provider prohibits
3724 // it. This functionality is implemented in CrxInstaller::ConfirmInstall().
3725 TEST_F(ExtensionServiceTest, ManagementPolicyProhibitsInstall) {
3726 InitializeEmptyExtensionService();
3728 GetManagementPolicy()->UnregisterAllProviders();
3729 extensions::TestManagementPolicyProvider provider_(
3730 extensions::TestManagementPolicyProvider::PROHIBIT_LOAD);
3731 GetManagementPolicy()->RegisterProvider(&provider_);
3733 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_FAILED);
3734 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3737 // Tests that extensions cannot be loaded from prefs if the policy provider
3738 // prohibits it. This functionality is implemented in InstalledLoader::Load().
3739 TEST_F(ExtensionServiceTest, ManagementPolicyProhibitsLoadFromPrefs) {
3740 InitializeEmptyExtensionService();
3742 // Create a fake extension to be loaded as though it were read from prefs.
3743 base::FilePath path =
3744 data_dir().AppendASCII("management").AppendASCII("simple_extension");
3745 base::DictionaryValue manifest;
3746 manifest.SetString(keys::kName, "simple_extension");
3747 manifest.SetString(keys::kVersion, "1");
3748 // UNPACKED is for extensions loaded from a directory. We use it here, even
3749 // though we're testing loading from prefs, so that we don't need to provide
3750 // an extension key.
3751 extensions::ExtensionInfo extension_info(
3752 &manifest, std::string(), path, Manifest::UNPACKED);
3754 // Ensure we can load it with no management policy in place.
3755 GetManagementPolicy()->UnregisterAllProviders();
3756 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3757 extensions::InstalledLoader(service()).Load(extension_info, false);
3758 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3760 const Extension* extension =
3761 (registry()->enabled_extensions().begin())->get();
3763 service()->UninstallExtension(extension->id(),
3764 extensions::UNINSTALL_REASON_FOR_TESTING,
3765 base::Bind(&base::DoNothing),
3767 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3769 // Ensure we cannot load it if management policy prohibits installation.
3770 extensions::TestManagementPolicyProvider provider_(
3771 extensions::TestManagementPolicyProvider::PROHIBIT_LOAD);
3772 GetManagementPolicy()->RegisterProvider(&provider_);
3774 extensions::InstalledLoader(service()).Load(extension_info, false);
3775 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3778 // Tests disabling an extension when prohibited by the ManagementPolicy.
3779 TEST_F(ExtensionServiceTest, ManagementPolicyProhibitsDisable) {
3780 InitializeEmptyExtensionService();
3782 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
3783 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3784 EXPECT_EQ(0u, registry()->disabled_extensions().size());
3786 GetManagementPolicy()->UnregisterAllProviders();
3787 extensions::TestManagementPolicyProvider provider(
3788 extensions::TestManagementPolicyProvider::PROHIBIT_MODIFY_STATUS);
3789 GetManagementPolicy()->RegisterProvider(&provider);
3791 // Attempt to disable it.
3792 service()->DisableExtension(good_crx, Extension::DISABLE_USER_ACTION);
3794 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3795 EXPECT_TRUE(service()->GetExtensionById(good_crx, false));
3796 EXPECT_EQ(0u, registry()->disabled_extensions().size());
3799 // Tests uninstalling an extension when prohibited by the ManagementPolicy.
3800 TEST_F(ExtensionServiceTest, ManagementPolicyProhibitsUninstall) {
3801 InitializeEmptyExtensionService();
3803 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
3804 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3805 EXPECT_EQ(0u, registry()->disabled_extensions().size());
3807 GetManagementPolicy()->UnregisterAllProviders();
3808 extensions::TestManagementPolicyProvider provider(
3809 extensions::TestManagementPolicyProvider::PROHIBIT_MODIFY_STATUS);
3810 GetManagementPolicy()->RegisterProvider(&provider);
3812 // Attempt to uninstall it.
3814 service()->UninstallExtension(good_crx,
3815 extensions::UNINSTALL_REASON_FOR_TESTING,
3816 base::Bind(&base::DoNothing),
3819 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3820 EXPECT_TRUE(service()->GetExtensionById(good_crx, false));
3823 // Tests that previously installed extensions that are now prohibited from
3824 // being installed are removed.
3825 TEST_F(ExtensionServiceTest, ManagementPolicyUnloadsAllProhibited) {
3826 InitializeEmptyExtensionService();
3828 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
3829 InstallCRX(data_dir().AppendASCII("page_action.crx"), INSTALL_NEW);
3830 EXPECT_EQ(2u, registry()->enabled_extensions().size());
3831 EXPECT_EQ(0u, registry()->disabled_extensions().size());
3833 GetManagementPolicy()->UnregisterAllProviders();
3834 extensions::TestManagementPolicyProvider provider(
3835 extensions::TestManagementPolicyProvider::PROHIBIT_LOAD);
3836 GetManagementPolicy()->RegisterProvider(&provider);
3838 // Run the policy check.
3839 service()->CheckManagementPolicy();
3840 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3841 EXPECT_EQ(0u, registry()->disabled_extensions().size());
3844 // Tests that previously disabled extensions that are now required to be
3845 // enabled are re-enabled on reinstall.
3846 TEST_F(ExtensionServiceTest, ManagementPolicyRequiresEnable) {
3847 InitializeEmptyExtensionService();
3849 // Install, then disable, an extension.
3850 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
3851 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3852 service()->DisableExtension(good_crx, Extension::DISABLE_USER_ACTION);
3853 EXPECT_EQ(1u, registry()->disabled_extensions().size());
3855 // Register an ExtensionMnagementPolicy that requires the extension to remain
3857 GetManagementPolicy()->UnregisterAllProviders();
3858 extensions::TestManagementPolicyProvider provider(
3859 extensions::TestManagementPolicyProvider::MUST_REMAIN_ENABLED);
3860 GetManagementPolicy()->RegisterProvider(&provider);
3862 // Reinstall the extension.
3863 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_UPDATED);
3864 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3865 EXPECT_EQ(0u, registry()->disabled_extensions().size());
3868 // Flaky on windows; http://crbug.com/309833
3870 #define MAYBE_ExternalExtensionAutoAcknowledgement DISABLED_ExternalExtensionAutoAcknowledgement
3872 #define MAYBE_ExternalExtensionAutoAcknowledgement ExternalExtensionAutoAcknowledgement
3874 TEST_F(ExtensionServiceTest, MAYBE_ExternalExtensionAutoAcknowledgement) {
3875 InitializeEmptyExtensionService();
3876 service()->set_extensions_enabled(true);
3879 // Register and install an external extension.
3880 MockExtensionProvider* provider =
3881 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF);
3882 AddMockExternalProvider(provider);
3883 provider->UpdateOrAddExtension(
3884 good_crx, "1.0.0.0", data_dir().AppendASCII("good.crx"));
3887 // Have policy force-install an extension.
3888 MockExtensionProvider* provider = new MockExtensionProvider(
3889 service(), Manifest::EXTERNAL_POLICY_DOWNLOAD);
3890 AddMockExternalProvider(provider);
3891 provider->UpdateOrAddExtension(
3892 page_action, "1.0.0.0", data_dir().AppendASCII("page_action.crx"));
3895 // Providers are set up. Let them run.
3897 content::WindowedNotificationObserver observer(
3898 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
3899 base::Bind(&WaitForCountNotificationsCallback, &count));
3900 service()->CheckForExternalUpdates();
3904 ASSERT_EQ(2u, registry()->enabled_extensions().size());
3905 EXPECT_TRUE(service()->GetExtensionById(good_crx, false));
3906 EXPECT_TRUE(service()->GetExtensionById(page_action, false));
3907 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
3908 ASSERT_TRUE(!prefs->IsExternalExtensionAcknowledged(good_crx));
3909 ASSERT_TRUE(prefs->IsExternalExtensionAcknowledged(page_action));
3912 #if !defined(OS_CHROMEOS)
3913 // This tests if default apps are installed correctly.
3914 TEST_F(ExtensionServiceTest, DefaultAppsInstall) {
3915 InitializeEmptyExtensionService();
3916 service()->set_extensions_enabled(true);
3919 std::string json_data =
3921 " \"ldnnhddmnhbkjipkidpdiheffobcpfmf\" : {"
3922 " \"external_crx\": \"good.crx\","
3923 " \"external_version\": \"1.0.0.0\","
3924 " \"is_bookmark_app\": false"
3927 default_apps::Provider* provider = new default_apps::Provider(
3930 new extensions::ExternalTestingLoader(json_data, data_dir()),
3932 Manifest::INVALID_LOCATION,
3933 Extension::FROM_WEBSTORE | Extension::WAS_INSTALLED_BY_DEFAULT);
3935 AddMockExternalProvider(provider);
3938 ASSERT_EQ(0u, registry()->enabled_extensions().size());
3939 content::WindowedNotificationObserver observer(
3940 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
3941 content::NotificationService::AllSources());
3942 service()->CheckForExternalUpdates();
3945 ASSERT_EQ(1u, registry()->enabled_extensions().size());
3946 EXPECT_TRUE(service()->GetExtensionById(good_crx, false));
3947 const Extension* extension = service()->GetExtensionById(good_crx, false);
3948 EXPECT_TRUE(extension->from_webstore());
3949 EXPECT_TRUE(extension->was_installed_by_default());
3953 // Tests disabling extensions
3954 TEST_F(ExtensionServiceTest, DisableExtension) {
3955 InitializeEmptyExtensionService();
3957 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
3958 EXPECT_TRUE(service()->GetExtensionById(good_crx, true));
3959 EXPECT_TRUE(service()->GetExtensionById(good_crx, false));
3961 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3962 EXPECT_EQ(0u, registry()->disabled_extensions().size());
3963 EXPECT_EQ(0u, registry()->terminated_extensions().size());
3964 EXPECT_EQ(0u, registry()->blacklisted_extensions().size());
3967 service()->DisableExtension(good_crx, Extension::DISABLE_USER_ACTION);
3969 EXPECT_TRUE(service()->GetExtensionById(good_crx, true));
3970 EXPECT_FALSE(service()->GetExtensionById(good_crx, false));
3971 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3972 EXPECT_EQ(1u, registry()->disabled_extensions().size());
3973 EXPECT_EQ(0u, registry()->terminated_extensions().size());
3974 EXPECT_EQ(0u, registry()->blacklisted_extensions().size());
3977 TEST_F(ExtensionServiceTest, TerminateExtension) {
3978 InitializeEmptyExtensionService();
3980 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
3981 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3982 EXPECT_EQ(0u, registry()->disabled_extensions().size());
3983 EXPECT_EQ(0u, registry()->terminated_extensions().size());
3984 EXPECT_EQ(0u, registry()->blacklisted_extensions().size());
3986 TerminateExtension(good_crx);
3988 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3989 EXPECT_EQ(0u, registry()->disabled_extensions().size());
3990 EXPECT_EQ(1u, registry()->terminated_extensions().size());
3991 EXPECT_EQ(0u, registry()->blacklisted_extensions().size());
3994 TEST_F(ExtensionServiceTest, DisableTerminatedExtension) {
3995 InitializeEmptyExtensionService();
3997 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
3998 TerminateExtension(good_crx);
3999 EXPECT_TRUE(registry()->GetExtensionById(
4000 good_crx, extensions::ExtensionRegistry::TERMINATED));
4003 service()->DisableExtension(good_crx, Extension::DISABLE_USER_ACTION);
4005 EXPECT_FALSE(registry()->GetExtensionById(
4006 good_crx, extensions::ExtensionRegistry::TERMINATED));
4007 EXPECT_TRUE(service()->GetExtensionById(good_crx, true));
4009 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4010 EXPECT_EQ(1u, registry()->disabled_extensions().size());
4011 EXPECT_EQ(0u, registry()->terminated_extensions().size());
4012 EXPECT_EQ(0u, registry()->blacklisted_extensions().size());
4015 // Tests disabling all extensions (simulating --disable-extensions flag).
4016 TEST_F(ExtensionServiceTest, DisableAllExtensions) {
4017 InitializeEmptyExtensionService();
4019 base::FilePath path = data_dir().AppendASCII("good.crx");
4020 InstallCRX(path, INSTALL_NEW);
4022 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4023 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4025 // Disable extensions.
4026 service()->set_extensions_enabled(false);
4027 service()->ReloadExtensionsForTest();
4029 // There shouldn't be extensions in either list.
4030 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4031 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4033 // This shouldn't do anything when all extensions are disabled.
4034 service()->EnableExtension(good_crx);
4035 service()->ReloadExtensionsForTest();
4037 // There still shouldn't be extensions in either list.
4038 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4039 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4041 // And then re-enable the extensions.
4042 service()->set_extensions_enabled(true);
4043 service()->ReloadExtensionsForTest();
4045 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4046 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4049 // Tests reloading extensions.
4050 TEST_F(ExtensionServiceTest, ReloadExtensions) {
4051 InitializeEmptyExtensionService();
4053 // Simple extension that should install without error.
4054 base::FilePath path = data_dir().AppendASCII("good.crx");
4055 InstallCRX(path, INSTALL_NEW,
4056 Extension::FROM_WEBSTORE | Extension::WAS_INSTALLED_BY_DEFAULT);
4057 const char* extension_id = good_crx;
4058 service()->DisableExtension(extension_id, Extension::DISABLE_USER_ACTION);
4060 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4061 EXPECT_EQ(1u, registry()->disabled_extensions().size());
4063 service()->ReloadExtensionsForTest();
4065 // The creation flags should not change when reloading the extension.
4066 const Extension* extension = service()->GetExtensionById(good_crx, true);
4067 EXPECT_TRUE(extension->from_webstore());
4068 EXPECT_TRUE(extension->was_installed_by_default());
4069 EXPECT_FALSE(extension->from_bookmark());
4071 // Extension counts shouldn't change.
4072 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4073 EXPECT_EQ(1u, registry()->disabled_extensions().size());
4075 service()->EnableExtension(extension_id);
4077 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4078 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4080 // Need to clear |loaded_| manually before reloading as the
4081 // EnableExtension() call above inserted into it and
4082 // UnloadAllExtensions() doesn't send out notifications.
4084 service()->ReloadExtensionsForTest();
4086 // Extension counts shouldn't change.
4087 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4088 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4091 // Tests reloading an extension.
4092 TEST_F(ExtensionServiceTest, ReloadExtension) {
4093 InitializeEmptyExtensionService();
4094 InitializeProcessManager();
4096 // Simple extension that should install without error.
4097 const char* extension_id = "behllobkkfkfnphdnhnkndlbkcpglgmj";
4098 base::FilePath ext = data_dir()
4099 .AppendASCII("good")
4100 .AppendASCII("Extensions")
4101 .AppendASCII(extension_id)
4102 .AppendASCII("1.0.0.0");
4103 extensions::UnpackedInstaller::Create(service())->Load(ext);
4104 base::RunLoop().RunUntilIdle();
4106 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4107 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4109 service()->ReloadExtension(extension_id);
4111 // Extension should be disabled now, waiting to be reloaded.
4112 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4113 EXPECT_EQ(1u, registry()->disabled_extensions().size());
4114 EXPECT_EQ(Extension::DISABLE_RELOAD,
4115 ExtensionPrefs::Get(profile())->GetDisableReasons(extension_id));
4117 // Reloading again should not crash.
4118 service()->ReloadExtension(extension_id);
4121 base::RunLoop().RunUntilIdle();
4123 // Extension should be enabled again.
4124 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4125 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4128 TEST_F(ExtensionServiceTest, UninstallExtension) {
4129 InitializeEmptyExtensionService();
4130 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
4131 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4132 UninstallExtension(good_crx, false);
4133 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4134 EXPECT_EQ(UnloadedExtensionInfo::REASON_UNINSTALL, unloaded_reason_);
4137 TEST_F(ExtensionServiceTest, UninstallTerminatedExtension) {
4138 InitializeEmptyExtensionService();
4139 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
4140 TerminateExtension(good_crx);
4141 UninstallExtension(good_crx, false);
4142 EXPECT_EQ(UnloadedExtensionInfo::REASON_TERMINATE, unloaded_reason_);
4145 // Tests the uninstaller helper.
4146 TEST_F(ExtensionServiceTest, UninstallExtensionHelper) {
4147 InitializeEmptyExtensionService();
4148 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
4149 UninstallExtension(good_crx, true);
4150 EXPECT_EQ(UnloadedExtensionInfo::REASON_UNINSTALL, unloaded_reason_);
4153 TEST_F(ExtensionServiceTest, UninstallExtensionHelperTerminated) {
4154 InitializeEmptyExtensionService();
4155 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
4156 TerminateExtension(good_crx);
4157 UninstallExtension(good_crx, true);
4158 EXPECT_EQ(UnloadedExtensionInfo::REASON_TERMINATE, unloaded_reason_);
4161 // An extension disabled because of unsupported requirements should re-enabled
4162 // if updated to a version with supported requirements as long as there are no
4163 // other disable reasons.
4164 TEST_F(ExtensionServiceTest, UpgradingRequirementsEnabled) {
4165 InitializeEmptyExtensionService();
4168 base::FilePath path = data_dir().AppendASCII("requirements");
4169 base::FilePath pem_path =
4170 data_dir().AppendASCII("requirements").AppendASCII("v1_good.pem");
4171 const Extension* extension_v1 = PackAndInstallCRX(path.AppendASCII("v1_good"),
4174 std::string id = extension_v1->id();
4175 EXPECT_TRUE(service()->IsExtensionEnabled(id));
4177 base::FilePath v2_bad_requirements_crx = GetTemporaryFile();
4179 PackCRX(path.AppendASCII("v2_bad_requirements"),
4181 v2_bad_requirements_crx);
4182 UpdateExtension(id, v2_bad_requirements_crx, INSTALLED);
4183 EXPECT_FALSE(service()->IsExtensionEnabled(id));
4185 base::FilePath v3_good_crx = GetTemporaryFile();
4187 PackCRX(path.AppendASCII("v3_good"), pem_path, v3_good_crx);
4188 UpdateExtension(id, v3_good_crx, ENABLED);
4189 EXPECT_TRUE(service()->IsExtensionEnabled(id));
4192 // Extensions disabled through user action should stay disabled.
4193 TEST_F(ExtensionServiceTest, UpgradingRequirementsDisabled) {
4194 InitializeEmptyExtensionService();
4197 base::FilePath path = data_dir().AppendASCII("requirements");
4198 base::FilePath pem_path =
4199 data_dir().AppendASCII("requirements").AppendASCII("v1_good.pem");
4200 const Extension* extension_v1 = PackAndInstallCRX(path.AppendASCII("v1_good"),
4203 std::string id = extension_v1->id();
4204 service()->DisableExtension(id, Extension::DISABLE_USER_ACTION);
4205 EXPECT_FALSE(service()->IsExtensionEnabled(id));
4207 base::FilePath v2_bad_requirements_crx = GetTemporaryFile();
4209 PackCRX(path.AppendASCII("v2_bad_requirements"),
4211 v2_bad_requirements_crx);
4212 UpdateExtension(id, v2_bad_requirements_crx, INSTALLED);
4213 EXPECT_FALSE(service()->IsExtensionEnabled(id));
4215 base::FilePath v3_good_crx = GetTemporaryFile();
4217 PackCRX(path.AppendASCII("v3_good"), pem_path, v3_good_crx);
4218 UpdateExtension(id, v3_good_crx, INSTALLED);
4219 EXPECT_FALSE(service()->IsExtensionEnabled(id));
4222 // The extension should not re-enabled because it was disabled from a
4223 // permission increase.
4224 TEST_F(ExtensionServiceTest, UpgradingRequirementsPermissions) {
4225 InitializeEmptyExtensionService();
4228 base::FilePath path = data_dir().AppendASCII("requirements");
4229 base::FilePath pem_path =
4230 data_dir().AppendASCII("requirements").AppendASCII("v1_good.pem");
4231 const Extension* extension_v1 = PackAndInstallCRX(path.AppendASCII("v1_good"),
4234 std::string id = extension_v1->id();
4235 EXPECT_TRUE(service()->IsExtensionEnabled(id));
4237 base::FilePath v2_bad_requirements_and_permissions_crx = GetTemporaryFile();
4239 PackCRX(path.AppendASCII("v2_bad_requirements_and_permissions"),
4241 v2_bad_requirements_and_permissions_crx);
4242 UpdateExtension(id, v2_bad_requirements_and_permissions_crx, INSTALLED);
4243 EXPECT_FALSE(service()->IsExtensionEnabled(id));
4245 base::FilePath v3_bad_permissions_crx = GetTemporaryFile();
4247 PackCRX(path.AppendASCII("v3_bad_permissions"),
4249 v3_bad_permissions_crx);
4250 UpdateExtension(id, v3_bad_permissions_crx, INSTALLED);
4251 EXPECT_FALSE(service()->IsExtensionEnabled(id));
4254 // Unpacked extensions are not allowed to be installed if they have unsupported
4256 TEST_F(ExtensionServiceTest, UnpackedRequirements) {
4257 InitializeEmptyExtensionService();
4260 base::FilePath path =
4261 data_dir().AppendASCII("requirements").AppendASCII("v2_bad_requirements");
4262 extensions::UnpackedInstaller::Create(service())->Load(path);
4263 base::RunLoop().RunUntilIdle();
4264 EXPECT_EQ(1u, GetErrors().size());
4265 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4268 class ExtensionCookieCallback {
4270 ExtensionCookieCallback()
4272 weak_factory_(base::MessageLoop::current()) {}
4274 void SetCookieCallback(bool result) {
4275 base::MessageLoop::current()->PostTask(FROM_HERE,
4276 base::Bind(&base::MessageLoop::Quit, weak_factory_.GetWeakPtr()));
4280 void GetAllCookiesCallback(const net::CookieList& list) {
4281 base::MessageLoop::current()->PostTask(FROM_HERE,
4282 base::Bind(&base::MessageLoop::Quit, weak_factory_.GetWeakPtr()));
4285 net::CookieList list_;
4287 base::WeakPtrFactory<base::MessageLoop> weak_factory_;
4290 // Verifies extension state is removed upon uninstall.
4291 TEST_F(ExtensionServiceTest, ClearExtensionData) {
4292 InitializeEmptyExtensionService();
4293 ExtensionCookieCallback callback;
4295 // Load a test extension.
4296 base::FilePath path = data_dir();
4297 path = path.AppendASCII("good.crx");
4298 const Extension* extension = InstallCRX(path, INSTALL_NEW);
4299 ASSERT_TRUE(extension);
4300 GURL ext_url(extension->url());
4301 std::string origin_id = webkit_database::GetIdentifierFromOrigin(ext_url);
4303 // Set a cookie for the extension.
4304 net::CookieMonster* cookie_monster = profile()
4305 ->GetRequestContextForExtensions()
4306 ->GetURLRequestContext()
4308 ->GetCookieMonster();
4309 ASSERT_TRUE(cookie_monster);
4310 net::CookieOptions options;
4311 cookie_monster->SetCookieWithOptionsAsync(
4312 ext_url, "dummy=value", options,
4313 base::Bind(&ExtensionCookieCallback::SetCookieCallback,
4314 base::Unretained(&callback)));
4315 base::RunLoop().RunUntilIdle();
4316 EXPECT_TRUE(callback.result_);
4318 cookie_monster->GetAllCookiesForURLAsync(
4320 base::Bind(&ExtensionCookieCallback::GetAllCookiesCallback,
4321 base::Unretained(&callback)));
4322 base::RunLoop().RunUntilIdle();
4323 EXPECT_EQ(1U, callback.list_.size());
4326 webkit_database::DatabaseTracker* db_tracker =
4327 BrowserContext::GetDefaultStoragePartition(profile())
4328 ->GetDatabaseTracker();
4329 base::string16 db_name = base::UTF8ToUTF16("db");
4330 base::string16 description = base::UTF8ToUTF16("db_description");
4332 db_tracker->DatabaseOpened(origin_id, db_name, description, 1, &size);
4333 db_tracker->DatabaseClosed(origin_id, db_name);
4334 std::vector<webkit_database::OriginInfo> origins;
4335 db_tracker->GetAllOriginsInfo(&origins);
4336 EXPECT_EQ(1U, origins.size());
4337 EXPECT_EQ(origin_id, origins[0].GetOriginIdentifier());
4339 // Create local storage. We only simulate this by creating the backing files.
4340 // Note: This test depends on details of how the dom_storage library
4341 // stores data in the host file system.
4342 base::FilePath lso_dir_path =
4343 profile()->GetPath().AppendASCII("Local Storage");
4344 base::FilePath lso_file_path = lso_dir_path.AppendASCII(origin_id)
4345 .AddExtension(FILE_PATH_LITERAL(".localstorage"));
4346 EXPECT_TRUE(base::CreateDirectory(lso_dir_path));
4347 EXPECT_EQ(0, base::WriteFile(lso_file_path, NULL, 0));
4348 EXPECT_TRUE(base::PathExists(lso_file_path));
4350 // Create indexed db. Similarly, it is enough to only simulate this by
4351 // creating the directory on the disk.
4352 IndexedDBContext* idb_context = BrowserContext::GetDefaultStoragePartition(
4353 profile())->GetIndexedDBContext();
4354 idb_context->SetTaskRunnerForTesting(
4355 base::MessageLoop::current()->message_loop_proxy().get());
4356 base::FilePath idb_path = idb_context->GetFilePathForTesting(origin_id);
4357 EXPECT_TRUE(base::CreateDirectory(idb_path));
4358 EXPECT_TRUE(base::DirectoryExists(idb_path));
4360 // Uninstall the extension.
4361 base::RunLoop run_loop;
4363 service()->UninstallExtension(good_crx,
4364 extensions::UNINSTALL_REASON_FOR_TESTING,
4365 run_loop.QuitClosure(),
4367 // The data deletion happens on the IO thread.
4370 // Check that the cookie is gone.
4371 cookie_monster->GetAllCookiesForURLAsync(
4373 base::Bind(&ExtensionCookieCallback::GetAllCookiesCallback,
4374 base::Unretained(&callback)));
4375 base::RunLoop().RunUntilIdle();
4376 EXPECT_EQ(0U, callback.list_.size());
4378 // The database should have vanished as well.
4380 db_tracker->GetAllOriginsInfo(&origins);
4381 EXPECT_EQ(0U, origins.size());
4383 // Check that the LSO file has been removed.
4384 EXPECT_FALSE(base::PathExists(lso_file_path));
4386 // Check if the indexed db has disappeared too.
4387 EXPECT_FALSE(base::DirectoryExists(idb_path));
4390 // Verifies app state is removed upon uninstall.
4391 TEST_F(ExtensionServiceTest, ClearAppData) {
4392 InitializeEmptyExtensionService();
4393 ExtensionCookieCallback callback;
4397 // Install app1 with unlimited storage.
4398 const Extension* extension =
4399 PackAndInstallCRX(data_dir().AppendASCII("app1"), INSTALL_NEW);
4400 ValidatePrefKeyCount(++pref_count);
4401 ASSERT_EQ(1u, registry()->enabled_extensions().size());
4402 const std::string id1 = extension->id();
4403 EXPECT_TRUE(extension->permissions_data()->HasAPIPermission(
4404 APIPermission::kUnlimitedStorage));
4406 extensions::AppLaunchInfo::GetFullLaunchURL(extension).GetOrigin());
4407 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
4409 std::string origin_id = webkit_database::GetIdentifierFromOrigin(origin1);
4411 // Install app2 from the same origin with unlimited storage.
4412 extension = PackAndInstallCRX(data_dir().AppendASCII("app2"), INSTALL_NEW);
4413 ValidatePrefKeyCount(++pref_count);
4414 ASSERT_EQ(2u, registry()->enabled_extensions().size());
4415 const std::string id2 = extension->id();
4416 EXPECT_TRUE(extension->permissions_data()->HasAPIPermission(
4417 APIPermission::kUnlimitedStorage));
4418 EXPECT_TRUE(extension->web_extent().MatchesURL(
4419 extensions::AppLaunchInfo::GetFullLaunchURL(extension)));
4421 extensions::AppLaunchInfo::GetFullLaunchURL(extension).GetOrigin());
4422 EXPECT_EQ(origin1, origin2);
4423 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
4426 // Set a cookie for the extension.
4427 net::CookieMonster* cookie_monster = profile()
4428 ->GetRequestContext()
4429 ->GetURLRequestContext()
4431 ->GetCookieMonster();
4432 ASSERT_TRUE(cookie_monster);
4433 net::CookieOptions options;
4434 cookie_monster->SetCookieWithOptionsAsync(
4435 origin1, "dummy=value", options,
4436 base::Bind(&ExtensionCookieCallback::SetCookieCallback,
4437 base::Unretained(&callback)));
4438 base::RunLoop().RunUntilIdle();
4439 EXPECT_TRUE(callback.result_);
4441 cookie_monster->GetAllCookiesForURLAsync(
4443 base::Bind(&ExtensionCookieCallback::GetAllCookiesCallback,
4444 base::Unretained(&callback)));
4445 base::RunLoop().RunUntilIdle();
4446 EXPECT_EQ(1U, callback.list_.size());
4449 webkit_database::DatabaseTracker* db_tracker =
4450 BrowserContext::GetDefaultStoragePartition(profile())
4451 ->GetDatabaseTracker();
4452 base::string16 db_name = base::UTF8ToUTF16("db");
4453 base::string16 description = base::UTF8ToUTF16("db_description");
4455 db_tracker->DatabaseOpened(origin_id, db_name, description, 1, &size);
4456 db_tracker->DatabaseClosed(origin_id, db_name);
4457 std::vector<webkit_database::OriginInfo> origins;
4458 db_tracker->GetAllOriginsInfo(&origins);
4459 EXPECT_EQ(1U, origins.size());
4460 EXPECT_EQ(origin_id, origins[0].GetOriginIdentifier());
4462 // Create local storage. We only simulate this by creating the backing files.
4463 // Note: This test depends on details of how the dom_storage library
4464 // stores data in the host file system.
4465 base::FilePath lso_dir_path =
4466 profile()->GetPath().AppendASCII("Local Storage");
4467 base::FilePath lso_file_path = lso_dir_path.AppendASCII(origin_id)
4468 .AddExtension(FILE_PATH_LITERAL(".localstorage"));
4469 EXPECT_TRUE(base::CreateDirectory(lso_dir_path));
4470 EXPECT_EQ(0, base::WriteFile(lso_file_path, NULL, 0));
4471 EXPECT_TRUE(base::PathExists(lso_file_path));
4473 // Create indexed db. Similarly, it is enough to only simulate this by
4474 // creating the directory on the disk.
4475 IndexedDBContext* idb_context = BrowserContext::GetDefaultStoragePartition(
4476 profile())->GetIndexedDBContext();
4477 idb_context->SetTaskRunnerForTesting(
4478 base::MessageLoop::current()->message_loop_proxy().get());
4479 base::FilePath idb_path = idb_context->GetFilePathForTesting(origin_id);
4480 EXPECT_TRUE(base::CreateDirectory(idb_path));
4481 EXPECT_TRUE(base::DirectoryExists(idb_path));
4483 // Uninstall one of them, unlimited storage should still be granted
4485 UninstallExtension(id1, false);
4486 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4487 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
4490 // Check that the cookie is still there.
4491 cookie_monster->GetAllCookiesForURLAsync(
4493 base::Bind(&ExtensionCookieCallback::GetAllCookiesCallback,
4494 base::Unretained(&callback)));
4495 base::RunLoop().RunUntilIdle();
4496 EXPECT_EQ(1U, callback.list_.size());
4498 // Now uninstall the other. Storage should be cleared for the apps.
4499 UninstallExtension(id2, false);
4500 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4502 profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
4505 // Check that the cookie is gone.
4506 cookie_monster->GetAllCookiesForURLAsync(
4508 base::Bind(&ExtensionCookieCallback::GetAllCookiesCallback,
4509 base::Unretained(&callback)));
4510 base::RunLoop().RunUntilIdle();
4511 EXPECT_EQ(0U, callback.list_.size());
4513 // The database should have vanished as well.
4515 db_tracker->GetAllOriginsInfo(&origins);
4516 EXPECT_EQ(0U, origins.size());
4518 // Check that the LSO file has been removed.
4519 EXPECT_FALSE(base::PathExists(lso_file_path));
4521 // Check if the indexed db has disappeared too.
4522 EXPECT_FALSE(base::DirectoryExists(idb_path));
4525 // Tests loading single extensions (like --load-extension)
4526 // Flaky crashes. http://crbug.com/231806
4527 TEST_F(ExtensionServiceTest, DISABLED_LoadExtension) {
4528 InitializeEmptyExtensionService();
4530 base::FilePath ext1 = data_dir()
4531 .AppendASCII("good")
4532 .AppendASCII("Extensions")
4533 .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
4534 .AppendASCII("1.0.0.0");
4535 extensions::UnpackedInstaller::Create(service())->Load(ext1);
4536 base::RunLoop().RunUntilIdle();
4537 EXPECT_EQ(0u, GetErrors().size());
4538 ASSERT_EQ(1u, loaded_.size());
4539 EXPECT_EQ(Manifest::UNPACKED, loaded_[0]->location());
4540 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4542 ValidatePrefKeyCount(1);
4544 base::FilePath no_manifest =
4547 // .AppendASCII("Extensions")
4548 .AppendASCII("cccccccccccccccccccccccccccccccc")
4550 extensions::UnpackedInstaller::Create(service())->Load(no_manifest);
4551 base::RunLoop().RunUntilIdle();
4552 EXPECT_EQ(1u, GetErrors().size());
4553 ASSERT_EQ(1u, loaded_.size());
4554 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4557 std::string id = loaded_[0]->id();
4558 EXPECT_FALSE(unloaded_id_.length());
4559 service()->UninstallExtension(id,
4560 extensions::UNINSTALL_REASON_FOR_TESTING,
4561 base::Bind(&base::DoNothing),
4563 base::RunLoop().RunUntilIdle();
4564 EXPECT_EQ(id, unloaded_id_);
4565 ASSERT_EQ(0u, loaded_.size());
4566 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4569 // Tests that we generate IDs when they are not specified in the manifest for
4570 // --load-extension.
4571 TEST_F(ExtensionServiceTest, GenerateID) {
4572 InitializeEmptyExtensionService();
4574 base::FilePath no_id_ext = data_dir().AppendASCII("no_id");
4575 extensions::UnpackedInstaller::Create(service())->Load(no_id_ext);
4576 base::RunLoop().RunUntilIdle();
4577 EXPECT_EQ(0u, GetErrors().size());
4578 ASSERT_EQ(1u, loaded_.size());
4579 ASSERT_TRUE(Extension::IdIsValid(loaded_[0]->id()));
4580 EXPECT_EQ(loaded_[0]->location(), Manifest::UNPACKED);
4582 ValidatePrefKeyCount(1);
4584 std::string previous_id = loaded_[0]->id();
4586 // If we reload the same path, we should get the same extension ID.
4587 extensions::UnpackedInstaller::Create(service())->Load(no_id_ext);
4588 base::RunLoop().RunUntilIdle();
4589 ASSERT_EQ(1u, loaded_.size());
4590 ASSERT_EQ(previous_id, loaded_[0]->id());
4593 TEST_F(ExtensionServiceTest, UnpackedValidatesLocales) {
4594 InitializeEmptyExtensionService();
4596 base::FilePath bad_locale =
4597 data_dir().AppendASCII("unpacked").AppendASCII("bad_messages_file");
4598 extensions::UnpackedInstaller::Create(service())->Load(bad_locale);
4599 base::RunLoop().RunUntilIdle();
4600 EXPECT_EQ(1u, GetErrors().size());
4601 base::FilePath ms_messages_file = bad_locale.AppendASCII("_locales")
4603 .AppendASCII("messages.json");
4604 EXPECT_THAT(base::UTF16ToUTF8(GetErrors()[0]), testing::AllOf(
4606 base::UTF16ToUTF8(ms_messages_file.LossyDisplayName())),
4607 testing::HasSubstr("Dictionary keys must be quoted.")));
4608 ASSERT_EQ(0u, loaded_.size());
4611 void ExtensionServiceTest::TestExternalProvider(
4612 MockExtensionProvider* provider, Manifest::Location location) {
4613 // Verify that starting with no providers loads no extensions.
4615 ASSERT_EQ(0u, loaded_.size());
4617 provider->set_visit_count(0);
4619 // Register a test extension externally using the mock registry provider.
4620 base::FilePath source_path = data_dir().AppendASCII("good.crx");
4622 // Add the extension.
4623 provider->UpdateOrAddExtension(good_crx, "1.0.0.0", source_path);
4625 // Reloading extensions should find our externally registered extension
4627 content::WindowedNotificationObserver observer(
4628 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
4629 content::NotificationService::AllSources());
4630 service()->CheckForExternalUpdates();
4633 ASSERT_EQ(0u, GetErrors().size());
4634 ASSERT_EQ(1u, loaded_.size());
4635 ASSERT_EQ(location, loaded_[0]->location());
4636 ASSERT_EQ("1.0.0.0", loaded_[0]->version()->GetString());
4637 ValidatePrefKeyCount(1);
4638 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
4639 ValidateIntegerPref(good_crx, "location", location);
4641 // Reload extensions without changing anything. The extension should be
4644 service()->ReloadExtensionsForTest();
4645 base::RunLoop().RunUntilIdle();
4646 ASSERT_EQ(0u, GetErrors().size());
4647 ASSERT_EQ(1u, loaded_.size());
4648 ValidatePrefKeyCount(1);
4649 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
4650 ValidateIntegerPref(good_crx, "location", location);
4652 // Now update the extension with a new version. We should get upgraded.
4653 source_path = source_path.DirName().AppendASCII("good2.crx");
4654 provider->UpdateOrAddExtension(good_crx, "1.0.0.1", source_path);
4657 content::WindowedNotificationObserver observer_2(
4658 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
4659 content::NotificationService::AllSources());
4660 service()->CheckForExternalUpdates();
4662 ASSERT_EQ(0u, GetErrors().size());
4663 ASSERT_EQ(1u, loaded_.size());
4664 ASSERT_EQ("1.0.0.1", loaded_[0]->version()->GetString());
4665 ValidatePrefKeyCount(1);
4666 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
4667 ValidateIntegerPref(good_crx, "location", location);
4669 // Uninstall the extension and reload. Nothing should happen because the
4670 // preference should prevent us from reinstalling.
4671 std::string id = loaded_[0]->id();
4673 GetManagementPolicy()->MustRemainEnabled(loaded_[0].get(), NULL);
4674 service()->UninstallExtension(id,
4675 extensions::UNINSTALL_REASON_FOR_TESTING,
4676 base::Bind(&base::DoNothing),
4678 base::RunLoop().RunUntilIdle();
4680 base::FilePath install_path = extensions_install_dir().AppendASCII(id);
4682 // Policy controlled extensions should not have been touched by uninstall.
4683 ASSERT_TRUE(base::PathExists(install_path));
4685 // The extension should also be gone from the install directory.
4686 ASSERT_FALSE(base::PathExists(install_path));
4688 service()->CheckForExternalUpdates();
4689 base::RunLoop().RunUntilIdle();
4690 ASSERT_EQ(0u, loaded_.size());
4691 ValidatePrefKeyCount(1);
4692 ValidateIntegerPref(good_crx, "state",
4693 Extension::EXTERNAL_EXTENSION_UNINSTALLED);
4694 ValidateIntegerPref(good_crx, "location", location);
4696 // Now clear the preference and reinstall.
4697 SetPrefInteg(good_crx, "state", Extension::ENABLED);
4700 content::WindowedNotificationObserver observer(
4701 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
4702 content::NotificationService::AllSources());
4703 service()->CheckForExternalUpdates();
4705 ASSERT_EQ(1u, loaded_.size());
4707 ValidatePrefKeyCount(1);
4708 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
4709 ValidateIntegerPref(good_crx, "location", location);
4711 if (GetManagementPolicy()->MustRemainEnabled(loaded_[0].get(), NULL)) {
4712 EXPECT_EQ(2, provider->visit_count());
4714 // Now test an externally triggered uninstall (deleting the registry key or
4716 provider->RemoveExtension(good_crx);
4719 service()->OnExternalProviderReady(provider);
4720 base::RunLoop().RunUntilIdle();
4721 ASSERT_EQ(0u, loaded_.size());
4722 ValidatePrefKeyCount(0);
4724 // The extension should also be gone from the install directory.
4725 ASSERT_FALSE(base::PathExists(install_path));
4727 // Now test the case where user uninstalls and then the extension is removed
4728 // from the external provider.
4729 content::WindowedNotificationObserver observer(
4730 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
4731 content::NotificationService::AllSources());
4732 provider->UpdateOrAddExtension(good_crx, "1.0.0.1", source_path);
4733 service()->CheckForExternalUpdates();
4736 ASSERT_EQ(1u, loaded_.size());
4737 ASSERT_EQ(0u, GetErrors().size());
4741 service()->UninstallExtension(id,
4742 extensions::UNINSTALL_REASON_FOR_TESTING,
4743 base::Bind(&base::DoNothing),
4745 base::RunLoop().RunUntilIdle();
4746 ASSERT_EQ(0u, loaded_.size());
4748 // Then remove the extension from the extension provider.
4749 provider->RemoveExtension(good_crx);
4751 // Should still be at 0.
4753 extensions::InstalledLoader(service()).LoadAllExtensions();
4754 base::RunLoop().RunUntilIdle();
4755 ASSERT_EQ(0u, loaded_.size());
4756 ValidatePrefKeyCount(1);
4758 EXPECT_EQ(5, provider->visit_count());
4762 // Tests the external installation feature
4764 TEST_F(ExtensionServiceTest, ExternalInstallRegistry) {
4765 // This should all work, even when normal extension installation is disabled.
4766 InitializeEmptyExtensionService();
4767 service()->set_extensions_enabled(false);
4769 // Now add providers. Extension system takes ownership of the objects.
4770 MockExtensionProvider* reg_provider =
4771 new MockExtensionProvider(service(), Manifest::EXTERNAL_REGISTRY);
4772 AddMockExternalProvider(reg_provider);
4773 TestExternalProvider(reg_provider, Manifest::EXTERNAL_REGISTRY);
4777 TEST_F(ExtensionServiceTest, ExternalInstallPref) {
4778 InitializeEmptyExtensionService();
4780 // Now add providers. Extension system takes ownership of the objects.
4781 MockExtensionProvider* pref_provider =
4782 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF);
4784 AddMockExternalProvider(pref_provider);
4785 TestExternalProvider(pref_provider, Manifest::EXTERNAL_PREF);
4788 TEST_F(ExtensionServiceTest, ExternalInstallPrefUpdateUrl) {
4789 // This should all work, even when normal extension installation is disabled.
4790 InitializeEmptyExtensionService();
4791 service()->set_extensions_enabled(false);
4793 // TODO(skerner): The mock provider is not a good model of a provider
4794 // that works with update URLs, because it adds file and version info.
4795 // Extend the mock to work with update URLs. This test checks the
4796 // behavior that is common to all external extension visitors. The
4797 // browser test ExtensionManagementTest.ExternalUrlUpdate tests that
4798 // what the visitor does results in an extension being downloaded and
4800 MockExtensionProvider* pref_provider =
4801 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF_DOWNLOAD);
4802 AddMockExternalProvider(pref_provider);
4803 TestExternalProvider(pref_provider, Manifest::EXTERNAL_PREF_DOWNLOAD);
4806 TEST_F(ExtensionServiceTest, ExternalInstallPolicyUpdateUrl) {
4807 // This should all work, even when normal extension installation is disabled.
4808 InitializeEmptyExtensionService();
4809 service()->set_extensions_enabled(false);
4811 // TODO(skerner): The mock provider is not a good model of a provider
4812 // that works with update URLs, because it adds file and version info.
4813 // Extend the mock to work with update URLs. This test checks the
4814 // behavior that is common to all external extension visitors. The
4815 // browser test ExtensionManagementTest.ExternalUrlUpdate tests that
4816 // what the visitor does results in an extension being downloaded and
4818 MockExtensionProvider* pref_provider =
4819 new MockExtensionProvider(service(), Manifest::EXTERNAL_POLICY_DOWNLOAD);
4820 AddMockExternalProvider(pref_provider);
4821 TestExternalProvider(pref_provider, Manifest::EXTERNAL_POLICY_DOWNLOAD);
4824 // Tests that external extensions get uninstalled when the external extension
4825 // providers can't account for them.
4826 TEST_F(ExtensionServiceTest, ExternalUninstall) {
4827 // Start the extensions service with one external extension already installed.
4828 base::FilePath source_install_dir =
4829 data_dir().AppendASCII("good").AppendASCII("Extensions");
4830 base::FilePath pref_path = source_install_dir
4832 .AppendASCII("PreferencesExternal");
4834 // This initializes the extensions service with no ExternalProviders.
4835 InitializeInstalledExtensionService(pref_path, source_install_dir);
4836 service()->set_extensions_enabled(false);
4840 ASSERT_EQ(0u, GetErrors().size());
4841 ASSERT_EQ(0u, loaded_.size());
4843 // Verify that it's not the disabled extensions flag causing it not to load.
4844 service()->set_extensions_enabled(true);
4845 service()->ReloadExtensionsForTest();
4846 base::RunLoop().RunUntilIdle();
4848 ASSERT_EQ(0u, GetErrors().size());
4849 ASSERT_EQ(0u, loaded_.size());
4852 // Test that running multiple update checks simultaneously does not
4853 // keep the update from succeeding.
4854 TEST_F(ExtensionServiceTest, MultipleExternalUpdateCheck) {
4855 InitializeEmptyExtensionService();
4857 MockExtensionProvider* provider =
4858 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF);
4859 AddMockExternalProvider(provider);
4861 // Verify that starting with no providers loads no extensions.
4863 ASSERT_EQ(0u, loaded_.size());
4865 // Start two checks for updates.
4866 provider->set_visit_count(0);
4867 service()->CheckForExternalUpdates();
4868 service()->CheckForExternalUpdates();
4869 base::RunLoop().RunUntilIdle();
4871 // Two calls should cause two checks for external extensions.
4872 EXPECT_EQ(2, provider->visit_count());
4873 EXPECT_EQ(0u, GetErrors().size());
4874 EXPECT_EQ(0u, loaded_.size());
4876 // Register a test extension externally using the mock registry provider.
4877 base::FilePath source_path = data_dir().AppendASCII("good.crx");
4878 provider->UpdateOrAddExtension(good_crx, "1.0.0.0", source_path);
4880 // Two checks for external updates should find the extension, and install it
4882 content::WindowedNotificationObserver observer(
4883 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
4884 content::NotificationService::AllSources());
4885 provider->set_visit_count(0);
4886 service()->CheckForExternalUpdates();
4887 service()->CheckForExternalUpdates();
4889 EXPECT_EQ(2, provider->visit_count());
4890 ASSERT_EQ(0u, GetErrors().size());
4891 ASSERT_EQ(1u, loaded_.size());
4892 ASSERT_EQ(Manifest::EXTERNAL_PREF, loaded_[0]->location());
4893 ASSERT_EQ("1.0.0.0", loaded_[0]->version()->GetString());
4894 ValidatePrefKeyCount(1);
4895 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
4896 ValidateIntegerPref(good_crx, "location", Manifest::EXTERNAL_PREF);
4898 provider->RemoveExtension(good_crx);
4899 provider->set_visit_count(0);
4900 service()->CheckForExternalUpdates();
4901 service()->CheckForExternalUpdates();
4902 base::RunLoop().RunUntilIdle();
4904 // Two calls should cause two checks for external extensions.
4905 // Because the external source no longer includes good_crx,
4906 // good_crx will be uninstalled. So, expect that no extensions
4908 EXPECT_EQ(2, provider->visit_count());
4909 EXPECT_EQ(0u, GetErrors().size());
4910 EXPECT_EQ(0u, loaded_.size());
4913 TEST_F(ExtensionServiceTest, ExternalPrefProvider) {
4914 InitializeEmptyExtensionService();
4916 // Test some valid extension records.
4917 // Set a base path to avoid erroring out on relative paths.
4918 // Paths starting with // are absolute on every platform we support.
4919 base::FilePath base_path(FILE_PATH_LITERAL("//base/path"));
4920 ASSERT_TRUE(base_path.IsAbsolute());
4921 MockProviderVisitor visitor(base_path);
4922 std::string json_data =
4924 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
4925 " \"external_crx\": \"RandomExtension.crx\","
4926 " \"external_version\": \"1.0\""
4928 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\": {"
4929 " \"external_crx\": \"RandomExtension2.crx\","
4930 " \"external_version\": \"2.0\""
4932 " \"cccccccccccccccccccccccccccccccc\": {"
4933 " \"external_update_url\": \"http:\\\\foo.com/update\","
4934 " \"install_parameter\": \"id\""
4937 EXPECT_EQ(3, visitor.Visit(json_data));
4939 // Simulate an external_extensions.json file that contains seven invalid
4941 // - One that is missing the 'external_crx' key.
4942 // - One that is missing the 'external_version' key.
4943 // - One that is specifying .. in the path.
4944 // - One that specifies both a file and update URL.
4945 // - One that specifies no file or update URL.
4946 // - One that has an update URL that is not well formed.
4947 // - One that contains a malformed version.
4948 // - One that has an invalid id.
4949 // - One that has a non-dictionary value.
4950 // - One that has an integer 'external_version' instead of a string.
4951 // The final extension is valid, and we check that it is read to make sure
4952 // failures don't stop valid records from being read.
4955 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
4956 " \"external_version\": \"1.0\""
4958 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\": {"
4959 " \"external_crx\": \"RandomExtension.crx\""
4961 " \"cccccccccccccccccccccccccccccccc\": {"
4962 " \"external_crx\": \"..\\\\foo\\\\RandomExtension2.crx\","
4963 " \"external_version\": \"2.0\""
4965 " \"dddddddddddddddddddddddddddddddd\": {"
4966 " \"external_crx\": \"RandomExtension2.crx\","
4967 " \"external_version\": \"2.0\","
4968 " \"external_update_url\": \"http:\\\\foo.com/update\""
4970 " \"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\": {"
4972 " \"ffffffffffffffffffffffffffffffff\": {"
4973 " \"external_update_url\": \"This string is not a valid URL\""
4975 " \"gggggggggggggggggggggggggggggggg\": {"
4976 " \"external_crx\": \"RandomExtension3.crx\","
4977 " \"external_version\": \"This is not a valid version!\""
4979 " \"This is not a valid id!\": {},"
4980 " \"hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh\": true,"
4981 " \"iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii\": {"
4982 " \"external_crx\": \"RandomExtension4.crx\","
4983 " \"external_version\": 1.0"
4985 " \"pppppppppppppppppppppppppppppppp\": {"
4986 " \"external_crx\": \"RandomValidExtension.crx\","
4987 " \"external_version\": \"1.0\""
4990 EXPECT_EQ(1, visitor.Visit(json_data));
4992 // Check that if a base path is not provided, use of a relative
4994 base::FilePath empty;
4995 MockProviderVisitor visitor_no_relative_paths(empty);
4997 // Use absolute paths. Expect success.
5000 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5001 " \"external_crx\": \"//RandomExtension1.crx\","
5002 " \"external_version\": \"3.0\""
5004 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\": {"
5005 " \"external_crx\": \"//path/to/RandomExtension2.crx\","
5006 " \"external_version\": \"3.0\""
5009 EXPECT_EQ(2, visitor_no_relative_paths.Visit(json_data));
5011 // Use a relative path. Expect that it will error out.
5014 " \"cccccccccccccccccccccccccccccccc\": {"
5015 " \"external_crx\": \"RandomExtension2.crx\","
5016 " \"external_version\": \"3.0\""
5019 EXPECT_EQ(0, visitor_no_relative_paths.Visit(json_data));
5021 // Test supported_locales.
5024 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5025 " \"external_crx\": \"RandomExtension.crx\","
5026 " \"external_version\": \"1.0\","
5027 " \"supported_locales\": [ \"en\" ]"
5029 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\": {"
5030 " \"external_crx\": \"RandomExtension2.crx\","
5031 " \"external_version\": \"2.0\","
5032 " \"supported_locales\": [ \"en-GB\" ]"
5034 " \"cccccccccccccccccccccccccccccccc\": {"
5035 " \"external_crx\": \"RandomExtension2.crx\","
5036 " \"external_version\": \"3.0\","
5037 " \"supported_locales\": [ \"en_US\", \"fr\" ]"
5041 ScopedBrowserLocale guard("en-US");
5042 EXPECT_EQ(2, visitor.Visit(json_data));
5045 // Test keep_if_present.
5048 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5049 " \"external_crx\": \"RandomExtension.crx\","
5050 " \"external_version\": \"1.0\","
5051 " \"keep_if_present\": true"
5055 EXPECT_EQ(0, visitor.Visit(json_data));
5058 // Test is_bookmark_app.
5059 MockProviderVisitor from_bookmark_visitor(
5060 base_path, Extension::FROM_BOOKMARK);
5063 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5064 " \"external_crx\": \"RandomExtension.crx\","
5065 " \"external_version\": \"1.0\","
5066 " \"is_bookmark_app\": true"
5069 EXPECT_EQ(1, from_bookmark_visitor.Visit(json_data));
5071 // Test is_from_webstore.
5072 MockProviderVisitor from_webstore_visitor(
5073 base_path, Extension::FROM_WEBSTORE);
5076 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5077 " \"external_crx\": \"RandomExtension.crx\","
5078 " \"external_version\": \"1.0\","
5079 " \"is_from_webstore\": true"
5082 EXPECT_EQ(1, from_webstore_visitor.Visit(json_data));
5084 // Test was_installed_by_eom.
5085 MockProviderVisitor was_installed_by_eom_visitor(
5086 base_path, Extension::WAS_INSTALLED_BY_OEM);
5089 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5090 " \"external_crx\": \"RandomExtension.crx\","
5091 " \"external_version\": \"1.0\","
5092 " \"was_installed_by_oem\": true"
5095 EXPECT_EQ(1, was_installed_by_eom_visitor.Visit(json_data));
5098 // Test loading good extensions from the profile directory.
5099 TEST_F(ExtensionServiceTest, LoadAndRelocalizeExtensions) {
5100 // Ensure we're testing in "en" and leave global state untouched.
5101 extension_l10n_util::ScopedLocaleForTest testLocale("en");
5103 // Initialize the test dir with a good Preferences/extensions.
5104 base::FilePath source_install_dir = data_dir().AppendASCII("l10n");
5105 base::FilePath pref_path =
5106 source_install_dir.Append(chrome::kPreferencesFilename);
5107 InitializeInstalledExtensionService(pref_path, source_install_dir);
5111 ASSERT_EQ(3u, loaded_.size());
5113 // This was equal to "sr" on load.
5114 ValidateStringPref(loaded_[0]->id(), keys::kCurrentLocale, "en");
5116 // These are untouched by re-localization.
5117 ValidateStringPref(loaded_[1]->id(), keys::kCurrentLocale, "en");
5118 EXPECT_FALSE(IsPrefExist(loaded_[1]->id(), keys::kCurrentLocale));
5120 // This one starts with Serbian name, and gets re-localized into English.
5121 EXPECT_EQ("My name is simple.", loaded_[0]->name());
5123 // These are untouched by re-localization.
5124 EXPECT_EQ("My name is simple.", loaded_[1]->name());
5125 EXPECT_EQ("no l10n", loaded_[2]->name());
5128 class ExtensionsReadyRecorder : public content::NotificationObserver {
5130 ExtensionsReadyRecorder() : ready_(false) {
5131 registrar_.Add(this,
5132 extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED,
5133 content::NotificationService::AllSources());
5136 void set_ready(bool value) { ready_ = value; }
5137 bool ready() { return ready_; }
5140 virtual void Observe(int type,
5141 const content::NotificationSource& source,
5142 const content::NotificationDetails& details) OVERRIDE {
5144 case extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED:
5152 content::NotificationRegistrar registrar_;
5156 // Test that we get enabled/disabled correctly for all the pref/command-line
5157 // combinations. We don't want to derive from the ExtensionServiceTest class
5158 // for this test, so we use ExtensionServiceTestSimple.
5160 // Also tests that we always fire EXTENSIONS_READY, no matter whether we are
5162 TEST(ExtensionServiceTestSimple, Enabledness) {
5163 // Make sure the PluginService singleton is destroyed at the end of the test.
5164 base::ShadowingAtExitManager at_exit_manager;
5165 #if defined(ENABLE_PLUGINS)
5166 content::PluginService::GetInstance()->Init();
5167 content::PluginService::GetInstance()->DisablePluginsDiscoveryForTesting();
5170 ExtensionErrorReporter::Init(false); // no noisy errors
5171 ExtensionsReadyRecorder recorder;
5172 scoped_ptr<TestingProfile> profile(new TestingProfile());
5173 content::TestBrowserThreadBundle thread_bundle_;
5174 #if defined OS_CHROMEOS
5175 chromeos::ScopedTestDeviceSettingsService device_settings_service;
5176 chromeos::ScopedTestCrosSettings cros_settings;
5177 scoped_ptr<chromeos::ScopedTestUserManager> user_manager(
5178 new chromeos::ScopedTestUserManager);
5180 scoped_ptr<CommandLine> command_line;
5181 base::FilePath install_dir = profile->GetPath()
5182 .AppendASCII(extensions::kInstallDirectoryName);
5184 // By default, we are enabled.
5185 command_line.reset(new CommandLine(CommandLine::NO_PROGRAM));
5186 ExtensionService* service = static_cast<extensions::TestExtensionSystem*>(
5187 ExtensionSystem::Get(profile.get()))->
5188 CreateExtensionService(
5192 EXPECT_TRUE(service->extensions_enabled());
5194 base::RunLoop().RunUntilIdle();
5195 EXPECT_TRUE(recorder.ready());
5196 #if defined OS_CHROMEOS
5197 user_manager.reset();
5200 // If either the command line or pref is set, we are disabled.
5201 recorder.set_ready(false);
5202 profile.reset(new TestingProfile());
5203 command_line->AppendSwitch(switches::kDisableExtensions);
5204 service = static_cast<extensions::TestExtensionSystem*>(
5205 ExtensionSystem::Get(profile.get()))->
5206 CreateExtensionService(
5210 EXPECT_FALSE(service->extensions_enabled());
5212 base::RunLoop().RunUntilIdle();
5213 EXPECT_TRUE(recorder.ready());
5215 recorder.set_ready(false);
5216 profile.reset(new TestingProfile());
5217 profile->GetPrefs()->SetBoolean(prefs::kDisableExtensions, true);
5218 service = static_cast<extensions::TestExtensionSystem*>(
5219 ExtensionSystem::Get(profile.get()))->
5220 CreateExtensionService(
5224 EXPECT_FALSE(service->extensions_enabled());
5226 base::RunLoop().RunUntilIdle();
5227 EXPECT_TRUE(recorder.ready());
5229 recorder.set_ready(false);
5230 profile.reset(new TestingProfile());
5231 profile->GetPrefs()->SetBoolean(prefs::kDisableExtensions, true);
5232 command_line.reset(new CommandLine(CommandLine::NO_PROGRAM));
5233 service = static_cast<extensions::TestExtensionSystem*>(
5234 ExtensionSystem::Get(profile.get()))->
5235 CreateExtensionService(
5239 EXPECT_FALSE(service->extensions_enabled());
5241 base::RunLoop().RunUntilIdle();
5242 EXPECT_TRUE(recorder.ready());
5244 // Explicitly delete all the resources used in this test.
5247 // Execute any pending deletion tasks.
5248 base::RunLoop().RunUntilIdle();
5251 // Test loading extensions that require limited and unlimited storage quotas.
5252 TEST_F(ExtensionServiceTest, StorageQuota) {
5253 InitializeEmptyExtensionService();
5255 base::FilePath extensions_path = data_dir().AppendASCII("storage_quota");
5257 base::FilePath limited_quota_ext =
5258 extensions_path.AppendASCII("limited_quota")
5259 .AppendASCII("1.0");
5261 // The old permission name for unlimited quota was "unlimited_storage", but
5262 // we changed it to "unlimitedStorage". This tests both versions.
5263 base::FilePath unlimited_quota_ext =
5264 extensions_path.AppendASCII("unlimited_quota")
5265 .AppendASCII("1.0");
5266 base::FilePath unlimited_quota_ext2 =
5267 extensions_path.AppendASCII("unlimited_quota")
5268 .AppendASCII("2.0");
5269 extensions::UnpackedInstaller::Create(service())->Load(limited_quota_ext);
5270 extensions::UnpackedInstaller::Create(service())->Load(unlimited_quota_ext);
5271 extensions::UnpackedInstaller::Create(service())->Load(unlimited_quota_ext2);
5272 base::RunLoop().RunUntilIdle();
5274 ASSERT_EQ(3u, loaded_.size());
5275 EXPECT_TRUE(profile());
5276 EXPECT_FALSE(profile()->IsOffTheRecord());
5278 profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
5279 loaded_[0]->url()));
5280 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
5281 loaded_[1]->url()));
5282 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
5283 loaded_[2]->url()));
5286 // Tests ComponentLoader::Add().
5287 TEST_F(ExtensionServiceTest, ComponentExtensions) {
5288 InitializeEmptyExtensionService();
5290 // Component extensions should work even when extensions are disabled.
5291 service()->set_extensions_enabled(false);
5293 base::FilePath path = data_dir()
5294 .AppendASCII("good")
5295 .AppendASCII("Extensions")
5296 .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
5297 .AppendASCII("1.0.0.0");
5299 std::string manifest;
5300 ASSERT_TRUE(base::ReadFileToString(
5301 path.Append(extensions::kManifestFilename), &manifest));
5303 service()->component_loader()->Add(manifest, path);
5306 // Note that we do not pump messages -- the extension should be loaded
5309 EXPECT_EQ(0u, GetErrors().size());
5310 ASSERT_EQ(1u, loaded_.size());
5311 EXPECT_EQ(Manifest::COMPONENT, loaded_[0]->location());
5312 EXPECT_EQ(1u, registry()->enabled_extensions().size());
5314 // Component extensions get a prefs entry on first install.
5315 ValidatePrefKeyCount(1);
5317 // Reload all extensions, and make sure it comes back.
5318 std::string extension_id = (*registry()->enabled_extensions().begin())->id();
5320 service()->ReloadExtensionsForTest();
5321 ASSERT_EQ(1u, registry()->enabled_extensions().size());
5322 EXPECT_EQ(extension_id, (*registry()->enabled_extensions().begin())->id());
5325 TEST_F(ExtensionServiceTest, DeferredSyncStartupPreInstalledComponent) {
5326 InitializeEmptyExtensionService();
5327 InitializeExtensionSyncService();
5329 bool flare_was_called = false;
5330 syncer::ModelType triggered_type(syncer::UNSPECIFIED);
5331 base::WeakPtrFactory<ExtensionServiceTest> factory(this);
5332 extension_sync_service()->SetSyncStartFlare(
5333 base::Bind(&ExtensionServiceTest::MockSyncStartFlare,
5334 factory.GetWeakPtr(),
5335 &flare_was_called, // Safe due to WeakPtrFactory scope.
5336 &triggered_type)); // Safe due to WeakPtrFactory scope.
5338 // Install a component extension.
5339 std::string manifest;
5340 ASSERT_TRUE(base::ReadFileToString(
5341 good0_path().Append(extensions::kManifestFilename), &manifest));
5342 service()->component_loader()->Add(manifest, good0_path());
5343 ASSERT_FALSE(service()->is_ready());
5345 ASSERT_TRUE(service()->is_ready());
5347 // Extensions added before service is_ready() don't trigger sync startup.
5348 EXPECT_FALSE(flare_was_called);
5349 ASSERT_EQ(syncer::UNSPECIFIED, triggered_type);
5352 TEST_F(ExtensionServiceTest, DeferredSyncStartupPreInstalledNormal) {
5353 InitializeGoodInstalledExtensionService();
5354 InitializeExtensionSyncService();
5356 bool flare_was_called = false;
5357 syncer::ModelType triggered_type(syncer::UNSPECIFIED);
5358 base::WeakPtrFactory<ExtensionServiceTest> factory(this);
5359 extension_sync_service()->SetSyncStartFlare(
5360 base::Bind(&ExtensionServiceTest::MockSyncStartFlare,
5361 factory.GetWeakPtr(),
5362 &flare_was_called, // Safe due to WeakPtrFactory scope.
5363 &triggered_type)); // Safe due to WeakPtrFactory scope.
5365 ASSERT_FALSE(service()->is_ready());
5367 ASSERT_EQ(3u, loaded_.size());
5368 ASSERT_TRUE(service()->is_ready());
5370 // Extensions added before service is_ready() don't trigger sync startup.
5371 EXPECT_FALSE(flare_was_called);
5372 ASSERT_EQ(syncer::UNSPECIFIED, triggered_type);
5375 TEST_F(ExtensionServiceTest, DeferredSyncStartupOnInstall) {
5376 InitializeEmptyExtensionService();
5377 InitializeExtensionSyncService();
5379 ASSERT_TRUE(service()->is_ready());
5381 bool flare_was_called = false;
5382 syncer::ModelType triggered_type(syncer::UNSPECIFIED);
5383 base::WeakPtrFactory<ExtensionServiceTest> factory(this);
5384 extension_sync_service()->SetSyncStartFlare(
5385 base::Bind(&ExtensionServiceTest::MockSyncStartFlare,
5386 factory.GetWeakPtr(),
5387 &flare_was_called, // Safe due to WeakPtrFactory scope.
5388 &triggered_type)); // Safe due to WeakPtrFactory scope.
5390 base::FilePath path = data_dir().AppendASCII("good.crx");
5391 InstallCRX(path, INSTALL_NEW);
5393 EXPECT_TRUE(flare_was_called);
5394 EXPECT_EQ(syncer::EXTENSIONS, triggered_type);
5397 flare_was_called = false;
5398 triggered_type = syncer::UNSPECIFIED;
5400 // Once sync starts, flare should no longer be invoked.
5401 extension_sync_service()->MergeDataAndStartSyncing(
5403 syncer::SyncDataList(),
5404 scoped_ptr<syncer::SyncChangeProcessor>(
5405 new syncer::FakeSyncChangeProcessor),
5406 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5407 path = data_dir().AppendASCII("page_action.crx");
5408 InstallCRX(path, INSTALL_NEW);
5409 EXPECT_FALSE(flare_was_called);
5410 ASSERT_EQ(syncer::UNSPECIFIED, triggered_type);
5413 TEST_F(ExtensionServiceTest, DisableExtensionFromSync) {
5414 // Start the extensions service with one external extension already installed.
5415 base::FilePath source_install_dir =
5416 data_dir().AppendASCII("good").AppendASCII("Extensions");
5417 base::FilePath pref_path =
5418 source_install_dir.DirName().Append(chrome::kPreferencesFilename);
5420 InitializeInstalledExtensionService(pref_path, source_install_dir);
5421 InitializeExtensionSyncService();
5423 // The user has enabled sync.
5424 ProfileSyncService* sync_service =
5425 ProfileSyncServiceFactory::GetForProfile(profile());
5426 sync_service->SetSyncSetupCompleted();
5429 ASSERT_TRUE(service()->is_ready());
5431 ASSERT_EQ(3u, loaded_.size());
5433 // We start enabled.
5434 const Extension* extension = service()->GetExtensionById(good0, true);
5435 ASSERT_TRUE(extension);
5436 ASSERT_TRUE(service()->IsExtensionEnabled(good0));
5437 extensions::ExtensionSyncData disable_good_crx(
5438 *extension, false, false, false);
5440 // Then sync data arrives telling us to disable |good0|.
5441 syncer::SyncDataList sync_data;
5442 sync_data.push_back(disable_good_crx.GetSyncData());
5443 extension_sync_service()->MergeDataAndStartSyncing(
5446 scoped_ptr<syncer::SyncChangeProcessor>(
5447 new syncer::FakeSyncChangeProcessor),
5448 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5449 ASSERT_FALSE(service()->IsExtensionEnabled(good0));
5452 TEST_F(ExtensionServiceTest, DontDisableExtensionWithPendingEnableFromSync) {
5453 // Start the extensions service with one external extension already installed.
5454 base::FilePath source_install_dir =
5455 data_dir().AppendASCII("good").AppendASCII("Extensions");
5456 base::FilePath pref_path =
5457 source_install_dir.DirName().Append(chrome::kPreferencesFilename);
5459 InitializeInstalledExtensionService(pref_path, source_install_dir);
5460 InitializeExtensionSyncService();
5462 // The user has enabled sync.
5463 ProfileSyncService* sync_service =
5464 ProfileSyncServiceFactory::GetForProfile(profile());
5465 sync_service->SetSyncSetupCompleted();
5468 ASSERT_TRUE(service()->is_ready());
5469 ASSERT_EQ(3u, loaded_.size());
5471 const Extension* extension = service()->GetExtensionById(good0, true);
5472 ASSERT_TRUE(service()->IsExtensionEnabled(good0));
5474 // Disable extension before first sync data arrives.
5475 service()->DisableExtension(good0, Extension::DISABLE_USER_ACTION);
5476 ASSERT_FALSE(service()->IsExtensionEnabled(good0));
5478 // Enable extension - this is now the most recent state.
5479 service()->EnableExtension(good0);
5480 ASSERT_TRUE(service()->IsExtensionEnabled(good0));
5482 // Now sync data comes in that says to disable good0. This should be
5484 extensions::ExtensionSyncData disable_good_crx(
5485 *extension, false, false, false);
5486 syncer::SyncDataList sync_data;
5487 sync_data.push_back(disable_good_crx.GetSyncData());
5488 extension_sync_service()->MergeDataAndStartSyncing(
5491 scoped_ptr<syncer::SyncChangeProcessor>(
5492 new syncer::FakeSyncChangeProcessor),
5493 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5495 // The extension was enabled locally before the sync data arrived, so it
5496 // should still be enabled now.
5497 ASSERT_TRUE(service()->IsExtensionEnabled(good0));
5500 TEST_F(ExtensionServiceTest, GetSyncData) {
5501 InitializeEmptyExtensionService();
5502 InitializeExtensionSyncService();
5503 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
5504 const Extension* extension = service()->GetInstalledExtension(good_crx);
5505 ASSERT_TRUE(extension);
5507 extension_sync_service()->MergeDataAndStartSyncing(
5509 syncer::SyncDataList(),
5510 scoped_ptr<syncer::SyncChangeProcessor>(
5511 new syncer::FakeSyncChangeProcessor),
5512 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5514 syncer::SyncDataList list =
5515 extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS);
5516 ASSERT_EQ(list.size(), 1U);
5517 extensions::ExtensionSyncData data(list[0]);
5518 EXPECT_EQ(extension->id(), data.id());
5519 EXPECT_FALSE(data.uninstalled());
5520 EXPECT_EQ(service()->IsExtensionEnabled(good_crx), data.enabled());
5521 EXPECT_EQ(extensions::util::IsIncognitoEnabled(good_crx, profile()),
5522 data.incognito_enabled());
5523 EXPECT_TRUE(data.version().Equals(*extension->version()));
5524 EXPECT_EQ(extensions::ManifestURL::GetUpdateURL(extension),
5526 EXPECT_EQ(extension->name(), data.name());
5529 TEST_F(ExtensionServiceTest, GetSyncDataTerminated) {
5530 InitializeEmptyExtensionService();
5531 InitializeExtensionSyncService();
5532 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
5533 TerminateExtension(good_crx);
5534 const Extension* extension = service()->GetInstalledExtension(good_crx);
5535 ASSERT_TRUE(extension);
5537 syncer::FakeSyncChangeProcessor processor;
5538 extension_sync_service()->MergeDataAndStartSyncing(
5540 syncer::SyncDataList(),
5541 scoped_ptr<syncer::SyncChangeProcessor>(
5542 new syncer::FakeSyncChangeProcessor),
5543 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5545 syncer::SyncDataList list =
5546 extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS);
5547 ASSERT_EQ(list.size(), 1U);
5548 extensions::ExtensionSyncData data(list[0]);
5549 EXPECT_EQ(extension->id(), data.id());
5550 EXPECT_FALSE(data.uninstalled());
5551 EXPECT_EQ(service()->IsExtensionEnabled(good_crx), data.enabled());
5552 EXPECT_EQ(extensions::util::IsIncognitoEnabled(good_crx, profile()),
5553 data.incognito_enabled());
5554 EXPECT_TRUE(data.version().Equals(*extension->version()));
5555 EXPECT_EQ(extensions::ManifestURL::GetUpdateURL(extension),
5557 EXPECT_EQ(extension->name(), data.name());
5560 TEST_F(ExtensionServiceTest, GetSyncDataFilter) {
5561 InitializeEmptyExtensionService();
5562 InitializeExtensionSyncService();
5563 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
5564 const Extension* extension = service()->GetInstalledExtension(good_crx);
5565 ASSERT_TRUE(extension);
5567 syncer::FakeSyncChangeProcessor processor;
5568 extension_sync_service()->MergeDataAndStartSyncing(
5570 syncer::SyncDataList(),
5571 scoped_ptr<syncer::SyncChangeProcessor>(
5572 new syncer::FakeSyncChangeProcessor),
5573 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5575 syncer::SyncDataList list =
5576 extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS);
5577 ASSERT_EQ(list.size(), 0U);
5580 TEST_F(ExtensionServiceTest, GetSyncExtensionDataUserSettings) {
5581 InitializeEmptyExtensionService();
5582 InitializeProcessManager();
5583 InitializeExtensionSyncService();
5584 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
5585 const Extension* extension = service()->GetInstalledExtension(good_crx);
5586 ASSERT_TRUE(extension);
5588 syncer::FakeSyncChangeProcessor processor;
5589 extension_sync_service()->MergeDataAndStartSyncing(
5591 syncer::SyncDataList(),
5592 scoped_ptr<syncer::SyncChangeProcessor>(
5593 new syncer::FakeSyncChangeProcessor),
5594 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5597 syncer::SyncDataList list =
5598 extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS);
5599 ASSERT_EQ(list.size(), 1U);
5600 extensions::ExtensionSyncData data(list[0]);
5601 EXPECT_TRUE(data.enabled());
5602 EXPECT_FALSE(data.incognito_enabled());
5605 service()->DisableExtension(good_crx, Extension::DISABLE_USER_ACTION);
5607 syncer::SyncDataList list =
5608 extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS);
5609 ASSERT_EQ(list.size(), 1U);
5610 extensions::ExtensionSyncData data(list[0]);
5611 EXPECT_FALSE(data.enabled());
5612 EXPECT_FALSE(data.incognito_enabled());
5615 extensions::util::SetIsIncognitoEnabled(good_crx, profile(), true);
5617 syncer::SyncDataList list =
5618 extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS);
5619 ASSERT_EQ(list.size(), 1U);
5620 extensions::ExtensionSyncData data(list[0]);
5621 EXPECT_FALSE(data.enabled());
5622 EXPECT_TRUE(data.incognito_enabled());
5625 service()->EnableExtension(good_crx);
5627 syncer::SyncDataList list =
5628 extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS);
5629 ASSERT_EQ(list.size(), 1U);
5630 extensions::ExtensionSyncData data(list[0]);
5631 EXPECT_TRUE(data.enabled());
5632 EXPECT_TRUE(data.incognito_enabled());
5636 TEST_F(ExtensionServiceTest, SyncForUninstalledExternalExtension) {
5637 InitializeEmptyExtensionService();
5638 InitializeExtensionSyncService();
5639 InstallCRXWithLocation(
5640 data_dir().AppendASCII("good.crx"), Manifest::EXTERNAL_PREF, INSTALL_NEW);
5641 const Extension* extension = service()->GetInstalledExtension(good_crx);
5642 ASSERT_TRUE(extension);
5644 syncer::FakeSyncChangeProcessor processor;
5645 extension_sync_service()->MergeDataAndStartSyncing(
5647 syncer::SyncDataList(),
5648 scoped_ptr<syncer::SyncChangeProcessor>(
5649 new syncer::FakeSyncChangeProcessor),
5650 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5652 UninstallExtension(good_crx, false);
5654 ExtensionPrefs::Get(profile())->IsExternalExtensionUninstalled(good_crx));
5656 sync_pb::EntitySpecifics specifics;
5657 sync_pb::AppSpecifics* app_specifics = specifics.mutable_app();
5658 sync_pb::ExtensionSpecifics* extension_specifics =
5659 app_specifics->mutable_extension();
5660 extension_specifics->set_id(good_crx);
5661 extension_specifics->set_version("1.0");
5662 extension_specifics->set_enabled(true);
5664 syncer::SyncData sync_data =
5665 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
5666 syncer::SyncChange sync_change(FROM_HERE,
5667 syncer::SyncChange::ACTION_UPDATE,
5669 syncer::SyncChangeList list(1);
5670 list[0] = sync_change;
5672 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
5674 ExtensionPrefs::Get(profile())->IsExternalExtensionUninstalled(good_crx));
5677 TEST_F(ExtensionServiceTest, GetSyncAppDataUserSettings) {
5678 InitializeEmptyExtensionService();
5679 InitializeExtensionSyncService();
5680 const Extension* app =
5681 PackAndInstallCRX(data_dir().AppendASCII("app"), INSTALL_NEW);
5683 ASSERT_TRUE(app->is_app());
5685 syncer::FakeSyncChangeProcessor processor;
5686 extension_sync_service()->MergeDataAndStartSyncing(
5688 syncer::SyncDataList(),
5689 scoped_ptr<syncer::SyncChangeProcessor>(
5690 new syncer::FakeSyncChangeProcessor),
5691 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5693 syncer::StringOrdinal initial_ordinal =
5694 syncer::StringOrdinal::CreateInitialOrdinal();
5696 syncer::SyncDataList list =
5697 extension_sync_service()->GetAllSyncData(syncer::APPS);
5698 ASSERT_EQ(list.size(), 1U);
5700 extensions::AppSyncData app_sync_data(list[0]);
5701 EXPECT_TRUE(initial_ordinal.Equals(app_sync_data.app_launch_ordinal()));
5702 EXPECT_TRUE(initial_ordinal.Equals(app_sync_data.page_ordinal()));
5705 AppSorting* sorting = ExtensionPrefs::Get(profile())->app_sorting();
5706 sorting->SetAppLaunchOrdinal(app->id(), initial_ordinal.CreateAfter());
5708 syncer::SyncDataList list =
5709 extension_sync_service()->GetAllSyncData(syncer::APPS);
5710 ASSERT_EQ(list.size(), 1U);
5712 extensions::AppSyncData app_sync_data(list[0]);
5713 EXPECT_TRUE(initial_ordinal.LessThan(app_sync_data.app_launch_ordinal()));
5714 EXPECT_TRUE(initial_ordinal.Equals(app_sync_data.page_ordinal()));
5717 sorting->SetPageOrdinal(app->id(), initial_ordinal.CreateAfter());
5719 syncer::SyncDataList list =
5720 extension_sync_service()->GetAllSyncData(syncer::APPS);
5721 ASSERT_EQ(list.size(), 1U);
5723 extensions::AppSyncData app_sync_data(list[0]);
5724 EXPECT_TRUE(initial_ordinal.LessThan(app_sync_data.app_launch_ordinal()));
5725 EXPECT_TRUE(initial_ordinal.LessThan(app_sync_data.page_ordinal()));
5729 // TODO (rdevlin.cronin): The OnExtensionMoved() method has been removed from
5730 // ExtensionService, so this test probably needs a new home. Unfortunately, it
5731 // relies pretty heavily on things like InitializeExtension[Sync]Service() and
5732 // PackAndInstallCRX(). When we clean up a bit more, this should move out.
5733 TEST_F(ExtensionServiceTest, GetSyncAppDataUserSettingsOnExtensionMoved) {
5734 InitializeEmptyExtensionService();
5735 InitializeExtensionSyncService();
5736 const size_t kAppCount = 3;
5737 const Extension* apps[kAppCount];
5738 apps[0] = PackAndInstallCRX(data_dir().AppendASCII("app1"), INSTALL_NEW);
5739 apps[1] = PackAndInstallCRX(data_dir().AppendASCII("app2"), INSTALL_NEW);
5740 apps[2] = PackAndInstallCRX(data_dir().AppendASCII("app4"), INSTALL_NEW);
5741 for (size_t i = 0; i < kAppCount; ++i) {
5742 ASSERT_TRUE(apps[i]);
5743 ASSERT_TRUE(apps[i]->is_app());
5746 syncer::FakeSyncChangeProcessor processor;
5747 extension_sync_service()->MergeDataAndStartSyncing(
5749 syncer::SyncDataList(),
5750 scoped_ptr<syncer::SyncChangeProcessor>(
5751 new syncer::FakeSyncChangeProcessor),
5752 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5754 ExtensionPrefs::Get(service()->GetBrowserContext())
5756 ->OnExtensionMoved(apps[0]->id(), apps[1]->id(), apps[2]->id());
5758 syncer::SyncDataList list =
5759 extension_sync_service()->GetAllSyncData(syncer::APPS);
5760 ASSERT_EQ(list.size(), 3U);
5762 extensions::AppSyncData data[kAppCount];
5763 for (size_t i = 0; i < kAppCount; ++i) {
5764 data[i] = extensions::AppSyncData(list[i]);
5767 // The sync data is not always in the same order our apps were installed in,
5768 // so we do that sorting here so we can make sure the values are changed as
5770 syncer::StringOrdinal app_launch_ordinals[kAppCount];
5771 for (size_t i = 0; i < kAppCount; ++i) {
5772 for (size_t j = 0; j < kAppCount; ++j) {
5773 if (apps[i]->id() == data[j].id())
5774 app_launch_ordinals[i] = data[j].app_launch_ordinal();
5778 EXPECT_TRUE(app_launch_ordinals[1].LessThan(app_launch_ordinals[0]));
5779 EXPECT_TRUE(app_launch_ordinals[0].LessThan(app_launch_ordinals[2]));
5783 TEST_F(ExtensionServiceTest, GetSyncDataList) {
5784 InitializeEmptyExtensionService();
5785 InitializeExtensionSyncService();
5786 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
5787 InstallCRX(data_dir().AppendASCII("page_action.crx"), INSTALL_NEW);
5788 InstallCRX(data_dir().AppendASCII("theme.crx"), INSTALL_NEW);
5789 InstallCRX(data_dir().AppendASCII("theme2.crx"), INSTALL_NEW);
5791 syncer::FakeSyncChangeProcessor processor;
5792 extension_sync_service()->MergeDataAndStartSyncing(
5794 syncer::SyncDataList(),
5795 scoped_ptr<syncer::SyncChangeProcessor>(
5796 new syncer::FakeSyncChangeProcessor),
5797 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5798 extension_sync_service()->MergeDataAndStartSyncing(
5800 syncer::SyncDataList(),
5801 scoped_ptr<syncer::SyncChangeProcessor>(
5802 new syncer::FakeSyncChangeProcessor),
5803 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5805 service()->DisableExtension(page_action, Extension::DISABLE_USER_ACTION);
5806 TerminateExtension(theme2_crx);
5808 EXPECT_EQ(0u, extension_sync_service()->GetAllSyncData(syncer::APPS).size());
5810 2u, extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS).size());
5813 TEST_F(ExtensionServiceTest, ProcessSyncDataUninstall) {
5814 InitializeEmptyExtensionService();
5815 InitializeExtensionSyncService();
5816 syncer::FakeSyncChangeProcessor processor;
5817 extension_sync_service()->MergeDataAndStartSyncing(
5819 syncer::SyncDataList(),
5820 scoped_ptr<syncer::SyncChangeProcessor>(
5821 new syncer::FakeSyncChangeProcessor),
5822 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5824 sync_pb::EntitySpecifics specifics;
5825 sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension();
5826 ext_specifics->set_id(good_crx);
5827 ext_specifics->set_version("1.0");
5828 syncer::SyncData sync_data =
5829 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
5830 syncer::SyncChange sync_change(FROM_HERE,
5831 syncer::SyncChange::ACTION_DELETE,
5833 syncer::SyncChangeList list(1);
5834 list[0] = sync_change;
5836 // Should do nothing.
5837 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
5838 EXPECT_FALSE(service()->GetExtensionById(good_crx, true));
5840 // Install the extension.
5841 base::FilePath extension_path = data_dir().AppendASCII("good.crx");
5842 InstallCRX(extension_path, INSTALL_NEW);
5843 EXPECT_TRUE(service()->GetExtensionById(good_crx, true));
5845 // Should uninstall the extension.
5846 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
5847 EXPECT_FALSE(service()->GetExtensionById(good_crx, true));
5849 // Should again do nothing.
5850 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
5851 EXPECT_FALSE(service()->GetExtensionById(good_crx, true));
5854 TEST_F(ExtensionServiceTest, ProcessSyncDataWrongType) {
5855 InitializeEmptyExtensionService();
5856 InitializeExtensionSyncService();
5858 // Install the extension.
5859 base::FilePath extension_path = data_dir().AppendASCII("good.crx");
5860 InstallCRX(extension_path, INSTALL_NEW);
5861 EXPECT_TRUE(service()->GetExtensionById(good_crx, true));
5863 sync_pb::EntitySpecifics specifics;
5864 sync_pb::AppSpecifics* app_specifics = specifics.mutable_app();
5865 sync_pb::ExtensionSpecifics* extension_specifics =
5866 app_specifics->mutable_extension();
5867 extension_specifics->set_id(good_crx);
5868 extension_specifics->set_version(
5869 service()->GetInstalledExtension(good_crx)->version()->GetString());
5872 extension_specifics->set_enabled(true);
5873 syncer::SyncData sync_data =
5874 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
5875 syncer::SyncChange sync_change(FROM_HERE,
5876 syncer::SyncChange::ACTION_DELETE,
5878 syncer::SyncChangeList list(1);
5879 list[0] = sync_change;
5881 // Should do nothing
5882 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
5883 EXPECT_TRUE(service()->GetExtensionById(good_crx, true));
5887 extension_specifics->set_enabled(false);
5888 syncer::SyncData sync_data =
5889 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
5890 syncer::SyncChange sync_change(FROM_HERE,
5891 syncer::SyncChange::ACTION_UPDATE,
5893 syncer::SyncChangeList list(1);
5894 list[0] = sync_change;
5896 // Should again do nothing.
5897 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
5898 EXPECT_TRUE(service()->GetExtensionById(good_crx, false));
5902 TEST_F(ExtensionServiceTest, ProcessSyncDataSettings) {
5903 InitializeEmptyExtensionService();
5904 InitializeProcessManager();
5905 InitializeExtensionSyncService();
5906 syncer::FakeSyncChangeProcessor processor;
5907 extension_sync_service()->MergeDataAndStartSyncing(
5909 syncer::SyncDataList(),
5910 scoped_ptr<syncer::SyncChangeProcessor>(
5911 new syncer::FakeSyncChangeProcessor),
5912 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5914 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
5915 EXPECT_TRUE(service()->IsExtensionEnabled(good_crx));
5916 EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
5918 sync_pb::EntitySpecifics specifics;
5919 sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension();
5920 ext_specifics->set_id(good_crx);
5921 ext_specifics->set_version(
5922 service()->GetInstalledExtension(good_crx)->version()->GetString());
5923 ext_specifics->set_enabled(false);
5926 syncer::SyncData sync_data =
5927 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
5928 syncer::SyncChange sync_change(FROM_HERE,
5929 syncer::SyncChange::ACTION_UPDATE,
5931 syncer::SyncChangeList list(1);
5932 list[0] = sync_change;
5933 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
5934 EXPECT_FALSE(service()->IsExtensionEnabled(good_crx));
5935 EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
5939 ext_specifics->set_enabled(true);
5940 ext_specifics->set_incognito_enabled(true);
5941 syncer::SyncData sync_data =
5942 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
5943 syncer::SyncChange sync_change(FROM_HERE,
5944 syncer::SyncChange::ACTION_UPDATE,
5946 syncer::SyncChangeList list(1);
5947 list[0] = sync_change;
5948 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
5949 EXPECT_TRUE(service()->IsExtensionEnabled(good_crx));
5950 EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
5954 ext_specifics->set_enabled(false);
5955 ext_specifics->set_incognito_enabled(true);
5956 syncer::SyncData sync_data =
5957 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
5958 syncer::SyncChange sync_change(FROM_HERE,
5959 syncer::SyncChange::ACTION_UPDATE,
5961 syncer::SyncChangeList list(1);
5962 list[0] = sync_change;
5963 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
5964 EXPECT_FALSE(service()->IsExtensionEnabled(good_crx));
5965 EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
5968 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(good_crx));
5971 TEST_F(ExtensionServiceTest, ProcessSyncDataTerminatedExtension) {
5972 InitializeExtensionServiceWithUpdater();
5973 InitializeExtensionSyncService();
5974 syncer::FakeSyncChangeProcessor processor;
5975 extension_sync_service()->MergeDataAndStartSyncing(
5977 syncer::SyncDataList(),
5978 scoped_ptr<syncer::SyncChangeProcessor>(
5979 new syncer::FakeSyncChangeProcessor),
5980 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5982 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
5983 TerminateExtension(good_crx);
5984 EXPECT_TRUE(service()->IsExtensionEnabled(good_crx));
5985 EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
5987 sync_pb::EntitySpecifics specifics;
5988 sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension();
5989 ext_specifics->set_id(good_crx);
5990 ext_specifics->set_version(
5991 service()->GetInstalledExtension(good_crx)->version()->GetString());
5992 ext_specifics->set_enabled(false);
5993 ext_specifics->set_incognito_enabled(true);
5994 syncer::SyncData sync_data =
5995 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
5996 syncer::SyncChange sync_change(FROM_HERE,
5997 syncer::SyncChange::ACTION_UPDATE,
5999 syncer::SyncChangeList list(1);
6000 list[0] = sync_change;
6002 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6003 EXPECT_FALSE(service()->IsExtensionEnabled(good_crx));
6004 EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
6006 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(good_crx));
6009 TEST_F(ExtensionServiceTest, ProcessSyncDataVersionCheck) {
6010 InitializeExtensionServiceWithUpdater();
6011 InitializeExtensionSyncService();
6012 syncer::FakeSyncChangeProcessor processor;
6013 extension_sync_service()->MergeDataAndStartSyncing(
6015 syncer::SyncDataList(),
6016 scoped_ptr<syncer::SyncChangeProcessor>(
6017 new syncer::FakeSyncChangeProcessor),
6018 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6020 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
6021 EXPECT_TRUE(service()->IsExtensionEnabled(good_crx));
6022 EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
6024 sync_pb::EntitySpecifics specifics;
6025 sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension();
6026 ext_specifics->set_id(good_crx);
6027 ext_specifics->set_enabled(true);
6030 ext_specifics->set_version(
6031 service()->GetInstalledExtension(good_crx)->version()->GetString());
6032 syncer::SyncData sync_data =
6033 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6034 syncer::SyncChange sync_change(FROM_HERE,
6035 syncer::SyncChange::ACTION_UPDATE,
6037 syncer::SyncChangeList list(1);
6038 list[0] = sync_change;
6040 // Should do nothing if extension version == sync version.
6041 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6042 EXPECT_FALSE(service()->updater()->WillCheckSoon());
6045 // Should do nothing if extension version > sync version (but see
6046 // the TODO in ProcessExtensionSyncData).
6048 ext_specifics->set_version("0.0.0.0");
6049 syncer::SyncData sync_data =
6050 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6051 syncer::SyncChange sync_change(FROM_HERE,
6052 syncer::SyncChange::ACTION_UPDATE,
6054 syncer::SyncChangeList list(1);
6055 list[0] = sync_change;
6057 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6058 EXPECT_FALSE(service()->updater()->WillCheckSoon());
6061 // Should kick off an update if extension version < sync version.
6063 ext_specifics->set_version("9.9.9.9");
6064 syncer::SyncData sync_data =
6065 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6066 syncer::SyncChange sync_change(FROM_HERE,
6067 syncer::SyncChange::ACTION_UPDATE,
6069 syncer::SyncChangeList list(1);
6070 list[0] = sync_change;
6072 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6073 EXPECT_TRUE(service()->updater()->WillCheckSoon());
6076 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(good_crx));
6079 TEST_F(ExtensionServiceTest, ProcessSyncDataNotInstalled) {
6080 InitializeExtensionServiceWithUpdater();
6081 InitializeExtensionSyncService();
6082 syncer::FakeSyncChangeProcessor processor;
6083 extension_sync_service()->MergeDataAndStartSyncing(
6085 syncer::SyncDataList(),
6086 scoped_ptr<syncer::SyncChangeProcessor>(
6087 new syncer::FakeSyncChangeProcessor),
6088 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6090 sync_pb::EntitySpecifics specifics;
6091 sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension();
6092 ext_specifics->set_id(good_crx);
6093 ext_specifics->set_enabled(false);
6094 ext_specifics->set_incognito_enabled(true);
6095 ext_specifics->set_update_url("http://www.google.com/");
6096 ext_specifics->set_version("1.2.3.4");
6097 syncer::SyncData sync_data =
6098 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6099 syncer::SyncChange sync_change(FROM_HERE,
6100 syncer::SyncChange::ACTION_UPDATE,
6102 syncer::SyncChangeList list(1);
6103 list[0] = sync_change;
6105 EXPECT_TRUE(service()->IsExtensionEnabled(good_crx));
6106 EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
6107 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6108 EXPECT_TRUE(service()->updater()->WillCheckSoon());
6109 EXPECT_FALSE(service()->IsExtensionEnabled(good_crx));
6110 EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
6112 const extensions::PendingExtensionInfo* info;
6114 (info = service()->pending_extension_manager()->GetById(good_crx)));
6115 EXPECT_EQ(ext_specifics->update_url(), info->update_url().spec());
6116 EXPECT_TRUE(info->is_from_sync());
6117 EXPECT_TRUE(info->install_silently());
6118 EXPECT_EQ(Manifest::INTERNAL, info->install_source());
6119 // TODO(akalin): Figure out a way to test |info.ShouldAllowInstall()|.
6122 TEST_F(ExtensionServiceTest, SupervisedUser_InstallOnlyAllowedByCustodian) {
6123 ExtensionServiceInitParams params = CreateDefaultInitParams();
6124 params.profile_is_supervised = true;
6125 InitializeExtensionService(params);
6127 SupervisedUserService* supervised_user_service =
6128 SupervisedUserServiceFactory::GetForProfile(profile());
6129 GetManagementPolicy()->RegisterProvider(supervised_user_service);
6131 base::FilePath path1 = data_dir().AppendASCII("good.crx");
6132 base::FilePath path2 = data_dir().AppendASCII("good2048.crx");
6133 const Extension* extensions[] = {
6134 InstallCRX(path1, INSTALL_FAILED),
6135 InstallCRX(path2, INSTALL_NEW, Extension::WAS_INSTALLED_BY_CUSTODIAN)
6138 // Only the extension with the "installed by custodian" flag should have been
6139 // installed and enabled.
6140 EXPECT_FALSE(extensions[0]);
6141 ASSERT_TRUE(extensions[1]);
6142 EXPECT_TRUE(registry()->enabled_extensions().Contains(extensions[1]->id()));
6145 TEST_F(ExtensionServiceTest, SupervisedUser_UpdateWithoutPermissionIncrease) {
6146 ExtensionServiceInitParams params = CreateDefaultInitParams();
6147 params.profile_is_supervised = true;
6148 InitializeExtensionService(params);
6150 SupervisedUserService* supervised_user_service =
6151 SupervisedUserServiceFactory::GetForProfile(profile());
6152 GetManagementPolicy()->RegisterProvider(supervised_user_service);
6154 base::FilePath base_path = data_dir().AppendASCII("autoupdate");
6155 base::FilePath pem_path = base_path.AppendASCII("key.pem");
6157 base::FilePath path = base_path.AppendASCII("v1");
6158 const Extension* extension =
6159 PackAndInstallCRX(path, pem_path, INSTALL_NEW,
6160 Extension::WAS_INSTALLED_BY_CUSTODIAN);
6161 // The extension must now be installed and enabled.
6162 ASSERT_TRUE(extension);
6163 ASSERT_TRUE(registry()->enabled_extensions().Contains(extension->id()));
6165 // Save the id, as the extension object will be destroyed during updating.
6166 std::string id = extension->id();
6168 std::string old_version = extension->VersionString();
6170 // Update to a new version.
6171 path = base_path.AppendASCII("v2");
6172 PackCRXAndUpdateExtension(id, path, pem_path, ENABLED);
6174 // The extension should still be there and enabled.
6175 extension = registry()->enabled_extensions().GetByID(id);
6176 ASSERT_TRUE(extension);
6177 // The version should have changed.
6178 EXPECT_NE(extension->VersionString(), old_version);
6181 TEST_F(ExtensionServiceTest, SupervisedUser_UpdateWithPermissionIncrease) {
6182 ExtensionServiceInitParams params = CreateDefaultInitParams();
6183 params.profile_is_supervised = true;
6184 InitializeExtensionService(params);
6186 SupervisedUserService* supervised_user_service =
6187 SupervisedUserServiceFactory::GetForProfile(profile());
6188 GetManagementPolicy()->RegisterProvider(supervised_user_service);
6190 base::FilePath base_path = data_dir().AppendASCII("permissions_increase");
6191 base::FilePath pem_path = base_path.AppendASCII("permissions.pem");
6193 base::FilePath path = base_path.AppendASCII("v1");
6194 const Extension* extension =
6195 PackAndInstallCRX(path, pem_path, INSTALL_NEW,
6196 Extension::WAS_INSTALLED_BY_CUSTODIAN);
6197 // The extension must now be installed and enabled.
6198 ASSERT_TRUE(extension);
6199 ASSERT_TRUE(registry()->enabled_extensions().Contains(extension->id()));
6201 // Save the id, as the extension object will be destroyed during updating.
6202 std::string id = extension->id();
6204 std::string old_version = extension->VersionString();
6206 // Update to a new version with increased permissions.
6207 path = base_path.AppendASCII("v2");
6208 PackCRXAndUpdateExtension(id, path, pem_path, DISABLED);
6210 // The extension should still be there, but disabled.
6211 EXPECT_FALSE(registry()->enabled_extensions().Contains(id));
6212 extension = registry()->disabled_extensions().GetByID(id);
6213 ASSERT_TRUE(extension);
6214 // The version should have changed.
6215 EXPECT_NE(extension->VersionString(), old_version);
6218 TEST_F(ExtensionServiceTest,
6219 SupervisedUser_SyncUninstallByCustodianSkipsPolicy) {
6220 InitializeEmptyExtensionService();
6221 InitializeExtensionSyncService();
6222 extension_sync_service()->MergeDataAndStartSyncing(
6224 syncer::SyncDataList(),
6225 scoped_ptr<syncer::SyncChangeProcessor>(
6226 new syncer::FakeSyncChangeProcessor),
6227 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6229 // Install two extensions.
6230 base::FilePath path1 = data_dir().AppendASCII("good.crx");
6231 base::FilePath path2 = data_dir().AppendASCII("good2048.crx");
6232 const Extension* extensions[] = {
6233 InstallCRX(path1, INSTALL_NEW),
6234 InstallCRX(path2, INSTALL_NEW, Extension::WAS_INSTALLED_BY_CUSTODIAN)
6237 // Add a policy provider that will disallow any changes.
6238 extensions::TestManagementPolicyProvider provider(
6239 extensions::TestManagementPolicyProvider::PROHIBIT_MODIFY_STATUS);
6240 GetManagementPolicy()->RegisterProvider(&provider);
6242 // Create a sync deletion for each extension.
6243 syncer::SyncChangeList change_list;
6244 for (size_t i = 0; i < arraysize(extensions); i++) {
6245 const std::string& id = extensions[i]->id();
6246 sync_pb::EntitySpecifics specifics;
6247 sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension();
6248 ext_specifics->set_id(id);
6249 ext_specifics->set_version("1.0");
6250 ext_specifics->set_installed_by_custodian(
6251 extensions[i]->was_installed_by_custodian());
6252 syncer::SyncData sync_data =
6253 syncer::SyncData::CreateLocalData(id, "Name", specifics);
6254 change_list.push_back(syncer::SyncChange(FROM_HERE,
6255 syncer::SyncChange::ACTION_DELETE,
6259 // Save the extension ids, as uninstalling destroys the Extension instance.
6260 std::string extension_ids[] = {
6261 extensions[0]->id(),
6265 // Now apply the uninstallations.
6266 extension_sync_service()->ProcessSyncChanges(FROM_HERE, change_list);
6268 // Uninstalling the extension without installed_by_custodian should have been
6269 // blocked by policy, so it should still be there.
6270 EXPECT_TRUE(registry()->enabled_extensions().Contains(extension_ids[0]));
6272 // But installed_by_custodian should result in bypassing the policy check.
6274 registry()->GenerateInstalledExtensionsSet()->Contains(extension_ids[1]));
6277 TEST_F(ExtensionServiceTest, InstallPriorityExternalUpdateUrl) {
6278 InitializeEmptyExtensionService();
6280 base::FilePath path = data_dir().AppendASCII("good.crx");
6281 InstallCRX(path, INSTALL_NEW);
6282 ValidatePrefKeyCount(1u);
6283 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
6284 ValidateIntegerPref(good_crx, "location", Manifest::INTERNAL);
6286 extensions::PendingExtensionManager* pending =
6287 service()->pending_extension_manager();
6288 EXPECT_FALSE(pending->IsIdPending(kGoodId));
6290 // Skip install when the location is the same.
6292 service()->OnExternalExtensionUpdateUrlFound(kGoodId,
6294 GURL(kGoodUpdateURL),
6296 Extension::NO_FLAGS,
6298 EXPECT_FALSE(pending->IsIdPending(kGoodId));
6300 // Install when the location has higher priority.
6301 EXPECT_TRUE(service()->OnExternalExtensionUpdateUrlFound(
6304 GURL(kGoodUpdateURL),
6305 Manifest::EXTERNAL_POLICY_DOWNLOAD,
6306 Extension::NO_FLAGS,
6308 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6310 // Try the low priority again. Should be rejected.
6311 EXPECT_FALSE(service()->OnExternalExtensionUpdateUrlFound(
6314 GURL(kGoodUpdateURL),
6315 Manifest::EXTERNAL_PREF_DOWNLOAD,
6316 Extension::NO_FLAGS,
6318 // The existing record should still be present in the pending extension
6320 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6322 pending->Remove(kGoodId);
6324 // Skip install when the location has the same priority as the installed
6327 service()->OnExternalExtensionUpdateUrlFound(kGoodId,
6329 GURL(kGoodUpdateURL),
6331 Extension::NO_FLAGS,
6334 EXPECT_FALSE(pending->IsIdPending(kGoodId));
6337 TEST_F(ExtensionServiceTest, InstallPriorityExternalLocalFile) {
6338 Version older_version("0.1.0.0");
6339 Version newer_version("2.0.0.0");
6341 // We don't want the extension to be installed. A path that doesn't
6342 // point to a valid CRX ensures this.
6343 const base::FilePath kInvalidPathToCrx = base::FilePath();
6345 const int kCreationFlags = 0;
6346 const bool kDontMarkAcknowledged = false;
6348 InitializeEmptyExtensionService();
6350 // The test below uses install source constants to test that
6351 // priority is enforced. It assumes a specific ranking of install
6352 // sources: Registry (EXTERNAL_REGISTRY) overrides external pref
6353 // (EXTERNAL_PREF), and external pref overrides user install (INTERNAL).
6354 // The following assertions verify these assumptions:
6355 ASSERT_EQ(Manifest::EXTERNAL_REGISTRY,
6356 Manifest::GetHigherPriorityLocation(Manifest::EXTERNAL_REGISTRY,
6357 Manifest::EXTERNAL_PREF));
6358 ASSERT_EQ(Manifest::EXTERNAL_REGISTRY,
6359 Manifest::GetHigherPriorityLocation(Manifest::EXTERNAL_REGISTRY,
6360 Manifest::INTERNAL));
6361 ASSERT_EQ(Manifest::EXTERNAL_PREF,
6362 Manifest::GetHigherPriorityLocation(Manifest::EXTERNAL_PREF,
6363 Manifest::INTERNAL));
6365 extensions::PendingExtensionManager* pending =
6366 service()->pending_extension_manager();
6367 EXPECT_FALSE(pending->IsIdPending(kGoodId));
6370 // Simulate an external source adding the extension as INTERNAL.
6371 content::WindowedNotificationObserver observer(
6372 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
6373 content::NotificationService::AllSources());
6374 EXPECT_TRUE(service()->OnExternalExtensionFileFound(kGoodId,
6379 kDontMarkAcknowledged));
6380 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6382 VerifyCrxInstall(kInvalidPathToCrx, INSTALL_FAILED);
6386 // Simulate an external source adding the extension as EXTERNAL_PREF.
6387 content::WindowedNotificationObserver observer(
6388 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
6389 content::NotificationService::AllSources());
6390 EXPECT_TRUE(service()->OnExternalExtensionFileFound(kGoodId,
6393 Manifest::EXTERNAL_PREF,
6395 kDontMarkAcknowledged));
6396 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6398 VerifyCrxInstall(kInvalidPathToCrx, INSTALL_FAILED);
6401 // Simulate an external source adding as EXTERNAL_PREF again.
6402 // This is rejected because the version and the location are the same as
6403 // the previous installation, which is still pending.
6404 EXPECT_FALSE(service()->OnExternalExtensionFileFound(kGoodId,
6407 Manifest::EXTERNAL_PREF,
6409 kDontMarkAcknowledged));
6410 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6412 // Try INTERNAL again. Should fail.
6413 EXPECT_FALSE(service()->OnExternalExtensionFileFound(kGoodId,
6418 kDontMarkAcknowledged));
6419 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6422 // Now the registry adds the extension.
6423 content::WindowedNotificationObserver observer(
6424 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
6425 content::NotificationService::AllSources());
6427 service()->OnExternalExtensionFileFound(kGoodId,
6430 Manifest::EXTERNAL_REGISTRY,
6432 kDontMarkAcknowledged));
6433 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6435 VerifyCrxInstall(kInvalidPathToCrx, INSTALL_FAILED);
6438 // Registry outranks both external pref and internal, so both fail.
6439 EXPECT_FALSE(service()->OnExternalExtensionFileFound(kGoodId,
6442 Manifest::EXTERNAL_PREF,
6444 kDontMarkAcknowledged));
6445 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6447 EXPECT_FALSE(service()->OnExternalExtensionFileFound(kGoodId,
6452 kDontMarkAcknowledged));
6453 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6455 pending->Remove(kGoodId);
6457 // Install the extension.
6458 base::FilePath path = data_dir().AppendASCII("good.crx");
6459 const Extension* ext = InstallCRX(path, INSTALL_NEW);
6460 ValidatePrefKeyCount(1u);
6461 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
6462 ValidateIntegerPref(good_crx, "location", Manifest::INTERNAL);
6464 // Now test the logic of OnExternalExtensionFileFound() when the extension
6465 // being added is already installed.
6467 // Tests assume |older_version| is less than the installed version, and
6468 // |newer_version| is greater. Verify this:
6469 ASSERT_TRUE(older_version.IsOlderThan(ext->VersionString()));
6470 ASSERT_TRUE(ext->version()->IsOlderThan(newer_version.GetString()));
6472 // An external install for the same location should fail if the version is
6473 // older, or the same, and succeed if the version is newer.
6475 // Older than the installed version...
6476 EXPECT_FALSE(service()->OnExternalExtensionFileFound(kGoodId,
6481 kDontMarkAcknowledged));
6482 EXPECT_FALSE(pending->IsIdPending(kGoodId));
6484 // Same version as the installed version...
6485 EXPECT_FALSE(service()->OnExternalExtensionFileFound(kGoodId,
6490 kDontMarkAcknowledged));
6491 EXPECT_FALSE(pending->IsIdPending(kGoodId));
6493 // Newer than the installed version...
6494 EXPECT_TRUE(service()->OnExternalExtensionFileFound(kGoodId,
6499 kDontMarkAcknowledged));
6500 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6502 // An external install for a higher priority install source should succeed
6503 // if the version is greater. |older_version| is not...
6504 EXPECT_FALSE(service()->OnExternalExtensionFileFound(kGoodId,
6507 Manifest::EXTERNAL_PREF,
6509 kDontMarkAcknowledged));
6510 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6512 // |newer_version| is newer.
6513 EXPECT_TRUE(service()->OnExternalExtensionFileFound(kGoodId,
6516 Manifest::EXTERNAL_PREF,
6518 kDontMarkAcknowledged));
6519 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6521 // An external install for an even higher priority install source should
6522 // succeed if the version is greater.
6524 service()->OnExternalExtensionFileFound(kGoodId,
6527 Manifest::EXTERNAL_REGISTRY,
6529 kDontMarkAcknowledged));
6530 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6532 // Because EXTERNAL_PREF is a lower priority source than EXTERNAL_REGISTRY,
6533 // adding from external pref will now fail.
6534 EXPECT_FALSE(service()->OnExternalExtensionFileFound(kGoodId,
6537 Manifest::EXTERNAL_PREF,
6539 kDontMarkAcknowledged));
6540 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6543 TEST_F(ExtensionServiceTest, ConcurrentExternalLocalFile) {
6544 Version kVersion123("1.2.3");
6545 Version kVersion124("1.2.4");
6546 Version kVersion125("1.2.5");
6547 const base::FilePath kInvalidPathToCrx = base::FilePath();
6548 const int kCreationFlags = 0;
6549 const bool kDontMarkAcknowledged = false;
6551 InitializeEmptyExtensionService();
6553 extensions::PendingExtensionManager* pending =
6554 service()->pending_extension_manager();
6555 EXPECT_FALSE(pending->IsIdPending(kGoodId));
6557 // An external provider starts installing from a local crx.
6558 EXPECT_TRUE(service()->OnExternalExtensionFileFound(kGoodId,
6561 Manifest::EXTERNAL_PREF,
6563 kDontMarkAcknowledged));
6564 const extensions::PendingExtensionInfo* info;
6565 EXPECT_TRUE((info = pending->GetById(kGoodId)));
6566 EXPECT_TRUE(info->version().IsValid());
6567 EXPECT_TRUE(info->version().Equals(kVersion123));
6569 // Adding a newer version overrides the currently pending version.
6570 EXPECT_TRUE(service()->OnExternalExtensionFileFound(kGoodId,
6573 Manifest::EXTERNAL_PREF,
6575 kDontMarkAcknowledged));
6576 EXPECT_TRUE((info = pending->GetById(kGoodId)));
6577 EXPECT_TRUE(info->version().IsValid());
6578 EXPECT_TRUE(info->version().Equals(kVersion124));
6580 // Adding an older version fails.
6581 EXPECT_FALSE(service()->OnExternalExtensionFileFound(kGoodId,
6584 Manifest::EXTERNAL_PREF,
6586 kDontMarkAcknowledged));
6587 EXPECT_TRUE((info = pending->GetById(kGoodId)));
6588 EXPECT_TRUE(info->version().IsValid());
6589 EXPECT_TRUE(info->version().Equals(kVersion124));
6591 // Adding an older version fails even when coming from a higher-priority
6594 service()->OnExternalExtensionFileFound(kGoodId,
6597 Manifest::EXTERNAL_REGISTRY,
6599 kDontMarkAcknowledged));
6600 EXPECT_TRUE((info = pending->GetById(kGoodId)));
6601 EXPECT_TRUE(info->version().IsValid());
6602 EXPECT_TRUE(info->version().Equals(kVersion124));
6604 // Adding the latest version from the webstore overrides a specific version.
6605 GURL kUpdateUrl("http://example.com/update");
6606 EXPECT_TRUE(service()->OnExternalExtensionUpdateUrlFound(
6610 Manifest::EXTERNAL_POLICY_DOWNLOAD,
6611 Extension::NO_FLAGS,
6613 EXPECT_TRUE((info = pending->GetById(kGoodId)));
6614 EXPECT_FALSE(info->version().IsValid());
6617 // This makes sure we can package and install CRX files that use whitelisted
6619 TEST_F(ExtensionServiceTest, InstallWhitelistedExtension) {
6620 std::string test_id = "hdkklepkcpckhnpgjnmbdfhehckloojk";
6621 CommandLine::ForCurrentProcess()->AppendSwitchASCII(
6622 extensions::switches::kWhitelistedExtensionID, test_id);
6624 InitializeEmptyExtensionService();
6625 base::FilePath path = data_dir().AppendASCII("permissions");
6626 base::FilePath pem_path = path
6627 .AppendASCII("whitelist.pem");
6629 .AppendASCII("whitelist");
6631 const Extension* extension = PackAndInstallCRX(path, pem_path, INSTALL_NEW);
6632 EXPECT_EQ(0u, GetErrors().size());
6633 ASSERT_EQ(1u, registry()->enabled_extensions().size());
6634 EXPECT_EQ(test_id, extension->id());
6637 // Test that when multiple sources try to install an extension,
6638 // we consistently choose the right one. To make tests easy to read,
6639 // methods that fake requests to install crx files in several ways
6641 class ExtensionSourcePriorityTest : public ExtensionServiceTest {
6643 virtual void SetUp() {
6644 ExtensionServiceTest::SetUp();
6646 // All tests use a single extension. Put the id and path in member vars
6647 // that all methods can read.
6649 crx_path_ = data_dir().AppendASCII("good.crx");
6652 // Fake an external source adding a URL to fetch an extension from.
6653 bool AddPendingExternalPrefUrl() {
6654 return service()->pending_extension_manager()->AddFromExternalUpdateUrl(
6658 Manifest::EXTERNAL_PREF_DOWNLOAD,
6659 Extension::NO_FLAGS,
6663 // Fake an external file from external_extensions.json.
6664 bool AddPendingExternalPrefFileInstall() {
6665 Version version("1.0.0.0");
6667 return service()->OnExternalExtensionFileFound(crx_id_,
6670 Manifest::EXTERNAL_PREF,
6671 Extension::NO_FLAGS,
6675 // Fake a request from sync to install an extension.
6676 bool AddPendingSyncInstall() {
6677 return service()->pending_extension_manager()->AddFromSync(
6679 GURL(kGoodUpdateURL),
6681 kGoodInstallSilently,
6683 kGoodInstalledByCustodian);
6686 // Fake a policy install.
6687 bool AddPendingPolicyInstall() {
6688 // Get path to the CRX with id |kGoodId|.
6689 return service()->OnExternalExtensionUpdateUrlFound(
6693 Manifest::EXTERNAL_POLICY_DOWNLOAD,
6694 Extension::NO_FLAGS,
6698 // Get the install source of a pending extension.
6699 Manifest::Location GetPendingLocation() {
6700 const extensions::PendingExtensionInfo* info;
6702 (info = service()->pending_extension_manager()->GetById(crx_id_)));
6703 return info->install_source();
6706 // Is an extension pending from a sync request?
6707 bool GetPendingIsFromSync() {
6708 const extensions::PendingExtensionInfo* info;
6710 (info = service()->pending_extension_manager()->GetById(crx_id_)));
6711 return info->is_from_sync();
6714 // Is the CRX id these tests use pending?
6715 bool IsCrxPending() {
6716 return service()->pending_extension_manager()->IsIdPending(crx_id_);
6719 // Is an extension installed?
6720 bool IsCrxInstalled() {
6721 return (service()->GetExtensionById(crx_id_, true) != NULL);
6725 // All tests use a single extension. Making the id and path member
6726 // vars avoids pasing the same argument to every method.
6727 std::string crx_id_;
6728 base::FilePath crx_path_;
6731 // Test that a pending request for installation of an external CRX from
6732 // an update URL overrides a pending request to install the same extension
6734 TEST_F(ExtensionSourcePriorityTest, PendingExternalFileOverSync) {
6735 InitializeEmptyExtensionService();
6737 ASSERT_FALSE(IsCrxInstalled());
6739 // Install pending extension from sync.
6740 content::WindowedNotificationObserver observer(
6741 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
6742 content::NotificationService::AllSources());
6743 EXPECT_TRUE(AddPendingSyncInstall());
6744 ASSERT_EQ(Manifest::INTERNAL, GetPendingLocation());
6745 EXPECT_TRUE(GetPendingIsFromSync());
6746 ASSERT_FALSE(IsCrxInstalled());
6748 // Install pending as external prefs json would.
6749 AddPendingExternalPrefFileInstall();
6750 ASSERT_EQ(Manifest::EXTERNAL_PREF, GetPendingLocation());
6751 ASSERT_FALSE(IsCrxInstalled());
6753 // Another request from sync should be ignored.
6754 EXPECT_FALSE(AddPendingSyncInstall());
6755 ASSERT_EQ(Manifest::EXTERNAL_PREF, GetPendingLocation());
6756 ASSERT_FALSE(IsCrxInstalled());
6759 VerifyCrxInstall(crx_path_, INSTALL_NEW);
6760 ASSERT_TRUE(IsCrxInstalled());
6763 // Test that an install of an external CRX from an update overrides
6764 // an install of the same extension from sync.
6765 TEST_F(ExtensionSourcePriorityTest, PendingExternalUrlOverSync) {
6766 InitializeEmptyExtensionService();
6767 ASSERT_FALSE(IsCrxInstalled());
6769 EXPECT_TRUE(AddPendingSyncInstall());
6770 ASSERT_EQ(Manifest::INTERNAL, GetPendingLocation());
6771 EXPECT_TRUE(GetPendingIsFromSync());
6772 ASSERT_FALSE(IsCrxInstalled());
6774 ASSERT_TRUE(AddPendingExternalPrefUrl());
6775 ASSERT_EQ(Manifest::EXTERNAL_PREF_DOWNLOAD, GetPendingLocation());
6776 EXPECT_FALSE(GetPendingIsFromSync());
6777 ASSERT_FALSE(IsCrxInstalled());
6779 EXPECT_FALSE(AddPendingSyncInstall());
6780 ASSERT_EQ(Manifest::EXTERNAL_PREF_DOWNLOAD, GetPendingLocation());
6781 EXPECT_FALSE(GetPendingIsFromSync());
6782 ASSERT_FALSE(IsCrxInstalled());
6785 // Test that an external install request stops sync from installing
6786 // the same extension.
6787 TEST_F(ExtensionSourcePriorityTest, InstallExternalBlocksSyncRequest) {
6788 InitializeEmptyExtensionService();
6789 ASSERT_FALSE(IsCrxInstalled());
6791 // External prefs starts an install.
6792 AddPendingExternalPrefFileInstall();
6794 // Crx installer was made, but has not yet run.
6795 ASSERT_FALSE(IsCrxInstalled());
6797 // Before the CRX installer runs, Sync requests that the same extension
6798 // be installed. Should fail, because an external source is pending.
6799 content::WindowedNotificationObserver observer(
6800 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
6801 content::NotificationService::AllSources());
6802 ASSERT_FALSE(AddPendingSyncInstall());
6804 // Wait for the external source to install.
6806 VerifyCrxInstall(crx_path_, INSTALL_NEW);
6807 ASSERT_TRUE(IsCrxInstalled());
6809 // Now that the extension is installed, sync request should fail
6810 // because the extension is already installed.
6811 ASSERT_FALSE(AddPendingSyncInstall());
6814 // Test that installing an external extension displays a GlobalError.
6815 TEST_F(ExtensionServiceTest, ExternalInstallGlobalError) {
6816 FeatureSwitch::ScopedOverride prompt(
6817 FeatureSwitch::prompt_for_external_extensions(), true);
6819 InitializeEmptyExtensionService();
6820 MockExtensionProvider* provider =
6821 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF);
6822 AddMockExternalProvider(provider);
6824 service()->external_install_manager()->UpdateExternalExtensionAlert();
6825 // Should return false, meaning there aren't any extensions that the user
6826 // needs to know about.
6828 service()->external_install_manager()->HasExternalInstallError());
6830 // This is a normal extension, installed normally.
6831 // This should NOT trigger an alert.
6832 service()->set_extensions_enabled(true);
6833 base::FilePath path = data_dir().AppendASCII("good.crx");
6834 InstallCRX(path, INSTALL_NEW);
6836 service()->CheckForExternalUpdates();
6837 base::RunLoop().RunUntilIdle();
6839 service()->external_install_manager()->HasExternalInstallError());
6841 // A hosted app, installed externally.
6842 // This should NOT trigger an alert.
6843 provider->UpdateOrAddExtension(
6844 hosted_app, "1.0.0.0", data_dir().AppendASCII("hosted_app.crx"));
6846 content::WindowedNotificationObserver observer(
6847 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
6848 content::NotificationService::AllSources());
6849 service()->CheckForExternalUpdates();
6852 service()->external_install_manager()->HasExternalInstallError());
6854 // Another normal extension, but installed externally.
6855 // This SHOULD trigger an alert.
6856 provider->UpdateOrAddExtension(
6857 page_action, "1.0.0.0", data_dir().AppendASCII("page_action.crx"));
6859 content::WindowedNotificationObserver observer2(
6860 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
6861 content::NotificationService::AllSources());
6862 service()->CheckForExternalUpdates();
6864 EXPECT_TRUE(service()->external_install_manager()->HasExternalInstallError());
6867 // Test that external extensions are initially disabled, and that enabling
6868 // them clears the prompt.
6869 TEST_F(ExtensionServiceTest, ExternalInstallInitiallyDisabled) {
6870 FeatureSwitch::ScopedOverride prompt(
6871 FeatureSwitch::prompt_for_external_extensions(), true);
6873 InitializeEmptyExtensionService();
6874 MockExtensionProvider* provider =
6875 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF);
6876 AddMockExternalProvider(provider);
6878 provider->UpdateOrAddExtension(
6879 page_action, "1.0.0.0", data_dir().AppendASCII("page_action.crx"));
6881 content::WindowedNotificationObserver observer(
6882 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
6883 content::NotificationService::AllSources());
6884 service()->CheckForExternalUpdates();
6886 EXPECT_TRUE(service()->external_install_manager()->HasExternalInstallError());
6887 EXPECT_FALSE(service()->IsExtensionEnabled(page_action));
6889 const Extension* extension =
6890 registry()->disabled_extensions().GetByID(page_action);
6891 EXPECT_TRUE(extension);
6892 EXPECT_EQ(page_action, extension->id());
6894 service()->EnableExtension(page_action);
6896 service()->external_install_manager()->HasExternalInstallError());
6897 EXPECT_TRUE(service()->IsExtensionEnabled(page_action));
6900 // Test that installing multiple external extensions works.
6901 // Flaky on windows; http://crbug.com/295757 .
6903 #define MAYBE_ExternalInstallMultiple DISABLED_ExternalInstallMultiple
6905 #define MAYBE_ExternalInstallMultiple ExternalInstallMultiple
6907 TEST_F(ExtensionServiceTest, MAYBE_ExternalInstallMultiple) {
6908 FeatureSwitch::ScopedOverride prompt(
6909 FeatureSwitch::prompt_for_external_extensions(), true);
6911 InitializeEmptyExtensionService();
6912 MockExtensionProvider* provider =
6913 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF);
6914 AddMockExternalProvider(provider);
6916 provider->UpdateOrAddExtension(
6917 page_action, "1.0.0.0", data_dir().AppendASCII("page_action.crx"));
6918 provider->UpdateOrAddExtension(
6919 good_crx, "1.0.0.0", data_dir().AppendASCII("good.crx"));
6920 provider->UpdateOrAddExtension(
6921 theme_crx, "2.0", data_dir().AppendASCII("theme.crx"));
6924 content::WindowedNotificationObserver observer(
6925 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
6926 base::Bind(&WaitForCountNotificationsCallback, &count));
6927 service()->CheckForExternalUpdates();
6929 EXPECT_TRUE(service()->external_install_manager()->HasExternalInstallError());
6930 EXPECT_FALSE(service()->IsExtensionEnabled(page_action));
6931 EXPECT_FALSE(service()->IsExtensionEnabled(good_crx));
6932 EXPECT_FALSE(service()->IsExtensionEnabled(theme_crx));
6934 service()->EnableExtension(page_action);
6935 EXPECT_TRUE(service()->external_install_manager()->HasExternalInstallError());
6936 EXPECT_FALSE(service()
6937 ->external_install_manager()
6938 ->HasExternalInstallBubbleForTesting());
6940 service()->EnableExtension(theme_crx);
6941 EXPECT_TRUE(service()->external_install_manager()->HasExternalInstallError());
6942 EXPECT_FALSE(service()
6943 ->external_install_manager()
6944 ->HasExternalInstallBubbleForTesting());
6946 service()->EnableExtension(good_crx);
6948 service()->external_install_manager()->HasExternalInstallError());
6949 EXPECT_FALSE(service()
6950 ->external_install_manager()
6951 ->HasExternalInstallBubbleForTesting());
6954 // Test that there is a bubble for external extensions that update
6955 // from the webstore if the profile is not new.
6956 TEST_F(ExtensionServiceTest, ExternalInstallUpdatesFromWebstoreOldProfile) {
6957 FeatureSwitch::ScopedOverride prompt(
6958 FeatureSwitch::prompt_for_external_extensions(), true);
6960 // This sets up the ExtensionPrefs used by our ExtensionService to be
6962 ExtensionServiceInitParams params = CreateDefaultInitParams();
6963 params.is_first_run = false;
6964 InitializeExtensionService(params);
6966 base::FilePath crx_path = temp_dir().path().AppendASCII("webstore.crx");
6967 PackCRX(data_dir().AppendASCII("update_from_webstore"),
6968 data_dir().AppendASCII("update_from_webstore.pem"),
6971 MockExtensionProvider* provider =
6972 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF);
6973 AddMockExternalProvider(provider);
6974 provider->UpdateOrAddExtension(updates_from_webstore, "1", crx_path);
6976 content::WindowedNotificationObserver observer(
6977 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
6978 content::NotificationService::AllSources());
6979 service()->CheckForExternalUpdates();
6981 EXPECT_TRUE(service()->external_install_manager()->HasExternalInstallError());
6982 EXPECT_TRUE(service()
6983 ->external_install_manager()
6984 ->HasExternalInstallBubbleForTesting());
6985 EXPECT_FALSE(service()->IsExtensionEnabled(updates_from_webstore));
6988 // Test that there is no bubble for external extensions if the profile is new.
6989 TEST_F(ExtensionServiceTest, ExternalInstallUpdatesFromWebstoreNewProfile) {
6990 FeatureSwitch::ScopedOverride prompt(
6991 FeatureSwitch::prompt_for_external_extensions(), true);
6993 InitializeEmptyExtensionService();
6995 base::FilePath crx_path = temp_dir().path().AppendASCII("webstore.crx");
6996 PackCRX(data_dir().AppendASCII("update_from_webstore"),
6997 data_dir().AppendASCII("update_from_webstore.pem"),
7000 MockExtensionProvider* provider =
7001 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF);
7002 AddMockExternalProvider(provider);
7003 provider->UpdateOrAddExtension(updates_from_webstore, "1", crx_path);
7005 content::WindowedNotificationObserver observer(
7006 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
7007 content::NotificationService::AllSources());
7008 service()->CheckForExternalUpdates();
7010 EXPECT_TRUE(service()->external_install_manager()->HasExternalInstallError());
7011 EXPECT_FALSE(service()
7012 ->external_install_manager()
7013 ->HasExternalInstallBubbleForTesting());
7014 EXPECT_FALSE(service()->IsExtensionEnabled(updates_from_webstore));
7017 // Test that clicking to remove the extension on an external install warning
7018 // uninstalls the extension.
7019 TEST_F(ExtensionServiceTest, ExternalInstallClickToRemove) {
7020 FeatureSwitch::ScopedOverride prompt(
7021 FeatureSwitch::prompt_for_external_extensions(), true);
7023 ExtensionServiceInitParams params = CreateDefaultInitParams();
7024 params.is_first_run = false;
7025 InitializeExtensionService(params);
7027 base::FilePath crx_path = temp_dir().path().AppendASCII("webstore.crx");
7028 PackCRX(data_dir().AppendASCII("update_from_webstore"),
7029 data_dir().AppendASCII("update_from_webstore.pem"),
7032 MockExtensionProvider* provider =
7033 new MockExtensionProvider(service_, Manifest::EXTERNAL_PREF);
7034 AddMockExternalProvider(provider);
7035 provider->UpdateOrAddExtension(updates_from_webstore, "1", crx_path);
7037 content::WindowedNotificationObserver observer(
7038 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
7039 content::NotificationService::AllSources());
7040 service_->CheckForExternalUpdates();
7042 EXPECT_TRUE(service_->external_install_manager()->HasExternalInstallError());
7044 // We check both enabled and disabled, since these are "eventually exclusive"
7046 EXPECT_TRUE(registry()->disabled_extensions().GetByID(updates_from_webstore));
7047 EXPECT_FALSE(registry()->enabled_extensions().GetByID(updates_from_webstore));
7049 // Click the negative response.
7050 service_->external_install_manager()->error_for_testing()->InstallUIAbort(
7052 // The Extension should be uninstalled.
7053 EXPECT_FALSE(registry()->GetExtensionById(updates_from_webstore,
7054 ExtensionRegistry::EVERYTHING));
7055 // The error should be removed.
7056 EXPECT_FALSE(service_->external_install_manager()->HasExternalInstallError());
7059 // Test that clicking to keep the extension on an external install warning
7060 // re-enables the extension.
7061 TEST_F(ExtensionServiceTest, ExternalInstallClickToKeep) {
7062 FeatureSwitch::ScopedOverride prompt(
7063 FeatureSwitch::prompt_for_external_extensions(), true);
7065 ExtensionServiceInitParams params = CreateDefaultInitParams();
7066 params.is_first_run = false;
7067 InitializeExtensionService(params);
7069 base::FilePath crx_path = temp_dir().path().AppendASCII("webstore.crx");
7070 PackCRX(data_dir().AppendASCII("update_from_webstore"),
7071 data_dir().AppendASCII("update_from_webstore.pem"),
7074 MockExtensionProvider* provider =
7075 new MockExtensionProvider(service_, Manifest::EXTERNAL_PREF);
7076 AddMockExternalProvider(provider);
7077 provider->UpdateOrAddExtension(updates_from_webstore, "1", crx_path);
7079 content::WindowedNotificationObserver observer(
7080 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
7081 content::NotificationService::AllSources());
7082 service_->CheckForExternalUpdates();
7084 EXPECT_TRUE(service_->external_install_manager()->HasExternalInstallError());
7086 // We check both enabled and disabled, since these are "eventually exclusive"
7088 EXPECT_TRUE(registry()->disabled_extensions().GetByID(updates_from_webstore));
7089 EXPECT_FALSE(registry()->enabled_extensions().GetByID(updates_from_webstore));
7091 // Accept the extension.
7092 service_->external_install_manager()->error_for_testing()->InstallUIProceed();
7094 // It should be enabled again.
7095 EXPECT_TRUE(registry()->enabled_extensions().GetByID(updates_from_webstore));
7097 registry()->disabled_extensions().GetByID(updates_from_webstore));
7099 // The error should be removed.
7100 EXPECT_FALSE(service_->external_install_manager()->HasExternalInstallError());
7103 TEST_F(ExtensionServiceTest, InstallBlacklistedExtension) {
7104 InitializeEmptyExtensionService();
7106 scoped_refptr<Extension> extension = extensions::ExtensionBuilder()
7107 .SetManifest(extensions::DictionaryBuilder()
7108 .Set("name", "extension")
7109 .Set("version", "1.0")
7110 .Set("manifest_version", 2).Build())
7112 ASSERT_TRUE(extension.get());
7113 const std::string& id = extension->id();
7115 std::set<std::string> id_set;
7117 extensions::ExtensionNotificationObserver notifications(
7118 content::NotificationService::AllSources(), id_set);
7120 // Installation should be allowed but the extension should never have been
7121 // loaded and it should be blacklisted in prefs.
7122 service()->OnExtensionInstalled(
7124 syncer::StringOrdinal(),
7125 (extensions::kInstallFlagIsBlacklistedForMalware |
7126 extensions::kInstallFlagInstallImmediately));
7127 base::RunLoop().RunUntilIdle();
7129 // Extension was installed but not loaded.
7130 EXPECT_TRUE(notifications.CheckNotifications(
7131 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED));
7132 EXPECT_TRUE(service()->GetInstalledExtension(id));
7134 EXPECT_FALSE(registry()->enabled_extensions().Contains(id));
7135 EXPECT_TRUE(registry()->blacklisted_extensions().Contains(id));
7137 EXPECT_TRUE(ExtensionPrefs::Get(profile())->IsExtensionBlacklisted(id));
7139 ExtensionPrefs::Get(profile())->IsBlacklistedExtensionAcknowledged(id));
7142 // Tests a profile being destroyed correctly disables extensions.
7143 TEST_F(ExtensionServiceTest, DestroyingProfileClearsExtensions) {
7144 InitializeEmptyExtensionService();
7146 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
7147 EXPECT_NE(UnloadedExtensionInfo::REASON_PROFILE_SHUTDOWN, unloaded_reason_);
7148 EXPECT_EQ(1u, registry()->enabled_extensions().size());
7149 EXPECT_EQ(0u, registry()->disabled_extensions().size());
7150 EXPECT_EQ(0u, registry()->terminated_extensions().size());
7151 EXPECT_EQ(0u, registry()->blacklisted_extensions().size());
7153 service()->Observe(chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED,
7154 content::Source<Profile>(profile()),
7155 content::NotificationService::NoDetails());
7156 EXPECT_EQ(UnloadedExtensionInfo::REASON_PROFILE_SHUTDOWN, unloaded_reason_);
7157 EXPECT_EQ(0u, registry()->enabled_extensions().size());
7158 EXPECT_EQ(0u, registry()->disabled_extensions().size());
7159 EXPECT_EQ(0u, registry()->terminated_extensions().size());
7160 EXPECT_EQ(0u, registry()->blacklisted_extensions().size());