Revert of Add button to add new FSP services to Files app. (patchset #8 id:140001...
[chromium-blink-merge.git] / chrome / browser / extensions / extension_service_unittest.cc
blobba02841a42b11295310c78fbba2a9a1595008ce3
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.
5 #include <algorithm>
6 #include <set>
7 #include <vector>
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/files/file_enumerator.h"
14 #include "base/files/file_util.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_management_test_util.h"
41 #include "chrome/browser/extensions/extension_notification_observer.h"
42 #include "chrome/browser/extensions/extension_service.h"
43 #include "chrome/browser/extensions/extension_service_test_base.h"
44 #include "chrome/browser/extensions/extension_special_storage_policy.h"
45 #include "chrome/browser/extensions/extension_sync_data.h"
46 #include "chrome/browser/extensions/extension_sync_service.h"
47 #include "chrome/browser/extensions/extension_util.h"
48 #include "chrome/browser/extensions/external_install_error.h"
49 #include "chrome/browser/extensions/external_install_manager.h"
50 #include "chrome/browser/extensions/external_policy_loader.h"
51 #include "chrome/browser/extensions/external_pref_loader.h"
52 #include "chrome/browser/extensions/external_provider_impl.h"
53 #include "chrome/browser/extensions/fake_safe_browsing_database_manager.h"
54 #include "chrome/browser/extensions/installed_loader.h"
55 #include "chrome/browser/extensions/pack_extension_job.h"
56 #include "chrome/browser/extensions/pending_extension_info.h"
57 #include "chrome/browser/extensions/pending_extension_manager.h"
58 #include "chrome/browser/extensions/permissions_updater.h"
59 #include "chrome/browser/extensions/test_blacklist.h"
60 #include "chrome/browser/extensions/test_extension_system.h"
61 #include "chrome/browser/extensions/unpacked_installer.h"
62 #include "chrome/browser/extensions/updater/extension_updater.h"
63 #include "chrome/browser/prefs/pref_service_syncable.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/pref_names.h"
72 #include "chrome/common/url_constants.h"
73 #include "chrome/test/base/scoped_browser_locale.h"
74 #include "chrome/test/base/testing_pref_service_syncable.h"
75 #include "chrome/test/base/testing_profile.h"
76 #include "components/crx_file/id_util.h"
77 #include "components/pref_registry/pref_registry_syncable.h"
78 #include "content/public/browser/dom_storage_context.h"
79 #include "content/public/browser/gpu_data_manager.h"
80 #include "content/public/browser/indexed_db_context.h"
81 #include "content/public/browser/notification_registrar.h"
82 #include "content/public/browser/notification_service.h"
83 #include "content/public/browser/plugin_service.h"
84 #include "content/public/browser/render_process_host.h"
85 #include "content/public/browser/storage_partition.h"
86 #include "content/public/common/content_constants.h"
87 #include "content/public/test/test_utils.h"
88 #include "extensions/browser/extension_prefs.h"
89 #include "extensions/browser/extension_registry.h"
90 #include "extensions/browser/extension_system.h"
91 #include "extensions/browser/external_provider_interface.h"
92 #include "extensions/browser/install_flag.h"
93 #include "extensions/browser/management_policy.h"
94 #include "extensions/browser/test_management_policy.h"
95 #include "extensions/browser/uninstall_reason.h"
96 #include "extensions/common/constants.h"
97 #include "extensions/common/extension.h"
98 #include "extensions/common/extension_builder.h"
99 #include "extensions/common/extension_l10n_util.h"
100 #include "extensions/common/extension_resource.h"
101 #include "extensions/common/feature_switch.h"
102 #include "extensions/common/manifest_constants.h"
103 #include "extensions/common/manifest_handlers/background_info.h"
104 #include "extensions/common/manifest_handlers/permissions_parser.h"
105 #include "extensions/common/manifest_url_handlers.h"
106 #include "extensions/common/permissions/permission_set.h"
107 #include "extensions/common/permissions/permissions_data.h"
108 #include "extensions/common/switches.h"
109 #include "extensions/common/url_pattern.h"
110 #include "extensions/common/value_builder.h"
111 #include "gpu/config/gpu_info.h"
112 #include "grit/browser_resources.h"
113 #include "grit/generated_resources.h"
114 #include "net/cookies/canonical_cookie.h"
115 #include "net/cookies/cookie_monster.h"
116 #include "net/cookies/cookie_options.h"
117 #include "net/url_request/url_request_context.h"
118 #include "net/url_request/url_request_context_getter.h"
119 #include "storage/browser/database/database_tracker.h"
120 #include "storage/browser/quota/quota_manager.h"
121 #include "storage/common/database/database_identifier.h"
122 #include "sync/api/fake_sync_change_processor.h"
123 #include "sync/api/string_ordinal.h"
124 #include "sync/api/sync_data.h"
125 #include "sync/api/sync_error_factory.h"
126 #include "sync/api/sync_error_factory_mock.h"
127 #include "sync/api/syncable_service.h"
128 #include "sync/protocol/app_specifics.pb.h"
129 #include "sync/protocol/extension_specifics.pb.h"
130 #include "sync/protocol/sync.pb.h"
131 #include "testing/gtest/include/gtest/gtest.h"
132 #include "testing/platform_test.h"
133 #include "ui/base/l10n/l10n_util.h"
134 #include "url/gurl.h"
136 #if defined(ENABLE_SUPERVISED_USERS)
137 #include "chrome/browser/supervised_user/permission_request_creator.h"
138 #include "chrome/browser/supervised_user/supervised_user_service.h"
139 #include "chrome/browser/supervised_user/supervised_user_service_factory.h"
140 #endif
142 #if defined(OS_CHROMEOS)
143 #include "chrome/browser/chromeos/login/users/scoped_test_user_manager.h"
144 #include "chrome/browser/chromeos/settings/cros_settings.h"
145 #include "chrome/browser/chromeos/settings/device_settings_service.h"
146 #endif
148 // The blacklist tests rely on safe browsing.
149 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
150 #define ENABLE_BLACKLIST_TESTS
151 #endif
153 using base::DictionaryValue;
154 using base::ListValue;
155 using base::Value;
156 using content::BrowserContext;
157 using content::BrowserThread;
158 using content::DOMStorageContext;
159 using content::IndexedDBContext;
160 using content::PluginService;
161 using extensions::APIPermission;
162 using extensions::APIPermissionSet;
163 using extensions::AppSorting;
164 using extensions::AppSyncData;
165 using extensions::Blacklist;
166 using extensions::CrxInstaller;
167 using extensions::Extension;
168 using extensions::ExtensionCreator;
169 using extensions::ExtensionPrefs;
170 using extensions::ExtensionRegistry;
171 using extensions::ExtensionResource;
172 using extensions::ExtensionSyncData;
173 using extensions::ExtensionSystem;
174 using extensions::FakeSafeBrowsingDatabaseManager;
175 using extensions::FeatureSwitch;
176 using extensions::Manifest;
177 using extensions::PermissionSet;
178 using extensions::TestExtensionSystem;
179 using extensions::UnloadedExtensionInfo;
180 using extensions::URLPatternSet;
182 namespace keys = extensions::manifest_keys;
184 namespace {
186 // Extension ids used during testing.
187 const char good0[] = "behllobkkfkfnphdnhnkndlbkcpglgmj";
188 const char good1[] = "hpiknbiabeeppbpihjehijgoemciehgk";
189 const char good2[] = "bjafgdebaacbbbecmhlhpofkepfkgcpa";
190 const char all_zero[] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
191 const char good2048[] = "nmgjhmhbleinmjpbdhgajfjkbijcmgbh";
192 const char good_crx[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
193 const char hosted_app[] = "kbmnembihfiondgfjekmnmcbddelicoi";
194 const char page_action[] = "obcimlgaoabeegjmmpldobjndiealpln";
195 const char theme_crx[] = "iamefpfkojoapidjnbafmgkgncegbkad";
196 const char theme2_crx[] = "pjpgmfcmabopnnfonnhmdjglfpjjfkbf";
197 const char permissions_crx[] = "eagpmdpfmaekmmcejjbmjoecnejeiiin";
198 const char unpacked[] = "cbcdidchbppangcjoddlpdjlenngjldk";
199 const char updates_from_webstore[] = "akjooamlhcgeopfifcmlggaebeocgokj";
200 const char permissions_blocklist[] = "noffkehfcaggllbcojjbopcmlhcnhcdn";
202 struct ExtensionsOrder {
203 bool operator()(const scoped_refptr<const Extension>& a,
204 const scoped_refptr<const Extension>& b) {
205 return a->name() < b->name();
209 static std::vector<base::string16> GetErrors() {
210 const std::vector<base::string16>* errors =
211 ExtensionErrorReporter::GetInstance()->GetErrors();
212 std::vector<base::string16> ret_val;
214 for (std::vector<base::string16>::const_iterator iter = errors->begin();
215 iter != errors->end(); ++iter) {
216 std::string utf8_error = base::UTF16ToUTF8(*iter);
217 if (utf8_error.find(".svn") == std::string::npos) {
218 ret_val.push_back(*iter);
222 // The tests rely on the errors being in a certain order, which can vary
223 // depending on how filesystem iteration works.
224 std::stable_sort(ret_val.begin(), ret_val.end());
226 return ret_val;
229 static void AddPattern(URLPatternSet* extent, const std::string& pattern) {
230 int schemes = URLPattern::SCHEME_ALL;
231 extent->AddPattern(URLPattern(schemes, pattern));
234 base::FilePath GetTemporaryFile() {
235 base::FilePath temp_file;
236 CHECK(base::CreateTemporaryFile(&temp_file));
237 return temp_file;
240 bool WaitForCountNotificationsCallback(int *count) {
241 return --(*count) == 0;
244 } // namespace
246 class MockExtensionProvider : public extensions::ExternalProviderInterface {
247 public:
248 MockExtensionProvider(
249 VisitorInterface* visitor,
250 Manifest::Location location)
251 : location_(location), visitor_(visitor), visit_count_(0) {
254 ~MockExtensionProvider() override {}
256 void UpdateOrAddExtension(const std::string& id,
257 const std::string& version,
258 const base::FilePath& path) {
259 extension_map_[id] = std::make_pair(version, path);
262 void RemoveExtension(const std::string& id) {
263 extension_map_.erase(id);
266 // ExternalProvider implementation:
267 void VisitRegisteredExtension() override {
268 visit_count_++;
269 for (DataMap::const_iterator i = extension_map_.begin();
270 i != extension_map_.end(); ++i) {
271 Version version(i->second.first);
273 visitor_->OnExternalExtensionFileFound(
274 i->first, &version, i->second.second, location_,
275 Extension::NO_FLAGS, false, false);
277 visitor_->OnExternalProviderReady(this);
280 bool HasExtension(const std::string& id) const override {
281 return extension_map_.find(id) != extension_map_.end();
284 bool GetExtensionDetails(const std::string& id,
285 Manifest::Location* location,
286 scoped_ptr<Version>* version) const override {
287 DataMap::const_iterator it = extension_map_.find(id);
288 if (it == extension_map_.end())
289 return false;
291 if (version)
292 version->reset(new Version(it->second.first));
294 if (location)
295 *location = location_;
297 return true;
300 bool IsReady() const override { return true; }
302 void ServiceShutdown() override {}
304 int visit_count() const { return visit_count_; }
305 void set_visit_count(int visit_count) {
306 visit_count_ = visit_count;
309 private:
310 typedef std::map< std::string, std::pair<std::string, base::FilePath> >
311 DataMap;
312 DataMap extension_map_;
313 Manifest::Location location_;
314 VisitorInterface* visitor_;
316 // visit_count_ tracks the number of calls to VisitRegisteredExtension().
317 // Mutable because it must be incremented on each call to
318 // VisitRegisteredExtension(), which must be a const method to inherit
319 // from the class being mocked.
320 mutable int visit_count_;
322 DISALLOW_COPY_AND_ASSIGN(MockExtensionProvider);
325 class MockProviderVisitor
326 : public extensions::ExternalProviderInterface::VisitorInterface {
327 public:
328 // The provider will return |fake_base_path| from
329 // GetBaseCrxFilePath(). User can test the behavior with
330 // and without an empty path using this parameter.
331 explicit MockProviderVisitor(base::FilePath fake_base_path)
332 : ids_found_(0),
333 fake_base_path_(fake_base_path),
334 expected_creation_flags_(Extension::NO_FLAGS) {
335 profile_.reset(new TestingProfile);
338 MockProviderVisitor(base::FilePath fake_base_path,
339 int expected_creation_flags)
340 : ids_found_(0),
341 fake_base_path_(fake_base_path),
342 expected_creation_flags_(expected_creation_flags) {
345 int Visit(const std::string& json_data) {
346 // Give the test json file to the provider for parsing.
347 provider_.reset(new extensions::ExternalProviderImpl(
348 this,
349 new extensions::ExternalTestingLoader(json_data, fake_base_path_),
350 profile_.get(),
351 Manifest::EXTERNAL_PREF,
352 Manifest::EXTERNAL_PREF_DOWNLOAD,
353 Extension::NO_FLAGS));
355 // We also parse the file into a dictionary to compare what we get back
356 // from the provider.
357 JSONStringValueDeserializer deserializer(json_data);
358 base::Value* json_value = deserializer.Deserialize(NULL, NULL);
360 if (!json_value || !json_value->IsType(base::Value::TYPE_DICTIONARY)) {
361 NOTREACHED() << "Unable to deserialize json data";
362 return -1;
363 } else {
364 base::DictionaryValue* external_extensions =
365 static_cast<base::DictionaryValue*>(json_value);
366 prefs_.reset(external_extensions);
369 // Reset our counter.
370 ids_found_ = 0;
371 // Ask the provider to look up all extensions and return them.
372 provider_->VisitRegisteredExtension();
374 return ids_found_;
377 bool OnExternalExtensionFileFound(const std::string& id,
378 const Version* version,
379 const base::FilePath& path,
380 Manifest::Location unused,
381 int creation_flags,
382 bool mark_acknowledged,
383 bool install_immediately) override {
384 EXPECT_EQ(expected_creation_flags_, creation_flags);
386 ++ids_found_;
387 base::DictionaryValue* pref;
388 // This tests is to make sure that the provider only notifies us of the
389 // values we gave it. So if the id we doesn't exist in our internal
390 // dictionary then something is wrong.
391 EXPECT_TRUE(prefs_->GetDictionary(id, &pref))
392 << "Got back ID (" << id.c_str() << ") we weren't expecting";
394 EXPECT_TRUE(path.IsAbsolute());
395 if (!fake_base_path_.empty())
396 EXPECT_TRUE(fake_base_path_.IsParent(path));
398 if (pref) {
399 EXPECT_TRUE(provider_->HasExtension(id));
401 // Ask provider if the extension we got back is registered.
402 Manifest::Location location = Manifest::INVALID_LOCATION;
403 scoped_ptr<Version> v1;
404 base::FilePath crx_path;
406 EXPECT_TRUE(provider_->GetExtensionDetails(id, NULL, &v1));
407 EXPECT_STREQ(version->GetString().c_str(), v1->GetString().c_str());
409 scoped_ptr<Version> v2;
410 EXPECT_TRUE(provider_->GetExtensionDetails(id, &location, &v2));
411 EXPECT_STREQ(version->GetString().c_str(), v1->GetString().c_str());
412 EXPECT_STREQ(version->GetString().c_str(), v2->GetString().c_str());
413 EXPECT_EQ(Manifest::EXTERNAL_PREF, location);
415 // Remove it so we won't count it ever again.
416 prefs_->Remove(id, NULL);
418 return true;
421 bool OnExternalExtensionUpdateUrlFound(const std::string& id,
422 const std::string& install_parameter,
423 const GURL& update_url,
424 Manifest::Location location,
425 int creation_flags,
426 bool mark_acknowledged) override {
427 ++ids_found_;
428 base::DictionaryValue* pref;
429 // This tests is to make sure that the provider only notifies us of the
430 // values we gave it. So if the id we doesn't exist in our internal
431 // dictionary then something is wrong.
432 EXPECT_TRUE(prefs_->GetDictionary(id, &pref))
433 << L"Got back ID (" << id.c_str() << ") we weren't expecting";
434 EXPECT_EQ(Manifest::EXTERNAL_PREF_DOWNLOAD, location);
436 if (pref) {
437 EXPECT_TRUE(provider_->HasExtension(id));
439 // External extensions with update URLs do not have versions.
440 scoped_ptr<Version> v1;
441 Manifest::Location location1 = Manifest::INVALID_LOCATION;
442 EXPECT_TRUE(provider_->GetExtensionDetails(id, &location1, &v1));
443 EXPECT_FALSE(v1.get());
444 EXPECT_EQ(Manifest::EXTERNAL_PREF_DOWNLOAD, location1);
446 std::string parsed_install_parameter;
447 pref->GetString("install_parameter", &parsed_install_parameter);
448 EXPECT_EQ(parsed_install_parameter, install_parameter);
450 // Remove it so we won't count it again.
451 prefs_->Remove(id, NULL);
453 return true;
456 void OnExternalProviderReady(
457 const extensions::ExternalProviderInterface* provider) override {
458 EXPECT_EQ(provider, provider_.get());
459 EXPECT_TRUE(provider->IsReady());
462 private:
463 int ids_found_;
464 base::FilePath fake_base_path_;
465 int expected_creation_flags_;
466 scoped_ptr<extensions::ExternalProviderImpl> provider_;
467 scoped_ptr<base::DictionaryValue> prefs_;
468 scoped_ptr<TestingProfile> profile_;
470 DISALLOW_COPY_AND_ASSIGN(MockProviderVisitor);
473 class ExtensionServiceTest : public extensions::ExtensionServiceTestBase,
474 public content::NotificationObserver {
475 public:
476 ExtensionServiceTest()
477 : unloaded_reason_(UnloadedExtensionInfo::REASON_UNDEFINED),
478 installed_(NULL),
479 was_update_(false),
480 override_external_install_prompt_(
481 FeatureSwitch::prompt_for_external_extensions(),
482 false),
483 expected_extensions_count_(0) {
484 registrar_.Add(this,
485 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
486 content::NotificationService::AllSources());
487 registrar_.Add(this,
488 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
489 content::NotificationService::AllSources());
490 registrar_.Add(
491 this,
492 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
493 content::NotificationService::AllSources());
496 void Observe(int type,
497 const content::NotificationSource& source,
498 const content::NotificationDetails& details) override {
499 switch (type) {
500 case extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED: {
501 const Extension* extension =
502 content::Details<const Extension>(details).ptr();
503 loaded_.push_back(make_scoped_refptr(extension));
504 // The tests rely on the errors being in a certain order, which can vary
505 // depending on how filesystem iteration works.
506 std::stable_sort(loaded_.begin(), loaded_.end(), ExtensionsOrder());
507 break;
510 case extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED: {
511 UnloadedExtensionInfo* unloaded_info =
512 content::Details<UnloadedExtensionInfo>(details).ptr();
513 const Extension* e = unloaded_info->extension;
514 unloaded_id_ = e->id();
515 unloaded_reason_ = unloaded_info->reason;
516 extensions::ExtensionList::iterator i =
517 std::find(loaded_.begin(), loaded_.end(), e);
518 // TODO(erikkay) fix so this can be an assert. Right now the tests
519 // are manually calling clear() on loaded_, so this isn't doable.
520 if (i == loaded_.end())
521 return;
522 loaded_.erase(i);
523 break;
525 case extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED: {
526 const extensions::InstalledExtensionInfo* installed_info =
527 content::Details<const extensions::InstalledExtensionInfo>(details)
528 .ptr();
529 installed_ = installed_info->extension;
530 was_update_ = installed_info->is_update;
531 old_name_ = installed_info->old_name;
532 break;
535 default:
536 DCHECK(false);
540 void AddMockExternalProvider(
541 extensions::ExternalProviderInterface* provider) {
542 service()->AddProviderForTesting(provider);
545 void MockSyncStartFlare(bool* was_called,
546 syncer::ModelType* model_type_passed_in,
547 syncer::ModelType model_type) {
548 *was_called = true;
549 *model_type_passed_in = model_type;
552 protected:
553 // Paths to some of the fake extensions.
554 base::FilePath good0_path() {
555 return data_dir()
556 .AppendASCII("good")
557 .AppendASCII("Extensions")
558 .AppendASCII(good0)
559 .AppendASCII("1.0.0.0");
562 base::FilePath good1_path() {
563 return data_dir()
564 .AppendASCII("good")
565 .AppendASCII("Extensions")
566 .AppendASCII(good1)
567 .AppendASCII("2");
570 base::FilePath good2_path() {
571 return data_dir()
572 .AppendASCII("good")
573 .AppendASCII("Extensions")
574 .AppendASCII(good2)
575 .AppendASCII("1.0");
578 void TestExternalProvider(MockExtensionProvider* provider,
579 Manifest::Location location);
581 void PackCRX(const base::FilePath& dir_path,
582 const base::FilePath& pem_path,
583 const base::FilePath& crx_path) {
584 // Use the existing pem key, if provided.
585 base::FilePath pem_output_path;
586 if (pem_path.value().empty()) {
587 pem_output_path = crx_path.DirName().AppendASCII("temp.pem");
588 } else {
589 ASSERT_TRUE(base::PathExists(pem_path));
592 ASSERT_TRUE(base::DeleteFile(crx_path, false));
594 scoped_ptr<ExtensionCreator> creator(new ExtensionCreator());
595 ASSERT_TRUE(creator->Run(dir_path,
596 crx_path,
597 pem_path,
598 pem_output_path,
599 ExtensionCreator::kOverwriteCRX));
601 ASSERT_TRUE(base::PathExists(crx_path));
604 enum InstallState {
605 INSTALL_FAILED,
606 INSTALL_UPDATED,
607 INSTALL_NEW,
608 INSTALL_WITHOUT_LOAD,
611 const Extension* PackAndInstallCRX(const base::FilePath& dir_path,
612 const base::FilePath& pem_path,
613 InstallState install_state,
614 int creation_flags) {
615 base::FilePath crx_path;
616 base::ScopedTempDir temp_dir;
617 EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
618 crx_path = temp_dir.path().AppendASCII("temp.crx");
620 PackCRX(dir_path, pem_path, crx_path);
621 return InstallCRX(crx_path, install_state, creation_flags);
624 const Extension* PackAndInstallCRX(const base::FilePath& dir_path,
625 const base::FilePath& pem_path,
626 InstallState install_state) {
627 return PackAndInstallCRX(dir_path, pem_path, install_state,
628 Extension::NO_FLAGS);
631 const Extension* PackAndInstallCRX(const base::FilePath& dir_path,
632 InstallState install_state) {
633 return PackAndInstallCRX(dir_path, base::FilePath(), install_state,
634 Extension::NO_FLAGS);
637 // Attempts to install an extension. Use INSTALL_FAILED if the installation
638 // is expected to fail.
639 // If |install_state| is INSTALL_UPDATED, and |expected_old_name| is
640 // non-empty, expects that the existing extension's title was
641 // |expected_old_name|.
642 const Extension* InstallCRX(const base::FilePath& path,
643 InstallState install_state,
644 int creation_flags,
645 const std::string& expected_old_name) {
646 InstallCRXInternal(path, creation_flags);
647 return VerifyCrxInstall(path, install_state, expected_old_name);
650 // Attempts to install an extension. Use INSTALL_FAILED if the installation
651 // is expected to fail.
652 const Extension* InstallCRX(const base::FilePath& path,
653 InstallState install_state,
654 int creation_flags) {
655 return InstallCRX(path, install_state, creation_flags, std::string());
658 // Attempts to install an extension. Use INSTALL_FAILED if the installation
659 // is expected to fail.
660 const Extension* InstallCRX(const base::FilePath& path,
661 InstallState install_state) {
662 return InstallCRX(path, install_state, Extension::NO_FLAGS);
665 const Extension* InstallCRXFromWebStore(const base::FilePath& path,
666 InstallState install_state) {
667 InstallCRXInternal(path, Extension::FROM_WEBSTORE);
668 return VerifyCrxInstall(path, install_state);
671 const Extension* InstallCRXWithLocation(const base::FilePath& crx_path,
672 Manifest::Location install_location,
673 InstallState install_state) {
674 EXPECT_TRUE(base::PathExists(crx_path))
675 << "Path does not exist: "<< crx_path.value().c_str();
676 // no client (silent install)
677 scoped_refptr<CrxInstaller> installer(
678 CrxInstaller::CreateSilent(service()));
679 installer->set_install_source(install_location);
681 content::WindowedNotificationObserver observer(
682 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
683 content::NotificationService::AllSources());
684 installer->InstallCrx(crx_path);
685 observer.Wait();
687 return VerifyCrxInstall(crx_path, install_state);
690 // Verifies the result of a CRX installation. Used by InstallCRX. Set the
691 // |install_state| to INSTALL_FAILED if the installation is expected to fail.
692 // Returns an Extension pointer if the install succeeded, NULL otherwise.
693 const Extension* VerifyCrxInstall(const base::FilePath& path,
694 InstallState install_state) {
695 return VerifyCrxInstall(path, install_state, std::string());
698 // Verifies the result of a CRX installation. Used by InstallCRX. Set the
699 // |install_state| to INSTALL_FAILED if the installation is expected to fail.
700 // If |install_state| is INSTALL_UPDATED, and |expected_old_name| is
701 // non-empty, expects that the existing extension's title was
702 // |expected_old_name|.
703 // Returns an Extension pointer if the install succeeded, NULL otherwise.
704 const Extension* VerifyCrxInstall(const base::FilePath& path,
705 InstallState install_state,
706 const std::string& expected_old_name) {
707 std::vector<base::string16> errors = GetErrors();
708 const Extension* extension = NULL;
709 if (install_state != INSTALL_FAILED) {
710 if (install_state == INSTALL_NEW)
711 ++expected_extensions_count_;
713 EXPECT_TRUE(installed_) << path.value();
714 // If and only if INSTALL_UPDATED, it should have the is_update flag.
715 EXPECT_EQ(install_state == INSTALL_UPDATED, was_update_)
716 << path.value();
717 // If INSTALL_UPDATED, old_name_ should match the given string.
718 if (install_state == INSTALL_UPDATED && !expected_old_name.empty())
719 EXPECT_EQ(expected_old_name, old_name_);
720 EXPECT_EQ(0u, errors.size()) << path.value();
722 if (install_state == INSTALL_WITHOUT_LOAD) {
723 EXPECT_EQ(0u, loaded_.size()) << path.value();
724 } else {
725 EXPECT_EQ(1u, loaded_.size()) << path.value();
726 size_t actual_extension_count =
727 registry()->enabled_extensions().size() +
728 registry()->disabled_extensions().size();
729 EXPECT_EQ(expected_extensions_count_, actual_extension_count) <<
730 path.value();
731 extension = loaded_[0].get();
732 EXPECT_TRUE(service()->GetExtensionById(extension->id(), false))
733 << path.value();
736 for (std::vector<base::string16>::iterator err = errors.begin();
737 err != errors.end(); ++err) {
738 LOG(ERROR) << *err;
740 } else {
741 EXPECT_FALSE(installed_) << path.value();
742 EXPECT_EQ(0u, loaded_.size()) << path.value();
743 EXPECT_EQ(1u, errors.size()) << path.value();
746 installed_ = NULL;
747 was_update_ = false;
748 old_name_ = "";
749 loaded_.clear();
750 ExtensionErrorReporter::GetInstance()->ClearErrors();
751 return extension;
754 enum UpdateState {
755 FAILED_SILENTLY,
756 FAILED,
757 UPDATED,
758 INSTALLED,
759 DISABLED,
760 ENABLED
763 void BlackListWebGL() {
764 static const std::string json_blacklist =
765 "{\n"
766 " \"name\": \"gpu blacklist\",\n"
767 " \"version\": \"1.0\",\n"
768 " \"entries\": [\n"
769 " {\n"
770 " \"id\": 1,\n"
771 " \"features\": [\"webgl\"]\n"
772 " }\n"
773 " ]\n"
774 "}";
775 gpu::GPUInfo gpu_info;
776 content::GpuDataManager::GetInstance()->InitializeForTesting(
777 json_blacklist, gpu_info);
780 // Grants all optional permissions stated in manifest to active permission
781 // set for extension |id|.
782 void GrantAllOptionalPermissions(const std::string& id) {
783 const Extension* extension = service()->GetInstalledExtension(id);
784 scoped_refptr<const PermissionSet> all_optional_permissions =
785 extensions::PermissionsParser::GetOptionalPermissions(extension);
786 extensions::PermissionsUpdater perms_updater(profile());
787 perms_updater.AddPermissions(extension, all_optional_permissions.get());
790 // Helper method to set up a WindowedNotificationObserver to wait for a
791 // specific CrxInstaller to finish if we don't know the value of the
792 // |installer| yet.
793 static bool IsCrxInstallerDone(extensions::CrxInstaller** installer,
794 const content::NotificationSource& source,
795 const content::NotificationDetails& details) {
796 return content::Source<extensions::CrxInstaller>(source).ptr() ==
797 *installer;
800 void PackCRXAndUpdateExtension(const std::string& id,
801 const base::FilePath& dir_path,
802 const base::FilePath& pem_path,
803 UpdateState expected_state) {
804 base::ScopedTempDir temp_dir;
805 EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
806 base::FilePath crx_path = temp_dir.path().AppendASCII("temp.crx");
808 PackCRX(dir_path, pem_path, crx_path);
809 UpdateExtension(id, crx_path, expected_state);
812 void UpdateExtension(const std::string& id,
813 const base::FilePath& in_path,
814 UpdateState expected_state) {
815 ASSERT_TRUE(base::PathExists(in_path));
817 // We need to copy this to a temporary location because Update() will delete
818 // it.
819 base::FilePath path = temp_dir().path();
820 path = path.Append(in_path.BaseName());
821 ASSERT_TRUE(base::CopyFile(in_path, path));
823 int previous_enabled_extension_count =
824 registry()->enabled_extensions().size();
825 int previous_installed_extension_count =
826 previous_enabled_extension_count +
827 registry()->disabled_extensions().size();
829 extensions::CrxInstaller* installer = NULL;
830 content::WindowedNotificationObserver observer(
831 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
832 base::Bind(&IsCrxInstallerDone, &installer));
833 service()->UpdateExtension(extensions::CRXFileInfo(id, path), true,
834 &installer);
836 if (installer)
837 observer.Wait();
838 else
839 base::RunLoop().RunUntilIdle();
841 std::vector<base::string16> errors = GetErrors();
842 int error_count = errors.size();
843 int enabled_extension_count = registry()->enabled_extensions().size();
844 int installed_extension_count =
845 enabled_extension_count + registry()->disabled_extensions().size();
847 int expected_error_count = (expected_state == FAILED) ? 1 : 0;
848 EXPECT_EQ(expected_error_count, error_count) << path.value();
850 if (expected_state <= FAILED) {
851 EXPECT_EQ(previous_enabled_extension_count,
852 enabled_extension_count);
853 EXPECT_EQ(previous_installed_extension_count,
854 installed_extension_count);
855 } else {
856 int expected_installed_extension_count =
857 (expected_state >= INSTALLED) ? 1 : 0;
858 int expected_enabled_extension_count =
859 (expected_state >= ENABLED) ? 1 : 0;
860 EXPECT_EQ(expected_installed_extension_count,
861 installed_extension_count);
862 EXPECT_EQ(expected_enabled_extension_count,
863 enabled_extension_count);
866 // Update() should the temporary input file.
867 EXPECT_FALSE(base::PathExists(path));
870 void TerminateExtension(const std::string& id) {
871 const Extension* extension = service()->GetInstalledExtension(id);
872 if (!extension) {
873 ADD_FAILURE();
874 return;
876 service()->TrackTerminatedExtensionForTest(extension);
879 testing::AssertionResult IsBlocked(const std::string& id) {
880 scoped_ptr<extensions::ExtensionSet> all_unblocked_extensions =
881 registry()->GenerateInstalledExtensionsSet(
882 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::BLOCKED);
883 if (all_unblocked_extensions.get()->Contains(id))
884 return testing::AssertionFailure() << id << " is still unblocked!";
885 if (!registry()->blocked_extensions().Contains(id))
886 return testing::AssertionFailure() << id << " is not blocked!";
887 return testing::AssertionSuccess();
890 // Helper method to test that an extension moves through being blocked and
891 // unblocked as appropriate for its type.
892 void AssertExtensionBlocksAndUnblocks(
893 bool should_block, const std::string extension_id) {
894 // Assume we start in an unblocked state.
895 EXPECT_FALSE(IsBlocked(extension_id));
897 // Block the extensions.
898 service()->BlockAllExtensions();
899 base::RunLoop().RunUntilIdle();
901 if (should_block)
902 ASSERT_TRUE(IsBlocked(extension_id));
903 else
904 ASSERT_FALSE(IsBlocked(extension_id));
906 service()->UnblockAllExtensions();
907 base::RunLoop().RunUntilIdle();
909 ASSERT_FALSE(IsBlocked(extension_id));
912 size_t GetPrefKeyCount() {
913 const base::DictionaryValue* dict =
914 profile()->GetPrefs()->GetDictionary("extensions.settings");
915 if (!dict) {
916 ADD_FAILURE();
917 return 0;
919 return dict->size();
922 void UninstallExtension(const std::string& id, bool use_helper) {
923 // Verify that the extension is installed.
924 base::FilePath extension_path = extensions_install_dir().AppendASCII(id);
925 EXPECT_TRUE(base::PathExists(extension_path));
926 size_t pref_key_count = GetPrefKeyCount();
927 EXPECT_GT(pref_key_count, 0u);
928 ValidateIntegerPref(id, "state", Extension::ENABLED);
930 // Uninstall it.
931 if (use_helper) {
932 EXPECT_TRUE(ExtensionService::UninstallExtensionHelper(
933 service(), id, extensions::UNINSTALL_REASON_FOR_TESTING));
934 } else {
935 EXPECT_TRUE(service()->UninstallExtension(
937 extensions::UNINSTALL_REASON_FOR_TESTING,
938 base::Bind(&base::DoNothing),
939 NULL));
941 --expected_extensions_count_;
943 // We should get an unload notification.
944 EXPECT_FALSE(unloaded_id_.empty());
945 EXPECT_EQ(id, unloaded_id_);
947 // Verify uninstalled state.
948 size_t new_pref_key_count = GetPrefKeyCount();
949 if (new_pref_key_count == pref_key_count) {
950 ValidateIntegerPref(id, "state",
951 Extension::EXTERNAL_EXTENSION_UNINSTALLED);
952 } else {
953 EXPECT_EQ(new_pref_key_count, pref_key_count - 1);
956 // The extension should not be in the service anymore.
957 EXPECT_FALSE(service()->GetInstalledExtension(id));
958 base::RunLoop().RunUntilIdle();
960 // The directory should be gone.
961 EXPECT_FALSE(base::PathExists(extension_path));
964 void ValidatePrefKeyCount(size_t count) {
965 EXPECT_EQ(count, GetPrefKeyCount());
968 testing::AssertionResult ValidateBooleanPref(
969 const std::string& extension_id,
970 const std::string& pref_path,
971 bool expected_val) {
972 std::string msg = "while checking: ";
973 msg += extension_id;
974 msg += " ";
975 msg += pref_path;
976 msg += " == ";
977 msg += expected_val ? "true" : "false";
979 PrefService* prefs = profile()->GetPrefs();
980 const base::DictionaryValue* dict =
981 prefs->GetDictionary("extensions.settings");
982 if (!dict) {
983 return testing::AssertionFailure()
984 << "extension.settings does not exist " << msg;
987 const base::DictionaryValue* pref = NULL;
988 if (!dict->GetDictionary(extension_id, &pref)) {
989 return testing::AssertionFailure()
990 << "extension pref does not exist " << msg;
993 bool val;
994 if (!pref->GetBoolean(pref_path, &val)) {
995 return testing::AssertionFailure()
996 << pref_path << " pref not found " << msg;
999 return expected_val == val
1000 ? testing::AssertionSuccess()
1001 : testing::AssertionFailure() << "base::Value is incorrect " << msg;
1004 bool IsPrefExist(const std::string& extension_id,
1005 const std::string& pref_path) {
1006 const base::DictionaryValue* dict =
1007 profile()->GetPrefs()->GetDictionary("extensions.settings");
1008 if (dict == NULL) return false;
1009 const base::DictionaryValue* pref = NULL;
1010 if (!dict->GetDictionary(extension_id, &pref)) {
1011 return false;
1013 if (pref == NULL) {
1014 return false;
1016 bool val;
1017 if (!pref->GetBoolean(pref_path, &val)) {
1018 return false;
1020 return true;
1023 void ValidateIntegerPref(const std::string& extension_id,
1024 const std::string& pref_path,
1025 int expected_val) {
1026 std::string msg = " while checking: ";
1027 msg += extension_id;
1028 msg += " ";
1029 msg += pref_path;
1030 msg += " == ";
1031 msg += base::IntToString(expected_val);
1033 PrefService* prefs = profile()->GetPrefs();
1034 const base::DictionaryValue* dict =
1035 prefs->GetDictionary("extensions.settings");
1036 ASSERT_TRUE(dict != NULL) << msg;
1037 const base::DictionaryValue* pref = NULL;
1038 ASSERT_TRUE(dict->GetDictionary(extension_id, &pref)) << msg;
1039 EXPECT_TRUE(pref != NULL) << msg;
1040 int val;
1041 ASSERT_TRUE(pref->GetInteger(pref_path, &val)) << msg;
1042 EXPECT_EQ(expected_val, val) << msg;
1045 void ValidateStringPref(const std::string& extension_id,
1046 const std::string& pref_path,
1047 const std::string& expected_val) {
1048 std::string msg = " while checking: ";
1049 msg += extension_id;
1050 msg += ".manifest.";
1051 msg += pref_path;
1052 msg += " == ";
1053 msg += expected_val;
1055 const base::DictionaryValue* dict =
1056 profile()->GetPrefs()->GetDictionary("extensions.settings");
1057 ASSERT_TRUE(dict != NULL) << msg;
1058 const base::DictionaryValue* pref = NULL;
1059 std::string manifest_path = extension_id + ".manifest";
1060 ASSERT_TRUE(dict->GetDictionary(manifest_path, &pref)) << msg;
1061 EXPECT_TRUE(pref != NULL) << msg;
1062 std::string val;
1063 ASSERT_TRUE(pref->GetString(pref_path, &val)) << msg;
1064 EXPECT_EQ(expected_val, val) << msg;
1067 void SetPref(const std::string& extension_id,
1068 const std::string& pref_path,
1069 base::Value* value,
1070 const std::string& msg) {
1071 DictionaryPrefUpdate update(profile()->GetPrefs(), "extensions.settings");
1072 base::DictionaryValue* dict = update.Get();
1073 ASSERT_TRUE(dict != NULL) << msg;
1074 base::DictionaryValue* pref = NULL;
1075 ASSERT_TRUE(dict->GetDictionary(extension_id, &pref)) << msg;
1076 EXPECT_TRUE(pref != NULL) << msg;
1077 pref->Set(pref_path, value);
1080 void SetPrefInteg(const std::string& extension_id,
1081 const std::string& pref_path,
1082 int value) {
1083 std::string msg = " while setting: ";
1084 msg += extension_id;
1085 msg += " ";
1086 msg += pref_path;
1087 msg += " = ";
1088 msg += base::IntToString(value);
1090 SetPref(extension_id, pref_path, new base::FundamentalValue(value), msg);
1093 void SetPrefBool(const std::string& extension_id,
1094 const std::string& pref_path,
1095 bool value) {
1096 std::string msg = " while setting: ";
1097 msg += extension_id + " " + pref_path;
1098 msg += " = ";
1099 msg += (value ? "true" : "false");
1101 SetPref(extension_id, pref_path, new base::FundamentalValue(value), msg);
1104 void ClearPref(const std::string& extension_id,
1105 const std::string& pref_path) {
1106 std::string msg = " while clearing: ";
1107 msg += extension_id + " " + pref_path;
1109 DictionaryPrefUpdate update(profile()->GetPrefs(), "extensions.settings");
1110 base::DictionaryValue* dict = update.Get();
1111 ASSERT_TRUE(dict != NULL) << msg;
1112 base::DictionaryValue* pref = NULL;
1113 ASSERT_TRUE(dict->GetDictionary(extension_id, &pref)) << msg;
1114 EXPECT_TRUE(pref != NULL) << msg;
1115 pref->Remove(pref_path, NULL);
1118 void SetPrefStringSet(const std::string& extension_id,
1119 const std::string& pref_path,
1120 const std::set<std::string>& value) {
1121 std::string msg = " while setting: ";
1122 msg += extension_id + " " + pref_path;
1124 base::ListValue* list_value = new base::ListValue();
1125 for (std::set<std::string>::const_iterator iter = value.begin();
1126 iter != value.end(); ++iter)
1127 list_value->Append(new base::StringValue(*iter));
1129 SetPref(extension_id, pref_path, list_value, msg);
1132 void InitPluginService() {
1133 #if defined(ENABLE_PLUGINS)
1134 PluginService::GetInstance()->Init();
1135 #endif
1138 void InitializeExtensionSyncService() {
1139 extension_sync_service_.reset(new ExtensionSyncService(
1140 profile(), ExtensionPrefs::Get(browser_context()), service()));
1143 void InitializeEmptyExtensionServiceWithTestingPrefs() {
1144 ExtensionServiceTestBase::ExtensionServiceInitParams params =
1145 CreateDefaultInitParams();
1146 params.pref_file = base::FilePath();
1147 InitializeExtensionService(params);
1150 extensions::ManagementPolicy* GetManagementPolicy() {
1151 return ExtensionSystem::Get(browser_context())->management_policy();
1154 ExtensionSyncService* extension_sync_service() {
1155 return extension_sync_service_.get();
1158 protected:
1159 typedef extensions::ExtensionManagementPrefUpdater<TestingPrefServiceSyncable>
1160 ManagementPrefUpdater;
1161 scoped_ptr<ExtensionSyncService> extension_sync_service_;
1162 extensions::ExtensionList loaded_;
1163 std::string unloaded_id_;
1164 UnloadedExtensionInfo::Reason unloaded_reason_;
1165 const Extension* installed_;
1166 bool was_update_;
1167 std::string old_name_;
1168 FeatureSwitch::ScopedOverride override_external_install_prompt_;
1170 private:
1171 // Create a CrxInstaller and install the CRX file.
1172 // Instead of calling this method yourself, use InstallCRX(), which does extra
1173 // error checking.
1174 void InstallCRXInternal(const base::FilePath& crx_path) {
1175 InstallCRXInternal(crx_path, Extension::NO_FLAGS);
1178 void InstallCRXInternal(const base::FilePath& crx_path, int creation_flags) {
1179 ASSERT_TRUE(base::PathExists(crx_path))
1180 << "Path does not exist: "<< crx_path.value().c_str();
1181 scoped_refptr<CrxInstaller> installer(
1182 CrxInstaller::CreateSilent(service()));
1183 installer->set_creation_flags(creation_flags);
1184 if (!(creation_flags & Extension::WAS_INSTALLED_BY_DEFAULT))
1185 installer->set_allow_silent_install(true);
1187 content::WindowedNotificationObserver observer(
1188 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
1189 content::Source<extensions::CrxInstaller>(installer.get()));
1191 installer->InstallCrx(crx_path);
1193 observer.Wait();
1196 size_t expected_extensions_count_;
1197 content::NotificationRegistrar registrar_;
1200 // Receives notifications from a PackExtensionJob, indicating either that
1201 // packing succeeded or that there was some error.
1202 class PackExtensionTestClient : public extensions::PackExtensionJob::Client {
1203 public:
1204 PackExtensionTestClient(const base::FilePath& expected_crx_path,
1205 const base::FilePath& expected_private_key_path);
1206 void OnPackSuccess(const base::FilePath& crx_path,
1207 const base::FilePath& private_key_path) override;
1208 void OnPackFailure(const std::string& error_message,
1209 ExtensionCreator::ErrorType type) override;
1211 private:
1212 const base::FilePath expected_crx_path_;
1213 const base::FilePath expected_private_key_path_;
1214 DISALLOW_COPY_AND_ASSIGN(PackExtensionTestClient);
1217 PackExtensionTestClient::PackExtensionTestClient(
1218 const base::FilePath& expected_crx_path,
1219 const base::FilePath& expected_private_key_path)
1220 : expected_crx_path_(expected_crx_path),
1221 expected_private_key_path_(expected_private_key_path) {}
1223 // If packing succeeded, we make sure that the package names match our
1224 // expectations.
1225 void PackExtensionTestClient::OnPackSuccess(
1226 const base::FilePath& crx_path,
1227 const base::FilePath& private_key_path) {
1228 // We got the notification and processed it; we don't expect any further tasks
1229 // to be posted to the current thread, so we should stop blocking and continue
1230 // on with the rest of the test.
1231 // This call to |Quit()| matches the call to |Run()| in the
1232 // |PackPunctuatedExtension| test.
1233 base::MessageLoop::current()->Quit();
1234 EXPECT_EQ(expected_crx_path_.value(), crx_path.value());
1235 EXPECT_EQ(expected_private_key_path_.value(), private_key_path.value());
1236 ASSERT_TRUE(base::PathExists(private_key_path));
1239 // The tests are designed so that we never expect to see a packing error.
1240 void PackExtensionTestClient::OnPackFailure(const std::string& error_message,
1241 ExtensionCreator::ErrorType type) {
1242 if (type == ExtensionCreator::kCRXExists)
1243 FAIL() << "Packing should not fail.";
1244 else
1245 FAIL() << "Existing CRX should have been overwritten.";
1248 // Test loading good extensions from the profile directory.
1249 TEST_F(ExtensionServiceTest, LoadAllExtensionsFromDirectorySuccess) {
1250 InitPluginService();
1251 InitializeGoodInstalledExtensionService();
1252 service()->Init();
1254 uint32 expected_num_extensions = 3u;
1255 ASSERT_EQ(expected_num_extensions, loaded_.size());
1257 EXPECT_EQ(std::string(good0), loaded_[0]->id());
1258 EXPECT_EQ(std::string("My extension 1"),
1259 loaded_[0]->name());
1260 EXPECT_EQ(std::string("The first extension that I made."),
1261 loaded_[0]->description());
1262 EXPECT_EQ(Manifest::INTERNAL, loaded_[0]->location());
1263 EXPECT_TRUE(service()->GetExtensionById(loaded_[0]->id(), false));
1264 EXPECT_EQ(expected_num_extensions, registry()->enabled_extensions().size());
1266 ValidatePrefKeyCount(3);
1267 ValidateIntegerPref(good0, "state", Extension::ENABLED);
1268 ValidateIntegerPref(good0, "location", Manifest::INTERNAL);
1269 ValidateIntegerPref(good1, "state", Extension::ENABLED);
1270 ValidateIntegerPref(good1, "location", Manifest::INTERNAL);
1271 ValidateIntegerPref(good2, "state", Extension::ENABLED);
1272 ValidateIntegerPref(good2, "location", Manifest::INTERNAL);
1274 URLPatternSet expected_patterns;
1275 AddPattern(&expected_patterns, "file:///*");
1276 AddPattern(&expected_patterns, "http://*.google.com/*");
1277 AddPattern(&expected_patterns, "https://*.google.com/*");
1278 const Extension* extension = loaded_[0].get();
1279 const extensions::UserScriptList& scripts =
1280 extensions::ContentScriptsInfo::GetContentScripts(extension);
1281 ASSERT_EQ(2u, scripts.size());
1282 EXPECT_EQ(expected_patterns, scripts[0].url_patterns());
1283 EXPECT_EQ(2u, scripts[0].js_scripts().size());
1284 ExtensionResource resource00(extension->id(),
1285 scripts[0].js_scripts()[0].extension_root(),
1286 scripts[0].js_scripts()[0].relative_path());
1287 base::FilePath expected_path =
1288 base::MakeAbsoluteFilePath(extension->path().AppendASCII("script1.js"));
1289 EXPECT_TRUE(resource00.ComparePathWithDefault(expected_path));
1290 ExtensionResource resource01(extension->id(),
1291 scripts[0].js_scripts()[1].extension_root(),
1292 scripts[0].js_scripts()[1].relative_path());
1293 expected_path =
1294 base::MakeAbsoluteFilePath(extension->path().AppendASCII("script2.js"));
1295 EXPECT_TRUE(resource01.ComparePathWithDefault(expected_path));
1296 EXPECT_TRUE(!extensions::PluginInfo::HasPlugins(extension));
1297 EXPECT_EQ(1u, scripts[1].url_patterns().patterns().size());
1298 EXPECT_EQ("http://*.news.com/*",
1299 scripts[1].url_patterns().begin()->GetAsString());
1300 ExtensionResource resource10(extension->id(),
1301 scripts[1].js_scripts()[0].extension_root(),
1302 scripts[1].js_scripts()[0].relative_path());
1303 expected_path =
1304 extension->path().AppendASCII("js_files").AppendASCII("script3.js");
1305 expected_path = base::MakeAbsoluteFilePath(expected_path);
1306 EXPECT_TRUE(resource10.ComparePathWithDefault(expected_path));
1308 expected_patterns.ClearPatterns();
1309 AddPattern(&expected_patterns, "http://*.google.com/*");
1310 AddPattern(&expected_patterns, "https://*.google.com/*");
1311 EXPECT_EQ(
1312 expected_patterns,
1313 extension->permissions_data()->active_permissions()->explicit_hosts());
1315 EXPECT_EQ(std::string(good1), loaded_[1]->id());
1316 EXPECT_EQ(std::string("My extension 2"), loaded_[1]->name());
1317 EXPECT_EQ(std::string(), loaded_[1]->description());
1318 EXPECT_EQ(loaded_[1]->GetResourceURL("background.html"),
1319 extensions::BackgroundInfo::GetBackgroundURL(loaded_[1].get()));
1320 EXPECT_EQ(0u,
1321 extensions::ContentScriptsInfo::GetContentScripts(loaded_[1].get())
1322 .size());
1324 // We don't parse the plugins section on Chrome OS.
1325 #if defined(OS_CHROMEOS)
1326 EXPECT_TRUE(!extensions::PluginInfo::HasPlugins(loaded_[1].get()));
1327 #else
1328 ASSERT_TRUE(extensions::PluginInfo::HasPlugins(loaded_[1].get()));
1329 const std::vector<extensions::PluginInfo>* plugins =
1330 extensions::PluginInfo::GetPlugins(loaded_[1].get());
1331 ASSERT_TRUE(plugins);
1332 ASSERT_EQ(2u, plugins->size());
1333 EXPECT_EQ(loaded_[1]->path().AppendASCII("content_plugin.dll").value(),
1334 plugins->at(0).path.value());
1335 EXPECT_TRUE(plugins->at(0).is_public);
1336 EXPECT_EQ(loaded_[1]->path().AppendASCII("extension_plugin.dll").value(),
1337 plugins->at(1).path.value());
1338 EXPECT_FALSE(plugins->at(1).is_public);
1339 #endif
1341 EXPECT_EQ(Manifest::INTERNAL, loaded_[1]->location());
1343 int index = expected_num_extensions - 1;
1344 EXPECT_EQ(std::string(good2), loaded_[index]->id());
1345 EXPECT_EQ(std::string("My extension 3"), loaded_[index]->name());
1346 EXPECT_EQ(std::string(), loaded_[index]->description());
1347 EXPECT_EQ(0u,
1348 extensions::ContentScriptsInfo::GetContentScripts(
1349 loaded_[index].get()).size());
1350 EXPECT_EQ(Manifest::INTERNAL, loaded_[index]->location());
1353 // Test loading bad extensions from the profile directory.
1354 TEST_F(ExtensionServiceTest, LoadAllExtensionsFromDirectoryFail) {
1355 // Initialize the test dir with a bad Preferences/extensions.
1356 base::FilePath source_install_dir =
1357 data_dir().AppendASCII("bad").AppendASCII("Extensions");
1358 base::FilePath pref_path =
1359 source_install_dir.DirName().Append(chrome::kPreferencesFilename);
1361 InitializeInstalledExtensionService(pref_path, source_install_dir);
1363 service()->Init();
1365 ASSERT_EQ(4u, GetErrors().size());
1366 ASSERT_EQ(0u, loaded_.size());
1368 EXPECT_TRUE(MatchPattern(base::UTF16ToUTF8(GetErrors()[0]),
1369 l10n_util::GetStringUTF8(IDS_EXTENSIONS_LOAD_ERROR_MESSAGE) + " *. " +
1370 extensions::manifest_errors::kManifestUnreadable)) <<
1371 base::UTF16ToUTF8(GetErrors()[0]);
1373 EXPECT_TRUE(MatchPattern(base::UTF16ToUTF8(GetErrors()[1]),
1374 l10n_util::GetStringUTF8(IDS_EXTENSIONS_LOAD_ERROR_MESSAGE) + " *. " +
1375 extensions::manifest_errors::kManifestUnreadable)) <<
1376 base::UTF16ToUTF8(GetErrors()[1]);
1378 EXPECT_TRUE(MatchPattern(base::UTF16ToUTF8(GetErrors()[2]),
1379 l10n_util::GetStringUTF8(IDS_EXTENSIONS_LOAD_ERROR_MESSAGE) + " *. " +
1380 extensions::manifest_errors::kMissingFile)) <<
1381 base::UTF16ToUTF8(GetErrors()[2]);
1383 EXPECT_TRUE(MatchPattern(base::UTF16ToUTF8(GetErrors()[3]),
1384 l10n_util::GetStringUTF8(IDS_EXTENSIONS_LOAD_ERROR_MESSAGE) + " *. " +
1385 extensions::manifest_errors::kManifestUnreadable)) <<
1386 base::UTF16ToUTF8(GetErrors()[3]);
1389 // Test various cases for delayed install because of missing imports.
1390 TEST_F(ExtensionServiceTest, PendingImports) {
1391 InitPluginService();
1393 base::FilePath source_install_dir =
1394 data_dir().AppendASCII("pending_updates_with_imports").AppendASCII(
1395 "Extensions");
1396 base::FilePath pref_path =
1397 source_install_dir.DirName().Append(chrome::kPreferencesFilename);
1399 InitializeInstalledExtensionService(pref_path, source_install_dir);
1401 // Verify there are no pending extensions initially.
1402 EXPECT_FALSE(service()->pending_extension_manager()->HasPendingExtensions());
1404 service()->Init();
1405 // Wait for GarbageCollectExtensions task to complete.
1406 base::RunLoop().RunUntilIdle();
1408 // These extensions are used by the extensions we test below, they must be
1409 // installed.
1410 EXPECT_TRUE(base::PathExists(extensions_install_dir().AppendASCII(
1411 "bjafgdebaacbbbecmhlhpofkepfkgcpa/1.0")));
1412 EXPECT_TRUE(base::PathExists(extensions_install_dir().AppendASCII(
1413 "hpiknbiabeeppbpihjehijgoemciehgk/2")));
1415 // Each of these extensions should have been rejected because of dependencies
1416 // that cannot be satisfied.
1417 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
1418 EXPECT_FALSE(
1419 prefs->GetDelayedInstallInfo("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
1420 EXPECT_FALSE(
1421 prefs->GetInstalledExtensionInfo("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
1422 EXPECT_FALSE(
1423 prefs->GetDelayedInstallInfo("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"));
1424 EXPECT_FALSE(
1425 prefs->GetInstalledExtensionInfo("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"));
1426 EXPECT_FALSE(
1427 prefs->GetDelayedInstallInfo("cccccccccccccccccccccccccccccccc"));
1428 EXPECT_FALSE(
1429 prefs->GetInstalledExtensionInfo("cccccccccccccccccccccccccccccccc"));
1431 // Make sure the import started for the extension with a dependency.
1432 EXPECT_TRUE(
1433 prefs->GetDelayedInstallInfo("behllobkkfkfnphdnhnkndlbkcpglgmj"));
1434 EXPECT_EQ(ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS,
1435 prefs->GetDelayedInstallReason("behllobkkfkfnphdnhnkndlbkcpglgmj"));
1437 EXPECT_FALSE(base::PathExists(extensions_install_dir().AppendASCII(
1438 "behllobkkfkfnphdnhnkndlbkcpglgmj/1.0.0.0")));
1440 EXPECT_TRUE(service()->pending_extension_manager()->HasPendingExtensions());
1441 std::string pending_id("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
1442 EXPECT_TRUE(service()->pending_extension_manager()->IsIdPending(pending_id));
1443 // Remove it because we are not testing the pending extension manager's
1444 // ability to download and install extensions.
1445 EXPECT_TRUE(service()->pending_extension_manager()->Remove(pending_id));
1448 // Test installing extensions. This test tries to install few extensions using
1449 // crx files. If you need to change those crx files, feel free to repackage
1450 // them, throw away the key used and change the id's above.
1451 TEST_F(ExtensionServiceTest, InstallExtension) {
1452 InitializeEmptyExtensionService();
1454 // Extensions not enabled.
1455 service()->set_extensions_enabled(false);
1456 base::FilePath path = data_dir().AppendASCII("good.crx");
1457 InstallCRX(path, INSTALL_FAILED);
1458 service()->set_extensions_enabled(true);
1460 ValidatePrefKeyCount(0);
1462 // A simple extension that should install without error.
1463 path = data_dir().AppendASCII("good.crx");
1464 InstallCRX(path, INSTALL_NEW);
1465 // TODO(erikkay): verify the contents of the installed extension.
1467 int pref_count = 0;
1468 ValidatePrefKeyCount(++pref_count);
1469 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
1470 ValidateIntegerPref(good_crx, "location", Manifest::INTERNAL);
1472 // An extension with page actions.
1473 path = data_dir().AppendASCII("page_action.crx");
1474 InstallCRX(path, INSTALL_NEW);
1475 ValidatePrefKeyCount(++pref_count);
1476 ValidateIntegerPref(page_action, "state", Extension::ENABLED);
1477 ValidateIntegerPref(page_action, "location", Manifest::INTERNAL);
1479 // Bad signature.
1480 path = data_dir().AppendASCII("bad_signature.crx");
1481 InstallCRX(path, INSTALL_FAILED);
1482 ValidatePrefKeyCount(pref_count);
1484 // 0-length extension file.
1485 path = data_dir().AppendASCII("not_an_extension.crx");
1486 InstallCRX(path, INSTALL_FAILED);
1487 ValidatePrefKeyCount(pref_count);
1489 // Bad magic number.
1490 path = data_dir().AppendASCII("bad_magic.crx");
1491 InstallCRX(path, INSTALL_FAILED);
1492 ValidatePrefKeyCount(pref_count);
1494 // Packed extensions may have folders or files that have underscores.
1495 // This will only cause a warning, rather than a fatal error.
1496 path = data_dir().AppendASCII("bad_underscore.crx");
1497 InstallCRX(path, INSTALL_NEW);
1498 ValidatePrefKeyCount(++pref_count);
1500 // A test for an extension with a 2048-bit public key.
1501 path = data_dir().AppendASCII("good2048.crx");
1502 InstallCRX(path, INSTALL_NEW);
1503 ValidatePrefKeyCount(++pref_count);
1504 ValidateIntegerPref(good2048, "state", Extension::ENABLED);
1505 ValidateIntegerPref(good2048, "location", Manifest::INTERNAL);
1507 // TODO(erikkay): add more tests for many of the failure cases.
1508 // TODO(erikkay): add tests for upgrade cases.
1511 struct MockExtensionRegistryObserver
1512 : public extensions::ExtensionRegistryObserver {
1513 void OnExtensionWillBeInstalled(content::BrowserContext* browser_context,
1514 const Extension* extension,
1515 bool is_update,
1516 bool from_ephemeral,
1517 const std::string& old_name) override {
1518 last_extension_installed = extension->id();
1521 void OnExtensionUninstalled(content::BrowserContext* browser_context,
1522 const Extension* extension,
1523 extensions::UninstallReason reason) override {
1524 last_extension_uninstalled = extension->id();
1527 std::string last_extension_installed;
1528 std::string last_extension_uninstalled;
1531 // Test that correct notifications are sent to ExtensionRegistryObserver on
1532 // extension install and uninstall.
1533 TEST_F(ExtensionServiceTest, InstallObserverNotified) {
1534 InitializeEmptyExtensionService();
1536 extensions::ExtensionRegistry* registry(
1537 extensions::ExtensionRegistry::Get(profile()));
1538 MockExtensionRegistryObserver observer;
1539 registry->AddObserver(&observer);
1541 // A simple extension that should install without error.
1542 ASSERT_TRUE(observer.last_extension_installed.empty());
1543 base::FilePath path = data_dir().AppendASCII("good.crx");
1544 InstallCRX(path, INSTALL_NEW);
1545 ASSERT_EQ(good_crx, observer.last_extension_installed);
1547 // Uninstall the extension.
1548 ASSERT_TRUE(observer.last_extension_uninstalled.empty());
1549 UninstallExtension(good_crx, false);
1550 ASSERT_EQ(good_crx, observer.last_extension_uninstalled);
1552 registry->RemoveObserver(&observer);
1555 // Tests that flags passed to OnExternalExtensionFileFound() make it to the
1556 // extension object.
1557 TEST_F(ExtensionServiceTest, InstallingExternalExtensionWithFlags) {
1558 const char kPrefFromBookmark[] = "from_bookmark";
1560 InitializeEmptyExtensionService();
1562 base::FilePath path = data_dir().AppendASCII("good.crx");
1563 service()->set_extensions_enabled(true);
1565 // Register and install an external extension.
1566 Version version("1.0.0.0");
1567 content::WindowedNotificationObserver observer(
1568 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
1569 content::NotificationService::AllSources());
1570 if (service()->OnExternalExtensionFileFound(
1571 good_crx,
1572 &version,
1573 path,
1574 Manifest::EXTERNAL_PREF,
1575 Extension::FROM_BOOKMARK,
1576 false /* mark_acknowledged */,
1577 false /* install_immediately */)) {
1578 observer.Wait();
1581 const Extension* extension = service()->GetExtensionById(good_crx, false);
1582 ASSERT_TRUE(extension);
1583 ASSERT_TRUE(extension->from_bookmark());
1584 ASSERT_TRUE(ValidateBooleanPref(good_crx, kPrefFromBookmark, true));
1586 // Upgrade to version 2.0, the flag should be preserved.
1587 path = data_dir().AppendASCII("good2.crx");
1588 UpdateExtension(good_crx, path, ENABLED);
1589 ASSERT_TRUE(ValidateBooleanPref(good_crx, kPrefFromBookmark, true));
1590 extension = service()->GetExtensionById(good_crx, false);
1591 ASSERT_TRUE(extension);
1592 ASSERT_TRUE(extension->from_bookmark());
1595 // Test the handling of Extension::EXTERNAL_EXTENSION_UNINSTALLED
1596 TEST_F(ExtensionServiceTest, UninstallingExternalExtensions) {
1597 InitializeEmptyExtensionService();
1599 base::FilePath path = data_dir().AppendASCII("good.crx");
1600 service()->set_extensions_enabled(true);
1602 // Install an external extension.
1603 Version version("1.0.0.0");
1604 content::WindowedNotificationObserver observer(
1605 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
1606 content::NotificationService::AllSources());
1607 if (service()->OnExternalExtensionFileFound(good_crx,
1608 &version,
1609 path,
1610 Manifest::EXTERNAL_PREF,
1611 Extension::NO_FLAGS,
1612 false,
1613 false)) {
1614 observer.Wait();
1617 ASSERT_TRUE(service()->GetExtensionById(good_crx, false));
1619 // Uninstall it and check that its killbit gets set.
1620 UninstallExtension(good_crx, false);
1621 ValidateIntegerPref(good_crx, "state",
1622 Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1624 // Try to re-install it externally. This should fail because of the killbit.
1625 service()->OnExternalExtensionFileFound(good_crx,
1626 &version,
1627 path,
1628 Manifest::EXTERNAL_PREF,
1629 Extension::NO_FLAGS,
1630 false,
1631 false);
1632 base::RunLoop().RunUntilIdle();
1633 ASSERT_TRUE(NULL == service()->GetExtensionById(good_crx, false));
1634 ValidateIntegerPref(good_crx, "state",
1635 Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1637 version = Version("1.0.0.1");
1638 // Repeat the same thing with a newer version of the extension.
1639 path = data_dir().AppendASCII("good2.crx");
1640 service()->OnExternalExtensionFileFound(good_crx,
1641 &version,
1642 path,
1643 Manifest::EXTERNAL_PREF,
1644 Extension::NO_FLAGS,
1645 false,
1646 false);
1647 base::RunLoop().RunUntilIdle();
1648 ASSERT_TRUE(NULL == service()->GetExtensionById(good_crx, false));
1649 ValidateIntegerPref(good_crx, "state",
1650 Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1652 // Try adding the same extension from an external update URL.
1653 ASSERT_FALSE(service()->pending_extension_manager()->AddFromExternalUpdateUrl(
1654 good_crx,
1655 std::string(),
1656 GURL("http:://fake.update/url"),
1657 Manifest::EXTERNAL_PREF_DOWNLOAD,
1658 Extension::NO_FLAGS,
1659 false));
1661 ASSERT_FALSE(service()->pending_extension_manager()->IsIdPending(good_crx));
1664 // Test that uninstalling an external extension does not crash when
1665 // the extension could not be loaded.
1666 // This extension shown in preferences file requires an experimental permission.
1667 // It could not be loaded without such permission.
1668 TEST_F(ExtensionServiceTest, UninstallingNotLoadedExtension) {
1669 base::FilePath source_install_dir =
1670 data_dir().AppendASCII("good").AppendASCII("Extensions");
1671 // The preference contains an external extension
1672 // that requires 'experimental' permission.
1673 base::FilePath pref_path = source_install_dir
1674 .DirName()
1675 .AppendASCII("PreferencesExperimental");
1677 // Aforementioned extension will not be loaded if
1678 // there is no '--enable-experimental-extension-apis' command line flag.
1679 InitializeInstalledExtensionService(pref_path, source_install_dir);
1681 service()->Init();
1683 // Check and try to uninstall it.
1684 // If we don't check whether the extension is loaded before we uninstall it
1685 // in CheckExternalUninstall, a crash will happen here because we will get or
1686 // dereference a NULL pointer (extension) inside UninstallExtension.
1687 MockExtensionProvider provider(NULL, Manifest::EXTERNAL_REGISTRY);
1688 service()->OnExternalProviderReady(&provider);
1691 // Test that external extensions with incorrect IDs are not installed.
1692 TEST_F(ExtensionServiceTest, FailOnWrongId) {
1693 InitializeEmptyExtensionService();
1694 base::FilePath path = data_dir().AppendASCII("good.crx");
1695 service()->set_extensions_enabled(true);
1697 Version version("1.0.0.0");
1699 const std::string wrong_id = all_zero;
1700 const std::string correct_id = good_crx;
1701 ASSERT_NE(correct_id, wrong_id);
1703 // Install an external extension with an ID from the external
1704 // source that is not equal to the ID in the extension manifest.
1705 content::WindowedNotificationObserver observer(
1706 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
1707 content::NotificationService::AllSources());
1708 service()->OnExternalExtensionFileFound(wrong_id,
1709 &version,
1710 path,
1711 Manifest::EXTERNAL_PREF,
1712 Extension::NO_FLAGS,
1713 false,
1714 false);
1716 observer.Wait();
1717 ASSERT_FALSE(service()->GetExtensionById(good_crx, false));
1719 // Try again with the right ID. Expect success.
1720 content::WindowedNotificationObserver observer2(
1721 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
1722 content::NotificationService::AllSources());
1723 if (service()->OnExternalExtensionFileFound(correct_id,
1724 &version,
1725 path,
1726 Manifest::EXTERNAL_PREF,
1727 Extension::NO_FLAGS,
1728 false,
1729 false)) {
1730 observer2.Wait();
1732 ASSERT_TRUE(service()->GetExtensionById(good_crx, false));
1735 // Test that external extensions with incorrect versions are not installed.
1736 TEST_F(ExtensionServiceTest, FailOnWrongVersion) {
1737 InitializeEmptyExtensionService();
1738 base::FilePath path = data_dir().AppendASCII("good.crx");
1739 service()->set_extensions_enabled(true);
1741 // Install an external extension with a version from the external
1742 // source that is not equal to the version in the extension manifest.
1743 Version wrong_version("1.2.3.4");
1744 content::WindowedNotificationObserver observer(
1745 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
1746 content::NotificationService::AllSources());
1747 service()->OnExternalExtensionFileFound(good_crx,
1748 &wrong_version,
1749 path,
1750 Manifest::EXTERNAL_PREF,
1751 Extension::NO_FLAGS,
1752 false,
1753 false);
1755 observer.Wait();
1756 ASSERT_FALSE(service()->GetExtensionById(good_crx, false));
1758 // Try again with the right version. Expect success.
1759 service()->pending_extension_manager()->Remove(good_crx);
1760 Version correct_version("1.0.0.0");
1761 content::WindowedNotificationObserver observer2(
1762 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
1763 content::NotificationService::AllSources());
1764 if (service()->OnExternalExtensionFileFound(good_crx,
1765 &correct_version,
1766 path,
1767 Manifest::EXTERNAL_PREF,
1768 Extension::NO_FLAGS,
1769 false,
1770 false)) {
1771 observer2.Wait();
1773 ASSERT_TRUE(service()->GetExtensionById(good_crx, false));
1776 // Install a user script (they get converted automatically to an extension)
1777 TEST_F(ExtensionServiceTest, InstallUserScript) {
1778 // The details of script conversion are tested elsewhere, this just tests
1779 // integration with ExtensionService.
1780 InitializeEmptyExtensionService();
1782 base::FilePath path = data_dir().AppendASCII("user_script_basic.user.js");
1784 ASSERT_TRUE(base::PathExists(path));
1785 scoped_refptr<CrxInstaller> installer(CrxInstaller::CreateSilent(service()));
1786 installer->set_allow_silent_install(true);
1787 installer->InstallUserScript(
1788 path,
1789 GURL("http://www.aaronboodman.com/scripts/user_script_basic.user.js"));
1791 base::RunLoop().RunUntilIdle();
1792 std::vector<base::string16> errors = GetErrors();
1793 EXPECT_TRUE(installed_) << "Nothing was installed.";
1794 EXPECT_FALSE(was_update_) << path.value();
1795 ASSERT_EQ(1u, loaded_.size()) << "Nothing was loaded.";
1796 EXPECT_EQ(0u, errors.size()) << "There were errors: "
1797 << JoinString(errors, ',');
1798 EXPECT_TRUE(service()->GetExtensionById(loaded_[0]->id(), false))
1799 << path.value();
1801 installed_ = NULL;
1802 was_update_ = false;
1803 loaded_.clear();
1804 ExtensionErrorReporter::GetInstance()->ClearErrors();
1807 // Extensions don't install during shutdown.
1808 TEST_F(ExtensionServiceTest, InstallExtensionDuringShutdown) {
1809 InitializeEmptyExtensionService();
1811 // Simulate shutdown.
1812 service()->set_browser_terminating_for_test(true);
1814 base::FilePath path = data_dir().AppendASCII("good.crx");
1815 scoped_refptr<CrxInstaller> installer(CrxInstaller::CreateSilent(service()));
1816 installer->set_allow_silent_install(true);
1817 installer->InstallCrx(path);
1818 base::RunLoop().RunUntilIdle();
1820 EXPECT_FALSE(installed_) << "Extension installed during shutdown.";
1821 ASSERT_EQ(0u, loaded_.size()) << "Extension loaded during shutdown.";
1824 // This tests that the granted permissions preferences are correctly set when
1825 // installing an extension.
1826 TEST_F(ExtensionServiceTest, GrantedPermissions) {
1827 InitializeEmptyExtensionService();
1828 base::FilePath path = data_dir().AppendASCII("permissions");
1830 base::FilePath pem_path = path.AppendASCII("unknown.pem");
1831 path = path.AppendASCII("unknown");
1833 ASSERT_TRUE(base::PathExists(pem_path));
1834 ASSERT_TRUE(base::PathExists(path));
1836 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
1838 APIPermissionSet expected_api_perms;
1839 URLPatternSet expected_host_perms;
1841 // Make sure there aren't any granted permissions before the
1842 // extension is installed.
1843 scoped_refptr<PermissionSet> known_perms(
1844 prefs->GetGrantedPermissions(permissions_crx));
1845 EXPECT_FALSE(known_perms.get());
1847 const Extension* extension = PackAndInstallCRX(path, pem_path, INSTALL_NEW);
1849 EXPECT_EQ(0u, GetErrors().size());
1850 ASSERT_EQ(1u, registry()->enabled_extensions().size());
1851 EXPECT_EQ(permissions_crx, extension->id());
1853 // Verify that the valid API permissions have been recognized.
1854 expected_api_perms.insert(APIPermission::kTab);
1856 AddPattern(&expected_host_perms, "http://*.google.com/*");
1857 AddPattern(&expected_host_perms, "https://*.google.com/*");
1858 AddPattern(&expected_host_perms, "http://*.google.com.hk/*");
1859 AddPattern(&expected_host_perms, "http://www.example.com/*");
1861 known_perms = prefs->GetGrantedPermissions(extension->id());
1862 EXPECT_TRUE(known_perms.get());
1863 EXPECT_FALSE(known_perms->IsEmpty());
1864 EXPECT_EQ(expected_api_perms, known_perms->apis());
1865 EXPECT_FALSE(known_perms->HasEffectiveFullAccess());
1866 EXPECT_EQ(expected_host_perms, known_perms->effective_hosts());
1870 #if !defined(OS_CHROMEOS)
1871 // This tests that the granted permissions preferences are correctly set for
1872 // default apps.
1873 TEST_F(ExtensionServiceTest, DefaultAppsGrantedPermissions) {
1874 InitializeEmptyExtensionService();
1875 base::FilePath path = data_dir().AppendASCII("permissions");
1877 base::FilePath pem_path = path.AppendASCII("unknown.pem");
1878 path = path.AppendASCII("unknown");
1880 ASSERT_TRUE(base::PathExists(pem_path));
1881 ASSERT_TRUE(base::PathExists(path));
1883 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
1885 APIPermissionSet expected_api_perms;
1886 URLPatternSet expected_host_perms;
1888 // Make sure there aren't any granted permissions before the
1889 // extension is installed.
1890 scoped_refptr<PermissionSet> known_perms(
1891 prefs->GetGrantedPermissions(permissions_crx));
1892 EXPECT_FALSE(known_perms.get());
1894 const Extension* extension = PackAndInstallCRX(
1895 path, pem_path, INSTALL_NEW, Extension::WAS_INSTALLED_BY_DEFAULT);
1897 EXPECT_EQ(0u, GetErrors().size());
1898 ASSERT_EQ(1u, registry()->enabled_extensions().size());
1899 EXPECT_EQ(permissions_crx, extension->id());
1901 // Verify that the valid API permissions have been recognized.
1902 expected_api_perms.insert(APIPermission::kTab);
1904 known_perms = prefs->GetGrantedPermissions(extension->id());
1905 EXPECT_TRUE(known_perms.get());
1906 EXPECT_FALSE(known_perms->IsEmpty());
1907 EXPECT_EQ(expected_api_perms, known_perms->apis());
1908 EXPECT_FALSE(known_perms->HasEffectiveFullAccess());
1910 #endif
1912 #if !defined(OS_POSIX) || defined(OS_MACOSX)
1913 // Tests that the granted permissions full_access bit gets set correctly when
1914 // an extension contains an NPAPI plugin.
1915 // Only run this on platforms that support NPAPI plugins.
1916 TEST_F(ExtensionServiceTest, GrantedFullAccessPermissions) {
1917 InitPluginService();
1919 InitializeEmptyExtensionService();
1921 ASSERT_TRUE(base::PathExists(good1_path()));
1922 const Extension* extension = PackAndInstallCRX(good1_path(), INSTALL_NEW);
1923 EXPECT_EQ(0u, GetErrors().size());
1924 EXPECT_EQ(1u, registry()->enabled_extensions().size());
1925 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
1927 scoped_refptr<PermissionSet> permissions(
1928 prefs->GetGrantedPermissions(extension->id()));
1929 EXPECT_FALSE(permissions->IsEmpty());
1930 EXPECT_TRUE(permissions->HasEffectiveFullAccess());
1931 EXPECT_FALSE(permissions->apis().empty());
1932 EXPECT_TRUE(permissions->HasAPIPermission(APIPermission::kPlugin));
1934 // Full access implies full host access too...
1935 EXPECT_TRUE(permissions->HasEffectiveAccessToAllHosts());
1937 #endif
1939 // Tests that the extension is disabled when permissions are missing from
1940 // the extension's granted permissions preferences. (This simulates updating
1941 // the browser to a version which recognizes more permissions).
1942 TEST_F(ExtensionServiceTest, GrantedAPIAndHostPermissions) {
1943 InitializeEmptyExtensionService();
1945 base::FilePath path =
1946 data_dir().AppendASCII("permissions").AppendASCII("unknown");
1948 ASSERT_TRUE(base::PathExists(path));
1950 const Extension* extension = PackAndInstallCRX(path, INSTALL_NEW);
1952 EXPECT_EQ(0u, GetErrors().size());
1953 EXPECT_EQ(1u, registry()->enabled_extensions().size());
1954 std::string extension_id = extension->id();
1956 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
1958 APIPermissionSet expected_api_permissions;
1959 URLPatternSet expected_host_permissions;
1961 expected_api_permissions.insert(APIPermission::kTab);
1962 AddPattern(&expected_host_permissions, "http://*.google.com/*");
1963 AddPattern(&expected_host_permissions, "https://*.google.com/*");
1964 AddPattern(&expected_host_permissions, "http://*.google.com.hk/*");
1965 AddPattern(&expected_host_permissions, "http://www.example.com/*");
1967 std::set<std::string> host_permissions;
1969 // Test that the extension is disabled when an API permission is missing from
1970 // the extension's granted api permissions preference. (This simulates
1971 // updating the browser to a version which recognizes a new API permission).
1972 SetPref(extension_id, "granted_permissions.api",
1973 new base::ListValue(), "granted_permissions.api");
1974 service()->ReloadExtensionsForTest();
1976 EXPECT_EQ(1u, registry()->disabled_extensions().size());
1977 extension = registry()->disabled_extensions().begin()->get();
1979 ASSERT_TRUE(prefs->IsExtensionDisabled(extension_id));
1980 ASSERT_FALSE(service()->IsExtensionEnabled(extension_id));
1981 ASSERT_TRUE(prefs->DidExtensionEscalatePermissions(extension_id));
1983 // Now grant and re-enable the extension, making sure the prefs are updated.
1984 service()->GrantPermissionsAndEnableExtension(extension);
1986 ASSERT_FALSE(prefs->IsExtensionDisabled(extension_id));
1987 ASSERT_TRUE(service()->IsExtensionEnabled(extension_id));
1988 ASSERT_FALSE(prefs->DidExtensionEscalatePermissions(extension_id));
1990 scoped_refptr<PermissionSet> current_perms(
1991 prefs->GetGrantedPermissions(extension_id));
1992 ASSERT_TRUE(current_perms.get());
1993 ASSERT_FALSE(current_perms->IsEmpty());
1994 ASSERT_FALSE(current_perms->HasEffectiveFullAccess());
1995 ASSERT_EQ(expected_api_permissions, current_perms->apis());
1996 ASSERT_EQ(expected_host_permissions, current_perms->effective_hosts());
1998 // Tests that the extension is disabled when a host permission is missing from
1999 // the extension's granted host permissions preference. (This simulates
2000 // updating the browser to a version which recognizes additional host
2001 // permissions).
2002 host_permissions.clear();
2003 current_perms = NULL;
2005 host_permissions.insert("http://*.google.com/*");
2006 host_permissions.insert("https://*.google.com/*");
2007 host_permissions.insert("http://*.google.com.hk/*");
2009 base::ListValue* api_permissions = new base::ListValue();
2010 api_permissions->Append(
2011 new base::StringValue("tabs"));
2012 SetPref(extension_id, "granted_permissions.api",
2013 api_permissions, "granted_permissions.api");
2014 SetPrefStringSet(
2015 extension_id, "granted_permissions.scriptable_host", host_permissions);
2017 service()->ReloadExtensionsForTest();
2019 EXPECT_EQ(1u, registry()->disabled_extensions().size());
2020 extension = registry()->disabled_extensions().begin()->get();
2022 ASSERT_TRUE(prefs->IsExtensionDisabled(extension_id));
2023 ASSERT_FALSE(service()->IsExtensionEnabled(extension_id));
2024 ASSERT_TRUE(prefs->DidExtensionEscalatePermissions(extension_id));
2026 // Now grant and re-enable the extension, making sure the prefs are updated.
2027 service()->GrantPermissionsAndEnableExtension(extension);
2029 ASSERT_TRUE(service()->IsExtensionEnabled(extension_id));
2030 ASSERT_FALSE(prefs->DidExtensionEscalatePermissions(extension_id));
2032 current_perms = prefs->GetGrantedPermissions(extension_id);
2033 ASSERT_TRUE(current_perms.get());
2034 ASSERT_FALSE(current_perms->IsEmpty());
2035 ASSERT_FALSE(current_perms->HasEffectiveFullAccess());
2036 ASSERT_EQ(expected_api_permissions, current_perms->apis());
2037 ASSERT_EQ(expected_host_permissions, current_perms->effective_hosts());
2040 // Test Packaging and installing an extension.
2041 TEST_F(ExtensionServiceTest, PackExtension) {
2042 InitializeEmptyExtensionService();
2043 base::FilePath input_directory =
2044 data_dir()
2045 .AppendASCII("good")
2046 .AppendASCII("Extensions")
2047 .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
2048 .AppendASCII("1.0.0.0");
2050 base::ScopedTempDir temp_dir;
2051 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
2052 base::FilePath output_directory = temp_dir.path();
2054 base::FilePath crx_path(output_directory.AppendASCII("ex1.crx"));
2055 base::FilePath privkey_path(output_directory.AppendASCII("privkey.pem"));
2057 scoped_ptr<ExtensionCreator> creator(new ExtensionCreator());
2058 ASSERT_TRUE(creator->Run(input_directory, crx_path, base::FilePath(),
2059 privkey_path, ExtensionCreator::kNoRunFlags));
2060 ASSERT_TRUE(base::PathExists(crx_path));
2061 ASSERT_TRUE(base::PathExists(privkey_path));
2063 // Repeat the run with the pem file gone, and no special flags
2064 // Should refuse to overwrite the existing crx.
2065 base::DeleteFile(privkey_path, false);
2066 ASSERT_FALSE(creator->Run(input_directory, crx_path, base::FilePath(),
2067 privkey_path, ExtensionCreator::kNoRunFlags));
2069 // OK, now try it with a flag to overwrite existing crx. Should work.
2070 ASSERT_TRUE(creator->Run(input_directory, crx_path, base::FilePath(),
2071 privkey_path, ExtensionCreator::kOverwriteCRX));
2073 // Repeat the run allowing existing crx, but the existing pem is still
2074 // an error. Should fail.
2075 ASSERT_FALSE(creator->Run(input_directory, crx_path, base::FilePath(),
2076 privkey_path, ExtensionCreator::kOverwriteCRX));
2078 ASSERT_TRUE(base::PathExists(privkey_path));
2079 InstallCRX(crx_path, INSTALL_NEW);
2081 // Try packing with invalid paths.
2082 creator.reset(new ExtensionCreator());
2083 ASSERT_FALSE(
2084 creator->Run(base::FilePath(), base::FilePath(), base::FilePath(),
2085 base::FilePath(), ExtensionCreator::kOverwriteCRX));
2087 // Try packing an empty directory. Should fail because an empty directory is
2088 // not a valid extension.
2089 base::ScopedTempDir temp_dir2;
2090 ASSERT_TRUE(temp_dir2.CreateUniqueTempDir());
2091 creator.reset(new ExtensionCreator());
2092 ASSERT_FALSE(creator->Run(temp_dir2.path(), crx_path, privkey_path,
2093 base::FilePath(), ExtensionCreator::kOverwriteCRX));
2095 // Try packing with an invalid manifest.
2096 std::string invalid_manifest_content = "I am not a manifest.";
2097 ASSERT_TRUE(base::WriteFile(
2098 temp_dir2.path().Append(extensions::kManifestFilename),
2099 invalid_manifest_content.c_str(), invalid_manifest_content.size()));
2100 creator.reset(new ExtensionCreator());
2101 ASSERT_FALSE(creator->Run(temp_dir2.path(), crx_path, privkey_path,
2102 base::FilePath(), ExtensionCreator::kOverwriteCRX));
2104 // Try packing with a private key that is a valid key, but invalid for the
2105 // extension.
2106 base::FilePath bad_private_key_dir =
2107 data_dir().AppendASCII("bad_private_key");
2108 crx_path = output_directory.AppendASCII("bad_private_key.crx");
2109 privkey_path = data_dir().AppendASCII("bad_private_key.pem");
2110 ASSERT_FALSE(creator->Run(bad_private_key_dir, crx_path, base::FilePath(),
2111 privkey_path, ExtensionCreator::kOverwriteCRX));
2114 // Test Packaging and installing an extension whose name contains punctuation.
2115 TEST_F(ExtensionServiceTest, PackPunctuatedExtension) {
2116 InitializeEmptyExtensionService();
2117 base::FilePath input_directory = data_dir()
2118 .AppendASCII("good")
2119 .AppendASCII("Extensions")
2120 .AppendASCII(good0)
2121 .AppendASCII("1.0.0.0");
2123 base::ScopedTempDir temp_dir;
2124 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
2126 // Extension names containing punctuation, and the expected names for the
2127 // packed extensions.
2128 const base::FilePath punctuated_names[] = {
2129 base::FilePath(FILE_PATH_LITERAL("this.extensions.name.has.periods")),
2130 base::FilePath(FILE_PATH_LITERAL(".thisextensionsnamestartswithaperiod")),
2131 base::FilePath(FILE_PATH_LITERAL("thisextensionhasaslashinitsname/")).
2132 NormalizePathSeparators(),
2134 const base::FilePath expected_crx_names[] = {
2135 base::FilePath(FILE_PATH_LITERAL("this.extensions.name.has.periods.crx")),
2136 base::FilePath(
2137 FILE_PATH_LITERAL(".thisextensionsnamestartswithaperiod.crx")),
2138 base::FilePath(FILE_PATH_LITERAL("thisextensionhasaslashinitsname.crx")),
2140 const base::FilePath expected_private_key_names[] = {
2141 base::FilePath(FILE_PATH_LITERAL("this.extensions.name.has.periods.pem")),
2142 base::FilePath(
2143 FILE_PATH_LITERAL(".thisextensionsnamestartswithaperiod.pem")),
2144 base::FilePath(FILE_PATH_LITERAL("thisextensionhasaslashinitsname.pem")),
2147 for (size_t i = 0; i < arraysize(punctuated_names); ++i) {
2148 SCOPED_TRACE(punctuated_names[i].value().c_str());
2149 base::FilePath output_dir = temp_dir.path().Append(punctuated_names[i]);
2151 // Copy the extension into the output directory, as PackExtensionJob doesn't
2152 // let us choose where to output the packed extension.
2153 ASSERT_TRUE(base::CopyDirectory(input_directory, output_dir, true));
2155 base::FilePath expected_crx_path =
2156 temp_dir.path().Append(expected_crx_names[i]);
2157 base::FilePath expected_private_key_path =
2158 temp_dir.path().Append(expected_private_key_names[i]);
2159 PackExtensionTestClient pack_client(expected_crx_path,
2160 expected_private_key_path);
2161 scoped_refptr<extensions::PackExtensionJob> packer(
2162 new extensions::PackExtensionJob(&pack_client, output_dir,
2163 base::FilePath(),
2164 ExtensionCreator::kOverwriteCRX));
2165 packer->Start();
2167 // The packer will post a notification task to the current thread's message
2168 // loop when it is finished. We manually run the loop here so that we
2169 // block and catch the notification; otherwise, the process would exit.
2170 // This call to |Run()| is matched by a call to |Quit()| in the
2171 // |PackExtensionTestClient|'s notification handling code.
2172 base::MessageLoop::current()->Run();
2174 if (HasFatalFailure())
2175 return;
2177 InstallCRX(expected_crx_path, INSTALL_NEW);
2181 TEST_F(ExtensionServiceTest, PackExtensionContainingKeyFails) {
2182 InitializeEmptyExtensionService();
2184 base::ScopedTempDir extension_temp_dir;
2185 ASSERT_TRUE(extension_temp_dir.CreateUniqueTempDir());
2186 base::FilePath input_directory = extension_temp_dir.path().AppendASCII("ext");
2187 ASSERT_TRUE(
2188 base::CopyDirectory(data_dir()
2189 .AppendASCII("good")
2190 .AppendASCII("Extensions")
2191 .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
2192 .AppendASCII("1.0.0.0"),
2193 input_directory,
2194 /*recursive=*/true));
2196 base::ScopedTempDir output_temp_dir;
2197 ASSERT_TRUE(output_temp_dir.CreateUniqueTempDir());
2198 base::FilePath output_directory = output_temp_dir.path();
2200 base::FilePath crx_path(output_directory.AppendASCII("ex1.crx"));
2201 base::FilePath privkey_path(output_directory.AppendASCII("privkey.pem"));
2203 // Pack the extension once to get a private key.
2204 scoped_ptr<ExtensionCreator> creator(new ExtensionCreator());
2205 ASSERT_TRUE(creator->Run(input_directory, crx_path, base::FilePath(),
2206 privkey_path, ExtensionCreator::kNoRunFlags))
2207 << creator->error_message();
2208 ASSERT_TRUE(base::PathExists(crx_path));
2209 ASSERT_TRUE(base::PathExists(privkey_path));
2211 base::DeleteFile(crx_path, false);
2212 // Move the pem file into the extension.
2213 base::Move(privkey_path,
2214 input_directory.AppendASCII("privkey.pem"));
2216 // This pack should fail because of the contained private key.
2217 EXPECT_FALSE(creator->Run(input_directory, crx_path, base::FilePath(),
2218 privkey_path, ExtensionCreator::kNoRunFlags));
2219 EXPECT_THAT(creator->error_message(),
2220 testing::ContainsRegex(
2221 "extension includes the key file.*privkey.pem"));
2224 // Test Packaging and installing an extension using an openssl generated key.
2225 // The openssl is generated with the following:
2226 // > openssl genrsa -out privkey.pem 1024
2227 // > openssl pkcs8 -topk8 -nocrypt -in privkey.pem -out privkey_asn1.pem
2228 // The privkey.pem is a PrivateKey, and the pcks8 -topk8 creates a
2229 // PrivateKeyInfo ASN.1 structure, we our RSAPrivateKey expects.
2230 TEST_F(ExtensionServiceTest, PackExtensionOpenSSLKey) {
2231 InitializeEmptyExtensionService();
2232 base::FilePath input_directory =
2233 data_dir()
2234 .AppendASCII("good")
2235 .AppendASCII("Extensions")
2236 .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
2237 .AppendASCII("1.0.0.0");
2238 base::FilePath privkey_path(
2239 data_dir().AppendASCII("openssl_privkey_asn1.pem"));
2240 ASSERT_TRUE(base::PathExists(privkey_path));
2242 base::ScopedTempDir temp_dir;
2243 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
2244 base::FilePath output_directory = temp_dir.path();
2246 base::FilePath crx_path(output_directory.AppendASCII("ex1.crx"));
2248 scoped_ptr<ExtensionCreator> creator(new ExtensionCreator());
2249 ASSERT_TRUE(creator->Run(input_directory, crx_path, privkey_path,
2250 base::FilePath(), ExtensionCreator::kOverwriteCRX));
2252 InstallCRX(crx_path, INSTALL_NEW);
2255 #if defined(THREAD_SANITIZER)
2256 // Flaky under Tsan. http://crbug.com/377702
2257 #define MAYBE_InstallTheme DISABLED_InstallTheme
2258 #else
2259 #define MAYBE_InstallTheme InstallTheme
2260 #endif
2262 TEST_F(ExtensionServiceTest, MAYBE_InstallTheme) {
2263 InitializeEmptyExtensionService();
2264 service()->Init();
2266 // A theme.
2267 base::FilePath path = data_dir().AppendASCII("theme.crx");
2268 InstallCRX(path, INSTALL_NEW);
2269 int pref_count = 0;
2270 ValidatePrefKeyCount(++pref_count);
2271 ValidateIntegerPref(theme_crx, "state", Extension::ENABLED);
2272 ValidateIntegerPref(theme_crx, "location", Manifest::INTERNAL);
2274 // A theme when extensions are disabled. Themes can be installed, even when
2275 // extensions are disabled.
2276 service()->set_extensions_enabled(false);
2277 path = data_dir().AppendASCII("theme2.crx");
2278 InstallCRX(path, INSTALL_NEW);
2279 ValidatePrefKeyCount(++pref_count);
2280 ValidateIntegerPref(theme2_crx, "state", Extension::ENABLED);
2281 ValidateIntegerPref(theme2_crx, "location", Manifest::INTERNAL);
2283 // A theme with extension elements. Themes cannot have extension elements,
2284 // so any such elements (like content scripts) should be ignored.
2285 service()->set_extensions_enabled(true);
2287 path = data_dir().AppendASCII("theme_with_extension.crx");
2288 const Extension* extension = InstallCRX(path, INSTALL_NEW);
2289 ValidatePrefKeyCount(++pref_count);
2290 ASSERT_TRUE(extension);
2291 EXPECT_TRUE(extension->is_theme());
2292 EXPECT_EQ(
2294 extensions::ContentScriptsInfo::GetContentScripts(extension).size());
2297 // A theme with image resources missing (misspelt path).
2298 path = data_dir().AppendASCII("theme_missing_image.crx");
2299 InstallCRX(path, INSTALL_FAILED);
2300 ValidatePrefKeyCount(pref_count);
2303 TEST_F(ExtensionServiceTest, LoadLocalizedTheme) {
2304 // Load.
2305 InitializeEmptyExtensionService();
2306 service()->Init();
2308 base::FilePath extension_path = data_dir().AppendASCII("theme_i18n");
2310 extensions::UnpackedInstaller::Create(service())->Load(extension_path);
2311 base::RunLoop().RunUntilIdle();
2312 EXPECT_EQ(0u, GetErrors().size());
2313 ASSERT_EQ(1u, loaded_.size());
2314 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2315 const Extension* theme = registry()->enabled_extensions().begin()->get();
2316 EXPECT_EQ("name", theme->name());
2317 EXPECT_EQ("description", theme->description());
2319 // Cleanup the "Cached Theme.pak" file. Ideally, this would be installed in a
2320 // temporary directory, but it automatically installs to the extension's
2321 // directory, and we don't want to copy the whole extension for a unittest.
2322 base::FilePath theme_file = extension_path.Append(chrome::kThemePackFilename);
2323 ASSERT_TRUE(base::PathExists(theme_file));
2324 ASSERT_TRUE(base::DeleteFile(theme_file, false)); // Not recursive.
2327 // Tests that we can change the ID of an unpacked extension by adding a key
2328 // to its manifest.
2329 TEST_F(ExtensionServiceTest, UnpackedExtensionCanChangeID) {
2330 InitializeEmptyExtensionService();
2332 base::ScopedTempDir temp;
2333 ASSERT_TRUE(temp.CreateUniqueTempDir());
2335 base::FilePath extension_path = temp.path();
2336 base::FilePath manifest_path =
2337 extension_path.Append(extensions::kManifestFilename);
2338 base::FilePath manifest_no_key =
2339 data_dir().AppendASCII("unpacked").AppendASCII("manifest_no_key.json");
2341 base::FilePath manifest_with_key =
2342 data_dir().AppendASCII("unpacked").AppendASCII("manifest_with_key.json");
2344 ASSERT_TRUE(base::PathExists(manifest_no_key));
2345 ASSERT_TRUE(base::PathExists(manifest_with_key));
2347 // Load the unpacked extension with no key.
2348 base::CopyFile(manifest_no_key, manifest_path);
2349 extensions::UnpackedInstaller::Create(service())->Load(extension_path);
2351 base::RunLoop().RunUntilIdle();
2352 EXPECT_EQ(0u, GetErrors().size());
2353 ASSERT_EQ(1u, loaded_.size());
2354 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2356 // Add the key to the manifest.
2357 base::CopyFile(manifest_with_key, manifest_path);
2358 loaded_.clear();
2360 // Reload the extensions.
2361 service()->ReloadExtensionsForTest();
2362 const Extension* extension = service()->GetExtensionById(unpacked, false);
2363 EXPECT_EQ(unpacked, extension->id());
2364 ASSERT_EQ(1u, loaded_.size());
2366 // TODO(jstritar): Right now this just makes sure we don't crash and burn, but
2367 // we should also test that preferences are preserved.
2370 #if defined(OS_POSIX)
2371 TEST_F(ExtensionServiceTest, UnpackedExtensionMayContainSymlinkedFiles) {
2372 base::FilePath source_data_dir =
2373 data_dir().AppendASCII("unpacked").AppendASCII("symlinks_allowed");
2375 // Paths to test data files.
2376 base::FilePath source_manifest = source_data_dir.AppendASCII("manifest.json");
2377 ASSERT_TRUE(base::PathExists(source_manifest));
2378 base::FilePath source_icon = source_data_dir.AppendASCII("icon.png");
2379 ASSERT_TRUE(base::PathExists(source_icon));
2381 // Set up the temporary extension directory.
2382 base::ScopedTempDir temp;
2383 ASSERT_TRUE(temp.CreateUniqueTempDir());
2384 base::FilePath extension_path = temp.path();
2385 base::FilePath manifest = extension_path.Append(
2386 extensions::kManifestFilename);
2387 base::FilePath icon_symlink = extension_path.AppendASCII("icon.png");
2388 base::CopyFile(source_manifest, manifest);
2389 base::CreateSymbolicLink(source_icon, icon_symlink);
2391 // Load extension.
2392 InitializeEmptyExtensionService();
2393 extensions::UnpackedInstaller::Create(service())->Load(extension_path);
2394 base::RunLoop().RunUntilIdle();
2396 EXPECT_TRUE(GetErrors().empty());
2397 ASSERT_EQ(1u, loaded_.size());
2398 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2400 #endif
2402 TEST_F(ExtensionServiceTest, UnpackedExtensionMayNotHaveUnderscore) {
2403 InitializeEmptyExtensionService();
2404 base::FilePath extension_path = data_dir().AppendASCII("underscore_name");
2405 extensions::UnpackedInstaller::Create(service())->Load(extension_path);
2406 base::RunLoop().RunUntilIdle();
2407 EXPECT_EQ(1u, GetErrors().size());
2408 EXPECT_EQ(0u, registry()->enabled_extensions().size());
2411 TEST_F(ExtensionServiceTest, InstallLocalizedTheme) {
2412 InitializeEmptyExtensionService();
2413 service()->Init();
2415 base::FilePath theme_path = data_dir().AppendASCII("theme_i18n");
2417 const Extension* theme = PackAndInstallCRX(theme_path, INSTALL_NEW);
2419 EXPECT_EQ(0u, GetErrors().size());
2420 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2421 EXPECT_EQ("name", theme->name());
2422 EXPECT_EQ("description", theme->description());
2425 TEST_F(ExtensionServiceTest, InstallApps) {
2426 InitializeEmptyExtensionService();
2428 // An empty app.
2429 const Extension* app =
2430 PackAndInstallCRX(data_dir().AppendASCII("app1"), INSTALL_NEW);
2431 int pref_count = 0;
2432 ValidatePrefKeyCount(++pref_count);
2433 ASSERT_EQ(1u, registry()->enabled_extensions().size());
2434 ValidateIntegerPref(app->id(), "state", Extension::ENABLED);
2435 ValidateIntegerPref(app->id(), "location", Manifest::INTERNAL);
2437 // Another app with non-overlapping extent. Should succeed.
2438 PackAndInstallCRX(data_dir().AppendASCII("app2"), INSTALL_NEW);
2439 ValidatePrefKeyCount(++pref_count);
2441 // A third app whose extent overlaps the first. Should fail.
2442 PackAndInstallCRX(data_dir().AppendASCII("app3"), INSTALL_FAILED);
2443 ValidatePrefKeyCount(pref_count);
2446 // Tests that file access is OFF by default.
2447 TEST_F(ExtensionServiceTest, DefaultFileAccess) {
2448 InitializeEmptyExtensionService();
2449 const Extension* extension = PackAndInstallCRX(
2450 data_dir().AppendASCII("permissions").AppendASCII("files"), INSTALL_NEW);
2451 EXPECT_EQ(0u, GetErrors().size());
2452 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2453 EXPECT_FALSE(
2454 ExtensionPrefs::Get(profile())->AllowFileAccess(extension->id()));
2457 TEST_F(ExtensionServiceTest, UpdateApps) {
2458 InitializeEmptyExtensionService();
2459 base::FilePath extensions_path = data_dir().AppendASCII("app_update");
2461 // First install v1 of a hosted app.
2462 const Extension* extension =
2463 InstallCRX(extensions_path.AppendASCII("v1.crx"), INSTALL_NEW);
2464 ASSERT_EQ(1u, registry()->enabled_extensions().size());
2465 std::string id = extension->id();
2466 ASSERT_EQ(std::string("1"), extension->version()->GetString());
2468 // Now try updating to v2.
2469 UpdateExtension(id,
2470 extensions_path.AppendASCII("v2.crx"),
2471 ENABLED);
2472 ASSERT_EQ(std::string("2"),
2473 service()->GetExtensionById(id, false)->version()->GetString());
2476 // Verifies that the NTP page and launch ordinals are kept when updating apps.
2477 TEST_F(ExtensionServiceTest, UpdateAppsRetainOrdinals) {
2478 InitializeEmptyExtensionService();
2479 AppSorting* sorting = ExtensionPrefs::Get(profile())->app_sorting();
2480 base::FilePath extensions_path = data_dir().AppendASCII("app_update");
2482 // First install v1 of a hosted app.
2483 const Extension* extension =
2484 InstallCRX(extensions_path.AppendASCII("v1.crx"), INSTALL_NEW);
2485 ASSERT_EQ(1u, registry()->enabled_extensions().size());
2486 std::string id = extension->id();
2487 ASSERT_EQ(std::string("1"), extension->version()->GetString());
2489 // Modify the ordinals so we can distinguish them from the defaults.
2490 syncer::StringOrdinal new_page_ordinal =
2491 sorting->GetPageOrdinal(id).CreateAfter();
2492 syncer::StringOrdinal new_launch_ordinal =
2493 sorting->GetAppLaunchOrdinal(id).CreateBefore();
2495 sorting->SetPageOrdinal(id, new_page_ordinal);
2496 sorting->SetAppLaunchOrdinal(id, new_launch_ordinal);
2498 // Now try updating to v2.
2499 UpdateExtension(id, extensions_path.AppendASCII("v2.crx"), ENABLED);
2500 ASSERT_EQ(std::string("2"),
2501 service()->GetExtensionById(id, false)->version()->GetString());
2503 // Verify that the ordinals match.
2504 ASSERT_TRUE(new_page_ordinal.Equals(sorting->GetPageOrdinal(id)));
2505 ASSERT_TRUE(new_launch_ordinal.Equals(sorting->GetAppLaunchOrdinal(id)));
2508 // Ensures that the CWS has properly initialized ordinals.
2509 TEST_F(ExtensionServiceTest, EnsureCWSOrdinalsInitialized) {
2510 InitializeEmptyExtensionService();
2511 service()->component_loader()->Add(
2512 IDR_WEBSTORE_MANIFEST, base::FilePath(FILE_PATH_LITERAL("web_store")));
2513 service()->Init();
2515 AppSorting* sorting = ExtensionPrefs::Get(profile())->app_sorting();
2516 EXPECT_TRUE(
2517 sorting->GetPageOrdinal(extensions::kWebStoreAppId).IsValid());
2518 EXPECT_TRUE(
2519 sorting->GetAppLaunchOrdinal(extensions::kWebStoreAppId).IsValid());
2522 TEST_F(ExtensionServiceTest, InstallAppsWithUnlimitedStorage) {
2523 InitializeEmptyExtensionService();
2524 EXPECT_TRUE(registry()->enabled_extensions().is_empty());
2526 int pref_count = 0;
2528 // Install app1 with unlimited storage.
2529 const Extension* extension =
2530 PackAndInstallCRX(data_dir().AppendASCII("app1"), INSTALL_NEW);
2531 ValidatePrefKeyCount(++pref_count);
2532 ASSERT_EQ(1u, registry()->enabled_extensions().size());
2533 const std::string id1 = extension->id();
2534 EXPECT_TRUE(extension->permissions_data()->HasAPIPermission(
2535 APIPermission::kUnlimitedStorage));
2536 EXPECT_TRUE(extension->web_extent().MatchesURL(
2537 extensions::AppLaunchInfo::GetFullLaunchURL(extension)));
2538 const GURL origin1(
2539 extensions::AppLaunchInfo::GetFullLaunchURL(extension).GetOrigin());
2540 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
2541 origin1));
2543 // Install app2 from the same origin with unlimited storage.
2544 extension = PackAndInstallCRX(data_dir().AppendASCII("app2"), INSTALL_NEW);
2545 ValidatePrefKeyCount(++pref_count);
2546 ASSERT_EQ(2u, registry()->enabled_extensions().size());
2547 const std::string id2 = extension->id();
2548 EXPECT_TRUE(extension->permissions_data()->HasAPIPermission(
2549 APIPermission::kUnlimitedStorage));
2550 EXPECT_TRUE(extension->web_extent().MatchesURL(
2551 extensions::AppLaunchInfo::GetFullLaunchURL(extension)));
2552 const GURL origin2(
2553 extensions::AppLaunchInfo::GetFullLaunchURL(extension).GetOrigin());
2554 EXPECT_EQ(origin1, origin2);
2555 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
2556 origin2));
2558 // Uninstall one of them, unlimited storage should still be granted
2559 // to the origin.
2560 UninstallExtension(id1, false);
2561 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2562 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
2563 origin1));
2565 // Uninstall the other, unlimited storage should be revoked.
2566 UninstallExtension(id2, false);
2567 EXPECT_EQ(0u, registry()->enabled_extensions().size());
2568 EXPECT_FALSE(
2569 profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
2570 origin2));
2573 TEST_F(ExtensionServiceTest, InstallAppsAndCheckStorageProtection) {
2574 InitializeEmptyExtensionService();
2575 EXPECT_TRUE(registry()->enabled_extensions().is_empty());
2577 int pref_count = 0;
2579 const Extension* extension =
2580 PackAndInstallCRX(data_dir().AppendASCII("app1"), INSTALL_NEW);
2581 ValidatePrefKeyCount(++pref_count);
2582 ASSERT_EQ(1u, registry()->enabled_extensions().size());
2583 EXPECT_TRUE(extension->is_app());
2584 const std::string id1 = extension->id();
2585 const GURL origin1(
2586 extensions::AppLaunchInfo::GetFullLaunchURL(extension).GetOrigin());
2587 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageProtected(
2588 origin1));
2590 // App 4 has a different origin (maps.google.com).
2591 extension = PackAndInstallCRX(data_dir().AppendASCII("app4"), INSTALL_NEW);
2592 ValidatePrefKeyCount(++pref_count);
2593 ASSERT_EQ(2u, registry()->enabled_extensions().size());
2594 const std::string id2 = extension->id();
2595 const GURL origin2(
2596 extensions::AppLaunchInfo::GetFullLaunchURL(extension).GetOrigin());
2597 ASSERT_NE(origin1, origin2);
2598 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageProtected(
2599 origin2));
2601 UninstallExtension(id1, false);
2602 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2604 UninstallExtension(id2, false);
2606 EXPECT_TRUE(registry()->enabled_extensions().is_empty());
2607 EXPECT_FALSE(
2608 profile()->GetExtensionSpecialStoragePolicy()->IsStorageProtected(
2609 origin1));
2610 EXPECT_FALSE(
2611 profile()->GetExtensionSpecialStoragePolicy()->IsStorageProtected(
2612 origin2));
2615 // Test that when an extension version is reinstalled, nothing happens.
2616 TEST_F(ExtensionServiceTest, Reinstall) {
2617 InitializeEmptyExtensionService();
2619 // A simple extension that should install without error.
2620 base::FilePath path = data_dir().AppendASCII("good.crx");
2621 InstallCRX(path, INSTALL_NEW);
2623 ValidatePrefKeyCount(1);
2624 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
2625 ValidateIntegerPref(good_crx, "location", Manifest::INTERNAL);
2627 // Reinstall the same version, it should overwrite the previous one.
2628 InstallCRX(path, INSTALL_UPDATED);
2630 ValidatePrefKeyCount(1);
2631 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
2632 ValidateIntegerPref(good_crx, "location", Manifest::INTERNAL);
2635 // Test that we can determine if extensions came from the
2636 // Chrome web store.
2637 TEST_F(ExtensionServiceTest, FromWebStore) {
2638 InitializeEmptyExtensionService();
2640 // A simple extension that should install without error.
2641 base::FilePath path = data_dir().AppendASCII("good.crx");
2642 // Not from web store.
2643 const Extension* extension = InstallCRX(path, INSTALL_NEW);
2644 std::string id = extension->id();
2646 ValidatePrefKeyCount(1);
2647 ASSERT_TRUE(ValidateBooleanPref(good_crx, "from_webstore", false));
2648 ASSERT_FALSE(extension->from_webstore());
2650 // Test install from web store.
2651 InstallCRXFromWebStore(path, INSTALL_UPDATED); // From web store.
2653 ValidatePrefKeyCount(1);
2654 ASSERT_TRUE(ValidateBooleanPref(good_crx, "from_webstore", true));
2656 // Reload so extension gets reinitialized with new value.
2657 service()->ReloadExtensionsForTest();
2658 extension = service()->GetExtensionById(id, false);
2659 ASSERT_TRUE(extension->from_webstore());
2661 // Upgrade to version 2.0
2662 path = data_dir().AppendASCII("good2.crx");
2663 UpdateExtension(good_crx, path, ENABLED);
2664 ValidatePrefKeyCount(1);
2665 ASSERT_TRUE(ValidateBooleanPref(good_crx, "from_webstore", true));
2668 // Test upgrading a signed extension.
2669 TEST_F(ExtensionServiceTest, UpgradeSignedGood) {
2670 InitializeEmptyExtensionService();
2672 base::FilePath path = data_dir().AppendASCII("good.crx");
2673 const Extension* extension = InstallCRX(path, INSTALL_NEW);
2674 std::string id = extension->id();
2676 ASSERT_EQ("1.0.0.0", extension->version()->GetString());
2677 ASSERT_EQ(0u, GetErrors().size());
2679 // Upgrade to version 1.0.0.1.
2680 // Also test that the extension's old and new title are correctly retrieved.
2681 path = data_dir().AppendASCII("good2.crx");
2682 InstallCRX(path, INSTALL_UPDATED, Extension::NO_FLAGS, "My extension 1");
2683 extension = service()->GetExtensionById(id, false);
2685 ASSERT_EQ("1.0.0.1", extension->version()->GetString());
2686 ASSERT_EQ("My updated extension 1", extension->name());
2687 ASSERT_EQ(0u, GetErrors().size());
2690 // Test upgrading a signed extension with a bad signature.
2691 TEST_F(ExtensionServiceTest, UpgradeSignedBad) {
2692 InitializeEmptyExtensionService();
2694 base::FilePath path = data_dir().AppendASCII("good.crx");
2695 InstallCRX(path, INSTALL_NEW);
2697 // Try upgrading with a bad signature. This should fail during the unpack,
2698 // because the key will not match the signature.
2699 path = data_dir().AppendASCII("bad_signature.crx");
2700 InstallCRX(path, INSTALL_FAILED);
2703 // Test a normal update via the UpdateExtension API
2704 TEST_F(ExtensionServiceTest, UpdateExtension) {
2705 InitializeEmptyExtensionService();
2707 base::FilePath path = data_dir().AppendASCII("good.crx");
2709 const Extension* good = InstallCRX(path, INSTALL_NEW);
2710 ASSERT_EQ("1.0.0.0", good->VersionString());
2711 ASSERT_EQ(good_crx, good->id());
2713 path = data_dir().AppendASCII("good2.crx");
2714 UpdateExtension(good_crx, path, ENABLED);
2715 ASSERT_EQ(
2716 "1.0.0.1",
2717 service()->GetExtensionById(good_crx, false)->version()->GetString());
2720 // Extensions should not be updated during browser shutdown.
2721 TEST_F(ExtensionServiceTest, UpdateExtensionDuringShutdown) {
2722 InitializeEmptyExtensionService();
2724 // Install an extension.
2725 base::FilePath path = data_dir().AppendASCII("good.crx");
2726 const Extension* good = InstallCRX(path, INSTALL_NEW);
2727 ASSERT_EQ(good_crx, good->id());
2729 // Simulate shutdown.
2730 service()->set_browser_terminating_for_test(true);
2732 // Update should fail and extension should not be updated.
2733 path = data_dir().AppendASCII("good2.crx");
2734 bool updated = service()->UpdateExtension(
2735 extensions::CRXFileInfo(good_crx, path), true, NULL);
2736 ASSERT_FALSE(updated);
2737 ASSERT_EQ(
2738 "1.0.0.0",
2739 service()->GetExtensionById(good_crx, false)->version()->GetString());
2742 // Test updating a not-already-installed extension - this should fail
2743 TEST_F(ExtensionServiceTest, UpdateNotInstalledExtension) {
2744 InitializeEmptyExtensionService();
2746 base::FilePath path = data_dir().AppendASCII("good.crx");
2747 UpdateExtension(good_crx, path, UPDATED);
2748 base::RunLoop().RunUntilIdle();
2750 ASSERT_EQ(0u, registry()->enabled_extensions().size());
2751 ASSERT_FALSE(installed_);
2752 ASSERT_EQ(0u, loaded_.size());
2755 // Makes sure you can't downgrade an extension via UpdateExtension
2756 TEST_F(ExtensionServiceTest, UpdateWillNotDowngrade) {
2757 InitializeEmptyExtensionService();
2759 base::FilePath path = data_dir().AppendASCII("good2.crx");
2761 const Extension* good = InstallCRX(path, INSTALL_NEW);
2762 ASSERT_EQ("1.0.0.1", good->VersionString());
2763 ASSERT_EQ(good_crx, good->id());
2765 // Change path from good2.crx -> good.crx
2766 path = data_dir().AppendASCII("good.crx");
2767 UpdateExtension(good_crx, path, FAILED);
2768 ASSERT_EQ(
2769 "1.0.0.1",
2770 service()->GetExtensionById(good_crx, false)->version()->GetString());
2773 // Make sure calling update with an identical version does nothing
2774 TEST_F(ExtensionServiceTest, UpdateToSameVersionIsNoop) {
2775 InitializeEmptyExtensionService();
2777 base::FilePath path = data_dir().AppendASCII("good.crx");
2779 const Extension* good = InstallCRX(path, INSTALL_NEW);
2780 ASSERT_EQ(good_crx, good->id());
2781 UpdateExtension(good_crx, path, FAILED_SILENTLY);
2784 // Tests that updating an extension does not clobber old state.
2785 TEST_F(ExtensionServiceTest, UpdateExtensionPreservesState) {
2786 InitializeEmptyExtensionService();
2788 base::FilePath path = data_dir().AppendASCII("good.crx");
2790 const Extension* good = InstallCRX(path, INSTALL_NEW);
2791 ASSERT_EQ("1.0.0.0", good->VersionString());
2792 ASSERT_EQ(good_crx, good->id());
2794 // Disable it and allow it to run in incognito. These settings should carry
2795 // over to the updated version.
2796 service()->DisableExtension(good->id(), Extension::DISABLE_USER_ACTION);
2797 extensions::util::SetIsIncognitoEnabled(good->id(), profile(), true);
2798 ExtensionPrefs::Get(profile())
2799 ->SetDidExtensionEscalatePermissions(good, true);
2801 path = data_dir().AppendASCII("good2.crx");
2802 UpdateExtension(good_crx, path, INSTALLED);
2803 ASSERT_EQ(1u, registry()->disabled_extensions().size());
2804 const Extension* good2 = service()->GetExtensionById(good_crx, true);
2805 ASSERT_EQ("1.0.0.1", good2->version()->GetString());
2806 EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good2->id(), profile()));
2807 EXPECT_TRUE(ExtensionPrefs::Get(profile())
2808 ->DidExtensionEscalatePermissions(good2->id()));
2811 // Tests that updating preserves extension location.
2812 TEST_F(ExtensionServiceTest, UpdateExtensionPreservesLocation) {
2813 InitializeEmptyExtensionService();
2815 base::FilePath path = data_dir().AppendASCII("good.crx");
2817 const Extension* good =
2818 InstallCRXWithLocation(path, Manifest::EXTERNAL_PREF, INSTALL_NEW);
2820 ASSERT_EQ("1.0.0.0", good->VersionString());
2821 ASSERT_EQ(good_crx, good->id());
2823 path = data_dir().AppendASCII("good2.crx");
2824 UpdateExtension(good_crx, path, ENABLED);
2825 const Extension* good2 = service()->GetExtensionById(good_crx, false);
2826 ASSERT_EQ("1.0.0.1", good2->version()->GetString());
2827 EXPECT_EQ(good2->location(), Manifest::EXTERNAL_PREF);
2830 // Makes sure that LOAD extension types can downgrade.
2831 TEST_F(ExtensionServiceTest, LoadExtensionsCanDowngrade) {
2832 InitializeEmptyExtensionService();
2834 base::ScopedTempDir temp;
2835 ASSERT_TRUE(temp.CreateUniqueTempDir());
2837 // We'll write the extension manifest dynamically to a temporary path
2838 // to make it easier to change the version number.
2839 base::FilePath extension_path = temp.path();
2840 base::FilePath manifest_path =
2841 extension_path.Append(extensions::kManifestFilename);
2842 ASSERT_FALSE(base::PathExists(manifest_path));
2844 // Start with version 2.0.
2845 base::DictionaryValue manifest;
2846 manifest.SetString("version", "2.0");
2847 manifest.SetString("name", "LOAD Downgrade Test");
2848 manifest.SetInteger("manifest_version", 2);
2850 JSONFileValueSerializer serializer(manifest_path);
2851 ASSERT_TRUE(serializer.Serialize(manifest));
2853 extensions::UnpackedInstaller::Create(service())->Load(extension_path);
2854 base::RunLoop().RunUntilIdle();
2856 EXPECT_EQ(0u, GetErrors().size());
2857 ASSERT_EQ(1u, loaded_.size());
2858 EXPECT_EQ(Manifest::UNPACKED, loaded_[0]->location());
2859 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2860 EXPECT_EQ("2.0", loaded_[0]->VersionString());
2862 // Now set the version number to 1.0, reload the extensions and verify that
2863 // the downgrade was accepted.
2864 manifest.SetString("version", "1.0");
2865 ASSERT_TRUE(serializer.Serialize(manifest));
2867 extensions::UnpackedInstaller::Create(service())->Load(extension_path);
2868 base::RunLoop().RunUntilIdle();
2870 EXPECT_EQ(0u, GetErrors().size());
2871 ASSERT_EQ(1u, loaded_.size());
2872 EXPECT_EQ(Manifest::UNPACKED, loaded_[0]->location());
2873 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2874 EXPECT_EQ("1.0", loaded_[0]->VersionString());
2877 #if !defined(OS_POSIX) || defined(OS_MACOSX)
2878 // LOAD extensions with plugins require approval.
2879 // Only run this on platforms that support NPAPI plugins.
2880 TEST_F(ExtensionServiceTest, LoadExtensionsWithPlugins) {
2881 base::FilePath extension_with_plugin_path = good1_path();
2882 base::FilePath extension_no_plugin_path = good2_path();
2884 InitPluginService();
2885 InitializeEmptyExtensionService();
2886 service()->set_show_extensions_prompts(true);
2888 // Start by canceling any install prompts.
2889 ExtensionInstallPrompt::g_auto_confirm_for_tests =
2890 ExtensionInstallPrompt::CANCEL;
2892 // The extension that has a plugin should not install.
2893 extensions::UnpackedInstaller::Create(service())
2894 ->Load(extension_with_plugin_path);
2895 base::RunLoop().RunUntilIdle();
2896 EXPECT_EQ(0u, GetErrors().size());
2897 EXPECT_EQ(0u, loaded_.size());
2898 EXPECT_EQ(0u, registry()->enabled_extensions().size());
2899 EXPECT_EQ(0u, registry()->disabled_extensions().size());
2901 // But the extension with no plugin should since there's no prompt.
2902 ExtensionErrorReporter::GetInstance()->ClearErrors();
2903 extensions::UnpackedInstaller::Create(service())
2904 ->Load(extension_no_plugin_path);
2905 base::RunLoop().RunUntilIdle();
2906 EXPECT_EQ(0u, GetErrors().size());
2907 EXPECT_EQ(1u, loaded_.size());
2908 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2909 EXPECT_EQ(0u, registry()->disabled_extensions().size());
2910 EXPECT_TRUE(registry()->enabled_extensions().Contains(good2));
2912 // The plugin extension should install if we accept the dialog.
2913 ExtensionInstallPrompt::g_auto_confirm_for_tests =
2914 ExtensionInstallPrompt::ACCEPT;
2916 ExtensionErrorReporter::GetInstance()->ClearErrors();
2917 extensions::UnpackedInstaller::Create(service())
2918 ->Load(extension_with_plugin_path);
2919 base::RunLoop().RunUntilIdle();
2920 EXPECT_EQ(0u, GetErrors().size());
2921 EXPECT_EQ(2u, loaded_.size());
2922 EXPECT_EQ(2u, registry()->enabled_extensions().size());
2923 EXPECT_EQ(0u, registry()->disabled_extensions().size());
2924 EXPECT_TRUE(registry()->enabled_extensions().Contains(good1));
2925 EXPECT_TRUE(registry()->enabled_extensions().Contains(good2));
2927 // Make sure the granted permissions have been setup.
2928 scoped_refptr<PermissionSet> permissions(
2929 ExtensionPrefs::Get(profile())->GetGrantedPermissions(good1));
2930 EXPECT_FALSE(permissions->IsEmpty());
2931 EXPECT_TRUE(permissions->HasEffectiveFullAccess());
2932 EXPECT_FALSE(permissions->apis().empty());
2933 EXPECT_TRUE(permissions->HasAPIPermission(APIPermission::kPlugin));
2935 // We should be able to reload the extension without getting another prompt.
2936 loaded_.clear();
2937 ExtensionInstallPrompt::g_auto_confirm_for_tests =
2938 ExtensionInstallPrompt::CANCEL;
2940 service()->ReloadExtension(good1);
2941 base::RunLoop().RunUntilIdle();
2942 EXPECT_EQ(1u, loaded_.size());
2943 EXPECT_EQ(2u, registry()->enabled_extensions().size());
2944 EXPECT_EQ(0u, registry()->disabled_extensions().size());
2946 #endif // !defined(OS_POSIX) || defined(OS_MACOSX)
2948 namespace {
2950 bool IsExtension(const Extension* extension) {
2951 return extension->GetType() == Manifest::TYPE_EXTENSION;
2954 #if defined(ENABLE_BLACKLIST_TESTS)
2955 std::set<std::string> StringSet(const std::string& s) {
2956 std::set<std::string> set;
2957 set.insert(s);
2958 return set;
2960 std::set<std::string> StringSet(const std::string& s1, const std::string& s2) {
2961 std::set<std::string> set = StringSet(s1);
2962 set.insert(s2);
2963 return set;
2965 #endif // defined(ENABLE_BLACKLIST_TESTS)
2967 } // namespace
2969 // Test adding a pending extension.
2970 TEST_F(ExtensionServiceTest, AddPendingExtensionFromSync) {
2971 InitializeEmptyExtensionService();
2973 const std::string kFakeId(all_zero);
2974 const GURL kFakeUpdateURL("http:://fake.update/url");
2975 const bool kFakeRemoteInstall(false);
2976 const bool kFakeInstalledByCustodian(false);
2978 EXPECT_TRUE(
2979 service()->pending_extension_manager()->AddFromSync(
2980 kFakeId,
2981 kFakeUpdateURL,
2982 &IsExtension,
2983 kFakeRemoteInstall,
2984 kFakeInstalledByCustodian));
2986 const extensions::PendingExtensionInfo* pending_extension_info;
2987 ASSERT_TRUE((pending_extension_info =
2988 service()->pending_extension_manager()->GetById(kFakeId)));
2989 EXPECT_EQ(kFakeUpdateURL, pending_extension_info->update_url());
2990 EXPECT_EQ(&IsExtension, pending_extension_info->should_allow_install_);
2991 // Use
2992 // EXPECT_TRUE(kFakeRemoteInstall == pending_extension_info->remote_install())
2993 // instead of
2994 // EXPECT_EQ(kFakeRemoteInstall, pending_extension_info->remote_install())
2995 // as gcc 4.7 issues the following warning on EXPECT_EQ(false, x), which is
2996 // turned into an error with -Werror=conversion-null:
2997 // converting 'false' to pointer type for argument 1 of
2998 // 'char testing::internal::IsNullLiteralHelper(testing::internal::Secret*)'
2999 // https://code.google.com/p/googletest/issues/detail?id=458
3000 EXPECT_TRUE(kFakeRemoteInstall == pending_extension_info->remote_install());
3003 namespace {
3004 const char kGoodId[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
3005 const char kGoodUpdateURL[] = "http://good.update/url";
3006 const bool kGoodIsFromSync = true;
3007 const bool kGoodRemoteInstall = false;
3008 const bool kGoodInstalledByCustodian = false;
3009 } // namespace
3011 // Test updating a pending extension.
3012 TEST_F(ExtensionServiceTest, UpdatePendingExtension) {
3013 InitializeEmptyExtensionService();
3014 EXPECT_TRUE(
3015 service()->pending_extension_manager()->AddFromSync(
3016 kGoodId,
3017 GURL(kGoodUpdateURL),
3018 &IsExtension,
3019 kGoodRemoteInstall,
3020 kGoodInstalledByCustodian));
3021 EXPECT_TRUE(service()->pending_extension_manager()->IsIdPending(kGoodId));
3023 base::FilePath path = data_dir().AppendASCII("good.crx");
3024 UpdateExtension(kGoodId, path, ENABLED);
3026 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(kGoodId));
3028 const Extension* extension = service()->GetExtensionById(kGoodId, true);
3029 ASSERT_TRUE(extension);
3032 namespace {
3034 bool IsTheme(const Extension* extension) {
3035 return extension->is_theme();
3038 } // namespace
3040 // Test updating a pending theme.
3041 // Disabled due to ASAN failure. http://crbug.com/108320
3042 TEST_F(ExtensionServiceTest, DISABLED_UpdatePendingTheme) {
3043 InitializeEmptyExtensionService();
3044 EXPECT_TRUE(service()->pending_extension_manager()->AddFromSync(
3045 theme_crx, GURL(), &IsTheme, false, false));
3046 EXPECT_TRUE(service()->pending_extension_manager()->IsIdPending(theme_crx));
3048 base::FilePath path = data_dir().AppendASCII("theme.crx");
3049 UpdateExtension(theme_crx, path, ENABLED);
3051 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(theme_crx));
3053 const Extension* extension = service()->GetExtensionById(theme_crx, true);
3054 ASSERT_TRUE(extension);
3056 EXPECT_FALSE(
3057 ExtensionPrefs::Get(profile())->IsExtensionDisabled(extension->id()));
3058 EXPECT_TRUE(service()->IsExtensionEnabled(theme_crx));
3061 #if defined(OS_CHROMEOS)
3062 // Always fails on ChromeOS: http://crbug.com/79737
3063 #define MAYBE_UpdatePendingExternalCrx DISABLED_UpdatePendingExternalCrx
3064 #else
3065 #define MAYBE_UpdatePendingExternalCrx UpdatePendingExternalCrx
3066 #endif
3067 // Test updating a pending CRX as if the source is an external extension
3068 // with an update URL. In this case we don't know if the CRX is a theme
3069 // or not.
3070 TEST_F(ExtensionServiceTest, MAYBE_UpdatePendingExternalCrx) {
3071 InitializeEmptyExtensionService();
3072 EXPECT_TRUE(service()->pending_extension_manager()->AddFromExternalUpdateUrl(
3073 theme_crx,
3074 std::string(),
3075 GURL(),
3076 Manifest::EXTERNAL_PREF_DOWNLOAD,
3077 Extension::NO_FLAGS,
3078 false));
3080 EXPECT_TRUE(service()->pending_extension_manager()->IsIdPending(theme_crx));
3082 base::FilePath path = data_dir().AppendASCII("theme.crx");
3083 UpdateExtension(theme_crx, path, ENABLED);
3085 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(theme_crx));
3087 const Extension* extension = service()->GetExtensionById(theme_crx, true);
3088 ASSERT_TRUE(extension);
3090 EXPECT_FALSE(
3091 ExtensionPrefs::Get(profile())->IsExtensionDisabled(extension->id()));
3092 EXPECT_TRUE(service()->IsExtensionEnabled(extension->id()));
3093 EXPECT_FALSE(
3094 extensions::util::IsIncognitoEnabled(extension->id(), profile()));
3097 // Test updating a pending CRX as if the source is an external extension
3098 // with an update URL. The external update should overwrite a sync update,
3099 // but a sync update should not overwrite a non-sync update.
3100 TEST_F(ExtensionServiceTest, UpdatePendingExternalCrxWinsOverSync) {
3101 InitializeEmptyExtensionService();
3103 // Add a crx to be installed from the update mechanism.
3104 EXPECT_TRUE(
3105 service()->pending_extension_manager()->AddFromSync(
3106 kGoodId,
3107 GURL(kGoodUpdateURL),
3108 &IsExtension,
3109 kGoodRemoteInstall,
3110 kGoodInstalledByCustodian));
3112 // Check that there is a pending crx, with is_from_sync set to true.
3113 const extensions::PendingExtensionInfo* pending_extension_info;
3114 ASSERT_TRUE((pending_extension_info =
3115 service()->pending_extension_manager()->GetById(kGoodId)));
3116 EXPECT_TRUE(pending_extension_info->is_from_sync());
3118 // Add a crx to be updated, with the same ID, from a non-sync source.
3119 EXPECT_TRUE(service()->pending_extension_manager()->AddFromExternalUpdateUrl(
3120 kGoodId,
3121 std::string(),
3122 GURL(kGoodUpdateURL),
3123 Manifest::EXTERNAL_PREF_DOWNLOAD,
3124 Extension::NO_FLAGS,
3125 false));
3127 // Check that there is a pending crx, with is_from_sync set to false.
3128 ASSERT_TRUE((pending_extension_info =
3129 service()->pending_extension_manager()->GetById(kGoodId)));
3130 EXPECT_FALSE(pending_extension_info->is_from_sync());
3131 EXPECT_EQ(Manifest::EXTERNAL_PREF_DOWNLOAD,
3132 pending_extension_info->install_source());
3134 // Add a crx to be installed from the update mechanism.
3135 EXPECT_FALSE(
3136 service()->pending_extension_manager()->AddFromSync(
3137 kGoodId,
3138 GURL(kGoodUpdateURL),
3139 &IsExtension,
3140 kGoodRemoteInstall,
3141 kGoodInstalledByCustodian));
3143 // Check that the external, non-sync update was not overridden.
3144 ASSERT_TRUE((pending_extension_info =
3145 service()->pending_extension_manager()->GetById(kGoodId)));
3146 EXPECT_FALSE(pending_extension_info->is_from_sync());
3147 EXPECT_EQ(Manifest::EXTERNAL_PREF_DOWNLOAD,
3148 pending_extension_info->install_source());
3151 // Updating a theme should fail if the updater is explicitly told that
3152 // the CRX is not a theme.
3153 TEST_F(ExtensionServiceTest, UpdatePendingCrxThemeMismatch) {
3154 InitializeEmptyExtensionService();
3155 EXPECT_TRUE(service()->pending_extension_manager()->AddFromSync(
3156 theme_crx, GURL(), &IsExtension, false, false));
3158 EXPECT_TRUE(service()->pending_extension_manager()->IsIdPending(theme_crx));
3160 base::FilePath path = data_dir().AppendASCII("theme.crx");
3161 UpdateExtension(theme_crx, path, FAILED_SILENTLY);
3163 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(theme_crx));
3165 const Extension* extension = service()->GetExtensionById(theme_crx, true);
3166 ASSERT_FALSE(extension);
3169 // TODO(akalin): Test updating a pending extension non-silently once
3170 // we can mock out ExtensionInstallUI and inject our version into
3171 // UpdateExtension().
3173 // Test updating a pending extension which fails the should-install test.
3174 TEST_F(ExtensionServiceTest, UpdatePendingExtensionFailedShouldInstallTest) {
3175 InitializeEmptyExtensionService();
3176 // Add pending extension with a flipped is_theme.
3177 EXPECT_TRUE(
3178 service()->pending_extension_manager()->AddFromSync(
3179 kGoodId,
3180 GURL(kGoodUpdateURL),
3181 &IsTheme,
3182 kGoodRemoteInstall,
3183 kGoodInstalledByCustodian));
3184 EXPECT_TRUE(service()->pending_extension_manager()->IsIdPending(kGoodId));
3186 base::FilePath path = data_dir().AppendASCII("good.crx");
3187 UpdateExtension(kGoodId, path, UPDATED);
3189 // TODO(akalin): Figure out how to check that the extensions
3190 // directory is cleaned up properly in OnExtensionInstalled().
3192 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(kGoodId));
3195 // TODO(akalin): Figure out how to test that installs of pending
3196 // unsyncable extensions are blocked.
3198 // Test updating a pending extension for one that is not pending.
3199 TEST_F(ExtensionServiceTest, UpdatePendingExtensionNotPending) {
3200 InitializeEmptyExtensionService();
3202 base::FilePath path = data_dir().AppendASCII("good.crx");
3203 UpdateExtension(kGoodId, path, UPDATED);
3205 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(kGoodId));
3208 // Test updating a pending extension for one that is already
3209 // installed.
3210 TEST_F(ExtensionServiceTest, UpdatePendingExtensionAlreadyInstalled) {
3211 InitializeEmptyExtensionService();
3213 base::FilePath path = data_dir().AppendASCII("good.crx");
3214 const Extension* good = InstallCRX(path, INSTALL_NEW);
3215 ASSERT_EQ(1u, registry()->enabled_extensions().size());
3217 EXPECT_FALSE(good->is_theme());
3219 // Use AddExtensionImpl() as AddFrom*() would balk.
3220 service()->pending_extension_manager()->AddExtensionImpl(
3221 good->id(),
3222 std::string(),
3223 extensions::ManifestURL::GetUpdateURL(good),
3224 Version(),
3225 &IsExtension,
3226 kGoodIsFromSync,
3227 Manifest::INTERNAL,
3228 Extension::NO_FLAGS,
3229 false,
3230 kGoodRemoteInstall);
3231 UpdateExtension(good->id(), path, ENABLED);
3233 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(kGoodId));
3236 #if defined(ENABLE_BLACKLIST_TESTS)
3237 // Tests blacklisting then unblacklisting extensions after the service has been
3238 // initialized.
3239 TEST_F(ExtensionServiceTest, SetUnsetBlacklistInPrefs) {
3240 extensions::TestBlacklist test_blacklist;
3241 // A profile with 3 extensions installed: good0, good1, and good2.
3242 InitializeGoodInstalledExtensionService();
3243 test_blacklist.Attach(service()->blacklist_);
3244 service()->Init();
3246 const extensions::ExtensionSet& enabled_extensions =
3247 registry()->enabled_extensions();
3248 const extensions::ExtensionSet& blacklisted_extensions =
3249 registry()->blacklisted_extensions();
3251 EXPECT_TRUE(enabled_extensions.Contains(good0) &&
3252 !blacklisted_extensions.Contains(good0));
3253 EXPECT_TRUE(enabled_extensions.Contains(good1) &&
3254 !blacklisted_extensions.Contains(good1));
3255 EXPECT_TRUE(enabled_extensions.Contains(good2) &&
3256 !blacklisted_extensions.Contains(good2));
3258 EXPECT_FALSE(IsPrefExist(good0, "blacklist"));
3259 EXPECT_FALSE(IsPrefExist(good1, "blacklist"));
3260 EXPECT_FALSE(IsPrefExist(good2, "blacklist"));
3261 EXPECT_FALSE(IsPrefExist("invalid_id", "blacklist"));
3263 // Blacklist good0 and good1 (and an invalid extension ID).
3264 test_blacklist.SetBlacklistState(
3265 good0, extensions::BLACKLISTED_MALWARE, true);
3266 test_blacklist.SetBlacklistState(
3267 good1, extensions::BLACKLISTED_MALWARE, true);
3268 test_blacklist.SetBlacklistState(
3269 "invalid_id", extensions::BLACKLISTED_MALWARE, true);
3270 base::RunLoop().RunUntilIdle();
3272 EXPECT_TRUE(!enabled_extensions.Contains(good0) &&
3273 blacklisted_extensions.Contains(good0));
3274 EXPECT_TRUE(!enabled_extensions.Contains(good1) &&
3275 blacklisted_extensions.Contains(good1));
3276 EXPECT_TRUE(enabled_extensions.Contains(good2) &&
3277 !blacklisted_extensions.Contains(good2));
3279 EXPECT_TRUE(ValidateBooleanPref(good0, "blacklist", true));
3280 EXPECT_TRUE(ValidateBooleanPref(good1, "blacklist", true));
3281 EXPECT_FALSE(IsPrefExist(good2, "blacklist"));
3282 EXPECT_FALSE(IsPrefExist("invalid_id", "blacklist"));
3284 // Un-blacklist good1 and blacklist good2.
3285 test_blacklist.Clear(false);
3286 test_blacklist.SetBlacklistState(
3287 good0, extensions::BLACKLISTED_MALWARE, true);
3288 test_blacklist.SetBlacklistState(
3289 good2, extensions::BLACKLISTED_MALWARE, true);
3290 test_blacklist.SetBlacklistState(
3291 "invalid_id", extensions::BLACKLISTED_MALWARE, true);
3292 base::RunLoop().RunUntilIdle();
3294 EXPECT_TRUE(!enabled_extensions.Contains(good0) &&
3295 blacklisted_extensions.Contains(good0));
3296 EXPECT_TRUE(enabled_extensions.Contains(good1) &&
3297 !blacklisted_extensions.Contains(good1));
3298 EXPECT_TRUE(!enabled_extensions.Contains(good2) &&
3299 blacklisted_extensions.Contains(good2));
3301 EXPECT_TRUE(ValidateBooleanPref(good0, "blacklist", true));
3302 EXPECT_FALSE(IsPrefExist(good1, "blacklist"));
3303 EXPECT_TRUE(ValidateBooleanPref(good2, "blacklist", true));
3304 EXPECT_FALSE(IsPrefExist("invalid_id", "blacklist"));
3306 #endif // defined(ENABLE_BLACKLIST_TESTS)
3308 #if defined(ENABLE_BLACKLIST_TESTS)
3309 // Tests trying to install a blacklisted extension.
3310 TEST_F(ExtensionServiceTest, BlacklistedExtensionWillNotInstall) {
3311 scoped_refptr<FakeSafeBrowsingDatabaseManager> blacklist_db(
3312 new FakeSafeBrowsingDatabaseManager(true));
3313 Blacklist::ScopedDatabaseManagerForTest scoped_blacklist_db(blacklist_db);
3315 InitializeEmptyExtensionService();
3316 service()->Init();
3318 // After blacklisting good_crx, we cannot install it.
3319 blacklist_db->SetUnsafe(good_crx).NotifyUpdate();
3320 base::RunLoop().RunUntilIdle();
3322 base::FilePath path = data_dir().AppendASCII("good.crx");
3323 // HACK: specify WAS_INSTALLED_BY_DEFAULT so that test machinery doesn't
3324 // decide to install this silently. Somebody should fix these tests, all
3325 // 6,000 lines of them. Hah!
3326 InstallCRX(path, INSTALL_FAILED, Extension::WAS_INSTALLED_BY_DEFAULT);
3327 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3329 #endif // defined(ENABLE_BLACKLIST_TESTS)
3331 #if defined(ENABLE_BLACKLIST_TESTS)
3332 // Unload blacklisted extension on policy change.
3333 TEST_F(ExtensionServiceTest, UnloadBlacklistedExtensionPolicy) {
3334 extensions::TestBlacklist test_blacklist;
3336 // A profile with no extensions installed.
3337 InitializeEmptyExtensionServiceWithTestingPrefs();
3338 test_blacklist.Attach(service()->blacklist_);
3340 base::FilePath path = data_dir().AppendASCII("good.crx");
3342 const Extension* good = InstallCRX(path, INSTALL_NEW);
3343 EXPECT_EQ(good_crx, good->id());
3344 UpdateExtension(good_crx, path, FAILED_SILENTLY);
3345 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3348 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
3349 pref.SetIndividualExtensionInstallationAllowed(good_crx, true);
3352 test_blacklist.SetBlacklistState(
3353 good_crx, extensions::BLACKLISTED_MALWARE, true);
3354 base::RunLoop().RunUntilIdle();
3356 // The good_crx is blacklisted and the whitelist doesn't negate it.
3357 ASSERT_TRUE(ValidateBooleanPref(good_crx, "blacklist", true));
3358 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3360 #endif // defined(ENABLE_BLACKLIST_TESTS)
3362 #if defined(ENABLE_BLACKLIST_TESTS)
3363 // Tests that a blacklisted extension is eventually unloaded on startup, if it
3364 // wasn't already.
3365 TEST_F(ExtensionServiceTest, WillNotLoadBlacklistedExtensionsFromDirectory) {
3366 extensions::TestBlacklist test_blacklist;
3368 // A profile with 3 extensions installed: good0, good1, and good2.
3369 InitializeGoodInstalledExtensionService();
3370 test_blacklist.Attach(service()->blacklist_);
3372 // Blacklist good1 before the service initializes.
3373 test_blacklist.SetBlacklistState(
3374 good1, extensions::BLACKLISTED_MALWARE, false);
3376 // Load extensions.
3377 service()->Init();
3378 ASSERT_EQ(3u, loaded_.size()); // hasn't had time to blacklist yet
3380 base::RunLoop().RunUntilIdle();
3382 ASSERT_EQ(1u, registry()->blacklisted_extensions().size());
3383 ASSERT_EQ(2u, registry()->enabled_extensions().size());
3385 ASSERT_TRUE(registry()->enabled_extensions().Contains(good0));
3386 ASSERT_TRUE(registry()->blacklisted_extensions().Contains(good1));
3387 ASSERT_TRUE(registry()->enabled_extensions().Contains(good2));
3389 #endif // defined(ENABLE_BLACKLIST_TESTS)
3391 #if defined(ENABLE_BLACKLIST_TESTS)
3392 // Tests extensions blacklisted in prefs on startup; one still blacklisted by
3393 // safe browsing, the other not. The not-blacklisted one should recover.
3394 TEST_F(ExtensionServiceTest, BlacklistedInPrefsFromStartup) {
3395 extensions::TestBlacklist test_blacklist;
3397 InitializeGoodInstalledExtensionService();
3398 test_blacklist.Attach(service()->blacklist_);
3399 ExtensionPrefs::Get(profile())->SetExtensionBlacklisted(good0, true);
3400 ExtensionPrefs::Get(profile())->SetExtensionBlacklisted(good1, true);
3402 test_blacklist.SetBlacklistState(
3403 good1, extensions::BLACKLISTED_MALWARE, false);
3405 // Extension service hasn't loaded yet, but IsExtensionEnabled reads out of
3406 // prefs. Ensure it takes into account the blacklist state (crbug.com/373842).
3407 EXPECT_FALSE(service()->IsExtensionEnabled(good0));
3408 EXPECT_FALSE(service()->IsExtensionEnabled(good1));
3409 EXPECT_TRUE(service()->IsExtensionEnabled(good2));
3411 service()->Init();
3413 EXPECT_EQ(2u, registry()->blacklisted_extensions().size());
3414 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3416 EXPECT_TRUE(registry()->blacklisted_extensions().Contains(good0));
3417 EXPECT_TRUE(registry()->blacklisted_extensions().Contains(good1));
3418 EXPECT_TRUE(registry()->enabled_extensions().Contains(good2));
3420 // Give time for the blacklist to update.
3421 base::RunLoop().RunUntilIdle();
3423 EXPECT_EQ(1u, registry()->blacklisted_extensions().size());
3424 EXPECT_EQ(2u, registry()->enabled_extensions().size());
3426 EXPECT_TRUE(registry()->enabled_extensions().Contains(good0));
3427 EXPECT_TRUE(registry()->blacklisted_extensions().Contains(good1));
3428 EXPECT_TRUE(registry()->enabled_extensions().Contains(good2));
3430 #endif // defined(ENABLE_BLACKLIST_TESTS)
3432 #if defined(ENABLE_BLACKLIST_TESTS)
3433 // Extension is added to blacklist with BLACKLISTED_POTENTIALLY_UNWANTED state
3434 // after it is installed. It is then successfully re-enabled by the user.
3435 TEST_F(ExtensionServiceTest, GreylistedExtensionDisabled) {
3436 extensions::TestBlacklist test_blacklist;
3437 // A profile with 3 extensions installed: good0, good1, and good2.
3438 InitializeGoodInstalledExtensionService();
3439 test_blacklist.Attach(service()->blacklist_);
3440 service()->Init();
3442 const extensions::ExtensionSet& enabled_extensions =
3443 registry()->enabled_extensions();
3444 const extensions::ExtensionSet& disabled_extensions =
3445 registry()->disabled_extensions();
3447 EXPECT_TRUE(enabled_extensions.Contains(good0));
3448 EXPECT_TRUE(enabled_extensions.Contains(good1));
3449 EXPECT_TRUE(enabled_extensions.Contains(good2));
3451 // Blacklist good0 and good1 (and an invalid extension ID).
3452 test_blacklist.SetBlacklistState(
3453 good0, extensions::BLACKLISTED_CWS_POLICY_VIOLATION, true);
3454 test_blacklist.SetBlacklistState(
3455 good1, extensions::BLACKLISTED_POTENTIALLY_UNWANTED, true);
3456 test_blacklist.SetBlacklistState(
3457 "invalid_id", extensions::BLACKLISTED_MALWARE, true);
3458 base::RunLoop().RunUntilIdle();
3460 EXPECT_FALSE(enabled_extensions.Contains(good0));
3461 EXPECT_TRUE(disabled_extensions.Contains(good0));
3462 EXPECT_FALSE(enabled_extensions.Contains(good1));
3463 EXPECT_TRUE(disabled_extensions.Contains(good1));
3464 EXPECT_TRUE(enabled_extensions.Contains(good2));
3465 EXPECT_FALSE(disabled_extensions.Contains(good2));
3467 ValidateIntegerPref(
3468 good0, "blacklist_state", extensions::BLACKLISTED_CWS_POLICY_VIOLATION);
3469 ValidateIntegerPref(
3470 good1, "blacklist_state", extensions::BLACKLISTED_POTENTIALLY_UNWANTED);
3472 // Now user enables good0.
3473 service()->EnableExtension(good0);
3475 EXPECT_TRUE(enabled_extensions.Contains(good0));
3476 EXPECT_FALSE(disabled_extensions.Contains(good0));
3477 EXPECT_FALSE(enabled_extensions.Contains(good1));
3478 EXPECT_TRUE(disabled_extensions.Contains(good1));
3480 // Remove extensions from blacklist.
3481 test_blacklist.SetBlacklistState(
3482 good0, extensions::NOT_BLACKLISTED, true);
3483 test_blacklist.SetBlacklistState(
3484 good1, extensions::NOT_BLACKLISTED, true);
3485 base::RunLoop().RunUntilIdle();
3487 // All extensions are enabled.
3488 EXPECT_TRUE(enabled_extensions.Contains(good0));
3489 EXPECT_FALSE(disabled_extensions.Contains(good0));
3490 EXPECT_TRUE(enabled_extensions.Contains(good1));
3491 EXPECT_FALSE(disabled_extensions.Contains(good1));
3492 EXPECT_TRUE(enabled_extensions.Contains(good2));
3493 EXPECT_FALSE(disabled_extensions.Contains(good2));
3495 #endif // defined(ENABLE_BLACKLIST_TESTS)
3497 #if defined(ENABLE_BLACKLIST_TESTS)
3498 // When extension is removed from greylist, do not re-enable it if it is
3499 // disabled by user.
3500 TEST_F(ExtensionServiceTest, GreylistDontEnableManuallyDisabled) {
3501 extensions::TestBlacklist test_blacklist;
3502 // A profile with 3 extensions installed: good0, good1, and good2.
3503 InitializeGoodInstalledExtensionService();
3504 test_blacklist.Attach(service()->blacklist_);
3505 service()->Init();
3507 const extensions::ExtensionSet& enabled_extensions =
3508 registry()->enabled_extensions();
3509 const extensions::ExtensionSet& disabled_extensions =
3510 registry()->disabled_extensions();
3512 // Manually disable.
3513 service()->DisableExtension(good0,
3514 extensions::Extension::DISABLE_USER_ACTION);
3516 test_blacklist.SetBlacklistState(
3517 good0, extensions::BLACKLISTED_CWS_POLICY_VIOLATION, true);
3518 test_blacklist.SetBlacklistState(
3519 good1, extensions::BLACKLISTED_POTENTIALLY_UNWANTED, true);
3520 test_blacklist.SetBlacklistState(
3521 good2, extensions::BLACKLISTED_SECURITY_VULNERABILITY, true);
3522 base::RunLoop().RunUntilIdle();
3524 // All extensions disabled.
3525 EXPECT_FALSE(enabled_extensions.Contains(good0));
3526 EXPECT_TRUE(disabled_extensions.Contains(good0));
3527 EXPECT_FALSE(enabled_extensions.Contains(good1));
3528 EXPECT_TRUE(disabled_extensions.Contains(good1));
3529 EXPECT_FALSE(enabled_extensions.Contains(good2));
3530 EXPECT_TRUE(disabled_extensions.Contains(good2));
3532 // Greylisted extension can be enabled.
3533 service()->EnableExtension(good1);
3534 EXPECT_TRUE(enabled_extensions.Contains(good1));
3535 EXPECT_FALSE(disabled_extensions.Contains(good1));
3537 // good1 is now manually disabled.
3538 service()->DisableExtension(good1,
3539 extensions::Extension::DISABLE_USER_ACTION);
3540 EXPECT_FALSE(enabled_extensions.Contains(good1));
3541 EXPECT_TRUE(disabled_extensions.Contains(good1));
3543 // Remove extensions from blacklist.
3544 test_blacklist.SetBlacklistState(
3545 good0, extensions::NOT_BLACKLISTED, true);
3546 test_blacklist.SetBlacklistState(
3547 good1, extensions::NOT_BLACKLISTED, true);
3548 test_blacklist.SetBlacklistState(
3549 good2, extensions::NOT_BLACKLISTED, true);
3550 base::RunLoop().RunUntilIdle();
3552 // good0 and good1 remain disabled.
3553 EXPECT_FALSE(enabled_extensions.Contains(good0));
3554 EXPECT_TRUE(disabled_extensions.Contains(good0));
3555 EXPECT_FALSE(enabled_extensions.Contains(good1));
3556 EXPECT_TRUE(disabled_extensions.Contains(good1));
3557 EXPECT_TRUE(enabled_extensions.Contains(good2));
3558 EXPECT_FALSE(disabled_extensions.Contains(good2));
3560 #endif // defined(ENABLE_BLACKLIST_TESTS)
3562 #if defined(ENABLE_BLACKLIST_TESTS)
3563 // Blacklisted extension with unknown state are not enabled/disabled.
3564 TEST_F(ExtensionServiceTest, GreylistUnknownDontChange) {
3565 extensions::TestBlacklist test_blacklist;
3566 // A profile with 3 extensions installed: good0, good1, and good2.
3567 InitializeGoodInstalledExtensionService();
3568 test_blacklist.Attach(service()->blacklist_);
3569 service()->Init();
3571 const extensions::ExtensionSet& enabled_extensions =
3572 registry()->enabled_extensions();
3573 const extensions::ExtensionSet& disabled_extensions =
3574 registry()->disabled_extensions();
3576 test_blacklist.SetBlacklistState(
3577 good0, extensions::BLACKLISTED_CWS_POLICY_VIOLATION, true);
3578 test_blacklist.SetBlacklistState(
3579 good1, extensions::BLACKLISTED_POTENTIALLY_UNWANTED, true);
3580 base::RunLoop().RunUntilIdle();
3582 EXPECT_FALSE(enabled_extensions.Contains(good0));
3583 EXPECT_TRUE(disabled_extensions.Contains(good0));
3584 EXPECT_FALSE(enabled_extensions.Contains(good1));
3585 EXPECT_TRUE(disabled_extensions.Contains(good1));
3586 EXPECT_TRUE(enabled_extensions.Contains(good2));
3587 EXPECT_FALSE(disabled_extensions.Contains(good2));
3589 test_blacklist.SetBlacklistState(
3590 good0, extensions::NOT_BLACKLISTED, true);
3591 test_blacklist.SetBlacklistState(
3592 good1, extensions::BLACKLISTED_UNKNOWN, true);
3593 test_blacklist.SetBlacklistState(
3594 good2, extensions::BLACKLISTED_UNKNOWN, true);
3595 base::RunLoop().RunUntilIdle();
3597 // good0 re-enabled, other remain as they were.
3598 EXPECT_TRUE(enabled_extensions.Contains(good0));
3599 EXPECT_FALSE(disabled_extensions.Contains(good0));
3600 EXPECT_FALSE(enabled_extensions.Contains(good1));
3601 EXPECT_TRUE(disabled_extensions.Contains(good1));
3602 EXPECT_TRUE(enabled_extensions.Contains(good2));
3603 EXPECT_FALSE(disabled_extensions.Contains(good2));
3606 // Tests that blacklisted extensions cannot be reloaded, both those loaded
3607 // before and after extension service startup.
3608 TEST_F(ExtensionServiceTest, ReloadBlacklistedExtension) {
3609 extensions::TestBlacklist test_blacklist;
3611 InitializeGoodInstalledExtensionService();
3612 test_blacklist.Attach(service()->blacklist_);
3614 test_blacklist.SetBlacklistState(
3615 good1, extensions::BLACKLISTED_MALWARE, false);
3616 service()->Init();
3617 test_blacklist.SetBlacklistState(
3618 good2, extensions::BLACKLISTED_MALWARE, false);
3619 base::RunLoop().RunUntilIdle();
3621 EXPECT_EQ(StringSet(good0), registry()->enabled_extensions().GetIDs());
3622 EXPECT_EQ(StringSet(good1, good2),
3623 registry()->blacklisted_extensions().GetIDs());
3625 service()->ReloadExtension(good1);
3626 service()->ReloadExtension(good2);
3627 base::RunLoop().RunUntilIdle();
3629 EXPECT_EQ(StringSet(good0), registry()->enabled_extensions().GetIDs());
3630 EXPECT_EQ(StringSet(good1, good2),
3631 registry()->blacklisted_extensions().GetIDs());
3634 #endif // defined(ENABLE_BLACKLIST_TESTS)
3636 // Tests blocking then unblocking enabled extensions after the service has been
3637 // initialized.
3638 TEST_F(ExtensionServiceTest, BlockAndUnblockEnabledExtension) {
3639 InitializeGoodInstalledExtensionService();
3640 service()->Init();
3642 AssertExtensionBlocksAndUnblocks(true, good0);
3645 // Tests blocking then unblocking disabled extensions after the service has been
3646 // initialized.
3647 TEST_F(ExtensionServiceTest, BlockAndUnblockDisabledExtension) {
3648 InitializeGoodInstalledExtensionService();
3649 service()->Init();
3651 service()->DisableExtension(good0, Extension::DISABLE_RELOAD);
3653 AssertExtensionBlocksAndUnblocks(true, good0);
3656 // Tests blocking then unblocking terminated extensions after the service has
3657 // been initialized.
3658 TEST_F(ExtensionServiceTest, BlockAndUnblockTerminatedExtension) {
3659 InitializeGoodInstalledExtensionService();
3660 service()->Init();
3662 TerminateExtension(good0);
3664 AssertExtensionBlocksAndUnblocks(true, good0);
3667 // Tests blocking then unblocking policy-forced extensions after the service has
3668 // been initialized.
3669 TEST_F(ExtensionServiceTest, BlockAndUnblockPolicyExtension) {
3670 InitializeEmptyExtensionServiceWithTestingPrefs();
3673 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
3674 // // Blacklist everything.
3675 // pref.SetBlacklistedByDefault(true);
3676 // Mark good.crx for force-installation.
3677 pref.SetIndividualExtensionAutoInstalled(
3678 good_crx, "http://example.com/update_url", true);
3681 // Have policy force-install an extension.
3682 MockExtensionProvider* provider =
3683 new MockExtensionProvider(service(), Manifest::EXTERNAL_POLICY_DOWNLOAD);
3684 AddMockExternalProvider(provider);
3685 provider->UpdateOrAddExtension(
3686 good_crx, "1.0.0.0", data_dir().AppendASCII("good_crx"));
3688 // Reloading extensions should find our externally registered extension
3689 // and install it.
3690 content::WindowedNotificationObserver observer(
3691 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
3692 content::NotificationService::AllSources());
3693 service()->CheckForExternalUpdates();
3694 observer.Wait();
3696 AssertExtensionBlocksAndUnblocks(false, good_crx);
3700 #if defined(ENABLE_BLACKLIST_TESTS)
3701 // Tests blocking then unblocking extensions that are blacklisted both before
3702 // and after Init().
3703 TEST_F(ExtensionServiceTest, BlockAndUnblockBlacklistedExtension) {
3704 extensions::TestBlacklist test_blacklist;
3706 InitializeGoodInstalledExtensionService();
3707 test_blacklist.Attach(service()->blacklist_);
3709 test_blacklist.SetBlacklistState(
3710 good0, extensions::BLACKLISTED_MALWARE, true);
3711 base::RunLoop().RunUntilIdle();
3713 service()->Init();
3715 test_blacklist.SetBlacklistState(
3716 good1, extensions::BLACKLISTED_MALWARE, true);
3717 base::RunLoop().RunUntilIdle();
3719 // Blacklisted extensions stay blacklisted.
3720 AssertExtensionBlocksAndUnblocks(false, good0);
3721 AssertExtensionBlocksAndUnblocks(false, good1);
3723 service()->BlockAllExtensions();
3725 // Remove an extension from the blacklist while the service is blocked.
3726 test_blacklist.SetBlacklistState(
3727 good0, extensions::NOT_BLACKLISTED, true);
3728 // Add an extension to the blacklist while the service is blocked.
3729 test_blacklist.SetBlacklistState(
3730 good2, extensions::BLACKLISTED_MALWARE, true);
3731 base::RunLoop().RunUntilIdle();
3733 // Go directly to blocked, do not pass go, do not collect $200.
3734 ASSERT_TRUE(IsBlocked(good0));
3735 // Get on the blacklist - even if you were blocked!
3736 ASSERT_FALSE(IsBlocked(good2));
3738 #endif // defined(ENABLE_BLACKLIST_TESTS)
3740 // Tests blocking then unblocking enabled component extensions after the service
3741 // has been initialized.
3742 TEST_F(ExtensionServiceTest, BlockAndUnblockEnabledComponentExtension) {
3743 InitializeEmptyExtensionServiceWithTestingPrefs();
3745 // Install a component extension.
3746 base::FilePath path = data_dir()
3747 .AppendASCII("good")
3748 .AppendASCII("Extensions")
3749 .AppendASCII(good0)
3750 .AppendASCII("1.0.0.0");
3751 std::string manifest;
3752 ASSERT_TRUE(base::ReadFileToString(
3753 path.Append(extensions::kManifestFilename), &manifest));
3754 service()->component_loader()->Add(manifest, path);
3755 service()->Init();
3757 // Component extension should never block.
3758 AssertExtensionBlocksAndUnblocks(false, good0);
3761 // Tests blocking then unblocking a theme after the service has been
3762 // initialized.
3763 TEST_F(ExtensionServiceTest, BlockAndUnblockTheme) {
3764 InitializeEmptyExtensionService();
3765 service()->Init();
3767 base::FilePath path = data_dir().AppendASCII("theme.crx");
3768 InstallCRX(path, INSTALL_NEW);
3770 AssertExtensionBlocksAndUnblocks(true, theme_crx);
3773 // Tests that blocking extensions before Init() results in loading blocked
3774 // extensions.
3775 TEST_F(ExtensionServiceTest, WillNotLoadExtensionsWhenBlocked) {
3776 InitializeGoodInstalledExtensionService();
3778 service()->BlockAllExtensions();
3780 service()->Init();
3782 ASSERT_TRUE(IsBlocked(good0));
3783 ASSERT_TRUE(IsBlocked(good0));
3784 ASSERT_TRUE(IsBlocked(good0));
3787 // Tests that IsEnabledExtension won't crash on an uninstalled extension.
3788 TEST_F(ExtensionServiceTest, IsEnabledExtensionBlockedAndNotInstalled) {
3789 InitializeEmptyExtensionService();
3791 service()->BlockAllExtensions();
3793 service()->IsExtensionEnabled(theme_crx);
3796 // Will not install extension blacklisted by policy.
3797 TEST_F(ExtensionServiceTest, BlacklistedByPolicyWillNotInstall) {
3798 InitializeEmptyExtensionServiceWithTestingPrefs();
3800 // Blacklist everything.
3802 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
3803 pref.SetBlacklistedByDefault(true);
3806 // Blacklist prevents us from installing good_crx.
3807 base::FilePath path = data_dir().AppendASCII("good.crx");
3808 InstallCRX(path, INSTALL_FAILED);
3809 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3811 // Now whitelist this particular extension.
3813 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
3814 pref.SetIndividualExtensionInstallationAllowed(good_crx, true);
3817 // Ensure we can now install good_crx.
3818 InstallCRX(path, INSTALL_NEW);
3819 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3822 // Extension blacklisted by policy get unloaded after installing.
3823 TEST_F(ExtensionServiceTest, BlacklistedByPolicyRemovedIfRunning) {
3824 InitializeEmptyExtensionServiceWithTestingPrefs();
3826 // Install good_crx.
3827 base::FilePath path = data_dir().AppendASCII("good.crx");
3828 InstallCRX(path, INSTALL_NEW);
3829 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3832 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
3833 // Blacklist this extension.
3834 pref.SetIndividualExtensionInstallationAllowed(good_crx, false);
3837 // Extension should not be running now.
3838 base::RunLoop().RunUntilIdle();
3839 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3842 // Tests that component extensions are not blacklisted by policy.
3843 TEST_F(ExtensionServiceTest, ComponentExtensionWhitelisted) {
3844 InitializeEmptyExtensionServiceWithTestingPrefs();
3846 // Blacklist everything.
3848 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
3849 pref.SetBlacklistedByDefault(true);
3852 // Install a component extension.
3853 base::FilePath path = data_dir()
3854 .AppendASCII("good")
3855 .AppendASCII("Extensions")
3856 .AppendASCII(good0)
3857 .AppendASCII("1.0.0.0");
3858 std::string manifest;
3859 ASSERT_TRUE(base::ReadFileToString(
3860 path.Append(extensions::kManifestFilename), &manifest));
3861 service()->component_loader()->Add(manifest, path);
3862 service()->Init();
3864 // Extension should be installed despite blacklist.
3865 ASSERT_EQ(1u, registry()->enabled_extensions().size());
3866 EXPECT_TRUE(service()->GetExtensionById(good0, false));
3868 // Poke external providers and make sure the extension is still present.
3869 service()->CheckForExternalUpdates();
3870 ASSERT_EQ(1u, registry()->enabled_extensions().size());
3871 EXPECT_TRUE(service()->GetExtensionById(good0, false));
3873 // Extension should not be uninstalled on blacklist changes.
3875 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
3876 pref.SetIndividualExtensionInstallationAllowed(good0, false);
3878 base::RunLoop().RunUntilIdle();
3879 ASSERT_EQ(1u, registry()->enabled_extensions().size());
3880 EXPECT_TRUE(service()->GetExtensionById(good0, false));
3883 // Tests that policy-installed extensions are not blacklisted by policy.
3884 TEST_F(ExtensionServiceTest, PolicyInstalledExtensionsWhitelisted) {
3885 InitializeEmptyExtensionServiceWithTestingPrefs();
3888 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
3889 // Blacklist everything.
3890 pref.SetBlacklistedByDefault(true);
3891 // Mark good.crx for force-installation.
3892 pref.SetIndividualExtensionAutoInstalled(
3893 good_crx, "http://example.com/update_url", true);
3896 // Have policy force-install an extension.
3897 MockExtensionProvider* provider =
3898 new MockExtensionProvider(service(), Manifest::EXTERNAL_POLICY_DOWNLOAD);
3899 AddMockExternalProvider(provider);
3900 provider->UpdateOrAddExtension(
3901 good_crx, "1.0.0.0", data_dir().AppendASCII("good.crx"));
3903 // Reloading extensions should find our externally registered extension
3904 // and install it.
3905 content::WindowedNotificationObserver observer(
3906 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
3907 content::NotificationService::AllSources());
3908 service()->CheckForExternalUpdates();
3909 observer.Wait();
3911 // Extension should be installed despite blacklist.
3912 ASSERT_EQ(1u, registry()->enabled_extensions().size());
3913 EXPECT_TRUE(service()->GetExtensionById(good_crx, false));
3915 // Blacklist update should not uninstall the extension.
3917 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
3918 pref.SetIndividualExtensionInstallationAllowed(good0, false);
3920 base::RunLoop().RunUntilIdle();
3921 ASSERT_EQ(1u, registry()->enabled_extensions().size());
3922 EXPECT_TRUE(service()->GetExtensionById(good_crx, false));
3925 // Tests that extensions cannot be installed if the policy provider prohibits
3926 // it. This functionality is implemented in CrxInstaller::ConfirmInstall().
3927 TEST_F(ExtensionServiceTest, ManagementPolicyProhibitsInstall) {
3928 InitializeEmptyExtensionService();
3930 GetManagementPolicy()->UnregisterAllProviders();
3931 extensions::TestManagementPolicyProvider provider_(
3932 extensions::TestManagementPolicyProvider::PROHIBIT_LOAD);
3933 GetManagementPolicy()->RegisterProvider(&provider_);
3935 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_FAILED);
3936 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3939 // Tests that extensions cannot be loaded from prefs if the policy provider
3940 // prohibits it. This functionality is implemented in InstalledLoader::Load().
3941 TEST_F(ExtensionServiceTest, ManagementPolicyProhibitsLoadFromPrefs) {
3942 InitializeEmptyExtensionService();
3944 // Create a fake extension to be loaded as though it were read from prefs.
3945 base::FilePath path =
3946 data_dir().AppendASCII("management").AppendASCII("simple_extension");
3947 base::DictionaryValue manifest;
3948 manifest.SetString(keys::kName, "simple_extension");
3949 manifest.SetString(keys::kVersion, "1");
3950 // UNPACKED is for extensions loaded from a directory. We use it here, even
3951 // though we're testing loading from prefs, so that we don't need to provide
3952 // an extension key.
3953 extensions::ExtensionInfo extension_info(
3954 &manifest, std::string(), path, Manifest::UNPACKED);
3956 // Ensure we can load it with no management policy in place.
3957 GetManagementPolicy()->UnregisterAllProviders();
3958 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3959 extensions::InstalledLoader(service()).Load(extension_info, false);
3960 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3962 const Extension* extension =
3963 (registry()->enabled_extensions().begin())->get();
3964 EXPECT_TRUE(
3965 service()->UninstallExtension(extension->id(),
3966 extensions::UNINSTALL_REASON_FOR_TESTING,
3967 base::Bind(&base::DoNothing),
3968 NULL));
3969 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3971 // Ensure we cannot load it if management policy prohibits installation.
3972 extensions::TestManagementPolicyProvider provider_(
3973 extensions::TestManagementPolicyProvider::PROHIBIT_LOAD);
3974 GetManagementPolicy()->RegisterProvider(&provider_);
3976 extensions::InstalledLoader(service()).Load(extension_info, false);
3977 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3980 // Tests disabling an extension when prohibited by the ManagementPolicy.
3981 TEST_F(ExtensionServiceTest, ManagementPolicyProhibitsDisable) {
3982 InitializeEmptyExtensionService();
3984 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
3985 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3986 EXPECT_EQ(0u, registry()->disabled_extensions().size());
3988 GetManagementPolicy()->UnregisterAllProviders();
3989 extensions::TestManagementPolicyProvider provider(
3990 extensions::TestManagementPolicyProvider::PROHIBIT_MODIFY_STATUS);
3991 GetManagementPolicy()->RegisterProvider(&provider);
3993 // Attempt to disable it.
3994 service()->DisableExtension(good_crx, Extension::DISABLE_USER_ACTION);
3996 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3997 EXPECT_TRUE(service()->GetExtensionById(good_crx, false));
3998 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4001 // Tests uninstalling an extension when prohibited by the ManagementPolicy.
4002 TEST_F(ExtensionServiceTest, ManagementPolicyProhibitsUninstall) {
4003 InitializeEmptyExtensionService();
4005 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
4006 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4007 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4009 GetManagementPolicy()->UnregisterAllProviders();
4010 extensions::TestManagementPolicyProvider provider(
4011 extensions::TestManagementPolicyProvider::PROHIBIT_MODIFY_STATUS);
4012 GetManagementPolicy()->RegisterProvider(&provider);
4014 // Attempt to uninstall it.
4015 EXPECT_FALSE(
4016 service()->UninstallExtension(good_crx,
4017 extensions::UNINSTALL_REASON_FOR_TESTING,
4018 base::Bind(&base::DoNothing),
4019 NULL));
4021 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4022 EXPECT_TRUE(service()->GetExtensionById(good_crx, false));
4025 // Tests that previously installed extensions that are now prohibited from
4026 // being installed are removed.
4027 TEST_F(ExtensionServiceTest, ManagementPolicyUnloadsAllProhibited) {
4028 InitializeEmptyExtensionService();
4030 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
4031 InstallCRX(data_dir().AppendASCII("page_action.crx"), INSTALL_NEW);
4032 EXPECT_EQ(2u, registry()->enabled_extensions().size());
4033 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4035 GetManagementPolicy()->UnregisterAllProviders();
4036 extensions::TestManagementPolicyProvider provider(
4037 extensions::TestManagementPolicyProvider::PROHIBIT_LOAD);
4038 GetManagementPolicy()->RegisterProvider(&provider);
4040 // Run the policy check.
4041 service()->CheckManagementPolicy();
4042 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4043 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4046 // Tests that previously disabled extensions that are now required to be
4047 // enabled are re-enabled on reinstall.
4048 TEST_F(ExtensionServiceTest, ManagementPolicyRequiresEnable) {
4049 InitializeEmptyExtensionService();
4051 // Install, then disable, an extension.
4052 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
4053 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4054 service()->DisableExtension(good_crx, Extension::DISABLE_USER_ACTION);
4055 EXPECT_EQ(1u, registry()->disabled_extensions().size());
4057 // Register an ExtensionManagementPolicy that requires the extension to remain
4058 // enabled.
4059 GetManagementPolicy()->UnregisterAllProviders();
4060 extensions::TestManagementPolicyProvider provider(
4061 extensions::TestManagementPolicyProvider::MUST_REMAIN_ENABLED);
4062 GetManagementPolicy()->RegisterProvider(&provider);
4064 // Reinstall the extension.
4065 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_UPDATED);
4066 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4067 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4070 // Tests that extensions disabled by management policy can be installed but
4071 // will get disabled after installing.
4072 TEST_F(ExtensionServiceTest, ManagementPolicyProhibitsEnableOnInstalled) {
4073 InitializeEmptyExtensionService();
4075 // Register an ExtensionManagementPolicy that disables all extensions, with
4076 // a specified Extension::DisableReason.
4077 GetManagementPolicy()->UnregisterAllProviders();
4078 extensions::TestManagementPolicyProvider provider(
4079 extensions::TestManagementPolicyProvider::MUST_REMAIN_DISABLED);
4080 provider.SetDisableReason(Extension::DISABLE_NOT_VERIFIED);
4081 GetManagementPolicy()->RegisterProvider(&provider);
4083 // Attempts to install an extensions, it should be installed but disabled.
4084 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4085 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4086 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_WITHOUT_LOAD);
4087 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4088 EXPECT_EQ(1u, registry()->disabled_extensions().size());
4090 // Verifies that the disable reason is set properly.
4091 EXPECT_EQ(Extension::DISABLE_NOT_VERIFIED,
4092 service()->extension_prefs_->GetDisableReasons(kGoodId));
4095 // Tests that extensions with conflicting required permissions by enterprise
4096 // policy cannot be installed.
4097 TEST_F(ExtensionServiceTest, PolicyBlockedPermissionNewExtensionInstall) {
4098 InitializeEmptyExtensionServiceWithTestingPrefs();
4099 base::FilePath path = data_dir().AppendASCII("permissions_blocklist");
4102 // Update policy to block one of the required permissions of target.
4103 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
4104 pref.AddBlockedPermission("*", "tabs");
4107 // The extension should be failed to install.
4108 PackAndInstallCRX(path, INSTALL_FAILED);
4111 // Update policy to block one of the optional permissions instead.
4112 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
4113 pref.ClearBlockedPermissions("*");
4114 pref.AddBlockedPermission("*", "history");
4117 // The extension should succeed to install this time.
4118 std::string id = PackAndInstallCRX(path, INSTALL_NEW)->id();
4120 // Uninstall the extension and update policy to block some arbitrary
4121 // unknown permission.
4122 UninstallExtension(id, false);
4124 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
4125 pref.ClearBlockedPermissions("*");
4126 pref.AddBlockedPermission("*", "unknown.permission.for.testing");
4129 // The extension should succeed to install as well.
4130 PackAndInstallCRX(path, INSTALL_NEW);
4133 // Tests that extension supposed to be force installed but with conflicting
4134 // required permissions cannot be installed.
4135 TEST_F(ExtensionServiceTest, PolicyBlockedPermissionConflictsWithForceInstall) {
4136 InitializeEmptyExtensionServiceWithTestingPrefs();
4138 // Pack the crx file.
4139 base::FilePath path = data_dir().AppendASCII("permissions_blocklist");
4140 base::FilePath pem_path = data_dir().AppendASCII("permissions_blocklist.pem");
4141 base::ScopedTempDir temp_dir;
4142 EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
4143 base::FilePath crx_path = temp_dir.path().AppendASCII("temp.crx");
4145 PackCRX(path, pem_path, crx_path);
4148 // Block one of the required permissions.
4149 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
4150 pref.AddBlockedPermission("*", "tabs");
4153 // Use MockExtensionProvider to simulate force installing extension.
4154 MockExtensionProvider* provider =
4155 new MockExtensionProvider(service(), Manifest::EXTERNAL_POLICY_DOWNLOAD);
4156 AddMockExternalProvider(provider);
4157 provider->UpdateOrAddExtension(permissions_blocklist, "1.0", crx_path);
4160 // Attempts to force install this extension.
4161 content::WindowedNotificationObserver observer(
4162 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
4163 content::NotificationService::AllSources());
4164 service()->CheckForExternalUpdates();
4165 observer.Wait();
4168 // The extension should not be installed.
4169 ASSERT_FALSE(service()->GetInstalledExtension(permissions_blocklist));
4171 // Remove this extension from pending extension manager as we would like to
4172 // give another attempt later.
4173 service()->pending_extension_manager()->Remove(permissions_blocklist);
4176 // Clears the permission block list.
4177 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
4178 pref.ClearBlockedPermissions("*");
4182 // Attempts to force install this extension again.
4183 content::WindowedNotificationObserver observer(
4184 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
4185 content::NotificationService::AllSources());
4186 service()->CheckForExternalUpdates();
4187 observer.Wait();
4190 const Extension* installed =
4191 service()->GetInstalledExtension(permissions_blocklist);
4192 ASSERT_TRUE(installed);
4193 EXPECT_EQ(installed->location(), Manifest::EXTERNAL_POLICY_DOWNLOAD);
4196 // Tests that newer versions of an extension with conflicting required
4197 // permissions by enterprise policy cannot be updated to.
4198 TEST_F(ExtensionServiceTest, PolicyBlockedPermissionExtensionUpdate) {
4199 InitializeEmptyExtensionServiceWithTestingPrefs();
4201 base::FilePath path = data_dir().AppendASCII("permissions_blocklist");
4202 base::FilePath path2 = data_dir().AppendASCII("permissions_blocklist2");
4203 base::FilePath pem_path = data_dir().AppendASCII("permissions_blocklist.pem");
4205 // Install 'permissions_blocklist'.
4206 const Extension* installed = PackAndInstallCRX(path, pem_path, INSTALL_NEW);
4207 EXPECT_EQ(installed->id(), permissions_blocklist);
4210 // Block one of the required permissions of 'permissions_blocklist2'.
4211 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
4212 pref.AddBlockedPermission("*", "downloads");
4215 // Install 'permissions_blocklist' again, should be updated.
4216 const Extension* updated = PackAndInstallCRX(path, pem_path, INSTALL_UPDATED);
4217 EXPECT_EQ(updated->id(), permissions_blocklist);
4219 std::string old_version = updated->VersionString();
4221 // Attempts to update to 'permissions_blocklist2' should fail.
4222 PackAndInstallCRX(path2, pem_path, INSTALL_FAILED);
4224 // Verify that the old version is still enabled.
4225 updated = service()->GetExtensionById(permissions_blocklist, false);
4226 ASSERT_TRUE(updated);
4227 EXPECT_EQ(old_version, updated->VersionString());
4230 // Tests that policy update with additional permissions blocked revoke
4231 // conflicting granted optional permissions and unload extensions with
4232 // conflicting required permissions, including the force installed ones.
4233 TEST_F(ExtensionServiceTest, PolicyBlockedPermissionPolicyUpdate) {
4234 InitializeEmptyExtensionServiceWithTestingPrefs();
4236 base::FilePath path = data_dir().AppendASCII("permissions_blocklist");
4237 base::FilePath path2 = data_dir().AppendASCII("permissions_blocklist2");
4238 base::FilePath pem_path = data_dir().AppendASCII("permissions_blocklist.pem");
4240 // Pack the crx file.
4241 base::ScopedTempDir temp_dir;
4242 EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
4243 base::FilePath crx_path = temp_dir.path().AppendASCII("temp.crx");
4245 PackCRX(path2, pem_path, crx_path);
4247 // Install two arbitary extensions with specified manifest.
4248 std::string ext1 = PackAndInstallCRX(path, INSTALL_NEW)->id();
4249 std::string ext2 = PackAndInstallCRX(path2, INSTALL_NEW)->id();
4250 ASSERT_NE(ext1, permissions_blocklist);
4251 ASSERT_NE(ext2, permissions_blocklist);
4252 ASSERT_NE(ext1, ext2);
4254 // Force install another extension with known id and same manifest as 'ext2'.
4255 std::string ext2_forced = permissions_blocklist;
4256 MockExtensionProvider* provider =
4257 new MockExtensionProvider(service(), Manifest::EXTERNAL_POLICY_DOWNLOAD);
4258 AddMockExternalProvider(provider);
4259 provider->UpdateOrAddExtension(ext2_forced, "2.0", crx_path);
4261 content::WindowedNotificationObserver observer(
4262 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
4263 content::NotificationService::AllSources());
4264 service()->CheckForExternalUpdates();
4265 observer.Wait();
4267 extensions::ExtensionRegistry* registry =
4268 extensions::ExtensionRegistry::Get(profile());
4270 // Verify all three extensions are installed and enabled.
4271 ASSERT_TRUE(registry->enabled_extensions().GetByID(ext1));
4272 ASSERT_TRUE(registry->enabled_extensions().GetByID(ext2));
4273 ASSERT_TRUE(registry->enabled_extensions().GetByID(ext2_forced));
4275 // Grant all optional permissions to each extension.
4276 GrantAllOptionalPermissions(ext1);
4277 GrantAllOptionalPermissions(ext2);
4278 GrantAllOptionalPermissions(ext2_forced);
4280 scoped_refptr<const PermissionSet> active_permissions(
4281 ExtensionPrefs::Get(profile())->GetActivePermissions(ext1));
4282 EXPECT_TRUE(active_permissions->HasAPIPermission(
4283 extensions::APIPermission::kDownloads));
4285 // Set policy to block 'downloads' permission.
4287 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
4288 pref.AddBlockedPermission("*", "downloads");
4291 base::RunLoop().RunUntilIdle();
4293 // 'ext1' should still be enabled, but with 'downloads' permission revoked.
4294 EXPECT_TRUE(registry->enabled_extensions().GetByID(ext1));
4295 active_permissions =
4296 ExtensionPrefs::Get(profile())->GetActivePermissions(ext1);
4297 EXPECT_FALSE(active_permissions->HasAPIPermission(
4298 extensions::APIPermission::kDownloads));
4300 // 'ext2' should be disabled because one of its required permissions is
4301 // blocked.
4302 EXPECT_FALSE(registry->enabled_extensions().GetByID(ext2));
4304 // 'ext2_forced' should be handled the same as 'ext2'
4305 EXPECT_FALSE(registry->enabled_extensions().GetByID(ext2_forced));
4308 // Flaky on windows; http://crbug.com/309833
4309 #if defined(OS_WIN)
4310 #define MAYBE_ExternalExtensionAutoAcknowledgement DISABLED_ExternalExtensionAutoAcknowledgement
4311 #else
4312 #define MAYBE_ExternalExtensionAutoAcknowledgement ExternalExtensionAutoAcknowledgement
4313 #endif
4314 TEST_F(ExtensionServiceTest, MAYBE_ExternalExtensionAutoAcknowledgement) {
4315 InitializeEmptyExtensionService();
4316 service()->set_extensions_enabled(true);
4319 // Register and install an external extension.
4320 MockExtensionProvider* provider =
4321 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF);
4322 AddMockExternalProvider(provider);
4323 provider->UpdateOrAddExtension(
4324 good_crx, "1.0.0.0", data_dir().AppendASCII("good.crx"));
4327 // Have policy force-install an extension.
4328 MockExtensionProvider* provider = new MockExtensionProvider(
4329 service(), Manifest::EXTERNAL_POLICY_DOWNLOAD);
4330 AddMockExternalProvider(provider);
4331 provider->UpdateOrAddExtension(
4332 page_action, "1.0.0.0", data_dir().AppendASCII("page_action.crx"));
4335 // Providers are set up. Let them run.
4336 int count = 2;
4337 content::WindowedNotificationObserver observer(
4338 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
4339 base::Bind(&WaitForCountNotificationsCallback, &count));
4340 service()->CheckForExternalUpdates();
4342 observer.Wait();
4344 ASSERT_EQ(2u, registry()->enabled_extensions().size());
4345 EXPECT_TRUE(service()->GetExtensionById(good_crx, false));
4346 EXPECT_TRUE(service()->GetExtensionById(page_action, false));
4347 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
4348 ASSERT_TRUE(!prefs->IsExternalExtensionAcknowledged(good_crx));
4349 ASSERT_TRUE(prefs->IsExternalExtensionAcknowledged(page_action));
4352 #if !defined(OS_CHROMEOS)
4353 // This tests if default apps are installed correctly.
4354 TEST_F(ExtensionServiceTest, DefaultAppsInstall) {
4355 InitializeEmptyExtensionService();
4356 service()->set_extensions_enabled(true);
4359 std::string json_data =
4361 " \"ldnnhddmnhbkjipkidpdiheffobcpfmf\" : {"
4362 " \"external_crx\": \"good.crx\","
4363 " \"external_version\": \"1.0.0.0\","
4364 " \"is_bookmark_app\": false"
4365 " }"
4366 "}";
4367 default_apps::Provider* provider = new default_apps::Provider(
4368 profile(),
4369 service(),
4370 new extensions::ExternalTestingLoader(json_data, data_dir()),
4371 Manifest::INTERNAL,
4372 Manifest::INVALID_LOCATION,
4373 Extension::FROM_WEBSTORE | Extension::WAS_INSTALLED_BY_DEFAULT);
4375 AddMockExternalProvider(provider);
4378 ASSERT_EQ(0u, registry()->enabled_extensions().size());
4379 content::WindowedNotificationObserver observer(
4380 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
4381 content::NotificationService::AllSources());
4382 service()->CheckForExternalUpdates();
4383 observer.Wait();
4385 ASSERT_EQ(1u, registry()->enabled_extensions().size());
4386 EXPECT_TRUE(service()->GetExtensionById(good_crx, false));
4387 const Extension* extension = service()->GetExtensionById(good_crx, false);
4388 EXPECT_TRUE(extension->from_webstore());
4389 EXPECT_TRUE(extension->was_installed_by_default());
4391 #endif
4393 // Tests disabling extensions
4394 TEST_F(ExtensionServiceTest, DisableExtension) {
4395 InitializeEmptyExtensionService();
4397 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
4398 EXPECT_TRUE(service()->GetExtensionById(good_crx, true));
4399 EXPECT_TRUE(service()->GetExtensionById(good_crx, false));
4401 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4402 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4403 EXPECT_EQ(0u, registry()->terminated_extensions().size());
4404 EXPECT_EQ(0u, registry()->blacklisted_extensions().size());
4406 // Disable it.
4407 service()->DisableExtension(good_crx, Extension::DISABLE_USER_ACTION);
4409 EXPECT_TRUE(service()->GetExtensionById(good_crx, true));
4410 EXPECT_FALSE(service()->GetExtensionById(good_crx, false));
4411 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4412 EXPECT_EQ(1u, registry()->disabled_extensions().size());
4413 EXPECT_EQ(0u, registry()->terminated_extensions().size());
4414 EXPECT_EQ(0u, registry()->blacklisted_extensions().size());
4417 TEST_F(ExtensionServiceTest, TerminateExtension) {
4418 InitializeEmptyExtensionService();
4420 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
4421 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4422 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4423 EXPECT_EQ(0u, registry()->terminated_extensions().size());
4424 EXPECT_EQ(0u, registry()->blacklisted_extensions().size());
4426 TerminateExtension(good_crx);
4428 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4429 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4430 EXPECT_EQ(1u, registry()->terminated_extensions().size());
4431 EXPECT_EQ(0u, registry()->blacklisted_extensions().size());
4434 TEST_F(ExtensionServiceTest, DisableTerminatedExtension) {
4435 InitializeEmptyExtensionService();
4437 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
4438 TerminateExtension(good_crx);
4439 EXPECT_TRUE(registry()->GetExtensionById(
4440 good_crx, extensions::ExtensionRegistry::TERMINATED));
4442 // Disable it.
4443 service()->DisableExtension(good_crx, Extension::DISABLE_USER_ACTION);
4445 EXPECT_FALSE(registry()->GetExtensionById(
4446 good_crx, extensions::ExtensionRegistry::TERMINATED));
4447 EXPECT_TRUE(service()->GetExtensionById(good_crx, true));
4449 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4450 EXPECT_EQ(1u, registry()->disabled_extensions().size());
4451 EXPECT_EQ(0u, registry()->terminated_extensions().size());
4452 EXPECT_EQ(0u, registry()->blacklisted_extensions().size());
4455 // Tests disabling all extensions (simulating --disable-extensions flag).
4456 TEST_F(ExtensionServiceTest, DisableAllExtensions) {
4457 InitializeEmptyExtensionService();
4459 base::FilePath path = data_dir().AppendASCII("good.crx");
4460 InstallCRX(path, INSTALL_NEW);
4462 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4463 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4465 // Disable extensions.
4466 service()->set_extensions_enabled(false);
4467 service()->ReloadExtensionsForTest();
4469 // There shouldn't be extensions in either list.
4470 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4471 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4473 // This shouldn't do anything when all extensions are disabled.
4474 service()->EnableExtension(good_crx);
4475 service()->ReloadExtensionsForTest();
4477 // There still shouldn't be extensions in either list.
4478 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4479 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4481 // And then re-enable the extensions.
4482 service()->set_extensions_enabled(true);
4483 service()->ReloadExtensionsForTest();
4485 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4486 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4489 // Tests reloading extensions.
4490 TEST_F(ExtensionServiceTest, ReloadExtensions) {
4491 InitializeEmptyExtensionService();
4493 // Simple extension that should install without error.
4494 base::FilePath path = data_dir().AppendASCII("good.crx");
4495 InstallCRX(path, INSTALL_NEW,
4496 Extension::FROM_WEBSTORE | Extension::WAS_INSTALLED_BY_DEFAULT);
4497 const char* const extension_id = good_crx;
4498 service()->DisableExtension(extension_id, Extension::DISABLE_USER_ACTION);
4500 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4501 EXPECT_EQ(1u, registry()->disabled_extensions().size());
4503 service()->ReloadExtensionsForTest();
4505 // The creation flags should not change when reloading the extension.
4506 const Extension* extension = service()->GetExtensionById(good_crx, true);
4507 EXPECT_TRUE(extension->from_webstore());
4508 EXPECT_TRUE(extension->was_installed_by_default());
4509 EXPECT_FALSE(extension->from_bookmark());
4511 // Extension counts shouldn't change.
4512 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4513 EXPECT_EQ(1u, registry()->disabled_extensions().size());
4515 service()->EnableExtension(extension_id);
4517 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4518 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4520 // Need to clear |loaded_| manually before reloading as the
4521 // EnableExtension() call above inserted into it and
4522 // UnloadAllExtensions() doesn't send out notifications.
4523 loaded_.clear();
4524 service()->ReloadExtensionsForTest();
4526 // Extension counts shouldn't change.
4527 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4528 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4531 // Tests reloading an extension.
4532 TEST_F(ExtensionServiceTest, ReloadExtension) {
4533 InitializeEmptyExtensionService();
4535 // Simple extension that should install without error.
4536 const char extension_id[] = "behllobkkfkfnphdnhnkndlbkcpglgmj";
4537 base::FilePath ext = data_dir()
4538 .AppendASCII("good")
4539 .AppendASCII("Extensions")
4540 .AppendASCII(extension_id)
4541 .AppendASCII("1.0.0.0");
4542 extensions::UnpackedInstaller::Create(service())->Load(ext);
4543 base::RunLoop().RunUntilIdle();
4545 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4546 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4548 service()->ReloadExtension(extension_id);
4550 // Extension should be disabled now, waiting to be reloaded.
4551 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4552 EXPECT_EQ(1u, registry()->disabled_extensions().size());
4553 EXPECT_EQ(Extension::DISABLE_RELOAD,
4554 ExtensionPrefs::Get(profile())->GetDisableReasons(extension_id));
4556 // Reloading again should not crash.
4557 service()->ReloadExtension(extension_id);
4559 // Finish reloading
4560 base::RunLoop().RunUntilIdle();
4562 // Extension should be enabled again.
4563 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4564 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4567 TEST_F(ExtensionServiceTest, UninstallExtension) {
4568 InitializeEmptyExtensionService();
4569 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
4570 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4571 UninstallExtension(good_crx, false);
4572 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4573 EXPECT_EQ(UnloadedExtensionInfo::REASON_UNINSTALL, unloaded_reason_);
4576 TEST_F(ExtensionServiceTest, UninstallTerminatedExtension) {
4577 InitializeEmptyExtensionService();
4578 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
4579 TerminateExtension(good_crx);
4580 UninstallExtension(good_crx, false);
4581 EXPECT_EQ(UnloadedExtensionInfo::REASON_TERMINATE, unloaded_reason_);
4584 // Tests the uninstaller helper.
4585 TEST_F(ExtensionServiceTest, UninstallExtensionHelper) {
4586 InitializeEmptyExtensionService();
4587 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
4588 UninstallExtension(good_crx, true);
4589 EXPECT_EQ(UnloadedExtensionInfo::REASON_UNINSTALL, unloaded_reason_);
4592 TEST_F(ExtensionServiceTest, UninstallExtensionHelperTerminated) {
4593 InitializeEmptyExtensionService();
4594 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
4595 TerminateExtension(good_crx);
4596 UninstallExtension(good_crx, true);
4597 EXPECT_EQ(UnloadedExtensionInfo::REASON_TERMINATE, unloaded_reason_);
4600 // An extension disabled because of unsupported requirements should re-enabled
4601 // if updated to a version with supported requirements as long as there are no
4602 // other disable reasons.
4603 TEST_F(ExtensionServiceTest, UpgradingRequirementsEnabled) {
4604 InitializeEmptyExtensionService();
4605 BlackListWebGL();
4607 base::FilePath path = data_dir().AppendASCII("requirements");
4608 base::FilePath pem_path =
4609 data_dir().AppendASCII("requirements").AppendASCII("v1_good.pem");
4610 const Extension* extension_v1 = PackAndInstallCRX(path.AppendASCII("v1_good"),
4611 pem_path,
4612 INSTALL_NEW);
4613 std::string id = extension_v1->id();
4614 EXPECT_TRUE(service()->IsExtensionEnabled(id));
4616 base::FilePath v2_bad_requirements_crx = GetTemporaryFile();
4618 PackCRX(path.AppendASCII("v2_bad_requirements"),
4619 pem_path,
4620 v2_bad_requirements_crx);
4621 UpdateExtension(id, v2_bad_requirements_crx, INSTALLED);
4622 EXPECT_FALSE(service()->IsExtensionEnabled(id));
4624 base::FilePath v3_good_crx = GetTemporaryFile();
4626 PackCRX(path.AppendASCII("v3_good"), pem_path, v3_good_crx);
4627 UpdateExtension(id, v3_good_crx, ENABLED);
4628 EXPECT_TRUE(service()->IsExtensionEnabled(id));
4631 // Extensions disabled through user action should stay disabled.
4632 TEST_F(ExtensionServiceTest, UpgradingRequirementsDisabled) {
4633 InitializeEmptyExtensionService();
4634 BlackListWebGL();
4636 base::FilePath path = data_dir().AppendASCII("requirements");
4637 base::FilePath pem_path =
4638 data_dir().AppendASCII("requirements").AppendASCII("v1_good.pem");
4639 const Extension* extension_v1 = PackAndInstallCRX(path.AppendASCII("v1_good"),
4640 pem_path,
4641 INSTALL_NEW);
4642 std::string id = extension_v1->id();
4643 service()->DisableExtension(id, Extension::DISABLE_USER_ACTION);
4644 EXPECT_FALSE(service()->IsExtensionEnabled(id));
4646 base::FilePath v2_bad_requirements_crx = GetTemporaryFile();
4648 PackCRX(path.AppendASCII("v2_bad_requirements"),
4649 pem_path,
4650 v2_bad_requirements_crx);
4651 UpdateExtension(id, v2_bad_requirements_crx, INSTALLED);
4652 EXPECT_FALSE(service()->IsExtensionEnabled(id));
4654 base::FilePath v3_good_crx = GetTemporaryFile();
4656 PackCRX(path.AppendASCII("v3_good"), pem_path, v3_good_crx);
4657 UpdateExtension(id, v3_good_crx, INSTALLED);
4658 EXPECT_FALSE(service()->IsExtensionEnabled(id));
4661 // The extension should not re-enabled because it was disabled from a
4662 // permission increase.
4663 TEST_F(ExtensionServiceTest, UpgradingRequirementsPermissions) {
4664 InitializeEmptyExtensionService();
4665 BlackListWebGL();
4667 base::FilePath path = data_dir().AppendASCII("requirements");
4668 base::FilePath pem_path =
4669 data_dir().AppendASCII("requirements").AppendASCII("v1_good.pem");
4670 const Extension* extension_v1 = PackAndInstallCRX(path.AppendASCII("v1_good"),
4671 pem_path,
4672 INSTALL_NEW);
4673 std::string id = extension_v1->id();
4674 EXPECT_TRUE(service()->IsExtensionEnabled(id));
4676 base::FilePath v2_bad_requirements_and_permissions_crx = GetTemporaryFile();
4678 PackCRX(path.AppendASCII("v2_bad_requirements_and_permissions"),
4679 pem_path,
4680 v2_bad_requirements_and_permissions_crx);
4681 UpdateExtension(id, v2_bad_requirements_and_permissions_crx, INSTALLED);
4682 EXPECT_FALSE(service()->IsExtensionEnabled(id));
4684 base::FilePath v3_bad_permissions_crx = GetTemporaryFile();
4686 PackCRX(path.AppendASCII("v3_bad_permissions"),
4687 pem_path,
4688 v3_bad_permissions_crx);
4689 UpdateExtension(id, v3_bad_permissions_crx, INSTALLED);
4690 EXPECT_FALSE(service()->IsExtensionEnabled(id));
4693 // Unpacked extensions are not allowed to be installed if they have unsupported
4694 // requirements.
4695 TEST_F(ExtensionServiceTest, UnpackedRequirements) {
4696 InitializeEmptyExtensionService();
4697 BlackListWebGL();
4699 base::FilePath path =
4700 data_dir().AppendASCII("requirements").AppendASCII("v2_bad_requirements");
4701 extensions::UnpackedInstaller::Create(service())->Load(path);
4702 base::RunLoop().RunUntilIdle();
4703 EXPECT_EQ(1u, GetErrors().size());
4704 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4707 class ExtensionCookieCallback {
4708 public:
4709 ExtensionCookieCallback()
4710 : result_(false),
4711 weak_factory_(base::MessageLoop::current()) {}
4713 void SetCookieCallback(bool result) {
4714 base::MessageLoop::current()->PostTask(FROM_HERE,
4715 base::Bind(&base::MessageLoop::Quit, weak_factory_.GetWeakPtr()));
4716 result_ = result;
4719 void GetAllCookiesCallback(const net::CookieList& list) {
4720 base::MessageLoop::current()->PostTask(FROM_HERE,
4721 base::Bind(&base::MessageLoop::Quit, weak_factory_.GetWeakPtr()));
4722 list_ = list;
4724 net::CookieList list_;
4725 bool result_;
4726 base::WeakPtrFactory<base::MessageLoop> weak_factory_;
4729 // Verifies extension state is removed upon uninstall.
4730 TEST_F(ExtensionServiceTest, ClearExtensionData) {
4731 InitializeEmptyExtensionService();
4732 ExtensionCookieCallback callback;
4734 // Load a test extension.
4735 base::FilePath path = data_dir();
4736 path = path.AppendASCII("good.crx");
4737 const Extension* extension = InstallCRX(path, INSTALL_NEW);
4738 ASSERT_TRUE(extension);
4739 GURL ext_url(extension->url());
4740 std::string origin_id = storage::GetIdentifierFromOrigin(ext_url);
4742 // Set a cookie for the extension.
4743 net::CookieMonster* cookie_monster = profile()
4744 ->GetRequestContextForExtensions()
4745 ->GetURLRequestContext()
4746 ->cookie_store()
4747 ->GetCookieMonster();
4748 ASSERT_TRUE(cookie_monster);
4749 net::CookieOptions options;
4750 cookie_monster->SetCookieWithOptionsAsync(
4751 ext_url, "dummy=value", options,
4752 base::Bind(&ExtensionCookieCallback::SetCookieCallback,
4753 base::Unretained(&callback)));
4754 base::RunLoop().RunUntilIdle();
4755 EXPECT_TRUE(callback.result_);
4757 cookie_monster->GetAllCookiesForURLAsync(
4758 ext_url,
4759 base::Bind(&ExtensionCookieCallback::GetAllCookiesCallback,
4760 base::Unretained(&callback)));
4761 base::RunLoop().RunUntilIdle();
4762 EXPECT_EQ(1U, callback.list_.size());
4764 // Open a database.
4765 storage::DatabaseTracker* db_tracker =
4766 BrowserContext::GetDefaultStoragePartition(profile())
4767 ->GetDatabaseTracker();
4768 base::string16 db_name = base::UTF8ToUTF16("db");
4769 base::string16 description = base::UTF8ToUTF16("db_description");
4770 int64 size;
4771 db_tracker->DatabaseOpened(origin_id, db_name, description, 1, &size);
4772 db_tracker->DatabaseClosed(origin_id, db_name);
4773 std::vector<storage::OriginInfo> origins;
4774 db_tracker->GetAllOriginsInfo(&origins);
4775 EXPECT_EQ(1U, origins.size());
4776 EXPECT_EQ(origin_id, origins[0].GetOriginIdentifier());
4778 // Create local storage. We only simulate this by creating the backing files.
4779 // Note: This test depends on details of how the dom_storage library
4780 // stores data in the host file system.
4781 base::FilePath lso_dir_path =
4782 profile()->GetPath().AppendASCII("Local Storage");
4783 base::FilePath lso_file_path = lso_dir_path.AppendASCII(origin_id)
4784 .AddExtension(FILE_PATH_LITERAL(".localstorage"));
4785 EXPECT_TRUE(base::CreateDirectory(lso_dir_path));
4786 EXPECT_EQ(0, base::WriteFile(lso_file_path, NULL, 0));
4787 EXPECT_TRUE(base::PathExists(lso_file_path));
4789 // Create indexed db. Similarly, it is enough to only simulate this by
4790 // creating the directory on the disk.
4791 IndexedDBContext* idb_context = BrowserContext::GetDefaultStoragePartition(
4792 profile())->GetIndexedDBContext();
4793 idb_context->SetTaskRunnerForTesting(
4794 base::MessageLoop::current()->message_loop_proxy().get());
4795 base::FilePath idb_path = idb_context->GetFilePathForTesting(origin_id);
4796 EXPECT_TRUE(base::CreateDirectory(idb_path));
4797 EXPECT_TRUE(base::DirectoryExists(idb_path));
4799 // Uninstall the extension.
4800 base::RunLoop run_loop;
4801 ASSERT_TRUE(
4802 service()->UninstallExtension(good_crx,
4803 extensions::UNINSTALL_REASON_FOR_TESTING,
4804 run_loop.QuitClosure(),
4805 NULL));
4806 // The data deletion happens on the IO thread.
4807 run_loop.Run();
4809 // Check that the cookie is gone.
4810 cookie_monster->GetAllCookiesForURLAsync(
4811 ext_url,
4812 base::Bind(&ExtensionCookieCallback::GetAllCookiesCallback,
4813 base::Unretained(&callback)));
4814 base::RunLoop().RunUntilIdle();
4815 EXPECT_EQ(0U, callback.list_.size());
4817 // The database should have vanished as well.
4818 origins.clear();
4819 db_tracker->GetAllOriginsInfo(&origins);
4820 EXPECT_EQ(0U, origins.size());
4822 // Check that the LSO file has been removed.
4823 EXPECT_FALSE(base::PathExists(lso_file_path));
4825 // Check if the indexed db has disappeared too.
4826 EXPECT_FALSE(base::DirectoryExists(idb_path));
4829 // Verifies app state is removed upon uninstall.
4830 TEST_F(ExtensionServiceTest, ClearAppData) {
4831 InitializeEmptyExtensionService();
4832 ExtensionCookieCallback callback;
4834 int pref_count = 0;
4836 // Install app1 with unlimited storage.
4837 const Extension* extension =
4838 PackAndInstallCRX(data_dir().AppendASCII("app1"), INSTALL_NEW);
4839 ValidatePrefKeyCount(++pref_count);
4840 ASSERT_EQ(1u, registry()->enabled_extensions().size());
4841 const std::string id1 = extension->id();
4842 EXPECT_TRUE(extension->permissions_data()->HasAPIPermission(
4843 APIPermission::kUnlimitedStorage));
4844 const GURL origin1(
4845 extensions::AppLaunchInfo::GetFullLaunchURL(extension).GetOrigin());
4846 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
4847 origin1));
4848 std::string origin_id = storage::GetIdentifierFromOrigin(origin1);
4850 // Install app2 from the same origin with unlimited storage.
4851 extension = PackAndInstallCRX(data_dir().AppendASCII("app2"), INSTALL_NEW);
4852 ValidatePrefKeyCount(++pref_count);
4853 ASSERT_EQ(2u, registry()->enabled_extensions().size());
4854 const std::string id2 = extension->id();
4855 EXPECT_TRUE(extension->permissions_data()->HasAPIPermission(
4856 APIPermission::kUnlimitedStorage));
4857 EXPECT_TRUE(extension->web_extent().MatchesURL(
4858 extensions::AppLaunchInfo::GetFullLaunchURL(extension)));
4859 const GURL origin2(
4860 extensions::AppLaunchInfo::GetFullLaunchURL(extension).GetOrigin());
4861 EXPECT_EQ(origin1, origin2);
4862 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
4863 origin2));
4865 // Set a cookie for the extension.
4866 net::CookieMonster* cookie_monster = profile()
4867 ->GetRequestContext()
4868 ->GetURLRequestContext()
4869 ->cookie_store()
4870 ->GetCookieMonster();
4871 ASSERT_TRUE(cookie_monster);
4872 net::CookieOptions options;
4873 cookie_monster->SetCookieWithOptionsAsync(
4874 origin1, "dummy=value", options,
4875 base::Bind(&ExtensionCookieCallback::SetCookieCallback,
4876 base::Unretained(&callback)));
4877 base::RunLoop().RunUntilIdle();
4878 EXPECT_TRUE(callback.result_);
4880 cookie_monster->GetAllCookiesForURLAsync(
4881 origin1,
4882 base::Bind(&ExtensionCookieCallback::GetAllCookiesCallback,
4883 base::Unretained(&callback)));
4884 base::RunLoop().RunUntilIdle();
4885 EXPECT_EQ(1U, callback.list_.size());
4887 // Open a database.
4888 storage::DatabaseTracker* db_tracker =
4889 BrowserContext::GetDefaultStoragePartition(profile())
4890 ->GetDatabaseTracker();
4891 base::string16 db_name = base::UTF8ToUTF16("db");
4892 base::string16 description = base::UTF8ToUTF16("db_description");
4893 int64 size;
4894 db_tracker->DatabaseOpened(origin_id, db_name, description, 1, &size);
4895 db_tracker->DatabaseClosed(origin_id, db_name);
4896 std::vector<storage::OriginInfo> origins;
4897 db_tracker->GetAllOriginsInfo(&origins);
4898 EXPECT_EQ(1U, origins.size());
4899 EXPECT_EQ(origin_id, origins[0].GetOriginIdentifier());
4901 // Create local storage. We only simulate this by creating the backing files.
4902 // Note: This test depends on details of how the dom_storage library
4903 // stores data in the host file system.
4904 base::FilePath lso_dir_path =
4905 profile()->GetPath().AppendASCII("Local Storage");
4906 base::FilePath lso_file_path = lso_dir_path.AppendASCII(origin_id)
4907 .AddExtension(FILE_PATH_LITERAL(".localstorage"));
4908 EXPECT_TRUE(base::CreateDirectory(lso_dir_path));
4909 EXPECT_EQ(0, base::WriteFile(lso_file_path, NULL, 0));
4910 EXPECT_TRUE(base::PathExists(lso_file_path));
4912 // Create indexed db. Similarly, it is enough to only simulate this by
4913 // creating the directory on the disk.
4914 IndexedDBContext* idb_context = BrowserContext::GetDefaultStoragePartition(
4915 profile())->GetIndexedDBContext();
4916 idb_context->SetTaskRunnerForTesting(
4917 base::MessageLoop::current()->message_loop_proxy().get());
4918 base::FilePath idb_path = idb_context->GetFilePathForTesting(origin_id);
4919 EXPECT_TRUE(base::CreateDirectory(idb_path));
4920 EXPECT_TRUE(base::DirectoryExists(idb_path));
4922 // Uninstall one of them, unlimited storage should still be granted
4923 // to the origin.
4924 UninstallExtension(id1, false);
4925 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4926 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
4927 origin1));
4929 // Check that the cookie is still there.
4930 cookie_monster->GetAllCookiesForURLAsync(
4931 origin1,
4932 base::Bind(&ExtensionCookieCallback::GetAllCookiesCallback,
4933 base::Unretained(&callback)));
4934 base::RunLoop().RunUntilIdle();
4935 EXPECT_EQ(1U, callback.list_.size());
4937 // Now uninstall the other. Storage should be cleared for the apps.
4938 UninstallExtension(id2, false);
4939 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4940 EXPECT_FALSE(
4941 profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
4942 origin1));
4944 // Check that the cookie is gone.
4945 cookie_monster->GetAllCookiesForURLAsync(
4946 origin1,
4947 base::Bind(&ExtensionCookieCallback::GetAllCookiesCallback,
4948 base::Unretained(&callback)));
4949 base::RunLoop().RunUntilIdle();
4950 EXPECT_EQ(0U, callback.list_.size());
4952 // The database should have vanished as well.
4953 origins.clear();
4954 db_tracker->GetAllOriginsInfo(&origins);
4955 EXPECT_EQ(0U, origins.size());
4957 // Check that the LSO file has been removed.
4958 EXPECT_FALSE(base::PathExists(lso_file_path));
4960 // Check if the indexed db has disappeared too.
4961 EXPECT_FALSE(base::DirectoryExists(idb_path));
4964 // Tests loading single extensions (like --load-extension)
4965 // Flaky crashes. http://crbug.com/231806
4966 TEST_F(ExtensionServiceTest, DISABLED_LoadExtension) {
4967 InitializeEmptyExtensionService();
4969 base::FilePath ext1 = data_dir()
4970 .AppendASCII("good")
4971 .AppendASCII("Extensions")
4972 .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
4973 .AppendASCII("1.0.0.0");
4974 extensions::UnpackedInstaller::Create(service())->Load(ext1);
4975 base::RunLoop().RunUntilIdle();
4976 EXPECT_EQ(0u, GetErrors().size());
4977 ASSERT_EQ(1u, loaded_.size());
4978 EXPECT_EQ(Manifest::UNPACKED, loaded_[0]->location());
4979 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4981 ValidatePrefKeyCount(1);
4983 base::FilePath no_manifest =
4984 data_dir()
4985 .AppendASCII("bad")
4986 // .AppendASCII("Extensions")
4987 .AppendASCII("cccccccccccccccccccccccccccccccc")
4988 .AppendASCII("1");
4989 extensions::UnpackedInstaller::Create(service())->Load(no_manifest);
4990 base::RunLoop().RunUntilIdle();
4991 EXPECT_EQ(1u, GetErrors().size());
4992 ASSERT_EQ(1u, loaded_.size());
4993 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4995 // Test uninstall.
4996 std::string id = loaded_[0]->id();
4997 EXPECT_FALSE(unloaded_id_.length());
4998 service()->UninstallExtension(id,
4999 extensions::UNINSTALL_REASON_FOR_TESTING,
5000 base::Bind(&base::DoNothing),
5001 NULL);
5002 base::RunLoop().RunUntilIdle();
5003 EXPECT_EQ(id, unloaded_id_);
5004 ASSERT_EQ(0u, loaded_.size());
5005 EXPECT_EQ(0u, registry()->enabled_extensions().size());
5008 // Tests that we generate IDs when they are not specified in the manifest for
5009 // --load-extension.
5010 TEST_F(ExtensionServiceTest, GenerateID) {
5011 InitializeEmptyExtensionService();
5013 base::FilePath no_id_ext = data_dir().AppendASCII("no_id");
5014 extensions::UnpackedInstaller::Create(service())->Load(no_id_ext);
5015 base::RunLoop().RunUntilIdle();
5016 EXPECT_EQ(0u, GetErrors().size());
5017 ASSERT_EQ(1u, loaded_.size());
5018 ASSERT_TRUE(crx_file::id_util::IdIsValid(loaded_[0]->id()));
5019 EXPECT_EQ(loaded_[0]->location(), Manifest::UNPACKED);
5021 ValidatePrefKeyCount(1);
5023 std::string previous_id = loaded_[0]->id();
5025 // If we reload the same path, we should get the same extension ID.
5026 extensions::UnpackedInstaller::Create(service())->Load(no_id_ext);
5027 base::RunLoop().RunUntilIdle();
5028 ASSERT_EQ(1u, loaded_.size());
5029 ASSERT_EQ(previous_id, loaded_[0]->id());
5032 TEST_F(ExtensionServiceTest, UnpackedValidatesLocales) {
5033 InitializeEmptyExtensionService();
5035 base::FilePath bad_locale =
5036 data_dir().AppendASCII("unpacked").AppendASCII("bad_messages_file");
5037 extensions::UnpackedInstaller::Create(service())->Load(bad_locale);
5038 base::RunLoop().RunUntilIdle();
5039 EXPECT_EQ(1u, GetErrors().size());
5040 base::FilePath ms_messages_file = bad_locale.AppendASCII("_locales")
5041 .AppendASCII("ms")
5042 .AppendASCII("messages.json");
5043 EXPECT_THAT(base::UTF16ToUTF8(GetErrors()[0]), testing::AllOf(
5044 testing::HasSubstr(
5045 base::UTF16ToUTF8(ms_messages_file.LossyDisplayName())),
5046 testing::HasSubstr("Dictionary keys must be quoted.")));
5047 ASSERT_EQ(0u, loaded_.size());
5050 void ExtensionServiceTest::TestExternalProvider(
5051 MockExtensionProvider* provider, Manifest::Location location) {
5052 // Verify that starting with no providers loads no extensions.
5053 service()->Init();
5054 ASSERT_EQ(0u, loaded_.size());
5056 provider->set_visit_count(0);
5058 // Register a test extension externally using the mock registry provider.
5059 base::FilePath source_path = data_dir().AppendASCII("good.crx");
5061 // Add the extension.
5062 provider->UpdateOrAddExtension(good_crx, "1.0.0.0", source_path);
5064 // Reloading extensions should find our externally registered extension
5065 // and install it.
5066 content::WindowedNotificationObserver observer(
5067 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
5068 content::NotificationService::AllSources());
5069 service()->CheckForExternalUpdates();
5070 observer.Wait();
5072 ASSERT_EQ(0u, GetErrors().size());
5073 ASSERT_EQ(1u, loaded_.size());
5074 ASSERT_EQ(location, loaded_[0]->location());
5075 ASSERT_EQ("1.0.0.0", loaded_[0]->version()->GetString());
5076 ValidatePrefKeyCount(1);
5077 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
5078 ValidateIntegerPref(good_crx, "location", location);
5080 // Reload extensions without changing anything. The extension should be
5081 // loaded again.
5082 loaded_.clear();
5083 service()->ReloadExtensionsForTest();
5084 base::RunLoop().RunUntilIdle();
5085 ASSERT_EQ(0u, GetErrors().size());
5086 ASSERT_EQ(1u, loaded_.size());
5087 ValidatePrefKeyCount(1);
5088 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
5089 ValidateIntegerPref(good_crx, "location", location);
5091 // Now update the extension with a new version. We should get upgraded.
5092 source_path = source_path.DirName().AppendASCII("good2.crx");
5093 provider->UpdateOrAddExtension(good_crx, "1.0.0.1", source_path);
5095 loaded_.clear();
5096 content::WindowedNotificationObserver observer_2(
5097 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
5098 content::NotificationService::AllSources());
5099 service()->CheckForExternalUpdates();
5100 observer_2.Wait();
5101 ASSERT_EQ(0u, GetErrors().size());
5102 ASSERT_EQ(1u, loaded_.size());
5103 ASSERT_EQ("1.0.0.1", loaded_[0]->version()->GetString());
5104 ValidatePrefKeyCount(1);
5105 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
5106 ValidateIntegerPref(good_crx, "location", location);
5108 // Uninstall the extension and reload. Nothing should happen because the
5109 // preference should prevent us from reinstalling.
5110 std::string id = loaded_[0]->id();
5111 bool no_uninstall =
5112 GetManagementPolicy()->MustRemainEnabled(loaded_[0].get(), NULL);
5113 service()->UninstallExtension(id,
5114 extensions::UNINSTALL_REASON_FOR_TESTING,
5115 base::Bind(&base::DoNothing),
5116 NULL);
5117 base::RunLoop().RunUntilIdle();
5119 base::FilePath install_path = extensions_install_dir().AppendASCII(id);
5120 if (no_uninstall) {
5121 // Policy controlled extensions should not have been touched by uninstall.
5122 ASSERT_TRUE(base::PathExists(install_path));
5123 } else {
5124 // The extension should also be gone from the install directory.
5125 ASSERT_FALSE(base::PathExists(install_path));
5126 loaded_.clear();
5127 service()->CheckForExternalUpdates();
5128 base::RunLoop().RunUntilIdle();
5129 ASSERT_EQ(0u, loaded_.size());
5130 ValidatePrefKeyCount(1);
5131 ValidateIntegerPref(good_crx, "state",
5132 Extension::EXTERNAL_EXTENSION_UNINSTALLED);
5133 ValidateIntegerPref(good_crx, "location", location);
5135 // Now clear the preference and reinstall.
5136 SetPrefInteg(good_crx, "state", Extension::ENABLED);
5138 loaded_.clear();
5139 content::WindowedNotificationObserver observer(
5140 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
5141 content::NotificationService::AllSources());
5142 service()->CheckForExternalUpdates();
5143 observer.Wait();
5144 ASSERT_EQ(1u, loaded_.size());
5146 ValidatePrefKeyCount(1);
5147 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
5148 ValidateIntegerPref(good_crx, "location", location);
5150 if (GetManagementPolicy()->MustRemainEnabled(loaded_[0].get(), NULL)) {
5151 EXPECT_EQ(2, provider->visit_count());
5152 } else {
5153 // Now test an externally triggered uninstall (deleting the registry key or
5154 // the pref entry).
5155 provider->RemoveExtension(good_crx);
5157 loaded_.clear();
5158 service()->OnExternalProviderReady(provider);
5159 base::RunLoop().RunUntilIdle();
5160 ASSERT_EQ(0u, loaded_.size());
5161 ValidatePrefKeyCount(0);
5163 // The extension should also be gone from the install directory.
5164 ASSERT_FALSE(base::PathExists(install_path));
5166 // Now test the case where user uninstalls and then the extension is removed
5167 // from the external provider.
5168 content::WindowedNotificationObserver observer(
5169 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
5170 content::NotificationService::AllSources());
5171 provider->UpdateOrAddExtension(good_crx, "1.0.0.1", source_path);
5172 service()->CheckForExternalUpdates();
5173 observer.Wait();
5175 ASSERT_EQ(1u, loaded_.size());
5176 ASSERT_EQ(0u, GetErrors().size());
5178 // User uninstalls.
5179 loaded_.clear();
5180 service()->UninstallExtension(id,
5181 extensions::UNINSTALL_REASON_FOR_TESTING,
5182 base::Bind(&base::DoNothing),
5183 NULL);
5184 base::RunLoop().RunUntilIdle();
5185 ASSERT_EQ(0u, loaded_.size());
5187 // Then remove the extension from the extension provider.
5188 provider->RemoveExtension(good_crx);
5190 // Should still be at 0.
5191 loaded_.clear();
5192 extensions::InstalledLoader(service()).LoadAllExtensions();
5193 base::RunLoop().RunUntilIdle();
5194 ASSERT_EQ(0u, loaded_.size());
5195 ValidatePrefKeyCount(1);
5197 EXPECT_EQ(5, provider->visit_count());
5201 // Tests the external installation feature
5202 #if defined(OS_WIN)
5203 TEST_F(ExtensionServiceTest, ExternalInstallRegistry) {
5204 // This should all work, even when normal extension installation is disabled.
5205 InitializeEmptyExtensionService();
5206 service()->set_extensions_enabled(false);
5208 // Now add providers. Extension system takes ownership of the objects.
5209 MockExtensionProvider* reg_provider =
5210 new MockExtensionProvider(service(), Manifest::EXTERNAL_REGISTRY);
5211 AddMockExternalProvider(reg_provider);
5212 TestExternalProvider(reg_provider, Manifest::EXTERNAL_REGISTRY);
5214 #endif
5216 TEST_F(ExtensionServiceTest, ExternalInstallPref) {
5217 InitializeEmptyExtensionService();
5219 // Now add providers. Extension system takes ownership of the objects.
5220 MockExtensionProvider* pref_provider =
5221 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF);
5223 AddMockExternalProvider(pref_provider);
5224 TestExternalProvider(pref_provider, Manifest::EXTERNAL_PREF);
5227 TEST_F(ExtensionServiceTest, ExternalInstallPrefUpdateUrl) {
5228 // This should all work, even when normal extension installation is disabled.
5229 InitializeEmptyExtensionService();
5230 service()->set_extensions_enabled(false);
5232 // TODO(skerner): The mock provider is not a good model of a provider
5233 // that works with update URLs, because it adds file and version info.
5234 // Extend the mock to work with update URLs. This test checks the
5235 // behavior that is common to all external extension visitors. The
5236 // browser test ExtensionManagementTest.ExternalUrlUpdate tests that
5237 // what the visitor does results in an extension being downloaded and
5238 // installed.
5239 MockExtensionProvider* pref_provider =
5240 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF_DOWNLOAD);
5241 AddMockExternalProvider(pref_provider);
5242 TestExternalProvider(pref_provider, Manifest::EXTERNAL_PREF_DOWNLOAD);
5245 TEST_F(ExtensionServiceTest, ExternalInstallPolicyUpdateUrl) {
5246 // This should all work, even when normal extension installation is disabled.
5247 InitializeEmptyExtensionService();
5248 service()->set_extensions_enabled(false);
5250 // TODO(skerner): The mock provider is not a good model of a provider
5251 // that works with update URLs, because it adds file and version info.
5252 // Extend the mock to work with update URLs. This test checks the
5253 // behavior that is common to all external extension visitors. The
5254 // browser test ExtensionManagementTest.ExternalUrlUpdate tests that
5255 // what the visitor does results in an extension being downloaded and
5256 // installed.
5257 MockExtensionProvider* pref_provider =
5258 new MockExtensionProvider(service(), Manifest::EXTERNAL_POLICY_DOWNLOAD);
5259 AddMockExternalProvider(pref_provider);
5260 TestExternalProvider(pref_provider, Manifest::EXTERNAL_POLICY_DOWNLOAD);
5263 // Tests that external extensions get uninstalled when the external extension
5264 // providers can't account for them.
5265 TEST_F(ExtensionServiceTest, ExternalUninstall) {
5266 // Start the extensions service with one external extension already installed.
5267 base::FilePath source_install_dir =
5268 data_dir().AppendASCII("good").AppendASCII("Extensions");
5269 base::FilePath pref_path = source_install_dir
5270 .DirName()
5271 .AppendASCII("PreferencesExternal");
5273 // This initializes the extensions service with no ExternalProviders.
5274 InitializeInstalledExtensionService(pref_path, source_install_dir);
5275 service()->set_extensions_enabled(false);
5277 service()->Init();
5279 ASSERT_EQ(0u, GetErrors().size());
5280 ASSERT_EQ(0u, loaded_.size());
5282 // Verify that it's not the disabled extensions flag causing it not to load.
5283 service()->set_extensions_enabled(true);
5284 service()->ReloadExtensionsForTest();
5285 base::RunLoop().RunUntilIdle();
5287 ASSERT_EQ(0u, GetErrors().size());
5288 ASSERT_EQ(0u, loaded_.size());
5291 // Test that running multiple update checks simultaneously does not
5292 // keep the update from succeeding.
5293 TEST_F(ExtensionServiceTest, MultipleExternalUpdateCheck) {
5294 InitializeEmptyExtensionService();
5296 MockExtensionProvider* provider =
5297 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF);
5298 AddMockExternalProvider(provider);
5300 // Verify that starting with no providers loads no extensions.
5301 service()->Init();
5302 ASSERT_EQ(0u, loaded_.size());
5304 // Start two checks for updates.
5305 provider->set_visit_count(0);
5306 service()->CheckForExternalUpdates();
5307 service()->CheckForExternalUpdates();
5308 base::RunLoop().RunUntilIdle();
5310 // Two calls should cause two checks for external extensions.
5311 EXPECT_EQ(2, provider->visit_count());
5312 EXPECT_EQ(0u, GetErrors().size());
5313 EXPECT_EQ(0u, loaded_.size());
5315 // Register a test extension externally using the mock registry provider.
5316 base::FilePath source_path = data_dir().AppendASCII("good.crx");
5317 provider->UpdateOrAddExtension(good_crx, "1.0.0.0", source_path);
5319 // Two checks for external updates should find the extension, and install it
5320 // once.
5321 content::WindowedNotificationObserver observer(
5322 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
5323 content::NotificationService::AllSources());
5324 provider->set_visit_count(0);
5325 service()->CheckForExternalUpdates();
5326 service()->CheckForExternalUpdates();
5327 observer.Wait();
5328 EXPECT_EQ(2, provider->visit_count());
5329 ASSERT_EQ(0u, GetErrors().size());
5330 ASSERT_EQ(1u, loaded_.size());
5331 ASSERT_EQ(Manifest::EXTERNAL_PREF, loaded_[0]->location());
5332 ASSERT_EQ("1.0.0.0", loaded_[0]->version()->GetString());
5333 ValidatePrefKeyCount(1);
5334 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
5335 ValidateIntegerPref(good_crx, "location", Manifest::EXTERNAL_PREF);
5337 provider->RemoveExtension(good_crx);
5338 provider->set_visit_count(0);
5339 service()->CheckForExternalUpdates();
5340 service()->CheckForExternalUpdates();
5341 base::RunLoop().RunUntilIdle();
5343 // Two calls should cause two checks for external extensions.
5344 // Because the external source no longer includes good_crx,
5345 // good_crx will be uninstalled. So, expect that no extensions
5346 // are loaded.
5347 EXPECT_EQ(2, provider->visit_count());
5348 EXPECT_EQ(0u, GetErrors().size());
5349 EXPECT_EQ(0u, loaded_.size());
5352 TEST_F(ExtensionServiceTest, ExternalPrefProvider) {
5353 InitializeEmptyExtensionService();
5355 // Test some valid extension records.
5356 // Set a base path to avoid erroring out on relative paths.
5357 // Paths starting with // are absolute on every platform we support.
5358 base::FilePath base_path(FILE_PATH_LITERAL("//base/path"));
5359 ASSERT_TRUE(base_path.IsAbsolute());
5360 MockProviderVisitor visitor(base_path);
5361 std::string json_data =
5363 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5364 " \"external_crx\": \"RandomExtension.crx\","
5365 " \"external_version\": \"1.0\""
5366 " },"
5367 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\": {"
5368 " \"external_crx\": \"RandomExtension2.crx\","
5369 " \"external_version\": \"2.0\""
5370 " },"
5371 " \"cccccccccccccccccccccccccccccccc\": {"
5372 " \"external_update_url\": \"http:\\\\foo.com/update\","
5373 " \"install_parameter\": \"id\""
5374 " }"
5375 "}";
5376 EXPECT_EQ(3, visitor.Visit(json_data));
5378 // Simulate an external_extensions.json file that contains seven invalid
5379 // records:
5380 // - One that is missing the 'external_crx' key.
5381 // - One that is missing the 'external_version' key.
5382 // - One that is specifying .. in the path.
5383 // - One that specifies both a file and update URL.
5384 // - One that specifies no file or update URL.
5385 // - One that has an update URL that is not well formed.
5386 // - One that contains a malformed version.
5387 // - One that has an invalid id.
5388 // - One that has a non-dictionary value.
5389 // - One that has an integer 'external_version' instead of a string.
5390 // The final extension is valid, and we check that it is read to make sure
5391 // failures don't stop valid records from being read.
5392 json_data =
5394 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5395 " \"external_version\": \"1.0\""
5396 " },"
5397 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\": {"
5398 " \"external_crx\": \"RandomExtension.crx\""
5399 " },"
5400 " \"cccccccccccccccccccccccccccccccc\": {"
5401 " \"external_crx\": \"..\\\\foo\\\\RandomExtension2.crx\","
5402 " \"external_version\": \"2.0\""
5403 " },"
5404 " \"dddddddddddddddddddddddddddddddd\": {"
5405 " \"external_crx\": \"RandomExtension2.crx\","
5406 " \"external_version\": \"2.0\","
5407 " \"external_update_url\": \"http:\\\\foo.com/update\""
5408 " },"
5409 " \"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\": {"
5410 " },"
5411 " \"ffffffffffffffffffffffffffffffff\": {"
5412 " \"external_update_url\": \"This string is not a valid URL\""
5413 " },"
5414 " \"gggggggggggggggggggggggggggggggg\": {"
5415 " \"external_crx\": \"RandomExtension3.crx\","
5416 " \"external_version\": \"This is not a valid version!\""
5417 " },"
5418 " \"This is not a valid id!\": {},"
5419 " \"hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh\": true,"
5420 " \"iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii\": {"
5421 " \"external_crx\": \"RandomExtension4.crx\","
5422 " \"external_version\": 1.0"
5423 " },"
5424 " \"pppppppppppppppppppppppppppppppp\": {"
5425 " \"external_crx\": \"RandomValidExtension.crx\","
5426 " \"external_version\": \"1.0\""
5427 " }"
5428 "}";
5429 EXPECT_EQ(1, visitor.Visit(json_data));
5431 // Check that if a base path is not provided, use of a relative
5432 // path fails.
5433 base::FilePath empty;
5434 MockProviderVisitor visitor_no_relative_paths(empty);
5436 // Use absolute paths. Expect success.
5437 json_data =
5439 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5440 " \"external_crx\": \"//RandomExtension1.crx\","
5441 " \"external_version\": \"3.0\""
5442 " },"
5443 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\": {"
5444 " \"external_crx\": \"//path/to/RandomExtension2.crx\","
5445 " \"external_version\": \"3.0\""
5446 " }"
5447 "}";
5448 EXPECT_EQ(2, visitor_no_relative_paths.Visit(json_data));
5450 // Use a relative path. Expect that it will error out.
5451 json_data =
5453 " \"cccccccccccccccccccccccccccccccc\": {"
5454 " \"external_crx\": \"RandomExtension2.crx\","
5455 " \"external_version\": \"3.0\""
5456 " }"
5457 "}";
5458 EXPECT_EQ(0, visitor_no_relative_paths.Visit(json_data));
5460 // Test supported_locales.
5461 json_data =
5463 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5464 " \"external_crx\": \"RandomExtension.crx\","
5465 " \"external_version\": \"1.0\","
5466 " \"supported_locales\": [ \"en\" ]"
5467 " },"
5468 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\": {"
5469 " \"external_crx\": \"RandomExtension2.crx\","
5470 " \"external_version\": \"2.0\","
5471 " \"supported_locales\": [ \"en-GB\" ]"
5472 " },"
5473 " \"cccccccccccccccccccccccccccccccc\": {"
5474 " \"external_crx\": \"RandomExtension2.crx\","
5475 " \"external_version\": \"3.0\","
5476 " \"supported_locales\": [ \"en_US\", \"fr\" ]"
5477 " }"
5478 "}";
5480 ScopedBrowserLocale guard("en-US");
5481 EXPECT_EQ(2, visitor.Visit(json_data));
5484 // Test keep_if_present.
5485 json_data =
5487 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5488 " \"external_crx\": \"RandomExtension.crx\","
5489 " \"external_version\": \"1.0\","
5490 " \"keep_if_present\": true"
5491 " }"
5492 "}";
5494 EXPECT_EQ(0, visitor.Visit(json_data));
5497 // Test is_bookmark_app.
5498 MockProviderVisitor from_bookmark_visitor(
5499 base_path, Extension::FROM_BOOKMARK);
5500 json_data =
5502 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5503 " \"external_crx\": \"RandomExtension.crx\","
5504 " \"external_version\": \"1.0\","
5505 " \"is_bookmark_app\": true"
5506 " }"
5507 "}";
5508 EXPECT_EQ(1, from_bookmark_visitor.Visit(json_data));
5510 // Test is_from_webstore.
5511 MockProviderVisitor from_webstore_visitor(
5512 base_path, Extension::FROM_WEBSTORE);
5513 json_data =
5515 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5516 " \"external_crx\": \"RandomExtension.crx\","
5517 " \"external_version\": \"1.0\","
5518 " \"is_from_webstore\": true"
5519 " }"
5520 "}";
5521 EXPECT_EQ(1, from_webstore_visitor.Visit(json_data));
5523 // Test was_installed_by_eom.
5524 MockProviderVisitor was_installed_by_eom_visitor(
5525 base_path, Extension::WAS_INSTALLED_BY_OEM);
5526 json_data =
5528 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5529 " \"external_crx\": \"RandomExtension.crx\","
5530 " \"external_version\": \"1.0\","
5531 " \"was_installed_by_oem\": true"
5532 " }"
5533 "}";
5534 EXPECT_EQ(1, was_installed_by_eom_visitor.Visit(json_data));
5537 // Test loading good extensions from the profile directory.
5538 TEST_F(ExtensionServiceTest, LoadAndRelocalizeExtensions) {
5539 // Ensure we're testing in "en" and leave global state untouched.
5540 extension_l10n_util::ScopedLocaleForTest testLocale("en");
5542 // Initialize the test dir with a good Preferences/extensions.
5543 base::FilePath source_install_dir = data_dir().AppendASCII("l10n");
5544 base::FilePath pref_path =
5545 source_install_dir.Append(chrome::kPreferencesFilename);
5546 InitializeInstalledExtensionService(pref_path, source_install_dir);
5548 service()->Init();
5550 ASSERT_EQ(3u, loaded_.size());
5552 // This was equal to "sr" on load.
5553 ValidateStringPref(loaded_[0]->id(), keys::kCurrentLocale, "en");
5555 // These are untouched by re-localization.
5556 ValidateStringPref(loaded_[1]->id(), keys::kCurrentLocale, "en");
5557 EXPECT_FALSE(IsPrefExist(loaded_[1]->id(), keys::kCurrentLocale));
5559 // This one starts with Serbian name, and gets re-localized into English.
5560 EXPECT_EQ("My name is simple.", loaded_[0]->name());
5562 // These are untouched by re-localization.
5563 EXPECT_EQ("My name is simple.", loaded_[1]->name());
5564 EXPECT_EQ("no l10n", loaded_[2]->name());
5567 class ExtensionsReadyRecorder : public content::NotificationObserver {
5568 public:
5569 ExtensionsReadyRecorder() : ready_(false) {
5570 registrar_.Add(this,
5571 extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED,
5572 content::NotificationService::AllSources());
5575 void set_ready(bool value) { ready_ = value; }
5576 bool ready() { return ready_; }
5578 private:
5579 void Observe(int type,
5580 const content::NotificationSource& source,
5581 const content::NotificationDetails& details) override {
5582 switch (type) {
5583 case extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED:
5584 ready_ = true;
5585 break;
5586 default:
5587 NOTREACHED();
5591 content::NotificationRegistrar registrar_;
5592 bool ready_;
5595 // Test that we get enabled/disabled correctly for all the pref/command-line
5596 // combinations. We don't want to derive from the ExtensionServiceTest class
5597 // for this test, so we use ExtensionServiceTestSimple.
5599 // Also tests that we always fire EXTENSIONS_READY, no matter whether we are
5600 // enabled or not.
5601 TEST(ExtensionServiceTestSimple, Enabledness) {
5602 // Make sure the PluginService singleton is destroyed at the end of the test.
5603 base::ShadowingAtExitManager at_exit_manager;
5604 #if defined(ENABLE_PLUGINS)
5605 content::PluginService::GetInstance()->Init();
5606 content::PluginService::GetInstance()->DisablePluginsDiscoveryForTesting();
5607 #endif
5609 ExtensionErrorReporter::Init(false); // no noisy errors
5610 ExtensionsReadyRecorder recorder;
5611 scoped_ptr<TestingProfile> profile(new TestingProfile());
5612 content::TestBrowserThreadBundle thread_bundle_;
5613 #if defined OS_CHROMEOS
5614 chromeos::ScopedTestDeviceSettingsService device_settings_service;
5615 chromeos::ScopedTestCrosSettings cros_settings;
5616 scoped_ptr<chromeos::ScopedTestUserManager> user_manager(
5617 new chromeos::ScopedTestUserManager);
5618 #endif
5619 scoped_ptr<base::CommandLine> command_line;
5620 base::FilePath install_dir = profile->GetPath()
5621 .AppendASCII(extensions::kInstallDirectoryName);
5623 // By default, we are enabled.
5624 command_line.reset(new base::CommandLine(base::CommandLine::NO_PROGRAM));
5625 ExtensionService* service = static_cast<extensions::TestExtensionSystem*>(
5626 ExtensionSystem::Get(profile.get()))->
5627 CreateExtensionService(
5628 command_line.get(),
5629 install_dir,
5630 false);
5631 EXPECT_TRUE(service->extensions_enabled());
5632 service->Init();
5633 base::RunLoop().RunUntilIdle();
5634 EXPECT_TRUE(recorder.ready());
5635 #if defined OS_CHROMEOS
5636 user_manager.reset();
5637 #endif
5639 // If either the command line or pref is set, we are disabled.
5640 recorder.set_ready(false);
5641 profile.reset(new TestingProfile());
5642 command_line->AppendSwitch(switches::kDisableExtensions);
5643 service = static_cast<extensions::TestExtensionSystem*>(
5644 ExtensionSystem::Get(profile.get()))->
5645 CreateExtensionService(
5646 command_line.get(),
5647 install_dir,
5648 false);
5649 EXPECT_FALSE(service->extensions_enabled());
5650 service->Init();
5651 base::RunLoop().RunUntilIdle();
5652 EXPECT_TRUE(recorder.ready());
5654 recorder.set_ready(false);
5655 profile.reset(new TestingProfile());
5656 profile->GetPrefs()->SetBoolean(prefs::kDisableExtensions, true);
5657 service = static_cast<extensions::TestExtensionSystem*>(
5658 ExtensionSystem::Get(profile.get()))->
5659 CreateExtensionService(
5660 command_line.get(),
5661 install_dir,
5662 false);
5663 EXPECT_FALSE(service->extensions_enabled());
5664 service->Init();
5665 base::RunLoop().RunUntilIdle();
5666 EXPECT_TRUE(recorder.ready());
5668 recorder.set_ready(false);
5669 profile.reset(new TestingProfile());
5670 profile->GetPrefs()->SetBoolean(prefs::kDisableExtensions, true);
5671 command_line.reset(new base::CommandLine(base::CommandLine::NO_PROGRAM));
5672 service = static_cast<extensions::TestExtensionSystem*>(
5673 ExtensionSystem::Get(profile.get()))->
5674 CreateExtensionService(
5675 command_line.get(),
5676 install_dir,
5677 false);
5678 EXPECT_FALSE(service->extensions_enabled());
5679 service->Init();
5680 base::RunLoop().RunUntilIdle();
5681 EXPECT_TRUE(recorder.ready());
5683 // Explicitly delete all the resources used in this test.
5684 profile.reset();
5685 service = NULL;
5686 // Execute any pending deletion tasks.
5687 base::RunLoop().RunUntilIdle();
5690 // Test loading extensions that require limited and unlimited storage quotas.
5691 TEST_F(ExtensionServiceTest, StorageQuota) {
5692 InitializeEmptyExtensionService();
5694 base::FilePath extensions_path = data_dir().AppendASCII("storage_quota");
5696 base::FilePath limited_quota_ext =
5697 extensions_path.AppendASCII("limited_quota")
5698 .AppendASCII("1.0");
5700 // The old permission name for unlimited quota was "unlimited_storage", but
5701 // we changed it to "unlimitedStorage". This tests both versions.
5702 base::FilePath unlimited_quota_ext =
5703 extensions_path.AppendASCII("unlimited_quota")
5704 .AppendASCII("1.0");
5705 base::FilePath unlimited_quota_ext2 =
5706 extensions_path.AppendASCII("unlimited_quota")
5707 .AppendASCII("2.0");
5708 extensions::UnpackedInstaller::Create(service())->Load(limited_quota_ext);
5709 extensions::UnpackedInstaller::Create(service())->Load(unlimited_quota_ext);
5710 extensions::UnpackedInstaller::Create(service())->Load(unlimited_quota_ext2);
5711 base::RunLoop().RunUntilIdle();
5713 ASSERT_EQ(3u, loaded_.size());
5714 EXPECT_TRUE(profile());
5715 EXPECT_FALSE(profile()->IsOffTheRecord());
5716 EXPECT_FALSE(
5717 profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
5718 loaded_[0]->url()));
5719 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
5720 loaded_[1]->url()));
5721 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
5722 loaded_[2]->url()));
5725 // Tests ComponentLoader::Add().
5726 TEST_F(ExtensionServiceTest, ComponentExtensions) {
5727 InitializeEmptyExtensionService();
5729 // Component extensions should work even when extensions are disabled.
5730 service()->set_extensions_enabled(false);
5732 base::FilePath path = data_dir()
5733 .AppendASCII("good")
5734 .AppendASCII("Extensions")
5735 .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
5736 .AppendASCII("1.0.0.0");
5738 std::string manifest;
5739 ASSERT_TRUE(base::ReadFileToString(
5740 path.Append(extensions::kManifestFilename), &manifest));
5742 service()->component_loader()->Add(manifest, path);
5743 service()->Init();
5745 // Note that we do not pump messages -- the extension should be loaded
5746 // immediately.
5748 EXPECT_EQ(0u, GetErrors().size());
5749 ASSERT_EQ(1u, loaded_.size());
5750 EXPECT_EQ(Manifest::COMPONENT, loaded_[0]->location());
5751 EXPECT_EQ(1u, registry()->enabled_extensions().size());
5753 // Component extensions get a prefs entry on first install.
5754 ValidatePrefKeyCount(1);
5756 // Reload all extensions, and make sure it comes back.
5757 std::string extension_id = (*registry()->enabled_extensions().begin())->id();
5758 loaded_.clear();
5759 service()->ReloadExtensionsForTest();
5760 ASSERT_EQ(1u, registry()->enabled_extensions().size());
5761 EXPECT_EQ(extension_id, (*registry()->enabled_extensions().begin())->id());
5764 TEST_F(ExtensionServiceTest, DeferredSyncStartupPreInstalledComponent) {
5765 InitializeEmptyExtensionService();
5766 InitializeExtensionSyncService();
5768 bool flare_was_called = false;
5769 syncer::ModelType triggered_type(syncer::UNSPECIFIED);
5770 base::WeakPtrFactory<ExtensionServiceTest> factory(this);
5771 extension_sync_service()->SetSyncStartFlare(
5772 base::Bind(&ExtensionServiceTest::MockSyncStartFlare,
5773 factory.GetWeakPtr(),
5774 &flare_was_called, // Safe due to WeakPtrFactory scope.
5775 &triggered_type)); // Safe due to WeakPtrFactory scope.
5777 // Install a component extension.
5778 std::string manifest;
5779 ASSERT_TRUE(base::ReadFileToString(
5780 good0_path().Append(extensions::kManifestFilename), &manifest));
5781 service()->component_loader()->Add(manifest, good0_path());
5782 ASSERT_FALSE(service()->is_ready());
5783 service()->Init();
5784 ASSERT_TRUE(service()->is_ready());
5786 // Extensions added before service is_ready() don't trigger sync startup.
5787 EXPECT_FALSE(flare_was_called);
5788 ASSERT_EQ(syncer::UNSPECIFIED, triggered_type);
5791 TEST_F(ExtensionServiceTest, DeferredSyncStartupPreInstalledNormal) {
5792 InitializeGoodInstalledExtensionService();
5793 InitializeExtensionSyncService();
5795 bool flare_was_called = false;
5796 syncer::ModelType triggered_type(syncer::UNSPECIFIED);
5797 base::WeakPtrFactory<ExtensionServiceTest> factory(this);
5798 extension_sync_service()->SetSyncStartFlare(
5799 base::Bind(&ExtensionServiceTest::MockSyncStartFlare,
5800 factory.GetWeakPtr(),
5801 &flare_was_called, // Safe due to WeakPtrFactory scope.
5802 &triggered_type)); // Safe due to WeakPtrFactory scope.
5804 ASSERT_FALSE(service()->is_ready());
5805 service()->Init();
5806 ASSERT_EQ(3u, loaded_.size());
5807 ASSERT_TRUE(service()->is_ready());
5809 // Extensions added before service is_ready() don't trigger sync startup.
5810 EXPECT_FALSE(flare_was_called);
5811 ASSERT_EQ(syncer::UNSPECIFIED, triggered_type);
5814 TEST_F(ExtensionServiceTest, DeferredSyncStartupOnInstall) {
5815 InitializeEmptyExtensionService();
5816 InitializeExtensionSyncService();
5817 service()->Init();
5818 ASSERT_TRUE(service()->is_ready());
5820 bool flare_was_called = false;
5821 syncer::ModelType triggered_type(syncer::UNSPECIFIED);
5822 base::WeakPtrFactory<ExtensionServiceTest> factory(this);
5823 extension_sync_service()->SetSyncStartFlare(
5824 base::Bind(&ExtensionServiceTest::MockSyncStartFlare,
5825 factory.GetWeakPtr(),
5826 &flare_was_called, // Safe due to WeakPtrFactory scope.
5827 &triggered_type)); // Safe due to WeakPtrFactory scope.
5829 base::FilePath path = data_dir().AppendASCII("good.crx");
5830 InstallCRX(path, INSTALL_NEW);
5832 EXPECT_TRUE(flare_was_called);
5833 EXPECT_EQ(syncer::EXTENSIONS, triggered_type);
5835 // Reset.
5836 flare_was_called = false;
5837 triggered_type = syncer::UNSPECIFIED;
5839 // Once sync starts, flare should no longer be invoked.
5840 extension_sync_service()->MergeDataAndStartSyncing(
5841 syncer::EXTENSIONS,
5842 syncer::SyncDataList(),
5843 scoped_ptr<syncer::SyncChangeProcessor>(
5844 new syncer::FakeSyncChangeProcessor),
5845 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5846 path = data_dir().AppendASCII("page_action.crx");
5847 InstallCRX(path, INSTALL_NEW);
5848 EXPECT_FALSE(flare_was_called);
5849 ASSERT_EQ(syncer::UNSPECIFIED, triggered_type);
5852 TEST_F(ExtensionServiceTest, DisableExtensionFromSync) {
5853 // Start the extensions service with one external extension already installed.
5854 base::FilePath source_install_dir =
5855 data_dir().AppendASCII("good").AppendASCII("Extensions");
5856 base::FilePath pref_path =
5857 source_install_dir.DirName().Append(chrome::kPreferencesFilename);
5859 InitializeInstalledExtensionService(pref_path, source_install_dir);
5860 InitializeExtensionSyncService();
5862 // The user has enabled sync.
5863 ProfileSyncService* sync_service =
5864 ProfileSyncServiceFactory::GetForProfile(profile());
5865 sync_service->SetSyncSetupCompleted();
5867 service()->Init();
5868 ASSERT_TRUE(service()->is_ready());
5870 ASSERT_EQ(3u, loaded_.size());
5872 // We start enabled.
5873 const Extension* extension = service()->GetExtensionById(good0, true);
5874 ASSERT_TRUE(extension);
5875 ASSERT_TRUE(service()->IsExtensionEnabled(good0));
5876 ExtensionSyncData disable_good_crx(*extension, false, false, false,
5877 ExtensionSyncData::BOOLEAN_UNSET);
5879 // Then sync data arrives telling us to disable |good0|.
5880 syncer::SyncDataList sync_data;
5881 sync_data.push_back(disable_good_crx.GetSyncData());
5882 extension_sync_service()->MergeDataAndStartSyncing(
5883 syncer::EXTENSIONS,
5884 sync_data,
5885 scoped_ptr<syncer::SyncChangeProcessor>(
5886 new syncer::FakeSyncChangeProcessor),
5887 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5888 ASSERT_FALSE(service()->IsExtensionEnabled(good0));
5891 TEST_F(ExtensionServiceTest, DontDisableExtensionWithPendingEnableFromSync) {
5892 // Start the extensions service with one external extension already installed.
5893 base::FilePath source_install_dir =
5894 data_dir().AppendASCII("good").AppendASCII("Extensions");
5895 base::FilePath pref_path =
5896 source_install_dir.DirName().Append(chrome::kPreferencesFilename);
5898 InitializeInstalledExtensionService(pref_path, source_install_dir);
5899 InitializeExtensionSyncService();
5901 // The user has enabled sync.
5902 ProfileSyncService* sync_service =
5903 ProfileSyncServiceFactory::GetForProfile(profile());
5904 sync_service->SetSyncSetupCompleted();
5906 service()->Init();
5907 ASSERT_TRUE(service()->is_ready());
5908 ASSERT_EQ(3u, loaded_.size());
5910 const Extension* extension = service()->GetExtensionById(good0, true);
5911 ASSERT_TRUE(service()->IsExtensionEnabled(good0));
5913 // Disable extension before first sync data arrives.
5914 service()->DisableExtension(good0, Extension::DISABLE_USER_ACTION);
5915 ASSERT_FALSE(service()->IsExtensionEnabled(good0));
5917 // Enable extension - this is now the most recent state.
5918 service()->EnableExtension(good0);
5919 ASSERT_TRUE(service()->IsExtensionEnabled(good0));
5921 // Now sync data comes in that says to disable good0. This should be
5922 // ignored.
5923 ExtensionSyncData disable_good_crx(*extension, false, false, false,
5924 ExtensionSyncData::BOOLEAN_FALSE);
5925 syncer::SyncDataList sync_data;
5926 sync_data.push_back(disable_good_crx.GetSyncData());
5927 extension_sync_service()->MergeDataAndStartSyncing(
5928 syncer::EXTENSIONS,
5929 sync_data,
5930 scoped_ptr<syncer::SyncChangeProcessor>(
5931 new syncer::FakeSyncChangeProcessor),
5932 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5934 // The extension was enabled locally before the sync data arrived, so it
5935 // should still be enabled now.
5936 ASSERT_TRUE(service()->IsExtensionEnabled(good0));
5939 TEST_F(ExtensionServiceTest, GetSyncData) {
5940 InitializeEmptyExtensionService();
5941 InitializeExtensionSyncService();
5942 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
5943 const Extension* extension = service()->GetInstalledExtension(good_crx);
5944 ASSERT_TRUE(extension);
5946 extension_sync_service()->MergeDataAndStartSyncing(
5947 syncer::EXTENSIONS,
5948 syncer::SyncDataList(),
5949 scoped_ptr<syncer::SyncChangeProcessor>(
5950 new syncer::FakeSyncChangeProcessor),
5951 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5953 syncer::SyncDataList list =
5954 extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS);
5955 ASSERT_EQ(list.size(), 1U);
5956 scoped_ptr<ExtensionSyncData> data =
5957 ExtensionSyncData::CreateFromSyncData(list[0]);
5958 ASSERT_TRUE(data.get());
5959 EXPECT_EQ(extension->id(), data->id());
5960 EXPECT_FALSE(data->uninstalled());
5961 EXPECT_EQ(service()->IsExtensionEnabled(good_crx), data->enabled());
5962 EXPECT_EQ(extensions::util::IsIncognitoEnabled(good_crx, profile()),
5963 data->incognito_enabled());
5964 EXPECT_EQ(ExtensionSyncData::BOOLEAN_UNSET, data->all_urls_enabled());
5965 EXPECT_TRUE(data->version().Equals(*extension->version()));
5966 EXPECT_EQ(extensions::ManifestURL::GetUpdateURL(extension),
5967 data->update_url());
5968 EXPECT_EQ(extension->name(), data->name());
5971 TEST_F(ExtensionServiceTest, GetSyncDataTerminated) {
5972 InitializeEmptyExtensionService();
5973 InitializeExtensionSyncService();
5974 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
5975 TerminateExtension(good_crx);
5976 const Extension* extension = service()->GetInstalledExtension(good_crx);
5977 ASSERT_TRUE(extension);
5979 syncer::FakeSyncChangeProcessor processor;
5980 extension_sync_service()->MergeDataAndStartSyncing(
5981 syncer::EXTENSIONS,
5982 syncer::SyncDataList(),
5983 scoped_ptr<syncer::SyncChangeProcessor>(
5984 new syncer::FakeSyncChangeProcessor),
5985 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5987 syncer::SyncDataList list =
5988 extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS);
5989 ASSERT_EQ(list.size(), 1U);
5990 scoped_ptr<ExtensionSyncData> data =
5991 ExtensionSyncData::CreateFromSyncData(list[0]);
5992 ASSERT_TRUE(data.get());
5993 EXPECT_EQ(extension->id(), data->id());
5994 EXPECT_FALSE(data->uninstalled());
5995 EXPECT_EQ(service()->IsExtensionEnabled(good_crx), data->enabled());
5996 EXPECT_EQ(extensions::util::IsIncognitoEnabled(good_crx, profile()),
5997 data->incognito_enabled());
5998 EXPECT_EQ(ExtensionSyncData::BOOLEAN_UNSET, data->all_urls_enabled());
5999 EXPECT_TRUE(data->version().Equals(*extension->version()));
6000 EXPECT_EQ(extensions::ManifestURL::GetUpdateURL(extension),
6001 data->update_url());
6002 EXPECT_EQ(extension->name(), data->name());
6005 TEST_F(ExtensionServiceTest, GetSyncDataFilter) {
6006 InitializeEmptyExtensionService();
6007 InitializeExtensionSyncService();
6008 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
6009 const Extension* extension = service()->GetInstalledExtension(good_crx);
6010 ASSERT_TRUE(extension);
6012 syncer::FakeSyncChangeProcessor processor;
6013 extension_sync_service()->MergeDataAndStartSyncing(
6014 syncer::APPS,
6015 syncer::SyncDataList(),
6016 scoped_ptr<syncer::SyncChangeProcessor>(
6017 new syncer::FakeSyncChangeProcessor),
6018 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6020 syncer::SyncDataList list =
6021 extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS);
6022 ASSERT_EQ(list.size(), 0U);
6025 TEST_F(ExtensionServiceTest, GetSyncExtensionDataUserSettings) {
6026 InitializeEmptyExtensionService();
6027 InitializeExtensionSyncService();
6028 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
6029 const Extension* extension = service()->GetInstalledExtension(good_crx);
6030 ASSERT_TRUE(extension);
6032 syncer::FakeSyncChangeProcessor processor;
6033 extension_sync_service()->MergeDataAndStartSyncing(
6034 syncer::EXTENSIONS,
6035 syncer::SyncDataList(),
6036 scoped_ptr<syncer::SyncChangeProcessor>(
6037 new syncer::FakeSyncChangeProcessor),
6038 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6041 syncer::SyncDataList list =
6042 extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS);
6043 ASSERT_EQ(list.size(), 1U);
6044 scoped_ptr<ExtensionSyncData> data =
6045 ExtensionSyncData::CreateFromSyncData(list[0]);
6046 ASSERT_TRUE(data.get());
6047 EXPECT_TRUE(data->enabled());
6048 EXPECT_FALSE(data->incognito_enabled());
6049 EXPECT_EQ(ExtensionSyncData::BOOLEAN_UNSET, data->all_urls_enabled());
6052 service()->DisableExtension(good_crx, Extension::DISABLE_USER_ACTION);
6054 syncer::SyncDataList list =
6055 extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS);
6056 ASSERT_EQ(list.size(), 1U);
6057 scoped_ptr<ExtensionSyncData> data =
6058 ExtensionSyncData::CreateFromSyncData(list[0]);
6059 ASSERT_TRUE(data.get());
6060 EXPECT_FALSE(data->enabled());
6061 EXPECT_FALSE(data->incognito_enabled());
6062 EXPECT_EQ(ExtensionSyncData::BOOLEAN_UNSET, data->all_urls_enabled());
6065 extensions::util::SetIsIncognitoEnabled(good_crx, profile(), true);
6066 extensions::util::SetAllowedScriptingOnAllUrls(
6067 good_crx, profile(), false);
6069 syncer::SyncDataList list =
6070 extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS);
6071 ASSERT_EQ(list.size(), 1U);
6072 scoped_ptr<ExtensionSyncData> data =
6073 ExtensionSyncData::CreateFromSyncData(list[0]);
6074 ASSERT_TRUE(data.get());
6075 EXPECT_FALSE(data->enabled());
6076 EXPECT_TRUE(data->incognito_enabled());
6077 EXPECT_EQ(ExtensionSyncData::BOOLEAN_FALSE, data->all_urls_enabled());
6080 service()->EnableExtension(good_crx);
6081 extensions::util::SetAllowedScriptingOnAllUrls(
6082 good_crx, profile(), true);
6084 syncer::SyncDataList list =
6085 extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS);
6086 ASSERT_EQ(list.size(), 1U);
6087 scoped_ptr<ExtensionSyncData> data =
6088 ExtensionSyncData::CreateFromSyncData(list[0]);
6089 ASSERT_TRUE(data.get());
6090 EXPECT_TRUE(data->enabled());
6091 EXPECT_TRUE(data->incognito_enabled());
6092 EXPECT_EQ(ExtensionSyncData::BOOLEAN_TRUE, data->all_urls_enabled());
6096 TEST_F(ExtensionServiceTest, SyncForUninstalledExternalExtension) {
6097 InitializeEmptyExtensionService();
6098 InitializeExtensionSyncService();
6099 InstallCRXWithLocation(
6100 data_dir().AppendASCII("good.crx"), Manifest::EXTERNAL_PREF, INSTALL_NEW);
6101 const Extension* extension = service()->GetInstalledExtension(good_crx);
6102 ASSERT_TRUE(extension);
6104 syncer::FakeSyncChangeProcessor processor;
6105 extension_sync_service()->MergeDataAndStartSyncing(
6106 syncer::EXTENSIONS,
6107 syncer::SyncDataList(),
6108 scoped_ptr<syncer::SyncChangeProcessor>(
6109 new syncer::FakeSyncChangeProcessor),
6110 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6112 UninstallExtension(good_crx, false);
6113 EXPECT_TRUE(
6114 ExtensionPrefs::Get(profile())->IsExternalExtensionUninstalled(good_crx));
6116 sync_pb::EntitySpecifics specifics;
6117 sync_pb::AppSpecifics* app_specifics = specifics.mutable_app();
6118 sync_pb::ExtensionSpecifics* extension_specifics =
6119 app_specifics->mutable_extension();
6120 extension_specifics->set_id(good_crx);
6121 extension_specifics->set_version("1.0");
6122 extension_specifics->set_enabled(true);
6124 syncer::SyncData sync_data =
6125 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6126 syncer::SyncChange sync_change(FROM_HERE,
6127 syncer::SyncChange::ACTION_UPDATE,
6128 sync_data);
6129 syncer::SyncChangeList list(1);
6130 list[0] = sync_change;
6132 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6133 EXPECT_TRUE(
6134 ExtensionPrefs::Get(profile())->IsExternalExtensionUninstalled(good_crx));
6137 TEST_F(ExtensionServiceTest, GetSyncAppDataUserSettings) {
6138 InitializeEmptyExtensionService();
6139 InitializeExtensionSyncService();
6140 const Extension* app =
6141 PackAndInstallCRX(data_dir().AppendASCII("app"), INSTALL_NEW);
6142 ASSERT_TRUE(app);
6143 ASSERT_TRUE(app->is_app());
6145 syncer::FakeSyncChangeProcessor processor;
6146 extension_sync_service()->MergeDataAndStartSyncing(
6147 syncer::APPS,
6148 syncer::SyncDataList(),
6149 scoped_ptr<syncer::SyncChangeProcessor>(
6150 new syncer::FakeSyncChangeProcessor),
6151 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6153 syncer::StringOrdinal initial_ordinal =
6154 syncer::StringOrdinal::CreateInitialOrdinal();
6156 syncer::SyncDataList list =
6157 extension_sync_service()->GetAllSyncData(syncer::APPS);
6158 ASSERT_EQ(list.size(), 1U);
6160 scoped_ptr<AppSyncData> app_sync_data =
6161 AppSyncData::CreateFromSyncData(list[0]);
6162 EXPECT_TRUE(initial_ordinal.Equals(app_sync_data->app_launch_ordinal()));
6163 EXPECT_TRUE(initial_ordinal.Equals(app_sync_data->page_ordinal()));
6166 AppSorting* sorting = ExtensionPrefs::Get(profile())->app_sorting();
6167 sorting->SetAppLaunchOrdinal(app->id(), initial_ordinal.CreateAfter());
6169 syncer::SyncDataList list =
6170 extension_sync_service()->GetAllSyncData(syncer::APPS);
6171 ASSERT_EQ(list.size(), 1U);
6173 scoped_ptr<AppSyncData> app_sync_data =
6174 AppSyncData::CreateFromSyncData(list[0]);
6175 ASSERT_TRUE(app_sync_data.get());
6176 EXPECT_TRUE(initial_ordinal.LessThan(app_sync_data->app_launch_ordinal()));
6177 EXPECT_TRUE(initial_ordinal.Equals(app_sync_data->page_ordinal()));
6180 sorting->SetPageOrdinal(app->id(), initial_ordinal.CreateAfter());
6182 syncer::SyncDataList list =
6183 extension_sync_service()->GetAllSyncData(syncer::APPS);
6184 ASSERT_EQ(list.size(), 1U);
6186 scoped_ptr<AppSyncData> app_sync_data =
6187 AppSyncData::CreateFromSyncData(list[0]);
6188 ASSERT_TRUE(app_sync_data.get());
6189 EXPECT_TRUE(initial_ordinal.LessThan(app_sync_data->app_launch_ordinal()));
6190 EXPECT_TRUE(initial_ordinal.LessThan(app_sync_data->page_ordinal()));
6194 // TODO (rdevlin.cronin): The OnExtensionMoved() method has been removed from
6195 // ExtensionService, so this test probably needs a new home. Unfortunately, it
6196 // relies pretty heavily on things like InitializeExtension[Sync]Service() and
6197 // PackAndInstallCRX(). When we clean up a bit more, this should move out.
6198 TEST_F(ExtensionServiceTest, GetSyncAppDataUserSettingsOnExtensionMoved) {
6199 InitializeEmptyExtensionService();
6200 InitializeExtensionSyncService();
6201 const size_t kAppCount = 3;
6202 const Extension* apps[kAppCount];
6203 apps[0] = PackAndInstallCRX(data_dir().AppendASCII("app1"), INSTALL_NEW);
6204 apps[1] = PackAndInstallCRX(data_dir().AppendASCII("app2"), INSTALL_NEW);
6205 apps[2] = PackAndInstallCRX(data_dir().AppendASCII("app4"), INSTALL_NEW);
6206 for (size_t i = 0; i < kAppCount; ++i) {
6207 ASSERT_TRUE(apps[i]);
6208 ASSERT_TRUE(apps[i]->is_app());
6211 syncer::FakeSyncChangeProcessor processor;
6212 extension_sync_service()->MergeDataAndStartSyncing(
6213 syncer::APPS,
6214 syncer::SyncDataList(),
6215 scoped_ptr<syncer::SyncChangeProcessor>(
6216 new syncer::FakeSyncChangeProcessor),
6217 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6219 ExtensionPrefs::Get(service()->GetBrowserContext())
6220 ->app_sorting()
6221 ->OnExtensionMoved(apps[0]->id(), apps[1]->id(), apps[2]->id());
6223 syncer::SyncDataList list =
6224 extension_sync_service()->GetAllSyncData(syncer::APPS);
6225 ASSERT_EQ(list.size(), 3U);
6227 scoped_ptr<AppSyncData> data[kAppCount];
6228 for (size_t i = 0; i < kAppCount; ++i) {
6229 data[i] = AppSyncData::CreateFromSyncData(list[i]);
6230 ASSERT_TRUE(data[i].get());
6233 // The sync data is not always in the same order our apps were installed in,
6234 // so we do that sorting here so we can make sure the values are changed as
6235 // expected.
6236 syncer::StringOrdinal app_launch_ordinals[kAppCount];
6237 for (size_t i = 0; i < kAppCount; ++i) {
6238 for (size_t j = 0; j < kAppCount; ++j) {
6239 if (apps[i]->id() == data[j]->id())
6240 app_launch_ordinals[i] = data[j]->app_launch_ordinal();
6244 EXPECT_TRUE(app_launch_ordinals[1].LessThan(app_launch_ordinals[0]));
6245 EXPECT_TRUE(app_launch_ordinals[0].LessThan(app_launch_ordinals[2]));
6249 TEST_F(ExtensionServiceTest, GetSyncDataList) {
6250 InitializeEmptyExtensionService();
6251 InitializeExtensionSyncService();
6252 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
6253 InstallCRX(data_dir().AppendASCII("page_action.crx"), INSTALL_NEW);
6254 InstallCRX(data_dir().AppendASCII("theme.crx"), INSTALL_NEW);
6255 InstallCRX(data_dir().AppendASCII("theme2.crx"), INSTALL_NEW);
6257 syncer::FakeSyncChangeProcessor processor;
6258 extension_sync_service()->MergeDataAndStartSyncing(
6259 syncer::APPS,
6260 syncer::SyncDataList(),
6261 scoped_ptr<syncer::SyncChangeProcessor>(
6262 new syncer::FakeSyncChangeProcessor),
6263 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6264 extension_sync_service()->MergeDataAndStartSyncing(
6265 syncer::EXTENSIONS,
6266 syncer::SyncDataList(),
6267 scoped_ptr<syncer::SyncChangeProcessor>(
6268 new syncer::FakeSyncChangeProcessor),
6269 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6271 service()->DisableExtension(page_action, Extension::DISABLE_USER_ACTION);
6272 TerminateExtension(theme2_crx);
6274 EXPECT_EQ(0u, extension_sync_service()->GetAllSyncData(syncer::APPS).size());
6275 EXPECT_EQ(
6276 2u, extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS).size());
6279 TEST_F(ExtensionServiceTest, ProcessSyncDataUninstall) {
6280 InitializeEmptyExtensionService();
6281 InitializeExtensionSyncService();
6282 syncer::FakeSyncChangeProcessor processor;
6283 extension_sync_service()->MergeDataAndStartSyncing(
6284 syncer::EXTENSIONS,
6285 syncer::SyncDataList(),
6286 scoped_ptr<syncer::SyncChangeProcessor>(
6287 new syncer::FakeSyncChangeProcessor),
6288 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6290 sync_pb::EntitySpecifics specifics;
6291 sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension();
6292 ext_specifics->set_id(good_crx);
6293 ext_specifics->set_version("1.0");
6294 syncer::SyncData sync_data =
6295 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6296 syncer::SyncChange sync_change(FROM_HERE,
6297 syncer::SyncChange::ACTION_DELETE,
6298 sync_data);
6299 syncer::SyncChangeList list(1);
6300 list[0] = sync_change;
6302 // Should do nothing.
6303 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6304 EXPECT_FALSE(service()->GetExtensionById(good_crx, true));
6306 // Install the extension.
6307 base::FilePath extension_path = data_dir().AppendASCII("good.crx");
6308 InstallCRX(extension_path, INSTALL_NEW);
6309 EXPECT_TRUE(service()->GetExtensionById(good_crx, true));
6311 // Should uninstall the extension.
6312 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6313 EXPECT_FALSE(service()->GetExtensionById(good_crx, true));
6315 // Should again do nothing.
6316 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6317 EXPECT_FALSE(service()->GetExtensionById(good_crx, true));
6320 TEST_F(ExtensionServiceTest, ProcessSyncDataWrongType) {
6321 InitializeEmptyExtensionService();
6322 InitializeExtensionSyncService();
6324 // Install the extension.
6325 base::FilePath extension_path = data_dir().AppendASCII("good.crx");
6326 InstallCRX(extension_path, INSTALL_NEW);
6327 EXPECT_TRUE(service()->GetExtensionById(good_crx, true));
6329 sync_pb::EntitySpecifics specifics;
6330 sync_pb::AppSpecifics* app_specifics = specifics.mutable_app();
6331 sync_pb::ExtensionSpecifics* extension_specifics =
6332 app_specifics->mutable_extension();
6333 extension_specifics->set_id(good_crx);
6334 extension_specifics->set_version(
6335 service()->GetInstalledExtension(good_crx)->version()->GetString());
6338 extension_specifics->set_enabled(true);
6339 syncer::SyncData sync_data =
6340 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6341 syncer::SyncChange sync_change(FROM_HERE,
6342 syncer::SyncChange::ACTION_DELETE,
6343 sync_data);
6344 syncer::SyncChangeList list(1);
6345 list[0] = sync_change;
6347 // Should do nothing
6348 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6349 EXPECT_TRUE(service()->GetExtensionById(good_crx, true));
6353 extension_specifics->set_enabled(false);
6354 syncer::SyncData sync_data =
6355 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6356 syncer::SyncChange sync_change(FROM_HERE,
6357 syncer::SyncChange::ACTION_UPDATE,
6358 sync_data);
6359 syncer::SyncChangeList list(1);
6360 list[0] = sync_change;
6362 // Should again do nothing.
6363 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6364 EXPECT_TRUE(service()->GetExtensionById(good_crx, false));
6368 TEST_F(ExtensionServiceTest, ProcessSyncDataSettings) {
6369 InitializeEmptyExtensionService();
6370 InitializeExtensionSyncService();
6371 syncer::FakeSyncChangeProcessor processor;
6372 extension_sync_service()->MergeDataAndStartSyncing(
6373 syncer::EXTENSIONS,
6374 syncer::SyncDataList(),
6375 scoped_ptr<syncer::SyncChangeProcessor>(
6376 new syncer::FakeSyncChangeProcessor),
6377 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6379 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
6380 EXPECT_TRUE(service()->IsExtensionEnabled(good_crx));
6381 EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
6382 EXPECT_FALSE(extensions::util::HasSetAllowedScriptingOnAllUrls(
6383 good_crx, profile()));
6384 const bool kDefaultAllowedScripting =
6385 extensions::util::DefaultAllowedScriptingOnAllUrls();
6386 EXPECT_EQ(kDefaultAllowedScripting,
6387 extensions::util::AllowedScriptingOnAllUrls(good_crx, profile()));
6389 sync_pb::EntitySpecifics specifics;
6390 sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension();
6391 ext_specifics->set_id(good_crx);
6392 ext_specifics->set_version(
6393 service()->GetInstalledExtension(good_crx)->version()->GetString());
6394 ext_specifics->set_enabled(false);
6397 syncer::SyncData sync_data =
6398 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6399 syncer::SyncChange sync_change(FROM_HERE,
6400 syncer::SyncChange::ACTION_UPDATE,
6401 sync_data);
6402 syncer::SyncChangeList list(1);
6403 list[0] = sync_change;
6404 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6405 EXPECT_FALSE(service()->IsExtensionEnabled(good_crx));
6406 EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
6407 EXPECT_FALSE(extensions::util::HasSetAllowedScriptingOnAllUrls(
6408 good_crx, profile()));
6409 EXPECT_EQ(kDefaultAllowedScripting,
6410 extensions::util::AllowedScriptingOnAllUrls(good_crx, profile()));
6414 ext_specifics->set_enabled(true);
6415 ext_specifics->set_incognito_enabled(true);
6416 syncer::SyncData sync_data =
6417 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6418 syncer::SyncChange sync_change(FROM_HERE,
6419 syncer::SyncChange::ACTION_UPDATE,
6420 sync_data);
6421 syncer::SyncChangeList list(1);
6422 list[0] = sync_change;
6423 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6424 EXPECT_TRUE(service()->IsExtensionEnabled(good_crx));
6425 EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
6429 ext_specifics->set_enabled(false);
6430 ext_specifics->set_incognito_enabled(true);
6431 syncer::SyncData sync_data =
6432 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6433 syncer::SyncChange sync_change(FROM_HERE,
6434 syncer::SyncChange::ACTION_UPDATE,
6435 sync_data);
6436 syncer::SyncChangeList list(1);
6437 list[0] = sync_change;
6438 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6439 EXPECT_FALSE(service()->IsExtensionEnabled(good_crx));
6440 EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
6444 ext_specifics->set_enabled(true);
6445 ext_specifics->set_all_urls_enabled(!kDefaultAllowedScripting);
6446 syncer::SyncData sync_data =
6447 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6448 syncer::SyncChange sync_change(FROM_HERE,
6449 syncer::SyncChange::ACTION_UPDATE,
6450 sync_data);
6451 syncer::SyncChangeList list(1);
6452 list[0] = sync_change;
6453 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6454 EXPECT_TRUE(service()->IsExtensionEnabled(good_crx));
6455 EXPECT_TRUE(extensions::util::HasSetAllowedScriptingOnAllUrls(
6456 good_crx, profile()));
6457 EXPECT_EQ(!kDefaultAllowedScripting,
6458 extensions::util::AllowedScriptingOnAllUrls(good_crx, profile()));
6462 ext_specifics->set_all_urls_enabled(kDefaultAllowedScripting);
6463 syncer::SyncData sync_data =
6464 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6465 syncer::SyncChange sync_change(FROM_HERE,
6466 syncer::SyncChange::ACTION_UPDATE,
6467 sync_data);
6468 syncer::SyncChangeList list(1);
6469 list[0] = sync_change;
6470 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6471 EXPECT_TRUE(service()->IsExtensionEnabled(good_crx));
6472 EXPECT_TRUE(extensions::util::HasSetAllowedScriptingOnAllUrls(
6473 good_crx, profile()));
6474 EXPECT_EQ(kDefaultAllowedScripting,
6475 extensions::util::AllowedScriptingOnAllUrls(good_crx, profile()));
6478 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(good_crx));
6481 TEST_F(ExtensionServiceTest, ProcessSyncDataTerminatedExtension) {
6482 InitializeExtensionServiceWithUpdater();
6483 InitializeExtensionSyncService();
6484 syncer::FakeSyncChangeProcessor processor;
6485 extension_sync_service()->MergeDataAndStartSyncing(
6486 syncer::EXTENSIONS,
6487 syncer::SyncDataList(),
6488 scoped_ptr<syncer::SyncChangeProcessor>(
6489 new syncer::FakeSyncChangeProcessor),
6490 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6492 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
6493 TerminateExtension(good_crx);
6494 EXPECT_TRUE(service()->IsExtensionEnabled(good_crx));
6495 EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
6497 sync_pb::EntitySpecifics specifics;
6498 sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension();
6499 ext_specifics->set_id(good_crx);
6500 ext_specifics->set_version(
6501 service()->GetInstalledExtension(good_crx)->version()->GetString());
6502 ext_specifics->set_enabled(false);
6503 ext_specifics->set_incognito_enabled(true);
6504 syncer::SyncData sync_data =
6505 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6506 syncer::SyncChange sync_change(FROM_HERE,
6507 syncer::SyncChange::ACTION_UPDATE,
6508 sync_data);
6509 syncer::SyncChangeList list(1);
6510 list[0] = sync_change;
6512 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6513 EXPECT_FALSE(service()->IsExtensionEnabled(good_crx));
6514 EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
6516 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(good_crx));
6519 TEST_F(ExtensionServiceTest, ProcessSyncDataVersionCheck) {
6520 InitializeExtensionServiceWithUpdater();
6521 InitializeExtensionSyncService();
6522 syncer::FakeSyncChangeProcessor processor;
6523 extension_sync_service()->MergeDataAndStartSyncing(
6524 syncer::EXTENSIONS,
6525 syncer::SyncDataList(),
6526 scoped_ptr<syncer::SyncChangeProcessor>(
6527 new syncer::FakeSyncChangeProcessor),
6528 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6530 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
6531 EXPECT_TRUE(service()->IsExtensionEnabled(good_crx));
6532 EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
6534 sync_pb::EntitySpecifics specifics;
6535 sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension();
6536 ext_specifics->set_id(good_crx);
6537 ext_specifics->set_enabled(true);
6540 ext_specifics->set_version(
6541 service()->GetInstalledExtension(good_crx)->version()->GetString());
6542 syncer::SyncData sync_data =
6543 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6544 syncer::SyncChange sync_change(FROM_HERE,
6545 syncer::SyncChange::ACTION_UPDATE,
6546 sync_data);
6547 syncer::SyncChangeList list(1);
6548 list[0] = sync_change;
6550 // Should do nothing if extension version == sync version.
6551 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6552 EXPECT_FALSE(service()->updater()->WillCheckSoon());
6555 // Should do nothing if extension version > sync version (but see
6556 // the TODO in ProcessExtensionSyncData).
6558 ext_specifics->set_version("0.0.0.0");
6559 syncer::SyncData sync_data =
6560 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6561 syncer::SyncChange sync_change(FROM_HERE,
6562 syncer::SyncChange::ACTION_UPDATE,
6563 sync_data);
6564 syncer::SyncChangeList list(1);
6565 list[0] = sync_change;
6567 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6568 EXPECT_FALSE(service()->updater()->WillCheckSoon());
6571 // Should kick off an update if extension version < sync version.
6573 ext_specifics->set_version("9.9.9.9");
6574 syncer::SyncData sync_data =
6575 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6576 syncer::SyncChange sync_change(FROM_HERE,
6577 syncer::SyncChange::ACTION_UPDATE,
6578 sync_data);
6579 syncer::SyncChangeList list(1);
6580 list[0] = sync_change;
6582 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6583 EXPECT_TRUE(service()->updater()->WillCheckSoon());
6586 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(good_crx));
6589 TEST_F(ExtensionServiceTest, ProcessSyncDataNotInstalled) {
6590 InitializeExtensionServiceWithUpdater();
6591 InitializeExtensionSyncService();
6592 syncer::FakeSyncChangeProcessor processor;
6593 extension_sync_service()->MergeDataAndStartSyncing(
6594 syncer::EXTENSIONS,
6595 syncer::SyncDataList(),
6596 scoped_ptr<syncer::SyncChangeProcessor>(
6597 new syncer::FakeSyncChangeProcessor),
6598 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6600 sync_pb::EntitySpecifics specifics;
6601 sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension();
6602 ext_specifics->set_id(good_crx);
6603 ext_specifics->set_enabled(false);
6604 ext_specifics->set_incognito_enabled(true);
6605 ext_specifics->set_update_url("http://www.google.com/");
6606 ext_specifics->set_version("1.2.3.4");
6607 syncer::SyncData sync_data =
6608 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6609 syncer::SyncChange sync_change(FROM_HERE,
6610 syncer::SyncChange::ACTION_UPDATE,
6611 sync_data);
6612 syncer::SyncChangeList list(1);
6613 list[0] = sync_change;
6615 EXPECT_TRUE(service()->IsExtensionEnabled(good_crx));
6616 EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
6617 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6618 EXPECT_TRUE(service()->updater()->WillCheckSoon());
6619 EXPECT_FALSE(service()->IsExtensionEnabled(good_crx));
6620 EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
6622 const extensions::PendingExtensionInfo* info;
6623 EXPECT_TRUE(
6624 (info = service()->pending_extension_manager()->GetById(good_crx)));
6625 EXPECT_EQ(ext_specifics->update_url(), info->update_url().spec());
6626 EXPECT_TRUE(info->is_from_sync());
6627 EXPECT_EQ(Manifest::INTERNAL, info->install_source());
6628 // TODO(akalin): Figure out a way to test |info.ShouldAllowInstall()|.
6631 #if defined(ENABLE_SUPERVISED_USERS)
6632 class MockPermissionRequestCreator : public PermissionRequestCreator {
6633 public:
6634 MockPermissionRequestCreator() {}
6635 ~MockPermissionRequestCreator() override {}
6637 bool IsEnabled() const override { return true; }
6639 void CreateURLAccessRequest(const GURL& url_requested,
6640 const SuccessCallback& callback) override {
6641 FAIL();
6644 MOCK_METHOD2(CreateExtensionUpdateRequest,
6645 void(const std::string& id,
6646 const SupervisedUserService::SuccessCallback& callback));
6648 private:
6649 DISALLOW_COPY_AND_ASSIGN(MockPermissionRequestCreator);
6652 TEST_F(ExtensionServiceTest, SupervisedUser_InstallOnlyAllowedByCustodian) {
6653 ExtensionServiceInitParams params = CreateDefaultInitParams();
6654 params.profile_is_supervised = true;
6655 InitializeExtensionService(params);
6657 SupervisedUserService* supervised_user_service =
6658 SupervisedUserServiceFactory::GetForProfile(profile());
6659 GetManagementPolicy()->RegisterProvider(supervised_user_service);
6661 base::FilePath path1 = data_dir().AppendASCII("good.crx");
6662 base::FilePath path2 = data_dir().AppendASCII("good2048.crx");
6663 const Extension* extensions[] = {
6664 InstallCRX(path1, INSTALL_FAILED),
6665 InstallCRX(path2, INSTALL_NEW, Extension::WAS_INSTALLED_BY_CUSTODIAN)
6668 // Only the extension with the "installed by custodian" flag should have been
6669 // installed and enabled.
6670 EXPECT_FALSE(extensions[0]);
6671 ASSERT_TRUE(extensions[1]);
6672 EXPECT_TRUE(registry()->enabled_extensions().Contains(extensions[1]->id()));
6675 TEST_F(ExtensionServiceTest, SupervisedUser_UpdateWithoutPermissionIncrease) {
6676 ExtensionServiceInitParams params = CreateDefaultInitParams();
6677 params.profile_is_supervised = true;
6678 InitializeExtensionService(params);
6680 SupervisedUserService* supervised_user_service =
6681 SupervisedUserServiceFactory::GetForProfile(profile());
6682 GetManagementPolicy()->RegisterProvider(supervised_user_service);
6684 base::FilePath base_path = data_dir().AppendASCII("autoupdate");
6685 base::FilePath pem_path = base_path.AppendASCII("key.pem");
6687 base::FilePath path = base_path.AppendASCII("v1");
6688 const Extension* extension =
6689 PackAndInstallCRX(path, pem_path, INSTALL_NEW,
6690 Extension::WAS_INSTALLED_BY_CUSTODIAN);
6691 // The extension must now be installed and enabled.
6692 ASSERT_TRUE(extension);
6693 ASSERT_TRUE(registry()->enabled_extensions().Contains(extension->id()));
6695 // Save the id, as the extension object will be destroyed during updating.
6696 std::string id = extension->id();
6698 std::string old_version = extension->VersionString();
6700 // Update to a new version.
6701 path = base_path.AppendASCII("v2");
6702 PackCRXAndUpdateExtension(id, path, pem_path, ENABLED);
6704 // The extension should still be there and enabled.
6705 extension = registry()->enabled_extensions().GetByID(id);
6706 ASSERT_TRUE(extension);
6707 // The version should have changed.
6708 EXPECT_NE(extension->VersionString(), old_version);
6711 TEST_F(ExtensionServiceTest, SupervisedUser_UpdateWithPermissionIncrease) {
6712 ExtensionServiceInitParams params = CreateDefaultInitParams();
6713 params.profile_is_supervised = true;
6714 InitializeExtensionService(params);
6716 SupervisedUserService* supervised_user_service =
6717 SupervisedUserServiceFactory::GetForProfile(profile());
6718 GetManagementPolicy()->RegisterProvider(supervised_user_service);
6719 MockPermissionRequestCreator* creator = new MockPermissionRequestCreator;
6720 supervised_user_service->AddPermissionRequestCreator(
6721 make_scoped_ptr(creator));
6723 base::FilePath base_path = data_dir().AppendASCII("permissions_increase");
6724 base::FilePath pem_path = base_path.AppendASCII("permissions.pem");
6726 base::FilePath path = base_path.AppendASCII("v1");
6727 const Extension* extension =
6728 PackAndInstallCRX(path, pem_path, INSTALL_NEW,
6729 Extension::WAS_INSTALLED_BY_CUSTODIAN);
6730 // The extension must now be installed and enabled.
6731 ASSERT_TRUE(extension);
6732 ASSERT_TRUE(registry()->enabled_extensions().Contains(extension->id()));
6734 // Save the id, as the extension object will be destroyed during updating.
6735 std::string id = extension->id();
6737 std::string old_version = extension->VersionString();
6739 // Update to a new version with increased permissions.
6740 EXPECT_CALL(*creator,
6741 CreateExtensionUpdateRequest(id + ":2", testing::_));
6742 path = base_path.AppendASCII("v2");
6743 PackCRXAndUpdateExtension(id, path, pem_path, DISABLED);
6745 // The extension should still be there, but disabled.
6746 EXPECT_FALSE(registry()->enabled_extensions().Contains(id));
6747 extension = registry()->disabled_extensions().GetByID(id);
6748 ASSERT_TRUE(extension);
6749 // The version should have changed.
6750 EXPECT_NE(extension->VersionString(), old_version);
6753 TEST_F(ExtensionServiceTest,
6754 SupervisedUser_SyncUninstallByCustodianSkipsPolicy) {
6755 InitializeEmptyExtensionService();
6756 InitializeExtensionSyncService();
6757 extension_sync_service()->MergeDataAndStartSyncing(
6758 syncer::EXTENSIONS,
6759 syncer::SyncDataList(),
6760 scoped_ptr<syncer::SyncChangeProcessor>(
6761 new syncer::FakeSyncChangeProcessor),
6762 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6764 // Install two extensions.
6765 base::FilePath path1 = data_dir().AppendASCII("good.crx");
6766 base::FilePath path2 = data_dir().AppendASCII("good2048.crx");
6767 const Extension* extensions[] = {
6768 InstallCRX(path1, INSTALL_NEW),
6769 InstallCRX(path2, INSTALL_NEW, Extension::WAS_INSTALLED_BY_CUSTODIAN)
6772 // Add a policy provider that will disallow any changes.
6773 extensions::TestManagementPolicyProvider provider(
6774 extensions::TestManagementPolicyProvider::PROHIBIT_MODIFY_STATUS);
6775 GetManagementPolicy()->RegisterProvider(&provider);
6777 // Create a sync deletion for each extension.
6778 syncer::SyncChangeList change_list;
6779 for (size_t i = 0; i < arraysize(extensions); i++) {
6780 const std::string& id = extensions[i]->id();
6781 sync_pb::EntitySpecifics specifics;
6782 sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension();
6783 ext_specifics->set_id(id);
6784 ext_specifics->set_version("1.0");
6785 ext_specifics->set_installed_by_custodian(
6786 extensions[i]->was_installed_by_custodian());
6787 syncer::SyncData sync_data =
6788 syncer::SyncData::CreateLocalData(id, "Name", specifics);
6789 change_list.push_back(syncer::SyncChange(FROM_HERE,
6790 syncer::SyncChange::ACTION_DELETE,
6791 sync_data));
6794 // Save the extension ids, as uninstalling destroys the Extension instance.
6795 std::string extension_ids[] = {
6796 extensions[0]->id(),
6797 extensions[1]->id()
6800 // Now apply the uninstallations.
6801 extension_sync_service()->ProcessSyncChanges(FROM_HERE, change_list);
6803 // Uninstalling the extension without installed_by_custodian should have been
6804 // blocked by policy, so it should still be there.
6805 EXPECT_TRUE(registry()->enabled_extensions().Contains(extension_ids[0]));
6807 // But installed_by_custodian should result in bypassing the policy check.
6808 EXPECT_FALSE(
6809 registry()->GenerateInstalledExtensionsSet()->Contains(extension_ids[1]));
6811 #endif // defined(ENABLE_SUPERVISED_USERS)
6813 TEST_F(ExtensionServiceTest, InstallPriorityExternalUpdateUrl) {
6814 InitializeEmptyExtensionService();
6816 base::FilePath path = data_dir().AppendASCII("good.crx");
6817 InstallCRX(path, INSTALL_NEW);
6818 ValidatePrefKeyCount(1u);
6819 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
6820 ValidateIntegerPref(good_crx, "location", Manifest::INTERNAL);
6822 extensions::PendingExtensionManager* pending =
6823 service()->pending_extension_manager();
6824 EXPECT_FALSE(pending->IsIdPending(kGoodId));
6826 // Skip install when the location is the same.
6827 EXPECT_FALSE(
6828 service()->OnExternalExtensionUpdateUrlFound(kGoodId,
6829 std::string(),
6830 GURL(kGoodUpdateURL),
6831 Manifest::INTERNAL,
6832 Extension::NO_FLAGS,
6833 false));
6834 EXPECT_FALSE(pending->IsIdPending(kGoodId));
6836 // Install when the location has higher priority.
6837 EXPECT_TRUE(service()->OnExternalExtensionUpdateUrlFound(
6838 kGoodId,
6839 std::string(),
6840 GURL(kGoodUpdateURL),
6841 Manifest::EXTERNAL_POLICY_DOWNLOAD,
6842 Extension::NO_FLAGS,
6843 false));
6844 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6846 // Try the low priority again. Should be rejected.
6847 EXPECT_FALSE(service()->OnExternalExtensionUpdateUrlFound(
6848 kGoodId,
6849 std::string(),
6850 GURL(kGoodUpdateURL),
6851 Manifest::EXTERNAL_PREF_DOWNLOAD,
6852 Extension::NO_FLAGS,
6853 false));
6854 // The existing record should still be present in the pending extension
6855 // manager.
6856 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6858 pending->Remove(kGoodId);
6860 // Skip install when the location has the same priority as the installed
6861 // location.
6862 EXPECT_FALSE(
6863 service()->OnExternalExtensionUpdateUrlFound(kGoodId,
6864 std::string(),
6865 GURL(kGoodUpdateURL),
6866 Manifest::INTERNAL,
6867 Extension::NO_FLAGS,
6868 false));
6870 EXPECT_FALSE(pending->IsIdPending(kGoodId));
6873 TEST_F(ExtensionServiceTest, InstallPriorityExternalLocalFile) {
6874 Version older_version("0.1.0.0");
6875 Version newer_version("2.0.0.0");
6877 // We don't want the extension to be installed. A path that doesn't
6878 // point to a valid CRX ensures this.
6879 const base::FilePath kInvalidPathToCrx(FILE_PATH_LITERAL("invalid_path"));
6881 const int kCreationFlags = 0;
6882 const bool kDontMarkAcknowledged = false;
6883 const bool kDontInstallImmediately = false;
6885 InitializeEmptyExtensionService();
6887 // The test below uses install source constants to test that
6888 // priority is enforced. It assumes a specific ranking of install
6889 // sources: Registry (EXTERNAL_REGISTRY) overrides external pref
6890 // (EXTERNAL_PREF), and external pref overrides user install (INTERNAL).
6891 // The following assertions verify these assumptions:
6892 ASSERT_EQ(Manifest::EXTERNAL_REGISTRY,
6893 Manifest::GetHigherPriorityLocation(Manifest::EXTERNAL_REGISTRY,
6894 Manifest::EXTERNAL_PREF));
6895 ASSERT_EQ(Manifest::EXTERNAL_REGISTRY,
6896 Manifest::GetHigherPriorityLocation(Manifest::EXTERNAL_REGISTRY,
6897 Manifest::INTERNAL));
6898 ASSERT_EQ(Manifest::EXTERNAL_PREF,
6899 Manifest::GetHigherPriorityLocation(Manifest::EXTERNAL_PREF,
6900 Manifest::INTERNAL));
6902 extensions::PendingExtensionManager* pending =
6903 service()->pending_extension_manager();
6904 EXPECT_FALSE(pending->IsIdPending(kGoodId));
6907 // Simulate an external source adding the extension as INTERNAL.
6908 content::WindowedNotificationObserver observer(
6909 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
6910 content::NotificationService::AllSources());
6911 EXPECT_TRUE(service()->OnExternalExtensionFileFound(
6912 kGoodId,
6913 &older_version,
6914 kInvalidPathToCrx,
6915 Manifest::INTERNAL,
6916 kCreationFlags,
6917 kDontMarkAcknowledged,
6918 kDontInstallImmediately));
6919 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6920 observer.Wait();
6921 VerifyCrxInstall(kInvalidPathToCrx, INSTALL_FAILED);
6925 // Simulate an external source adding the extension as EXTERNAL_PREF.
6926 content::WindowedNotificationObserver observer(
6927 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
6928 content::NotificationService::AllSources());
6929 EXPECT_TRUE(service()->OnExternalExtensionFileFound(
6930 kGoodId,
6931 &older_version,
6932 kInvalidPathToCrx,
6933 Manifest::EXTERNAL_PREF,
6934 kCreationFlags,
6935 kDontMarkAcknowledged,
6936 kDontInstallImmediately));
6937 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6938 observer.Wait();
6939 VerifyCrxInstall(kInvalidPathToCrx, INSTALL_FAILED);
6942 // Simulate an external source adding as EXTERNAL_PREF again.
6943 // This is rejected because the version and the location are the same as
6944 // the previous installation, which is still pending.
6945 EXPECT_FALSE(service()->OnExternalExtensionFileFound(
6946 kGoodId,
6947 &older_version,
6948 kInvalidPathToCrx,
6949 Manifest::EXTERNAL_PREF,
6950 kCreationFlags,
6951 kDontMarkAcknowledged,
6952 kDontInstallImmediately));
6953 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6955 // Try INTERNAL again. Should fail.
6956 EXPECT_FALSE(service()->OnExternalExtensionFileFound(
6957 kGoodId,
6958 &older_version,
6959 kInvalidPathToCrx,
6960 Manifest::INTERNAL,
6961 kCreationFlags,
6962 kDontMarkAcknowledged,
6963 kDontInstallImmediately));
6964 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6967 // Now the registry adds the extension.
6968 content::WindowedNotificationObserver observer(
6969 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
6970 content::NotificationService::AllSources());
6971 EXPECT_TRUE(service()->OnExternalExtensionFileFound(
6972 kGoodId,
6973 &older_version,
6974 kInvalidPathToCrx,
6975 Manifest::EXTERNAL_REGISTRY,
6976 kCreationFlags,
6977 kDontMarkAcknowledged,
6978 kDontInstallImmediately));
6979 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6980 observer.Wait();
6981 VerifyCrxInstall(kInvalidPathToCrx, INSTALL_FAILED);
6984 // Registry outranks both external pref and internal, so both fail.
6985 EXPECT_FALSE(service()->OnExternalExtensionFileFound(
6986 kGoodId,
6987 &older_version,
6988 kInvalidPathToCrx,
6989 Manifest::EXTERNAL_PREF,
6990 kCreationFlags,
6991 kDontMarkAcknowledged,
6992 kDontInstallImmediately));
6993 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6995 EXPECT_FALSE(service()->OnExternalExtensionFileFound(
6996 kGoodId,
6997 &older_version,
6998 kInvalidPathToCrx,
6999 Manifest::INTERNAL,
7000 kCreationFlags,
7001 kDontMarkAcknowledged,
7002 kDontInstallImmediately));
7003 EXPECT_TRUE(pending->IsIdPending(kGoodId));
7005 pending->Remove(kGoodId);
7007 // Install the extension.
7008 base::FilePath path = data_dir().AppendASCII("good.crx");
7009 const Extension* ext = InstallCRX(path, INSTALL_NEW);
7010 ValidatePrefKeyCount(1u);
7011 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
7012 ValidateIntegerPref(good_crx, "location", Manifest::INTERNAL);
7014 // Now test the logic of OnExternalExtensionFileFound() when the extension
7015 // being added is already installed.
7017 // Tests assume |older_version| is less than the installed version, and
7018 // |newer_version| is greater. Verify this:
7019 ASSERT_TRUE(older_version.IsOlderThan(ext->VersionString()));
7020 ASSERT_TRUE(ext->version()->IsOlderThan(newer_version.GetString()));
7022 // An external install for the same location should fail if the version is
7023 // older, or the same, and succeed if the version is newer.
7025 // Older than the installed version...
7026 EXPECT_FALSE(service()->OnExternalExtensionFileFound(
7027 kGoodId,
7028 &older_version,
7029 kInvalidPathToCrx,
7030 Manifest::INTERNAL,
7031 kCreationFlags,
7032 kDontMarkAcknowledged,
7033 kDontInstallImmediately));
7034 EXPECT_FALSE(pending->IsIdPending(kGoodId));
7036 // Same version as the installed version...
7037 EXPECT_FALSE(service()->OnExternalExtensionFileFound(
7038 kGoodId,
7039 ext->version(),
7040 kInvalidPathToCrx,
7041 Manifest::INTERNAL,
7042 kCreationFlags,
7043 kDontMarkAcknowledged,
7044 kDontInstallImmediately));
7045 EXPECT_FALSE(pending->IsIdPending(kGoodId));
7047 // Newer than the installed version...
7048 EXPECT_TRUE(service()->OnExternalExtensionFileFound(
7049 kGoodId,
7050 &newer_version,
7051 kInvalidPathToCrx,
7052 Manifest::INTERNAL,
7053 kCreationFlags,
7054 kDontMarkAcknowledged,
7055 kDontInstallImmediately));
7056 EXPECT_TRUE(pending->IsIdPending(kGoodId));
7058 // An external install for a higher priority install source should succeed
7059 // if the version is greater. |older_version| is not...
7060 EXPECT_FALSE(service()->OnExternalExtensionFileFound(
7061 kGoodId,
7062 &older_version,
7063 kInvalidPathToCrx,
7064 Manifest::EXTERNAL_PREF,
7065 kCreationFlags,
7066 kDontMarkAcknowledged,
7067 kDontInstallImmediately));
7068 EXPECT_TRUE(pending->IsIdPending(kGoodId));
7070 // |newer_version| is newer.
7071 EXPECT_TRUE(service()->OnExternalExtensionFileFound(
7072 kGoodId,
7073 &newer_version,
7074 kInvalidPathToCrx,
7075 Manifest::EXTERNAL_PREF,
7076 kCreationFlags,
7077 kDontMarkAcknowledged,
7078 kDontInstallImmediately));
7079 EXPECT_TRUE(pending->IsIdPending(kGoodId));
7081 // An external install for an even higher priority install source should
7082 // succeed if the version is greater.
7083 EXPECT_TRUE(service()->OnExternalExtensionFileFound(
7084 kGoodId,
7085 &newer_version,
7086 kInvalidPathToCrx,
7087 Manifest::EXTERNAL_REGISTRY,
7088 kCreationFlags,
7089 kDontMarkAcknowledged,
7090 kDontInstallImmediately));
7091 EXPECT_TRUE(pending->IsIdPending(kGoodId));
7093 // Because EXTERNAL_PREF is a lower priority source than EXTERNAL_REGISTRY,
7094 // adding from external pref will now fail.
7095 EXPECT_FALSE(service()->OnExternalExtensionFileFound(
7096 kGoodId,
7097 &newer_version,
7098 kInvalidPathToCrx,
7099 Manifest::EXTERNAL_PREF,
7100 kCreationFlags,
7101 kDontMarkAcknowledged,
7102 kDontInstallImmediately));
7103 EXPECT_TRUE(pending->IsIdPending(kGoodId));
7106 TEST_F(ExtensionServiceTest, ConcurrentExternalLocalFile) {
7107 Version kVersion123("1.2.3");
7108 Version kVersion124("1.2.4");
7109 Version kVersion125("1.2.5");
7110 const base::FilePath kInvalidPathToCrx(FILE_PATH_LITERAL("invalid_path"));
7111 const int kCreationFlags = 0;
7112 const bool kDontMarkAcknowledged = false;
7113 const bool kDontInstallImmediately = false;
7115 InitializeEmptyExtensionService();
7117 extensions::PendingExtensionManager* pending =
7118 service()->pending_extension_manager();
7119 EXPECT_FALSE(pending->IsIdPending(kGoodId));
7121 // An external provider starts installing from a local crx.
7122 EXPECT_TRUE(service()->OnExternalExtensionFileFound(
7123 kGoodId,
7124 &kVersion123,
7125 kInvalidPathToCrx,
7126 Manifest::EXTERNAL_PREF,
7127 kCreationFlags,
7128 kDontMarkAcknowledged,
7129 kDontInstallImmediately));
7130 const extensions::PendingExtensionInfo* info;
7131 EXPECT_TRUE((info = pending->GetById(kGoodId)));
7132 EXPECT_TRUE(info->version().IsValid());
7133 EXPECT_TRUE(info->version().Equals(kVersion123));
7135 // Adding a newer version overrides the currently pending version.
7136 EXPECT_TRUE(service()->OnExternalExtensionFileFound(
7137 kGoodId,
7138 &kVersion124,
7139 kInvalidPathToCrx,
7140 Manifest::EXTERNAL_PREF,
7141 kCreationFlags,
7142 kDontMarkAcknowledged,
7143 kDontInstallImmediately));
7144 EXPECT_TRUE((info = pending->GetById(kGoodId)));
7145 EXPECT_TRUE(info->version().IsValid());
7146 EXPECT_TRUE(info->version().Equals(kVersion124));
7148 // Adding an older version fails.
7149 EXPECT_FALSE(service()->OnExternalExtensionFileFound(
7150 kGoodId,
7151 &kVersion123,
7152 kInvalidPathToCrx,
7153 Manifest::EXTERNAL_PREF,
7154 kCreationFlags,
7155 kDontMarkAcknowledged,
7156 kDontInstallImmediately));
7157 EXPECT_TRUE((info = pending->GetById(kGoodId)));
7158 EXPECT_TRUE(info->version().IsValid());
7159 EXPECT_TRUE(info->version().Equals(kVersion124));
7161 // Adding an older version fails even when coming from a higher-priority
7162 // location.
7163 EXPECT_FALSE(service()->OnExternalExtensionFileFound(
7164 kGoodId,
7165 &kVersion123,
7166 kInvalidPathToCrx,
7167 Manifest::EXTERNAL_REGISTRY,
7168 kCreationFlags,
7169 kDontMarkAcknowledged,
7170 kDontInstallImmediately));
7171 EXPECT_TRUE((info = pending->GetById(kGoodId)));
7172 EXPECT_TRUE(info->version().IsValid());
7173 EXPECT_TRUE(info->version().Equals(kVersion124));
7175 // Adding the latest version from the webstore overrides a specific version.
7176 GURL kUpdateUrl("http://example.com/update");
7177 EXPECT_TRUE(service()->OnExternalExtensionUpdateUrlFound(
7178 kGoodId,
7179 std::string(),
7180 kUpdateUrl,
7181 Manifest::EXTERNAL_POLICY_DOWNLOAD,
7182 Extension::NO_FLAGS,
7183 false));
7184 EXPECT_TRUE((info = pending->GetById(kGoodId)));
7185 EXPECT_FALSE(info->version().IsValid());
7188 // This makes sure we can package and install CRX files that use whitelisted
7189 // permissions.
7190 TEST_F(ExtensionServiceTest, InstallWhitelistedExtension) {
7191 std::string test_id = "hdkklepkcpckhnpgjnmbdfhehckloojk";
7192 base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
7193 extensions::switches::kWhitelistedExtensionID, test_id);
7195 InitializeEmptyExtensionService();
7196 base::FilePath path = data_dir().AppendASCII("permissions");
7197 base::FilePath pem_path = path
7198 .AppendASCII("whitelist.pem");
7199 path = path
7200 .AppendASCII("whitelist");
7202 const Extension* extension = PackAndInstallCRX(path, pem_path, INSTALL_NEW);
7203 EXPECT_EQ(0u, GetErrors().size());
7204 ASSERT_EQ(1u, registry()->enabled_extensions().size());
7205 EXPECT_EQ(test_id, extension->id());
7208 // Test that when multiple sources try to install an extension,
7209 // we consistently choose the right one. To make tests easy to read,
7210 // methods that fake requests to install crx files in several ways
7211 // are provided.
7212 class ExtensionSourcePriorityTest : public ExtensionServiceTest {
7213 public:
7214 void SetUp() override {
7215 ExtensionServiceTest::SetUp();
7217 // All tests use a single extension. Put the id and path in member vars
7218 // that all methods can read.
7219 crx_id_ = kGoodId;
7220 crx_path_ = data_dir().AppendASCII("good.crx");
7223 // Fake an external source adding a URL to fetch an extension from.
7224 bool AddPendingExternalPrefUrl() {
7225 return service()->pending_extension_manager()->AddFromExternalUpdateUrl(
7226 crx_id_,
7227 std::string(),
7228 GURL(),
7229 Manifest::EXTERNAL_PREF_DOWNLOAD,
7230 Extension::NO_FLAGS,
7231 false);
7234 // Fake an external file from external_extensions.json.
7235 bool AddPendingExternalPrefFileInstall() {
7236 Version version("1.0.0.0");
7238 return service()->OnExternalExtensionFileFound(crx_id_,
7239 &version,
7240 crx_path_,
7241 Manifest::EXTERNAL_PREF,
7242 Extension::NO_FLAGS,
7243 false,
7244 false);
7247 // Fake a request from sync to install an extension.
7248 bool AddPendingSyncInstall() {
7249 return service()->pending_extension_manager()->AddFromSync(
7250 crx_id_,
7251 GURL(kGoodUpdateURL),
7252 &IsExtension,
7253 kGoodRemoteInstall,
7254 kGoodInstalledByCustodian);
7257 // Fake a policy install.
7258 bool AddPendingPolicyInstall() {
7259 // Get path to the CRX with id |kGoodId|.
7260 return service()->OnExternalExtensionUpdateUrlFound(
7261 crx_id_,
7262 std::string(),
7263 GURL(),
7264 Manifest::EXTERNAL_POLICY_DOWNLOAD,
7265 Extension::NO_FLAGS,
7266 false);
7269 // Get the install source of a pending extension.
7270 Manifest::Location GetPendingLocation() {
7271 const extensions::PendingExtensionInfo* info;
7272 EXPECT_TRUE(
7273 (info = service()->pending_extension_manager()->GetById(crx_id_)));
7274 return info->install_source();
7277 // Is an extension pending from a sync request?
7278 bool GetPendingIsFromSync() {
7279 const extensions::PendingExtensionInfo* info;
7280 EXPECT_TRUE(
7281 (info = service()->pending_extension_manager()->GetById(crx_id_)));
7282 return info->is_from_sync();
7285 // Is the CRX id these tests use pending?
7286 bool IsCrxPending() {
7287 return service()->pending_extension_manager()->IsIdPending(crx_id_);
7290 // Is an extension installed?
7291 bool IsCrxInstalled() {
7292 return (service()->GetExtensionById(crx_id_, true) != NULL);
7295 protected:
7296 // All tests use a single extension. Making the id and path member
7297 // vars avoids pasing the same argument to every method.
7298 std::string crx_id_;
7299 base::FilePath crx_path_;
7302 // Test that a pending request for installation of an external CRX from
7303 // an update URL overrides a pending request to install the same extension
7304 // from sync.
7305 TEST_F(ExtensionSourcePriorityTest, PendingExternalFileOverSync) {
7306 InitializeEmptyExtensionService();
7308 ASSERT_FALSE(IsCrxInstalled());
7310 // Install pending extension from sync.
7311 content::WindowedNotificationObserver observer(
7312 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
7313 content::NotificationService::AllSources());
7314 EXPECT_TRUE(AddPendingSyncInstall());
7315 ASSERT_EQ(Manifest::INTERNAL, GetPendingLocation());
7316 EXPECT_TRUE(GetPendingIsFromSync());
7317 ASSERT_FALSE(IsCrxInstalled());
7319 // Install pending as external prefs json would.
7320 AddPendingExternalPrefFileInstall();
7321 ASSERT_EQ(Manifest::EXTERNAL_PREF, GetPendingLocation());
7322 ASSERT_FALSE(IsCrxInstalled());
7324 // Another request from sync should be ignored.
7325 EXPECT_FALSE(AddPendingSyncInstall());
7326 ASSERT_EQ(Manifest::EXTERNAL_PREF, GetPendingLocation());
7327 ASSERT_FALSE(IsCrxInstalled());
7329 observer.Wait();
7330 VerifyCrxInstall(crx_path_, INSTALL_NEW);
7331 ASSERT_TRUE(IsCrxInstalled());
7334 // Test that an install of an external CRX from an update overrides
7335 // an install of the same extension from sync.
7336 TEST_F(ExtensionSourcePriorityTest, PendingExternalUrlOverSync) {
7337 InitializeEmptyExtensionService();
7338 ASSERT_FALSE(IsCrxInstalled());
7340 EXPECT_TRUE(AddPendingSyncInstall());
7341 ASSERT_EQ(Manifest::INTERNAL, GetPendingLocation());
7342 EXPECT_TRUE(GetPendingIsFromSync());
7343 ASSERT_FALSE(IsCrxInstalled());
7345 ASSERT_TRUE(AddPendingExternalPrefUrl());
7346 ASSERT_EQ(Manifest::EXTERNAL_PREF_DOWNLOAD, GetPendingLocation());
7347 EXPECT_FALSE(GetPendingIsFromSync());
7348 ASSERT_FALSE(IsCrxInstalled());
7350 EXPECT_FALSE(AddPendingSyncInstall());
7351 ASSERT_EQ(Manifest::EXTERNAL_PREF_DOWNLOAD, GetPendingLocation());
7352 EXPECT_FALSE(GetPendingIsFromSync());
7353 ASSERT_FALSE(IsCrxInstalled());
7356 // Test that an external install request stops sync from installing
7357 // the same extension.
7358 TEST_F(ExtensionSourcePriorityTest, InstallExternalBlocksSyncRequest) {
7359 InitializeEmptyExtensionService();
7360 ASSERT_FALSE(IsCrxInstalled());
7362 // External prefs starts an install.
7363 AddPendingExternalPrefFileInstall();
7365 // Crx installer was made, but has not yet run.
7366 ASSERT_FALSE(IsCrxInstalled());
7368 // Before the CRX installer runs, Sync requests that the same extension
7369 // be installed. Should fail, because an external source is pending.
7370 content::WindowedNotificationObserver observer(
7371 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
7372 content::NotificationService::AllSources());
7373 ASSERT_FALSE(AddPendingSyncInstall());
7375 // Wait for the external source to install.
7376 observer.Wait();
7377 VerifyCrxInstall(crx_path_, INSTALL_NEW);
7378 ASSERT_TRUE(IsCrxInstalled());
7380 // Now that the extension is installed, sync request should fail
7381 // because the extension is already installed.
7382 ASSERT_FALSE(AddPendingSyncInstall());
7385 // Test that installing an external extension displays a GlobalError.
7386 TEST_F(ExtensionServiceTest, ExternalInstallGlobalError) {
7387 FeatureSwitch::ScopedOverride prompt(
7388 FeatureSwitch::prompt_for_external_extensions(), true);
7390 InitializeEmptyExtensionService();
7391 MockExtensionProvider* provider =
7392 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF);
7393 AddMockExternalProvider(provider);
7395 service()->external_install_manager()->UpdateExternalExtensionAlert();
7396 // Should return false, meaning there aren't any extensions that the user
7397 // needs to know about.
7398 EXPECT_FALSE(
7399 service()->external_install_manager()->HasExternalInstallError());
7401 // This is a normal extension, installed normally.
7402 // This should NOT trigger an alert.
7403 service()->set_extensions_enabled(true);
7404 base::FilePath path = data_dir().AppendASCII("good.crx");
7405 InstallCRX(path, INSTALL_NEW);
7407 service()->CheckForExternalUpdates();
7408 base::RunLoop().RunUntilIdle();
7409 EXPECT_FALSE(
7410 service()->external_install_manager()->HasExternalInstallError());
7412 // A hosted app, installed externally.
7413 // This should NOT trigger an alert.
7414 provider->UpdateOrAddExtension(
7415 hosted_app, "1.0.0.0", data_dir().AppendASCII("hosted_app.crx"));
7417 content::WindowedNotificationObserver observer(
7418 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
7419 content::NotificationService::AllSources());
7420 service()->CheckForExternalUpdates();
7421 observer.Wait();
7422 EXPECT_FALSE(
7423 service()->external_install_manager()->HasExternalInstallError());
7425 // Another normal extension, but installed externally.
7426 // This SHOULD trigger an alert.
7427 provider->UpdateOrAddExtension(
7428 page_action, "1.0.0.0", data_dir().AppendASCII("page_action.crx"));
7430 content::WindowedNotificationObserver observer2(
7431 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
7432 content::NotificationService::AllSources());
7433 service()->CheckForExternalUpdates();
7434 observer2.Wait();
7435 EXPECT_TRUE(service()->external_install_manager()->HasExternalInstallError());
7438 // Test that external extensions are initially disabled, and that enabling
7439 // them clears the prompt.
7440 TEST_F(ExtensionServiceTest, ExternalInstallInitiallyDisabled) {
7441 FeatureSwitch::ScopedOverride prompt(
7442 FeatureSwitch::prompt_for_external_extensions(), true);
7444 InitializeEmptyExtensionService();
7445 MockExtensionProvider* provider =
7446 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF);
7447 AddMockExternalProvider(provider);
7449 provider->UpdateOrAddExtension(
7450 page_action, "1.0.0.0", data_dir().AppendASCII("page_action.crx"));
7452 content::WindowedNotificationObserver observer(
7453 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
7454 content::NotificationService::AllSources());
7455 service()->CheckForExternalUpdates();
7456 observer.Wait();
7457 EXPECT_TRUE(service()->external_install_manager()->HasExternalInstallError());
7458 EXPECT_FALSE(service()->IsExtensionEnabled(page_action));
7460 const Extension* extension =
7461 registry()->disabled_extensions().GetByID(page_action);
7462 EXPECT_TRUE(extension);
7463 EXPECT_EQ(page_action, extension->id());
7465 service()->EnableExtension(page_action);
7466 EXPECT_FALSE(
7467 service()->external_install_manager()->HasExternalInstallError());
7468 EXPECT_TRUE(service()->IsExtensionEnabled(page_action));
7471 // Test that installing multiple external extensions works.
7472 // Flaky on windows; http://crbug.com/295757 .
7473 #if defined(OS_WIN)
7474 #define MAYBE_ExternalInstallMultiple DISABLED_ExternalInstallMultiple
7475 #else
7476 #define MAYBE_ExternalInstallMultiple ExternalInstallMultiple
7477 #endif
7478 TEST_F(ExtensionServiceTest, MAYBE_ExternalInstallMultiple) {
7479 FeatureSwitch::ScopedOverride prompt(
7480 FeatureSwitch::prompt_for_external_extensions(), true);
7482 InitializeEmptyExtensionService();
7483 MockExtensionProvider* provider =
7484 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF);
7485 AddMockExternalProvider(provider);
7487 provider->UpdateOrAddExtension(
7488 page_action, "1.0.0.0", data_dir().AppendASCII("page_action.crx"));
7489 provider->UpdateOrAddExtension(
7490 good_crx, "1.0.0.0", data_dir().AppendASCII("good.crx"));
7491 provider->UpdateOrAddExtension(
7492 theme_crx, "2.0", data_dir().AppendASCII("theme.crx"));
7494 int count = 3;
7495 content::WindowedNotificationObserver observer(
7496 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
7497 base::Bind(&WaitForCountNotificationsCallback, &count));
7498 service()->CheckForExternalUpdates();
7499 observer.Wait();
7500 EXPECT_TRUE(service()->external_install_manager()->HasExternalInstallError());
7501 EXPECT_FALSE(service()->IsExtensionEnabled(page_action));
7502 EXPECT_FALSE(service()->IsExtensionEnabled(good_crx));
7503 EXPECT_FALSE(service()->IsExtensionEnabled(theme_crx));
7505 service()->EnableExtension(page_action);
7506 EXPECT_TRUE(service()->external_install_manager()->HasExternalInstallError());
7507 EXPECT_FALSE(service()
7508 ->external_install_manager()
7509 ->HasExternalInstallBubbleForTesting());
7511 service()->EnableExtension(theme_crx);
7512 EXPECT_TRUE(service()->external_install_manager()->HasExternalInstallError());
7513 EXPECT_FALSE(service()
7514 ->external_install_manager()
7515 ->HasExternalInstallBubbleForTesting());
7517 service()->EnableExtension(good_crx);
7518 EXPECT_FALSE(
7519 service()->external_install_manager()->HasExternalInstallError());
7520 EXPECT_FALSE(service()
7521 ->external_install_manager()
7522 ->HasExternalInstallBubbleForTesting());
7525 // Test that there is a bubble for external extensions that update
7526 // from the webstore if the profile is not new.
7527 TEST_F(ExtensionServiceTest, ExternalInstallUpdatesFromWebstoreOldProfile) {
7528 FeatureSwitch::ScopedOverride prompt(
7529 FeatureSwitch::prompt_for_external_extensions(), true);
7531 // This sets up the ExtensionPrefs used by our ExtensionService to be
7532 // post-first run.
7533 ExtensionServiceInitParams params = CreateDefaultInitParams();
7534 params.is_first_run = false;
7535 InitializeExtensionService(params);
7537 base::FilePath crx_path = temp_dir().path().AppendASCII("webstore.crx");
7538 PackCRX(data_dir().AppendASCII("update_from_webstore"),
7539 data_dir().AppendASCII("update_from_webstore.pem"),
7540 crx_path);
7542 MockExtensionProvider* provider =
7543 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF);
7544 AddMockExternalProvider(provider);
7545 provider->UpdateOrAddExtension(updates_from_webstore, "1", crx_path);
7547 content::WindowedNotificationObserver observer(
7548 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
7549 content::NotificationService::AllSources());
7550 service()->CheckForExternalUpdates();
7551 observer.Wait();
7552 EXPECT_TRUE(service()->external_install_manager()->HasExternalInstallError());
7553 EXPECT_TRUE(service()
7554 ->external_install_manager()
7555 ->HasExternalInstallBubbleForTesting());
7556 EXPECT_FALSE(service()->IsExtensionEnabled(updates_from_webstore));
7559 // Test that there is no bubble for external extensions if the profile is new.
7560 TEST_F(ExtensionServiceTest, ExternalInstallUpdatesFromWebstoreNewProfile) {
7561 FeatureSwitch::ScopedOverride prompt(
7562 FeatureSwitch::prompt_for_external_extensions(), true);
7564 InitializeEmptyExtensionService();
7566 base::FilePath crx_path = temp_dir().path().AppendASCII("webstore.crx");
7567 PackCRX(data_dir().AppendASCII("update_from_webstore"),
7568 data_dir().AppendASCII("update_from_webstore.pem"),
7569 crx_path);
7571 MockExtensionProvider* provider =
7572 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF);
7573 AddMockExternalProvider(provider);
7574 provider->UpdateOrAddExtension(updates_from_webstore, "1", crx_path);
7576 content::WindowedNotificationObserver observer(
7577 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
7578 content::NotificationService::AllSources());
7579 service()->CheckForExternalUpdates();
7580 observer.Wait();
7581 EXPECT_TRUE(service()->external_install_manager()->HasExternalInstallError());
7582 EXPECT_FALSE(service()
7583 ->external_install_manager()
7584 ->HasExternalInstallBubbleForTesting());
7585 EXPECT_FALSE(service()->IsExtensionEnabled(updates_from_webstore));
7588 // Test that clicking to remove the extension on an external install warning
7589 // uninstalls the extension.
7590 TEST_F(ExtensionServiceTest, ExternalInstallClickToRemove) {
7591 FeatureSwitch::ScopedOverride prompt(
7592 FeatureSwitch::prompt_for_external_extensions(), true);
7594 ExtensionServiceInitParams params = CreateDefaultInitParams();
7595 params.is_first_run = false;
7596 InitializeExtensionService(params);
7598 base::FilePath crx_path = temp_dir().path().AppendASCII("webstore.crx");
7599 PackCRX(data_dir().AppendASCII("update_from_webstore"),
7600 data_dir().AppendASCII("update_from_webstore.pem"),
7601 crx_path);
7603 MockExtensionProvider* provider =
7604 new MockExtensionProvider(service_, Manifest::EXTERNAL_PREF);
7605 AddMockExternalProvider(provider);
7606 provider->UpdateOrAddExtension(updates_from_webstore, "1", crx_path);
7608 content::WindowedNotificationObserver observer(
7609 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
7610 content::NotificationService::AllSources());
7611 service_->CheckForExternalUpdates();
7612 observer.Wait();
7613 EXPECT_TRUE(service_->external_install_manager()->HasExternalInstallError());
7615 // We check both enabled and disabled, since these are "eventually exclusive"
7616 // sets.
7617 EXPECT_TRUE(registry()->disabled_extensions().GetByID(updates_from_webstore));
7618 EXPECT_FALSE(registry()->enabled_extensions().GetByID(updates_from_webstore));
7620 // Click the negative response.
7621 service_->external_install_manager()->error_for_testing()->InstallUIAbort(
7622 true);
7623 // The Extension should be uninstalled.
7624 EXPECT_FALSE(registry()->GetExtensionById(updates_from_webstore,
7625 ExtensionRegistry::EVERYTHING));
7626 // The error should be removed.
7627 EXPECT_FALSE(service_->external_install_manager()->HasExternalInstallError());
7630 // Test that clicking to keep the extension on an external install warning
7631 // re-enables the extension.
7632 TEST_F(ExtensionServiceTest, ExternalInstallClickToKeep) {
7633 FeatureSwitch::ScopedOverride prompt(
7634 FeatureSwitch::prompt_for_external_extensions(), true);
7636 ExtensionServiceInitParams params = CreateDefaultInitParams();
7637 params.is_first_run = false;
7638 InitializeExtensionService(params);
7640 base::FilePath crx_path = temp_dir().path().AppendASCII("webstore.crx");
7641 PackCRX(data_dir().AppendASCII("update_from_webstore"),
7642 data_dir().AppendASCII("update_from_webstore.pem"),
7643 crx_path);
7645 MockExtensionProvider* provider =
7646 new MockExtensionProvider(service_, Manifest::EXTERNAL_PREF);
7647 AddMockExternalProvider(provider);
7648 provider->UpdateOrAddExtension(updates_from_webstore, "1", crx_path);
7650 content::WindowedNotificationObserver observer(
7651 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
7652 content::NotificationService::AllSources());
7653 service_->CheckForExternalUpdates();
7654 observer.Wait();
7655 EXPECT_TRUE(service_->external_install_manager()->HasExternalInstallError());
7657 // We check both enabled and disabled, since these are "eventually exclusive"
7658 // sets.
7659 EXPECT_TRUE(registry()->disabled_extensions().GetByID(updates_from_webstore));
7660 EXPECT_FALSE(registry()->enabled_extensions().GetByID(updates_from_webstore));
7662 // Accept the extension.
7663 service_->external_install_manager()->error_for_testing()->InstallUIProceed();
7665 // It should be enabled again.
7666 EXPECT_TRUE(registry()->enabled_extensions().GetByID(updates_from_webstore));
7667 EXPECT_FALSE(
7668 registry()->disabled_extensions().GetByID(updates_from_webstore));
7670 // The error should be removed.
7671 EXPECT_FALSE(service_->external_install_manager()->HasExternalInstallError());
7674 TEST_F(ExtensionServiceTest, InstallBlacklistedExtension) {
7675 InitializeEmptyExtensionService();
7677 scoped_refptr<Extension> extension = extensions::ExtensionBuilder()
7678 .SetManifest(extensions::DictionaryBuilder()
7679 .Set("name", "extension")
7680 .Set("version", "1.0")
7681 .Set("manifest_version", 2).Build())
7682 .Build();
7683 ASSERT_TRUE(extension.get());
7684 const std::string& id = extension->id();
7686 std::set<std::string> id_set;
7687 id_set.insert(id);
7688 extensions::ExtensionNotificationObserver notifications(
7689 content::NotificationService::AllSources(), id_set);
7691 // Installation should be allowed but the extension should never have been
7692 // loaded and it should be blacklisted in prefs.
7693 service()->OnExtensionInstalled(
7694 extension.get(),
7695 syncer::StringOrdinal(),
7696 (extensions::kInstallFlagIsBlacklistedForMalware |
7697 extensions::kInstallFlagInstallImmediately));
7698 base::RunLoop().RunUntilIdle();
7700 // Extension was installed but not loaded.
7701 EXPECT_TRUE(notifications.CheckNotifications(
7702 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED));
7703 EXPECT_TRUE(service()->GetInstalledExtension(id));
7705 EXPECT_FALSE(registry()->enabled_extensions().Contains(id));
7706 EXPECT_TRUE(registry()->blacklisted_extensions().Contains(id));
7708 EXPECT_TRUE(ExtensionPrefs::Get(profile())->IsExtensionBlacklisted(id));
7709 EXPECT_TRUE(
7710 ExtensionPrefs::Get(profile())->IsBlacklistedExtensionAcknowledged(id));
7713 // Tests a profile being destroyed correctly disables extensions.
7714 TEST_F(ExtensionServiceTest, DestroyingProfileClearsExtensions) {
7715 InitializeEmptyExtensionService();
7717 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
7718 EXPECT_NE(UnloadedExtensionInfo::REASON_PROFILE_SHUTDOWN, unloaded_reason_);
7719 EXPECT_EQ(1u, registry()->enabled_extensions().size());
7720 EXPECT_EQ(0u, registry()->disabled_extensions().size());
7721 EXPECT_EQ(0u, registry()->terminated_extensions().size());
7722 EXPECT_EQ(0u, registry()->blacklisted_extensions().size());
7724 service()->Observe(chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED,
7725 content::Source<Profile>(profile()),
7726 content::NotificationService::NoDetails());
7727 EXPECT_EQ(UnloadedExtensionInfo::REASON_PROFILE_SHUTDOWN, unloaded_reason_);
7728 EXPECT_EQ(0u, registry()->enabled_extensions().size());
7729 EXPECT_EQ(0u, registry()->disabled_extensions().size());
7730 EXPECT_EQ(0u, registry()->terminated_extensions().size());
7731 EXPECT_EQ(0u, registry()->blacklisted_extensions().size());