Rename GetIconID to GetIconId
[chromium-blink-merge.git] / chrome / browser / extensions / extension_service_unittest.cc
blob7984784f90229fb1c1c47c9412510e8989e11a5d
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/location.h"
20 #include "base/memory/scoped_ptr.h"
21 #include "base/memory/weak_ptr.h"
22 #include "base/metrics/field_trial.h"
23 #include "base/prefs/scoped_user_pref_update.h"
24 #include "base/single_thread_task_runner.h"
25 #include "base/stl_util.h"
26 #include "base/strings/pattern.h"
27 #include "base/strings/string16.h"
28 #include "base/strings/string_number_conversions.h"
29 #include "base/strings/string_util.h"
30 #include "base/strings/utf_string_conversions.h"
31 #include "base/test/mock_entropy_provider.h"
32 #include "base/thread_task_runner_handle.h"
33 #include "base/version.h"
34 #include "chrome/browser/browser_process.h"
35 #include "chrome/browser/chrome_notification_types.h"
36 #include "chrome/browser/extensions/blacklist.h"
37 #include "chrome/browser/extensions/chrome_app_sorting.h"
38 #include "chrome/browser/extensions/component_loader.h"
39 #include "chrome/browser/extensions/crx_installer.h"
40 #include "chrome/browser/extensions/default_apps.h"
41 #include "chrome/browser/extensions/extension_creator.h"
42 #include "chrome/browser/extensions/extension_error_reporter.h"
43 #include "chrome/browser/extensions/extension_error_ui.h"
44 #include "chrome/browser/extensions/extension_management_test_util.h"
45 #include "chrome/browser/extensions/extension_notification_observer.h"
46 #include "chrome/browser/extensions/extension_service.h"
47 #include "chrome/browser/extensions/extension_service_test_base.h"
48 #include "chrome/browser/extensions/extension_special_storage_policy.h"
49 #include "chrome/browser/extensions/extension_sync_data.h"
50 #include "chrome/browser/extensions/extension_sync_service.h"
51 #include "chrome/browser/extensions/extension_util.h"
52 #include "chrome/browser/extensions/external_install_error.h"
53 #include "chrome/browser/extensions/external_install_manager.h"
54 #include "chrome/browser/extensions/external_policy_loader.h"
55 #include "chrome/browser/extensions/external_pref_loader.h"
56 #include "chrome/browser/extensions/external_provider_impl.h"
57 #include "chrome/browser/extensions/fake_safe_browsing_database_manager.h"
58 #include "chrome/browser/extensions/installed_loader.h"
59 #include "chrome/browser/extensions/pack_extension_job.h"
60 #include "chrome/browser/extensions/pending_extension_info.h"
61 #include "chrome/browser/extensions/pending_extension_manager.h"
62 #include "chrome/browser/extensions/permissions_updater.h"
63 #include "chrome/browser/extensions/test_blacklist.h"
64 #include "chrome/browser/extensions/test_extension_system.h"
65 #include "chrome/browser/extensions/unpacked_installer.h"
66 #include "chrome/browser/extensions/updater/extension_updater.h"
67 #include "chrome/browser/policy/profile_policy_connector.h"
68 #include "chrome/browser/policy/profile_policy_connector_factory.h"
69 #include "chrome/browser/prefs/pref_service_syncable.h"
70 #include "chrome/browser/sync/profile_sync_service.h"
71 #include "chrome/browser/sync/profile_sync_service_factory.h"
72 #include "chrome/common/chrome_constants.h"
73 #include "chrome/common/chrome_switches.h"
74 #include "chrome/common/extensions/api/plugins/plugins_handler.h"
75 #include "chrome/common/extensions/manifest_handlers/app_launch_info.h"
76 #include "chrome/common/extensions/manifest_handlers/content_scripts_handler.h"
77 #include "chrome/common/extensions/sync_helper.h"
78 #include "chrome/common/pref_names.h"
79 #include "chrome/common/url_constants.h"
80 #include "chrome/test/base/scoped_browser_locale.h"
81 #include "chrome/test/base/testing_pref_service_syncable.h"
82 #include "chrome/test/base/testing_profile.h"
83 #include "components/crx_file/id_util.h"
84 #include "components/pref_registry/pref_registry_syncable.h"
85 #include "content/public/browser/dom_storage_context.h"
86 #include "content/public/browser/gpu_data_manager.h"
87 #include "content/public/browser/indexed_db_context.h"
88 #include "content/public/browser/notification_registrar.h"
89 #include "content/public/browser/notification_service.h"
90 #include "content/public/browser/plugin_service.h"
91 #include "content/public/browser/render_process_host.h"
92 #include "content/public/browser/storage_partition.h"
93 #include "content/public/common/content_constants.h"
94 #include "content/public/test/test_browser_thread_bundle.h"
95 #include "content/public/test/test_utils.h"
96 #include "extensions/browser/extension_dialog_auto_confirm.h"
97 #include "extensions/browser/extension_prefs.h"
98 #include "extensions/browser/extension_registry.h"
99 #include "extensions/browser/extension_system.h"
100 #include "extensions/browser/external_provider_interface.h"
101 #include "extensions/browser/install_flag.h"
102 #include "extensions/browser/management_policy.h"
103 #include "extensions/browser/test_management_policy.h"
104 #include "extensions/browser/uninstall_reason.h"
105 #include "extensions/common/constants.h"
106 #include "extensions/common/extension.h"
107 #include "extensions/common/extension_builder.h"
108 #include "extensions/common/extension_l10n_util.h"
109 #include "extensions/common/extension_resource.h"
110 #include "extensions/common/feature_switch.h"
111 #include "extensions/common/manifest_constants.h"
112 #include "extensions/common/manifest_handlers/background_info.h"
113 #include "extensions/common/manifest_handlers/permissions_parser.h"
114 #include "extensions/common/manifest_url_handlers.h"
115 #include "extensions/common/permissions/permission_set.h"
116 #include "extensions/common/permissions/permissions_data.h"
117 #include "extensions/common/switches.h"
118 #include "extensions/common/url_pattern.h"
119 #include "extensions/common/value_builder.h"
120 #include "gpu/config/gpu_info.h"
121 #include "grit/browser_resources.h"
122 #include "grit/generated_resources.h"
123 #include "net/cookies/canonical_cookie.h"
124 #include "net/cookies/cookie_monster.h"
125 #include "net/cookies/cookie_options.h"
126 #include "net/url_request/url_request_context.h"
127 #include "net/url_request/url_request_context_getter.h"
128 #include "storage/browser/database/database_tracker.h"
129 #include "storage/browser/quota/quota_manager.h"
130 #include "storage/common/database/database_identifier.h"
131 #include "sync/api/fake_sync_change_processor.h"
132 #include "sync/api/string_ordinal.h"
133 #include "sync/api/sync_data.h"
134 #include "sync/api/sync_error_factory.h"
135 #include "sync/api/sync_error_factory_mock.h"
136 #include "sync/api/syncable_service.h"
137 #include "sync/protocol/app_specifics.pb.h"
138 #include "sync/protocol/extension_specifics.pb.h"
139 #include "sync/protocol/sync.pb.h"
140 #include "testing/gtest/include/gtest/gtest.h"
141 #include "testing/platform_test.h"
142 #include "ui/base/l10n/l10n_util.h"
143 #include "url/gurl.h"
145 #if defined(ENABLE_SUPERVISED_USERS)
146 #include "chrome/browser/supervised_user/permission_request_creator.h"
147 #include "chrome/browser/supervised_user/supervised_user_constants.h"
148 #include "chrome/browser/supervised_user/supervised_user_service.h"
149 #include "chrome/browser/supervised_user/supervised_user_service_factory.h"
150 #endif
152 #if defined(OS_CHROMEOS)
153 #include "chrome/browser/chromeos/login/users/scoped_test_user_manager.h"
154 #include "chrome/browser/chromeos/settings/cros_settings.h"
155 #include "chrome/browser/chromeos/settings/device_settings_service.h"
156 #endif
158 // The blacklist tests rely on the safe-browsing database.
159 #if defined(SAFE_BROWSING_DB_LOCAL)
160 #define ENABLE_BLACKLIST_TESTS
161 #endif
163 using base::DictionaryValue;
164 using base::ListValue;
165 using base::Value;
166 using content::BrowserContext;
167 using content::BrowserThread;
168 using content::DOMStorageContext;
169 using content::IndexedDBContext;
170 using content::PluginService;
171 using extensions::APIPermission;
172 using extensions::APIPermissionSet;
173 using extensions::AppSorting;
174 using extensions::Blacklist;
175 using extensions::CrxInstaller;
176 using extensions::Extension;
177 using extensions::ExtensionCreator;
178 using extensions::ExtensionPrefs;
179 using extensions::ExtensionRegistry;
180 using extensions::ExtensionResource;
181 using extensions::ExtensionSyncData;
182 using extensions::ExtensionSystem;
183 using extensions::FakeSafeBrowsingDatabaseManager;
184 using extensions::FeatureSwitch;
185 using extensions::Manifest;
186 using extensions::PermissionSet;
187 using extensions::TestExtensionSystem;
188 using extensions::UnloadedExtensionInfo;
189 using extensions::URLPatternSet;
191 namespace keys = extensions::manifest_keys;
193 namespace {
195 // Extension ids used during testing.
196 const char good0[] = "behllobkkfkfnphdnhnkndlbkcpglgmj";
197 const char good1[] = "hpiknbiabeeppbpihjehijgoemciehgk";
198 const char good2[] = "bjafgdebaacbbbecmhlhpofkepfkgcpa";
199 const char all_zero[] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
200 const char good2048[] = "nmgjhmhbleinmjpbdhgajfjkbijcmgbh";
201 const char good_crx[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
202 const char hosted_app[] = "kbmnembihfiondgfjekmnmcbddelicoi";
203 const char page_action[] = "obcimlgaoabeegjmmpldobjndiealpln";
204 const char theme_crx[] = "iamefpfkojoapidjnbafmgkgncegbkad";
205 const char theme2_crx[] = "pjpgmfcmabopnnfonnhmdjglfpjjfkbf";
206 const char permissions_crx[] = "eagpmdpfmaekmmcejjbmjoecnejeiiin";
207 const char updates_from_webstore[] = "akjooamlhcgeopfifcmlggaebeocgokj";
208 const char permissions_blocklist[] = "noffkehfcaggllbcojjbopcmlhcnhcdn";
210 struct ExtensionsOrder {
211 bool operator()(const scoped_refptr<const Extension>& a,
212 const scoped_refptr<const Extension>& b) {
213 return a->name() < b->name();
217 static std::vector<base::string16> GetErrors() {
218 const std::vector<base::string16>* errors =
219 ExtensionErrorReporter::GetInstance()->GetErrors();
220 std::vector<base::string16> ret_val;
222 for (std::vector<base::string16>::const_iterator iter = errors->begin();
223 iter != errors->end(); ++iter) {
224 std::string utf8_error = base::UTF16ToUTF8(*iter);
225 if (utf8_error.find(".svn") == std::string::npos) {
226 ret_val.push_back(*iter);
230 // The tests rely on the errors being in a certain order, which can vary
231 // depending on how filesystem iteration works.
232 std::stable_sort(ret_val.begin(), ret_val.end());
234 return ret_val;
237 static void AddPattern(URLPatternSet* extent, const std::string& pattern) {
238 int schemes = URLPattern::SCHEME_ALL;
239 extent->AddPattern(URLPattern(schemes, pattern));
242 base::FilePath GetTemporaryFile() {
243 base::FilePath temp_file;
244 CHECK(base::CreateTemporaryFile(&temp_file));
245 return temp_file;
248 bool WaitForCountNotificationsCallback(int *count) {
249 return --(*count) == 0;
252 } // namespace
254 class MockExtensionProvider : public extensions::ExternalProviderInterface {
255 public:
256 MockExtensionProvider(
257 VisitorInterface* visitor,
258 Manifest::Location location)
259 : location_(location), visitor_(visitor), visit_count_(0) {
262 ~MockExtensionProvider() override {}
264 void UpdateOrAddExtension(const std::string& id,
265 const std::string& version,
266 const base::FilePath& path) {
267 extension_map_[id] = std::make_pair(version, path);
270 void RemoveExtension(const std::string& id) {
271 extension_map_.erase(id);
274 // ExternalProvider implementation:
275 void VisitRegisteredExtension() override {
276 visit_count_++;
277 for (DataMap::const_iterator i = extension_map_.begin();
278 i != extension_map_.end(); ++i) {
279 Version version(i->second.first);
281 visitor_->OnExternalExtensionFileFound(
282 i->first, &version, i->second.second, location_,
283 Extension::NO_FLAGS, false, false);
285 visitor_->OnExternalProviderReady(this);
288 bool HasExtension(const std::string& id) const override {
289 return extension_map_.find(id) != extension_map_.end();
292 bool GetExtensionDetails(const std::string& id,
293 Manifest::Location* location,
294 scoped_ptr<Version>* version) const override {
295 DataMap::const_iterator it = extension_map_.find(id);
296 if (it == extension_map_.end())
297 return false;
299 if (version)
300 version->reset(new Version(it->second.first));
302 if (location)
303 *location = location_;
305 return true;
308 bool IsReady() const override { return true; }
310 void ServiceShutdown() override {}
312 int visit_count() const { return visit_count_; }
313 void set_visit_count(int visit_count) {
314 visit_count_ = visit_count;
317 private:
318 typedef std::map< std::string, std::pair<std::string, base::FilePath> >
319 DataMap;
320 DataMap extension_map_;
321 Manifest::Location location_;
322 VisitorInterface* visitor_;
324 // visit_count_ tracks the number of calls to VisitRegisteredExtension().
325 // Mutable because it must be incremented on each call to
326 // VisitRegisteredExtension(), which must be a const method to inherit
327 // from the class being mocked.
328 mutable int visit_count_;
330 DISALLOW_COPY_AND_ASSIGN(MockExtensionProvider);
333 class MockProviderVisitor
334 : public extensions::ExternalProviderInterface::VisitorInterface {
335 public:
336 // The provider will return |fake_base_path| from
337 // GetBaseCrxFilePath(). User can test the behavior with
338 // and without an empty path using this parameter.
339 explicit MockProviderVisitor(base::FilePath fake_base_path)
340 : ids_found_(0),
341 fake_base_path_(fake_base_path),
342 expected_creation_flags_(Extension::NO_FLAGS) {
343 profile_.reset(new TestingProfile);
346 MockProviderVisitor(base::FilePath fake_base_path,
347 int expected_creation_flags)
348 : ids_found_(0),
349 fake_base_path_(fake_base_path),
350 expected_creation_flags_(expected_creation_flags) {
351 profile_.reset(new TestingProfile);
354 int Visit(const std::string& json_data) {
355 // Give the test json file to the provider for parsing.
356 provider_.reset(new extensions::ExternalProviderImpl(
357 this,
358 new extensions::ExternalTestingLoader(json_data, fake_base_path_),
359 profile_.get(),
360 Manifest::EXTERNAL_PREF,
361 Manifest::EXTERNAL_PREF_DOWNLOAD,
362 Extension::NO_FLAGS));
364 // We also parse the file into a dictionary to compare what we get back
365 // from the provider.
366 JSONStringValueDeserializer deserializer(json_data);
367 base::Value* json_value = deserializer.Deserialize(NULL, NULL);
369 if (!json_value || !json_value->IsType(base::Value::TYPE_DICTIONARY)) {
370 NOTREACHED() << "Unable to deserialize json data";
371 return -1;
372 } else {
373 base::DictionaryValue* external_extensions =
374 static_cast<base::DictionaryValue*>(json_value);
375 prefs_.reset(external_extensions);
378 // Reset our counter.
379 ids_found_ = 0;
380 // Ask the provider to look up all extensions and return them.
381 provider_->VisitRegisteredExtension();
383 return ids_found_;
386 bool OnExternalExtensionFileFound(const std::string& id,
387 const Version* version,
388 const base::FilePath& path,
389 Manifest::Location unused,
390 int creation_flags,
391 bool mark_acknowledged,
392 bool install_immediately) override {
393 EXPECT_EQ(expected_creation_flags_, creation_flags);
395 ++ids_found_;
396 base::DictionaryValue* pref;
397 // This tests is to make sure that the provider only notifies us of the
398 // values we gave it. So if the id we doesn't exist in our internal
399 // dictionary then something is wrong.
400 EXPECT_TRUE(prefs_->GetDictionary(id, &pref))
401 << "Got back ID (" << id.c_str() << ") we weren't expecting";
403 EXPECT_TRUE(path.IsAbsolute());
404 if (!fake_base_path_.empty())
405 EXPECT_TRUE(fake_base_path_.IsParent(path));
407 if (pref) {
408 EXPECT_TRUE(provider_->HasExtension(id));
410 // Ask provider if the extension we got back is registered.
411 Manifest::Location location = Manifest::INVALID_LOCATION;
412 scoped_ptr<Version> v1;
413 base::FilePath crx_path;
415 EXPECT_TRUE(provider_->GetExtensionDetails(id, NULL, &v1));
416 EXPECT_STREQ(version->GetString().c_str(), v1->GetString().c_str());
418 scoped_ptr<Version> v2;
419 EXPECT_TRUE(provider_->GetExtensionDetails(id, &location, &v2));
420 EXPECT_STREQ(version->GetString().c_str(), v1->GetString().c_str());
421 EXPECT_STREQ(version->GetString().c_str(), v2->GetString().c_str());
422 EXPECT_EQ(Manifest::EXTERNAL_PREF, location);
424 // Remove it so we won't count it ever again.
425 prefs_->Remove(id, NULL);
427 return true;
430 bool OnExternalExtensionUpdateUrlFound(const std::string& id,
431 const std::string& install_parameter,
432 const GURL& update_url,
433 Manifest::Location location,
434 int creation_flags,
435 bool mark_acknowledged) override {
436 ++ids_found_;
437 base::DictionaryValue* pref;
438 // This tests is to make sure that the provider only notifies us of the
439 // values we gave it. So if the id we doesn't exist in our internal
440 // dictionary then something is wrong.
441 EXPECT_TRUE(prefs_->GetDictionary(id, &pref))
442 << L"Got back ID (" << id.c_str() << ") we weren't expecting";
443 EXPECT_EQ(Manifest::EXTERNAL_PREF_DOWNLOAD, location);
445 if (pref) {
446 EXPECT_TRUE(provider_->HasExtension(id));
448 // External extensions with update URLs do not have versions.
449 scoped_ptr<Version> v1;
450 Manifest::Location location1 = Manifest::INVALID_LOCATION;
451 EXPECT_TRUE(provider_->GetExtensionDetails(id, &location1, &v1));
452 EXPECT_FALSE(v1.get());
453 EXPECT_EQ(Manifest::EXTERNAL_PREF_DOWNLOAD, location1);
455 std::string parsed_install_parameter;
456 pref->GetString("install_parameter", &parsed_install_parameter);
457 EXPECT_EQ(parsed_install_parameter, install_parameter);
459 // Remove it so we won't count it again.
460 prefs_->Remove(id, NULL);
462 return true;
465 void OnExternalProviderReady(
466 const extensions::ExternalProviderInterface* provider) override {
467 EXPECT_EQ(provider, provider_.get());
468 EXPECT_TRUE(provider->IsReady());
471 Profile* profile() { return profile_.get(); }
473 private:
474 int ids_found_;
475 base::FilePath fake_base_path_;
476 int expected_creation_flags_;
477 scoped_ptr<extensions::ExternalProviderImpl> provider_;
478 scoped_ptr<base::DictionaryValue> prefs_;
479 scoped_ptr<TestingProfile> profile_;
481 DISALLOW_COPY_AND_ASSIGN(MockProviderVisitor);
484 class ExtensionServiceTest : public extensions::ExtensionServiceTestBase,
485 public content::NotificationObserver {
486 public:
487 ExtensionServiceTest()
488 : unloaded_reason_(UnloadedExtensionInfo::REASON_UNDEFINED),
489 installed_(NULL),
490 was_update_(false),
491 override_external_install_prompt_(
492 FeatureSwitch::prompt_for_external_extensions(),
493 false),
494 expected_extensions_count_(0) {
495 registrar_.Add(this,
496 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
497 content::NotificationService::AllSources());
498 registrar_.Add(this,
499 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
500 content::NotificationService::AllSources());
501 registrar_.Add(
502 this,
503 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
504 content::NotificationService::AllSources());
507 void Observe(int type,
508 const content::NotificationSource& source,
509 const content::NotificationDetails& details) override {
510 switch (type) {
511 case extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED: {
512 const Extension* extension =
513 content::Details<const Extension>(details).ptr();
514 loaded_.push_back(make_scoped_refptr(extension));
515 // The tests rely on the errors being in a certain order, which can vary
516 // depending on how filesystem iteration works.
517 std::stable_sort(loaded_.begin(), loaded_.end(), ExtensionsOrder());
518 break;
521 case extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED: {
522 UnloadedExtensionInfo* unloaded_info =
523 content::Details<UnloadedExtensionInfo>(details).ptr();
524 const Extension* e = unloaded_info->extension;
525 unloaded_id_ = e->id();
526 unloaded_reason_ = unloaded_info->reason;
527 extensions::ExtensionList::iterator i =
528 std::find(loaded_.begin(), loaded_.end(), e);
529 // TODO(erikkay) fix so this can be an assert. Right now the tests
530 // are manually calling clear() on loaded_, so this isn't doable.
531 if (i == loaded_.end())
532 return;
533 loaded_.erase(i);
534 break;
536 case extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED: {
537 const extensions::InstalledExtensionInfo* installed_info =
538 content::Details<const extensions::InstalledExtensionInfo>(details)
539 .ptr();
540 installed_ = installed_info->extension;
541 was_update_ = installed_info->is_update;
542 old_name_ = installed_info->old_name;
543 break;
546 default:
547 DCHECK(false);
551 void AddMockExternalProvider(
552 extensions::ExternalProviderInterface* provider) {
553 service()->AddProviderForTesting(provider);
556 void MockSyncStartFlare(bool* was_called,
557 syncer::ModelType* model_type_passed_in,
558 syncer::ModelType model_type) {
559 *was_called = true;
560 *model_type_passed_in = model_type;
563 protected:
564 // Paths to some of the fake extensions.
565 base::FilePath good0_path() {
566 return data_dir()
567 .AppendASCII("good")
568 .AppendASCII("Extensions")
569 .AppendASCII(good0)
570 .AppendASCII("1.0.0.0");
573 base::FilePath good1_path() {
574 return data_dir()
575 .AppendASCII("good")
576 .AppendASCII("Extensions")
577 .AppendASCII(good1)
578 .AppendASCII("2");
581 base::FilePath good2_path() {
582 return data_dir()
583 .AppendASCII("good")
584 .AppendASCII("Extensions")
585 .AppendASCII(good2)
586 .AppendASCII("1.0");
589 void TestExternalProvider(MockExtensionProvider* provider,
590 Manifest::Location location);
592 void PackCRX(const base::FilePath& dir_path,
593 const base::FilePath& pem_path,
594 const base::FilePath& crx_path) {
595 // Use the existing pem key, if provided.
596 base::FilePath pem_output_path;
597 if (pem_path.value().empty()) {
598 pem_output_path = crx_path.DirName().AppendASCII("temp.pem");
599 } else {
600 ASSERT_TRUE(base::PathExists(pem_path));
603 ASSERT_TRUE(base::DeleteFile(crx_path, false));
605 scoped_ptr<ExtensionCreator> creator(new ExtensionCreator());
606 ASSERT_TRUE(creator->Run(dir_path,
607 crx_path,
608 pem_path,
609 pem_output_path,
610 ExtensionCreator::kOverwriteCRX));
612 ASSERT_TRUE(base::PathExists(crx_path));
615 enum InstallState {
616 INSTALL_FAILED,
617 INSTALL_UPDATED,
618 INSTALL_NEW,
619 INSTALL_WITHOUT_LOAD,
622 const Extension* PackAndInstallCRX(const base::FilePath& dir_path,
623 const base::FilePath& pem_path,
624 InstallState install_state,
625 int creation_flags) {
626 base::FilePath crx_path;
627 base::ScopedTempDir temp_dir;
628 EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
629 crx_path = temp_dir.path().AppendASCII("temp.crx");
631 PackCRX(dir_path, pem_path, crx_path);
632 return InstallCRX(crx_path, install_state, creation_flags);
635 const Extension* PackAndInstallCRX(const base::FilePath& dir_path,
636 const base::FilePath& pem_path,
637 InstallState install_state) {
638 return PackAndInstallCRX(dir_path, pem_path, install_state,
639 Extension::NO_FLAGS);
642 const Extension* PackAndInstallCRX(const base::FilePath& dir_path,
643 InstallState install_state) {
644 return PackAndInstallCRX(dir_path, base::FilePath(), install_state,
645 Extension::NO_FLAGS);
648 // Attempts to install an extension. Use INSTALL_FAILED if the installation
649 // is expected to fail.
650 // If |install_state| is INSTALL_UPDATED, and |expected_old_name| is
651 // non-empty, expects that the existing extension's title was
652 // |expected_old_name|.
653 const Extension* InstallCRX(const base::FilePath& path,
654 InstallState install_state,
655 int creation_flags,
656 const std::string& expected_old_name) {
657 InstallCRXInternal(path, creation_flags);
658 return VerifyCrxInstall(path, install_state, expected_old_name);
661 // Attempts to install an extension. Use INSTALL_FAILED if the installation
662 // is expected to fail.
663 const Extension* InstallCRX(const base::FilePath& path,
664 InstallState install_state,
665 int creation_flags) {
666 return InstallCRX(path, install_state, creation_flags, std::string());
669 // Attempts to install an extension. Use INSTALL_FAILED if the installation
670 // is expected to fail.
671 const Extension* InstallCRX(const base::FilePath& path,
672 InstallState install_state) {
673 return InstallCRX(path, install_state, Extension::NO_FLAGS);
676 const Extension* InstallCRXFromWebStore(const base::FilePath& path,
677 InstallState install_state) {
678 InstallCRXInternal(path, Extension::FROM_WEBSTORE);
679 return VerifyCrxInstall(path, install_state);
682 const Extension* InstallCRXWithLocation(const base::FilePath& crx_path,
683 Manifest::Location install_location,
684 InstallState install_state) {
685 EXPECT_TRUE(base::PathExists(crx_path))
686 << "Path does not exist: "<< crx_path.value().c_str();
687 // no client (silent install)
688 scoped_refptr<CrxInstaller> installer(
689 CrxInstaller::CreateSilent(service()));
690 installer->set_install_source(install_location);
692 content::WindowedNotificationObserver observer(
693 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
694 content::NotificationService::AllSources());
695 installer->InstallCrx(crx_path);
696 observer.Wait();
698 return VerifyCrxInstall(crx_path, install_state);
701 // Verifies the result of a CRX installation. Used by InstallCRX. Set the
702 // |install_state| to INSTALL_FAILED if the installation is expected to fail.
703 // Returns an Extension pointer if the install succeeded, NULL otherwise.
704 const Extension* VerifyCrxInstall(const base::FilePath& path,
705 InstallState install_state) {
706 return VerifyCrxInstall(path, install_state, std::string());
709 // Verifies the result of a CRX installation. Used by InstallCRX. Set the
710 // |install_state| to INSTALL_FAILED if the installation is expected to fail.
711 // If |install_state| is INSTALL_UPDATED, and |expected_old_name| is
712 // non-empty, expects that the existing extension's title was
713 // |expected_old_name|.
714 // Returns an Extension pointer if the install succeeded, NULL otherwise.
715 const Extension* VerifyCrxInstall(const base::FilePath& path,
716 InstallState install_state,
717 const std::string& expected_old_name) {
718 std::vector<base::string16> errors = GetErrors();
719 const Extension* extension = NULL;
720 if (install_state != INSTALL_FAILED) {
721 if (install_state == INSTALL_NEW)
722 ++expected_extensions_count_;
724 EXPECT_TRUE(installed_) << path.value();
725 // If and only if INSTALL_UPDATED, it should have the is_update flag.
726 EXPECT_EQ(install_state == INSTALL_UPDATED, was_update_)
727 << path.value();
728 // If INSTALL_UPDATED, old_name_ should match the given string.
729 if (install_state == INSTALL_UPDATED && !expected_old_name.empty())
730 EXPECT_EQ(expected_old_name, old_name_);
731 EXPECT_EQ(0u, errors.size()) << path.value();
733 if (install_state == INSTALL_WITHOUT_LOAD) {
734 EXPECT_EQ(0u, loaded_.size()) << path.value();
735 } else {
736 EXPECT_EQ(1u, loaded_.size()) << path.value();
737 size_t actual_extension_count =
738 registry()->enabled_extensions().size() +
739 registry()->disabled_extensions().size();
740 EXPECT_EQ(expected_extensions_count_, actual_extension_count) <<
741 path.value();
742 extension = loaded_[0].get();
743 EXPECT_TRUE(service()->GetExtensionById(extension->id(), false))
744 << path.value();
747 for (std::vector<base::string16>::iterator err = errors.begin();
748 err != errors.end(); ++err) {
749 LOG(ERROR) << *err;
751 } else {
752 EXPECT_FALSE(installed_) << path.value();
753 EXPECT_EQ(0u, loaded_.size()) << path.value();
754 EXPECT_EQ(1u, errors.size()) << path.value();
757 installed_ = NULL;
758 was_update_ = false;
759 old_name_ = "";
760 loaded_.clear();
761 ExtensionErrorReporter::GetInstance()->ClearErrors();
762 return extension;
765 enum UpdateState {
766 FAILED_SILENTLY,
767 FAILED,
768 UPDATED,
769 INSTALLED,
770 DISABLED,
771 ENABLED
774 void BlackListWebGL() {
775 static const std::string json_blacklist =
776 "{\n"
777 " \"name\": \"gpu blacklist\",\n"
778 " \"version\": \"1.0\",\n"
779 " \"entries\": [\n"
780 " {\n"
781 " \"id\": 1,\n"
782 " \"features\": [\"webgl\"]\n"
783 " }\n"
784 " ]\n"
785 "}";
786 gpu::GPUInfo gpu_info;
787 content::GpuDataManager::GetInstance()->InitializeForTesting(
788 json_blacklist, gpu_info);
791 // Grants all optional permissions stated in manifest to active permission
792 // set for extension |id|.
793 void GrantAllOptionalPermissions(const std::string& id) {
794 const Extension* extension = service()->GetInstalledExtension(id);
795 scoped_refptr<const PermissionSet> all_optional_permissions =
796 extensions::PermissionsParser::GetOptionalPermissions(extension);
797 extensions::PermissionsUpdater perms_updater(profile());
798 perms_updater.AddPermissions(extension, all_optional_permissions.get());
801 // Helper method to set up a WindowedNotificationObserver to wait for a
802 // specific CrxInstaller to finish if we don't know the value of the
803 // |installer| yet.
804 static bool IsCrxInstallerDone(extensions::CrxInstaller** installer,
805 const content::NotificationSource& source,
806 const content::NotificationDetails& details) {
807 return content::Source<extensions::CrxInstaller>(source).ptr() ==
808 *installer;
811 void PackCRXAndUpdateExtension(const std::string& id,
812 const base::FilePath& dir_path,
813 const base::FilePath& pem_path,
814 UpdateState expected_state) {
815 base::ScopedTempDir temp_dir;
816 EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
817 base::FilePath crx_path = temp_dir.path().AppendASCII("temp.crx");
819 PackCRX(dir_path, pem_path, crx_path);
820 UpdateExtension(id, crx_path, expected_state);
823 void UpdateExtension(const std::string& id,
824 const base::FilePath& in_path,
825 UpdateState expected_state) {
826 ASSERT_TRUE(base::PathExists(in_path));
828 // We need to copy this to a temporary location because Update() will delete
829 // it.
830 base::FilePath path = temp_dir().path();
831 path = path.Append(in_path.BaseName());
832 ASSERT_TRUE(base::CopyFile(in_path, path));
834 int previous_enabled_extension_count =
835 registry()->enabled_extensions().size();
836 int previous_installed_extension_count =
837 previous_enabled_extension_count +
838 registry()->disabled_extensions().size();
840 extensions::CrxInstaller* installer = NULL;
841 content::WindowedNotificationObserver observer(
842 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
843 base::Bind(&IsCrxInstallerDone, &installer));
844 service()->UpdateExtension(extensions::CRXFileInfo(id, path), true,
845 &installer);
847 if (installer)
848 observer.Wait();
849 else
850 base::RunLoop().RunUntilIdle();
852 std::vector<base::string16> errors = GetErrors();
853 int error_count = errors.size();
854 int enabled_extension_count = registry()->enabled_extensions().size();
855 int installed_extension_count =
856 enabled_extension_count + registry()->disabled_extensions().size();
858 int expected_error_count = (expected_state == FAILED) ? 1 : 0;
859 EXPECT_EQ(expected_error_count, error_count) << path.value();
861 if (expected_state <= FAILED) {
862 EXPECT_EQ(previous_enabled_extension_count,
863 enabled_extension_count);
864 EXPECT_EQ(previous_installed_extension_count,
865 installed_extension_count);
866 } else {
867 int expected_installed_extension_count =
868 (expected_state >= INSTALLED) ? 1 : 0;
869 int expected_enabled_extension_count =
870 (expected_state >= ENABLED) ? 1 : 0;
871 EXPECT_EQ(expected_installed_extension_count,
872 installed_extension_count);
873 EXPECT_EQ(expected_enabled_extension_count,
874 enabled_extension_count);
877 // Update() should the temporary input file.
878 EXPECT_FALSE(base::PathExists(path));
881 void TerminateExtension(const std::string& id) {
882 const Extension* extension = service()->GetInstalledExtension(id);
883 if (!extension) {
884 ADD_FAILURE();
885 return;
887 service()->TrackTerminatedExtensionForTest(extension);
890 testing::AssertionResult IsBlocked(const std::string& id) {
891 scoped_ptr<extensions::ExtensionSet> all_unblocked_extensions =
892 registry()->GenerateInstalledExtensionsSet(
893 ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::BLOCKED);
894 if (all_unblocked_extensions.get()->Contains(id))
895 return testing::AssertionFailure() << id << " is still unblocked!";
896 if (!registry()->blocked_extensions().Contains(id))
897 return testing::AssertionFailure() << id << " is not blocked!";
898 return testing::AssertionSuccess();
901 // Helper method to test that an extension moves through being blocked and
902 // unblocked as appropriate for its type.
903 void AssertExtensionBlocksAndUnblocks(
904 bool should_block, const std::string extension_id) {
905 // Assume we start in an unblocked state.
906 EXPECT_FALSE(IsBlocked(extension_id));
908 // Block the extensions.
909 service()->BlockAllExtensions();
910 base::RunLoop().RunUntilIdle();
912 if (should_block)
913 ASSERT_TRUE(IsBlocked(extension_id));
914 else
915 ASSERT_FALSE(IsBlocked(extension_id));
917 service()->UnblockAllExtensions();
918 base::RunLoop().RunUntilIdle();
920 ASSERT_FALSE(IsBlocked(extension_id));
923 size_t GetPrefKeyCount() {
924 const base::DictionaryValue* dict =
925 profile()->GetPrefs()->GetDictionary("extensions.settings");
926 if (!dict) {
927 ADD_FAILURE();
928 return 0;
930 return dict->size();
933 void UninstallExtension(const std::string& id, bool use_helper) {
934 UninstallExtension(id, use_helper, Extension::ENABLED);
937 void UninstallExtension(const std::string& id, bool use_helper,
938 Extension::State expected_state) {
939 // Verify that the extension is installed.
940 base::FilePath extension_path = extensions_install_dir().AppendASCII(id);
941 EXPECT_TRUE(base::PathExists(extension_path));
942 size_t pref_key_count = GetPrefKeyCount();
943 EXPECT_GT(pref_key_count, 0u);
944 ValidateIntegerPref(id, "state", expected_state);
946 // Uninstall it.
947 if (use_helper) {
948 EXPECT_TRUE(ExtensionService::UninstallExtensionHelper(
949 service(), id, extensions::UNINSTALL_REASON_FOR_TESTING));
950 } else {
951 EXPECT_TRUE(service()->UninstallExtension(
953 extensions::UNINSTALL_REASON_FOR_TESTING,
954 base::Bind(&base::DoNothing),
955 NULL));
957 --expected_extensions_count_;
959 // We should get an unload notification.
960 EXPECT_FALSE(unloaded_id_.empty());
961 EXPECT_EQ(id, unloaded_id_);
963 // Verify uninstalled state.
964 size_t new_pref_key_count = GetPrefKeyCount();
965 if (new_pref_key_count == pref_key_count) {
966 ValidateIntegerPref(id, "state",
967 Extension::EXTERNAL_EXTENSION_UNINSTALLED);
968 } else {
969 EXPECT_EQ(new_pref_key_count, pref_key_count - 1);
972 // The extension should not be in the service anymore.
973 EXPECT_FALSE(service()->GetInstalledExtension(id));
974 base::RunLoop().RunUntilIdle();
976 // The directory should be gone.
977 EXPECT_FALSE(base::PathExists(extension_path));
980 void ValidatePrefKeyCount(size_t count) {
981 EXPECT_EQ(count, GetPrefKeyCount());
984 testing::AssertionResult ValidateBooleanPref(
985 const std::string& extension_id,
986 const std::string& pref_path,
987 bool expected_val) {
988 std::string msg = "while checking: ";
989 msg += extension_id;
990 msg += " ";
991 msg += pref_path;
992 msg += " == ";
993 msg += expected_val ? "true" : "false";
995 PrefService* prefs = profile()->GetPrefs();
996 const base::DictionaryValue* dict =
997 prefs->GetDictionary("extensions.settings");
998 if (!dict) {
999 return testing::AssertionFailure()
1000 << "extension.settings does not exist " << msg;
1003 const base::DictionaryValue* pref = NULL;
1004 if (!dict->GetDictionary(extension_id, &pref)) {
1005 return testing::AssertionFailure()
1006 << "extension pref does not exist " << msg;
1009 bool val;
1010 if (!pref->GetBoolean(pref_path, &val)) {
1011 return testing::AssertionFailure()
1012 << pref_path << " pref not found " << msg;
1015 return expected_val == val
1016 ? testing::AssertionSuccess()
1017 : testing::AssertionFailure() << "base::Value is incorrect " << msg;
1020 bool IsPrefExist(const std::string& extension_id,
1021 const std::string& pref_path) {
1022 const base::DictionaryValue* dict =
1023 profile()->GetPrefs()->GetDictionary("extensions.settings");
1024 if (dict == NULL) return false;
1025 const base::DictionaryValue* pref = NULL;
1026 if (!dict->GetDictionary(extension_id, &pref)) {
1027 return false;
1029 if (pref == NULL) {
1030 return false;
1032 bool val;
1033 if (!pref->GetBoolean(pref_path, &val)) {
1034 return false;
1036 return true;
1039 void ValidateIntegerPref(const std::string& extension_id,
1040 const std::string& pref_path,
1041 int expected_val) {
1042 std::string msg = " while checking: ";
1043 msg += extension_id;
1044 msg += " ";
1045 msg += pref_path;
1046 msg += " == ";
1047 msg += base::IntToString(expected_val);
1049 PrefService* prefs = profile()->GetPrefs();
1050 const base::DictionaryValue* dict =
1051 prefs->GetDictionary("extensions.settings");
1052 ASSERT_TRUE(dict != NULL) << msg;
1053 const base::DictionaryValue* pref = NULL;
1054 ASSERT_TRUE(dict->GetDictionary(extension_id, &pref)) << msg;
1055 EXPECT_TRUE(pref != NULL) << msg;
1056 int val;
1057 ASSERT_TRUE(pref->GetInteger(pref_path, &val)) << msg;
1058 EXPECT_EQ(expected_val, val) << msg;
1061 void ValidateStringPref(const std::string& extension_id,
1062 const std::string& pref_path,
1063 const std::string& expected_val) {
1064 std::string msg = " while checking: ";
1065 msg += extension_id;
1066 msg += ".manifest.";
1067 msg += pref_path;
1068 msg += " == ";
1069 msg += expected_val;
1071 const base::DictionaryValue* dict =
1072 profile()->GetPrefs()->GetDictionary("extensions.settings");
1073 ASSERT_TRUE(dict != NULL) << msg;
1074 const base::DictionaryValue* pref = NULL;
1075 std::string manifest_path = extension_id + ".manifest";
1076 ASSERT_TRUE(dict->GetDictionary(manifest_path, &pref)) << msg;
1077 EXPECT_TRUE(pref != NULL) << msg;
1078 std::string val;
1079 ASSERT_TRUE(pref->GetString(pref_path, &val)) << msg;
1080 EXPECT_EQ(expected_val, val) << msg;
1083 void SetPref(const std::string& extension_id,
1084 const std::string& pref_path,
1085 base::Value* value,
1086 const std::string& msg) {
1087 DictionaryPrefUpdate update(profile()->GetPrefs(), "extensions.settings");
1088 base::DictionaryValue* dict = update.Get();
1089 ASSERT_TRUE(dict != NULL) << msg;
1090 base::DictionaryValue* pref = NULL;
1091 ASSERT_TRUE(dict->GetDictionary(extension_id, &pref)) << msg;
1092 EXPECT_TRUE(pref != NULL) << msg;
1093 pref->Set(pref_path, value);
1096 void SetPrefInteg(const std::string& extension_id,
1097 const std::string& pref_path,
1098 int value) {
1099 std::string msg = " while setting: ";
1100 msg += extension_id;
1101 msg += " ";
1102 msg += pref_path;
1103 msg += " = ";
1104 msg += base::IntToString(value);
1106 SetPref(extension_id, pref_path, new base::FundamentalValue(value), msg);
1109 void SetPrefBool(const std::string& extension_id,
1110 const std::string& pref_path,
1111 bool value) {
1112 std::string msg = " while setting: ";
1113 msg += extension_id + " " + pref_path;
1114 msg += " = ";
1115 msg += (value ? "true" : "false");
1117 SetPref(extension_id, pref_path, new base::FundamentalValue(value), msg);
1120 void ClearPref(const std::string& extension_id,
1121 const std::string& pref_path) {
1122 std::string msg = " while clearing: ";
1123 msg += extension_id + " " + pref_path;
1125 DictionaryPrefUpdate update(profile()->GetPrefs(), "extensions.settings");
1126 base::DictionaryValue* dict = update.Get();
1127 ASSERT_TRUE(dict != NULL) << msg;
1128 base::DictionaryValue* pref = NULL;
1129 ASSERT_TRUE(dict->GetDictionary(extension_id, &pref)) << msg;
1130 EXPECT_TRUE(pref != NULL) << msg;
1131 pref->Remove(pref_path, NULL);
1134 void SetPrefStringSet(const std::string& extension_id,
1135 const std::string& pref_path,
1136 const std::set<std::string>& value) {
1137 std::string msg = " while setting: ";
1138 msg += extension_id + " " + pref_path;
1140 base::ListValue* list_value = new base::ListValue();
1141 for (std::set<std::string>::const_iterator iter = value.begin();
1142 iter != value.end(); ++iter)
1143 list_value->Append(new base::StringValue(*iter));
1145 SetPref(extension_id, pref_path, list_value, msg);
1148 void InitPluginService() {
1149 #if defined(ENABLE_PLUGINS)
1150 PluginService::GetInstance()->Init();
1151 #endif
1154 void InitializeEmptyExtensionServiceWithTestingPrefs() {
1155 ExtensionServiceTestBase::ExtensionServiceInitParams params =
1156 CreateDefaultInitParams();
1157 params.pref_file = base::FilePath();
1158 InitializeExtensionService(params);
1161 extensions::ManagementPolicy* GetManagementPolicy() {
1162 return ExtensionSystem::Get(browser_context())->management_policy();
1165 ExtensionSyncService* extension_sync_service() {
1166 return ExtensionSyncService::Get(profile());
1169 protected:
1170 typedef extensions::ExtensionManagementPrefUpdater<TestingPrefServiceSyncable>
1171 ManagementPrefUpdater;
1172 extensions::ExtensionList loaded_;
1173 std::string unloaded_id_;
1174 UnloadedExtensionInfo::Reason unloaded_reason_;
1175 const Extension* installed_;
1176 bool was_update_;
1177 std::string old_name_;
1178 FeatureSwitch::ScopedOverride override_external_install_prompt_;
1180 private:
1181 // Create a CrxInstaller and install the CRX file.
1182 // Instead of calling this method yourself, use InstallCRX(), which does extra
1183 // error checking.
1184 void InstallCRXInternal(const base::FilePath& crx_path) {
1185 InstallCRXInternal(crx_path, Extension::NO_FLAGS);
1188 void InstallCRXInternal(const base::FilePath& crx_path, int creation_flags) {
1189 ASSERT_TRUE(base::PathExists(crx_path))
1190 << "Path does not exist: "<< crx_path.value().c_str();
1191 scoped_refptr<CrxInstaller> installer(
1192 CrxInstaller::CreateSilent(service()));
1193 installer->set_creation_flags(creation_flags);
1194 if (!(creation_flags & Extension::WAS_INSTALLED_BY_DEFAULT))
1195 installer->set_allow_silent_install(true);
1197 content::WindowedNotificationObserver observer(
1198 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
1199 content::Source<extensions::CrxInstaller>(installer.get()));
1201 installer->InstallCrx(crx_path);
1203 observer.Wait();
1206 size_t expected_extensions_count_;
1207 content::NotificationRegistrar registrar_;
1210 // Receives notifications from a PackExtensionJob, indicating either that
1211 // packing succeeded or that there was some error.
1212 class PackExtensionTestClient : public extensions::PackExtensionJob::Client {
1213 public:
1214 PackExtensionTestClient(const base::FilePath& expected_crx_path,
1215 const base::FilePath& expected_private_key_path);
1216 void OnPackSuccess(const base::FilePath& crx_path,
1217 const base::FilePath& private_key_path) override;
1218 void OnPackFailure(const std::string& error_message,
1219 ExtensionCreator::ErrorType type) override;
1221 private:
1222 const base::FilePath expected_crx_path_;
1223 const base::FilePath expected_private_key_path_;
1224 DISALLOW_COPY_AND_ASSIGN(PackExtensionTestClient);
1227 PackExtensionTestClient::PackExtensionTestClient(
1228 const base::FilePath& expected_crx_path,
1229 const base::FilePath& expected_private_key_path)
1230 : expected_crx_path_(expected_crx_path),
1231 expected_private_key_path_(expected_private_key_path) {}
1233 // If packing succeeded, we make sure that the package names match our
1234 // expectations.
1235 void PackExtensionTestClient::OnPackSuccess(
1236 const base::FilePath& crx_path,
1237 const base::FilePath& private_key_path) {
1238 // We got the notification and processed it; we don't expect any further tasks
1239 // to be posted to the current thread, so we should stop blocking and continue
1240 // on with the rest of the test.
1241 // This call to |Quit()| matches the call to |Run()| in the
1242 // |PackPunctuatedExtension| test.
1243 base::MessageLoop::current()->Quit();
1244 EXPECT_EQ(expected_crx_path_.value(), crx_path.value());
1245 EXPECT_EQ(expected_private_key_path_.value(), private_key_path.value());
1246 ASSERT_TRUE(base::PathExists(private_key_path));
1249 // The tests are designed so that we never expect to see a packing error.
1250 void PackExtensionTestClient::OnPackFailure(const std::string& error_message,
1251 ExtensionCreator::ErrorType type) {
1252 if (type == ExtensionCreator::kCRXExists)
1253 FAIL() << "Packing should not fail.";
1254 else
1255 FAIL() << "Existing CRX should have been overwritten.";
1258 // Test loading good extensions from the profile directory.
1259 TEST_F(ExtensionServiceTest, LoadAllExtensionsFromDirectorySuccess) {
1260 InitPluginService();
1261 InitializeGoodInstalledExtensionService();
1262 service()->Init();
1264 uint32 expected_num_extensions = 3u;
1265 ASSERT_EQ(expected_num_extensions, loaded_.size());
1267 EXPECT_EQ(std::string(good0), loaded_[0]->id());
1268 EXPECT_EQ(std::string("My extension 1"),
1269 loaded_[0]->name());
1270 EXPECT_EQ(std::string("The first extension that I made."),
1271 loaded_[0]->description());
1272 EXPECT_EQ(Manifest::INTERNAL, loaded_[0]->location());
1273 EXPECT_TRUE(service()->GetExtensionById(loaded_[0]->id(), false));
1274 EXPECT_EQ(expected_num_extensions, registry()->enabled_extensions().size());
1276 ValidatePrefKeyCount(3);
1277 ValidateIntegerPref(good0, "state", Extension::ENABLED);
1278 ValidateIntegerPref(good0, "location", Manifest::INTERNAL);
1279 ValidateIntegerPref(good1, "state", Extension::ENABLED);
1280 ValidateIntegerPref(good1, "location", Manifest::INTERNAL);
1281 ValidateIntegerPref(good2, "state", Extension::ENABLED);
1282 ValidateIntegerPref(good2, "location", Manifest::INTERNAL);
1284 URLPatternSet expected_patterns;
1285 AddPattern(&expected_patterns, "file:///*");
1286 AddPattern(&expected_patterns, "http://*.google.com/*");
1287 AddPattern(&expected_patterns, "https://*.google.com/*");
1288 const Extension* extension = loaded_[0].get();
1289 const extensions::UserScriptList& scripts =
1290 extensions::ContentScriptsInfo::GetContentScripts(extension);
1291 ASSERT_EQ(2u, scripts.size());
1292 EXPECT_EQ(expected_patterns, scripts[0].url_patterns());
1293 EXPECT_EQ(2u, scripts[0].js_scripts().size());
1294 ExtensionResource resource00(extension->id(),
1295 scripts[0].js_scripts()[0].extension_root(),
1296 scripts[0].js_scripts()[0].relative_path());
1297 base::FilePath expected_path =
1298 base::MakeAbsoluteFilePath(extension->path().AppendASCII("script1.js"));
1299 EXPECT_TRUE(resource00.ComparePathWithDefault(expected_path));
1300 ExtensionResource resource01(extension->id(),
1301 scripts[0].js_scripts()[1].extension_root(),
1302 scripts[0].js_scripts()[1].relative_path());
1303 expected_path =
1304 base::MakeAbsoluteFilePath(extension->path().AppendASCII("script2.js"));
1305 EXPECT_TRUE(resource01.ComparePathWithDefault(expected_path));
1306 EXPECT_TRUE(!extensions::PluginInfo::HasPlugins(extension));
1307 EXPECT_EQ(1u, scripts[1].url_patterns().patterns().size());
1308 EXPECT_EQ("http://*.news.com/*",
1309 scripts[1].url_patterns().begin()->GetAsString());
1310 ExtensionResource resource10(extension->id(),
1311 scripts[1].js_scripts()[0].extension_root(),
1312 scripts[1].js_scripts()[0].relative_path());
1313 expected_path =
1314 extension->path().AppendASCII("js_files").AppendASCII("script3.js");
1315 expected_path = base::MakeAbsoluteFilePath(expected_path);
1316 EXPECT_TRUE(resource10.ComparePathWithDefault(expected_path));
1318 expected_patterns.ClearPatterns();
1319 AddPattern(&expected_patterns, "http://*.google.com/*");
1320 AddPattern(&expected_patterns, "https://*.google.com/*");
1321 EXPECT_EQ(
1322 expected_patterns,
1323 extension->permissions_data()->active_permissions()->explicit_hosts());
1325 EXPECT_EQ(std::string(good1), loaded_[1]->id());
1326 EXPECT_EQ(std::string("My extension 2"), loaded_[1]->name());
1327 EXPECT_EQ(std::string(), loaded_[1]->description());
1328 EXPECT_EQ(loaded_[1]->GetResourceURL("background.html"),
1329 extensions::BackgroundInfo::GetBackgroundURL(loaded_[1].get()));
1330 EXPECT_EQ(0u,
1331 extensions::ContentScriptsInfo::GetContentScripts(loaded_[1].get())
1332 .size());
1334 // We don't parse the plugins section on Chrome OS.
1335 #if defined(OS_CHROMEOS)
1336 EXPECT_TRUE(!extensions::PluginInfo::HasPlugins(loaded_[1].get()));
1337 #else
1338 ASSERT_TRUE(extensions::PluginInfo::HasPlugins(loaded_[1].get()));
1339 const std::vector<extensions::PluginInfo>* plugins =
1340 extensions::PluginInfo::GetPlugins(loaded_[1].get());
1341 ASSERT_TRUE(plugins);
1342 ASSERT_EQ(2u, plugins->size());
1343 EXPECT_EQ(loaded_[1]->path().AppendASCII("content_plugin.dll").value(),
1344 plugins->at(0).path.value());
1345 EXPECT_TRUE(plugins->at(0).is_public);
1346 EXPECT_EQ(loaded_[1]->path().AppendASCII("extension_plugin.dll").value(),
1347 plugins->at(1).path.value());
1348 EXPECT_FALSE(plugins->at(1).is_public);
1349 #endif
1351 EXPECT_EQ(Manifest::INTERNAL, loaded_[1]->location());
1353 int index = expected_num_extensions - 1;
1354 EXPECT_EQ(std::string(good2), loaded_[index]->id());
1355 EXPECT_EQ(std::string("My extension 3"), loaded_[index]->name());
1356 EXPECT_EQ(std::string(), loaded_[index]->description());
1357 EXPECT_EQ(0u,
1358 extensions::ContentScriptsInfo::GetContentScripts(
1359 loaded_[index].get()).size());
1360 EXPECT_EQ(Manifest::INTERNAL, loaded_[index]->location());
1363 // Test loading bad extensions from the profile directory.
1364 TEST_F(ExtensionServiceTest, LoadAllExtensionsFromDirectoryFail) {
1365 // Initialize the test dir with a bad Preferences/extensions.
1366 base::FilePath source_install_dir =
1367 data_dir().AppendASCII("bad").AppendASCII("Extensions");
1368 base::FilePath pref_path =
1369 source_install_dir.DirName().Append(chrome::kPreferencesFilename);
1371 InitializeInstalledExtensionService(pref_path, source_install_dir);
1373 service()->Init();
1375 ASSERT_EQ(4u, GetErrors().size());
1376 ASSERT_EQ(0u, loaded_.size());
1378 EXPECT_TRUE(base::MatchPattern(base::UTF16ToUTF8(GetErrors()[0]),
1379 l10n_util::GetStringUTF8(IDS_EXTENSIONS_LOAD_ERROR_MESSAGE) + " *. " +
1380 extensions::manifest_errors::kManifestUnreadable)) <<
1381 base::UTF16ToUTF8(GetErrors()[0]);
1383 EXPECT_TRUE(base::MatchPattern(base::UTF16ToUTF8(GetErrors()[1]),
1384 l10n_util::GetStringUTF8(IDS_EXTENSIONS_LOAD_ERROR_MESSAGE) + " *. " +
1385 extensions::manifest_errors::kManifestUnreadable)) <<
1386 base::UTF16ToUTF8(GetErrors()[1]);
1388 EXPECT_TRUE(base::MatchPattern(base::UTF16ToUTF8(GetErrors()[2]),
1389 l10n_util::GetStringUTF8(IDS_EXTENSIONS_LOAD_ERROR_MESSAGE) + " *. " +
1390 extensions::manifest_errors::kMissingFile)) <<
1391 base::UTF16ToUTF8(GetErrors()[2]);
1393 EXPECT_TRUE(base::MatchPattern(base::UTF16ToUTF8(GetErrors()[3]),
1394 l10n_util::GetStringUTF8(IDS_EXTENSIONS_LOAD_ERROR_MESSAGE) + " *. " +
1395 extensions::manifest_errors::kManifestUnreadable)) <<
1396 base::UTF16ToUTF8(GetErrors()[3]);
1399 // Test various cases for delayed install because of missing imports.
1400 TEST_F(ExtensionServiceTest, PendingImports) {
1401 InitPluginService();
1403 base::FilePath source_install_dir =
1404 data_dir().AppendASCII("pending_updates_with_imports").AppendASCII(
1405 "Extensions");
1406 base::FilePath pref_path =
1407 source_install_dir.DirName().Append(chrome::kPreferencesFilename);
1409 InitializeInstalledExtensionService(pref_path, source_install_dir);
1411 // Verify there are no pending extensions initially.
1412 EXPECT_FALSE(service()->pending_extension_manager()->HasPendingExtensions());
1414 service()->Init();
1415 // Wait for GarbageCollectExtensions task to complete.
1416 base::RunLoop().RunUntilIdle();
1418 // These extensions are used by the extensions we test below, they must be
1419 // installed.
1420 EXPECT_TRUE(base::PathExists(extensions_install_dir().AppendASCII(
1421 "bjafgdebaacbbbecmhlhpofkepfkgcpa/1.0")));
1422 EXPECT_TRUE(base::PathExists(extensions_install_dir().AppendASCII(
1423 "hpiknbiabeeppbpihjehijgoemciehgk/2")));
1425 // Each of these extensions should have been rejected because of dependencies
1426 // that cannot be satisfied.
1427 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
1428 EXPECT_FALSE(
1429 prefs->GetDelayedInstallInfo("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
1430 EXPECT_FALSE(
1431 prefs->GetInstalledExtensionInfo("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
1432 EXPECT_FALSE(
1433 prefs->GetDelayedInstallInfo("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"));
1434 EXPECT_FALSE(
1435 prefs->GetInstalledExtensionInfo("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"));
1436 EXPECT_FALSE(
1437 prefs->GetDelayedInstallInfo("cccccccccccccccccccccccccccccccc"));
1438 EXPECT_FALSE(
1439 prefs->GetInstalledExtensionInfo("cccccccccccccccccccccccccccccccc"));
1441 // Make sure the import started for the extension with a dependency.
1442 EXPECT_TRUE(
1443 prefs->GetDelayedInstallInfo("behllobkkfkfnphdnhnkndlbkcpglgmj"));
1444 EXPECT_EQ(ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS,
1445 prefs->GetDelayedInstallReason("behllobkkfkfnphdnhnkndlbkcpglgmj"));
1447 EXPECT_FALSE(base::PathExists(extensions_install_dir().AppendASCII(
1448 "behllobkkfkfnphdnhnkndlbkcpglgmj/1.0.0.0")));
1450 EXPECT_TRUE(service()->pending_extension_manager()->HasPendingExtensions());
1451 std::string pending_id("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
1452 EXPECT_TRUE(service()->pending_extension_manager()->IsIdPending(pending_id));
1453 // Remove it because we are not testing the pending extension manager's
1454 // ability to download and install extensions.
1455 EXPECT_TRUE(service()->pending_extension_manager()->Remove(pending_id));
1458 // Test installing extensions. This test tries to install few extensions using
1459 // crx files. If you need to change those crx files, feel free to repackage
1460 // them, throw away the key used and change the id's above.
1461 TEST_F(ExtensionServiceTest, InstallExtension) {
1462 InitializeEmptyExtensionService();
1464 // Extensions not enabled.
1465 service()->set_extensions_enabled(false);
1466 base::FilePath path = data_dir().AppendASCII("good.crx");
1467 InstallCRX(path, INSTALL_FAILED);
1468 service()->set_extensions_enabled(true);
1470 ValidatePrefKeyCount(0);
1472 // A simple extension that should install without error.
1473 path = data_dir().AppendASCII("good.crx");
1474 InstallCRX(path, INSTALL_NEW);
1475 // TODO(erikkay): verify the contents of the installed extension.
1477 int pref_count = 0;
1478 ValidatePrefKeyCount(++pref_count);
1479 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
1480 ValidateIntegerPref(good_crx, "location", Manifest::INTERNAL);
1482 // An extension with page actions.
1483 path = data_dir().AppendASCII("page_action.crx");
1484 InstallCRX(path, INSTALL_NEW);
1485 ValidatePrefKeyCount(++pref_count);
1486 ValidateIntegerPref(page_action, "state", Extension::ENABLED);
1487 ValidateIntegerPref(page_action, "location", Manifest::INTERNAL);
1489 // Bad signature.
1490 path = data_dir().AppendASCII("bad_signature.crx");
1491 InstallCRX(path, INSTALL_FAILED);
1492 ValidatePrefKeyCount(pref_count);
1494 // 0-length extension file.
1495 path = data_dir().AppendASCII("not_an_extension.crx");
1496 InstallCRX(path, INSTALL_FAILED);
1497 ValidatePrefKeyCount(pref_count);
1499 // Bad magic number.
1500 path = data_dir().AppendASCII("bad_magic.crx");
1501 InstallCRX(path, INSTALL_FAILED);
1502 ValidatePrefKeyCount(pref_count);
1504 // Packed extensions may have folders or files that have underscores.
1505 // This will only cause a warning, rather than a fatal error.
1506 path = data_dir().AppendASCII("bad_underscore.crx");
1507 InstallCRX(path, INSTALL_NEW);
1508 ValidatePrefKeyCount(++pref_count);
1510 // A test for an extension with a 2048-bit public key.
1511 path = data_dir().AppendASCII("good2048.crx");
1512 InstallCRX(path, INSTALL_NEW);
1513 ValidatePrefKeyCount(++pref_count);
1514 ValidateIntegerPref(good2048, "state", Extension::ENABLED);
1515 ValidateIntegerPref(good2048, "location", Manifest::INTERNAL);
1517 // TODO(erikkay): add more tests for many of the failure cases.
1518 // TODO(erikkay): add tests for upgrade cases.
1521 struct MockExtensionRegistryObserver
1522 : public extensions::ExtensionRegistryObserver {
1523 void OnExtensionWillBeInstalled(content::BrowserContext* browser_context,
1524 const Extension* extension,
1525 bool is_update,
1526 bool from_ephemeral,
1527 const std::string& old_name) override {
1528 last_extension_installed = extension->id();
1531 void OnExtensionUninstalled(content::BrowserContext* browser_context,
1532 const Extension* extension,
1533 extensions::UninstallReason reason) override {
1534 last_extension_uninstalled = extension->id();
1537 std::string last_extension_installed;
1538 std::string last_extension_uninstalled;
1541 // Test that correct notifications are sent to ExtensionRegistryObserver on
1542 // extension install and uninstall.
1543 TEST_F(ExtensionServiceTest, InstallObserverNotified) {
1544 InitializeEmptyExtensionService();
1546 extensions::ExtensionRegistry* registry(
1547 extensions::ExtensionRegistry::Get(profile()));
1548 MockExtensionRegistryObserver observer;
1549 registry->AddObserver(&observer);
1551 // A simple extension that should install without error.
1552 ASSERT_TRUE(observer.last_extension_installed.empty());
1553 base::FilePath path = data_dir().AppendASCII("good.crx");
1554 InstallCRX(path, INSTALL_NEW);
1555 ASSERT_EQ(good_crx, observer.last_extension_installed);
1557 // Uninstall the extension.
1558 ASSERT_TRUE(observer.last_extension_uninstalled.empty());
1559 UninstallExtension(good_crx, false);
1560 ASSERT_EQ(good_crx, observer.last_extension_uninstalled);
1562 registry->RemoveObserver(&observer);
1565 // Tests that flags passed to OnExternalExtensionFileFound() make it to the
1566 // extension object.
1567 TEST_F(ExtensionServiceTest, InstallingExternalExtensionWithFlags) {
1568 const char kPrefFromBookmark[] = "from_bookmark";
1570 InitializeEmptyExtensionService();
1572 base::FilePath path = data_dir().AppendASCII("good.crx");
1573 service()->set_extensions_enabled(true);
1575 // Register and install an external extension.
1576 Version version("1.0.0.0");
1577 content::WindowedNotificationObserver observer(
1578 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
1579 content::NotificationService::AllSources());
1580 if (service()->OnExternalExtensionFileFound(
1581 good_crx,
1582 &version,
1583 path,
1584 Manifest::EXTERNAL_PREF,
1585 Extension::FROM_BOOKMARK,
1586 false /* mark_acknowledged */,
1587 false /* install_immediately */)) {
1588 observer.Wait();
1591 const Extension* extension = service()->GetExtensionById(good_crx, false);
1592 ASSERT_TRUE(extension);
1593 ASSERT_TRUE(extension->from_bookmark());
1594 ASSERT_TRUE(ValidateBooleanPref(good_crx, kPrefFromBookmark, true));
1596 // Upgrade to version 2.0, the flag should be preserved.
1597 path = data_dir().AppendASCII("good2.crx");
1598 UpdateExtension(good_crx, path, ENABLED);
1599 ASSERT_TRUE(ValidateBooleanPref(good_crx, kPrefFromBookmark, true));
1600 extension = service()->GetExtensionById(good_crx, false);
1601 ASSERT_TRUE(extension);
1602 ASSERT_TRUE(extension->from_bookmark());
1605 // Test the handling of Extension::EXTERNAL_EXTENSION_UNINSTALLED
1606 TEST_F(ExtensionServiceTest, UninstallingExternalExtensions) {
1607 InitializeEmptyExtensionService();
1609 base::FilePath path = data_dir().AppendASCII("good.crx");
1610 service()->set_extensions_enabled(true);
1612 // Install an external extension.
1613 Version version("1.0.0.0");
1614 content::WindowedNotificationObserver observer(
1615 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
1616 content::NotificationService::AllSources());
1617 if (service()->OnExternalExtensionFileFound(good_crx,
1618 &version,
1619 path,
1620 Manifest::EXTERNAL_PREF,
1621 Extension::NO_FLAGS,
1622 false,
1623 false)) {
1624 observer.Wait();
1627 ASSERT_TRUE(service()->GetExtensionById(good_crx, false));
1629 // Uninstall it and check that its killbit gets set.
1630 UninstallExtension(good_crx, false);
1631 ValidateIntegerPref(good_crx, "state",
1632 Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1634 // Try to re-install it externally. This should fail because of the killbit.
1635 service()->OnExternalExtensionFileFound(good_crx,
1636 &version,
1637 path,
1638 Manifest::EXTERNAL_PREF,
1639 Extension::NO_FLAGS,
1640 false,
1641 false);
1642 base::RunLoop().RunUntilIdle();
1643 ASSERT_TRUE(NULL == service()->GetExtensionById(good_crx, false));
1644 ValidateIntegerPref(good_crx, "state",
1645 Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1647 version = Version("1.0.0.1");
1648 // Repeat the same thing with a newer version of the extension.
1649 path = data_dir().AppendASCII("good2.crx");
1650 service()->OnExternalExtensionFileFound(good_crx,
1651 &version,
1652 path,
1653 Manifest::EXTERNAL_PREF,
1654 Extension::NO_FLAGS,
1655 false,
1656 false);
1657 base::RunLoop().RunUntilIdle();
1658 ASSERT_TRUE(NULL == service()->GetExtensionById(good_crx, false));
1659 ValidateIntegerPref(good_crx, "state",
1660 Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1662 // Try adding the same extension from an external update URL.
1663 ASSERT_FALSE(service()->pending_extension_manager()->AddFromExternalUpdateUrl(
1664 good_crx,
1665 std::string(),
1666 GURL("http:://fake.update/url"),
1667 Manifest::EXTERNAL_PREF_DOWNLOAD,
1668 Extension::NO_FLAGS,
1669 false));
1671 ASSERT_FALSE(service()->pending_extension_manager()->IsIdPending(good_crx));
1674 // Test that uninstalling an external extension does not crash when
1675 // the extension could not be loaded.
1676 // This extension shown in preferences file requires an experimental permission.
1677 // It could not be loaded without such permission.
1678 TEST_F(ExtensionServiceTest, UninstallingNotLoadedExtension) {
1679 base::FilePath source_install_dir =
1680 data_dir().AppendASCII("good").AppendASCII("Extensions");
1681 // The preference contains an external extension
1682 // that requires 'experimental' permission.
1683 base::FilePath pref_path = source_install_dir
1684 .DirName()
1685 .AppendASCII("PreferencesExperimental");
1687 // Aforementioned extension will not be loaded if
1688 // there is no '--enable-experimental-extension-apis' command line flag.
1689 InitializeInstalledExtensionService(pref_path, source_install_dir);
1691 service()->Init();
1693 // Check and try to uninstall it.
1694 // If we don't check whether the extension is loaded before we uninstall it
1695 // in CheckExternalUninstall, a crash will happen here because we will get or
1696 // dereference a NULL pointer (extension) inside UninstallExtension.
1697 MockExtensionProvider provider(NULL, Manifest::EXTERNAL_REGISTRY);
1698 service()->OnExternalProviderReady(&provider);
1701 // Test that external extensions with incorrect IDs are not installed.
1702 TEST_F(ExtensionServiceTest, FailOnWrongId) {
1703 InitializeEmptyExtensionService();
1704 base::FilePath path = data_dir().AppendASCII("good.crx");
1705 service()->set_extensions_enabled(true);
1707 Version version("1.0.0.0");
1709 const std::string wrong_id = all_zero;
1710 const std::string correct_id = good_crx;
1711 ASSERT_NE(correct_id, wrong_id);
1713 // Install an external extension with an ID from the external
1714 // source that is not equal to the ID in the extension manifest.
1715 content::WindowedNotificationObserver observer(
1716 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
1717 content::NotificationService::AllSources());
1718 service()->OnExternalExtensionFileFound(wrong_id,
1719 &version,
1720 path,
1721 Manifest::EXTERNAL_PREF,
1722 Extension::NO_FLAGS,
1723 false,
1724 false);
1726 observer.Wait();
1727 ASSERT_FALSE(service()->GetExtensionById(good_crx, false));
1729 // Try again with the right ID. Expect success.
1730 content::WindowedNotificationObserver observer2(
1731 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
1732 content::NotificationService::AllSources());
1733 if (service()->OnExternalExtensionFileFound(correct_id,
1734 &version,
1735 path,
1736 Manifest::EXTERNAL_PREF,
1737 Extension::NO_FLAGS,
1738 false,
1739 false)) {
1740 observer2.Wait();
1742 ASSERT_TRUE(service()->GetExtensionById(good_crx, false));
1745 // Test that external extensions with incorrect versions are not installed.
1746 TEST_F(ExtensionServiceTest, FailOnWrongVersion) {
1747 InitializeEmptyExtensionService();
1748 base::FilePath path = data_dir().AppendASCII("good.crx");
1749 service()->set_extensions_enabled(true);
1751 // Install an external extension with a version from the external
1752 // source that is not equal to the version in the extension manifest.
1753 Version wrong_version("1.2.3.4");
1754 content::WindowedNotificationObserver observer(
1755 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
1756 content::NotificationService::AllSources());
1757 service()->OnExternalExtensionFileFound(good_crx,
1758 &wrong_version,
1759 path,
1760 Manifest::EXTERNAL_PREF,
1761 Extension::NO_FLAGS,
1762 false,
1763 false);
1765 observer.Wait();
1766 ASSERT_FALSE(service()->GetExtensionById(good_crx, false));
1768 // Try again with the right version. Expect success.
1769 service()->pending_extension_manager()->Remove(good_crx);
1770 Version correct_version("1.0.0.0");
1771 content::WindowedNotificationObserver observer2(
1772 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
1773 content::NotificationService::AllSources());
1774 if (service()->OnExternalExtensionFileFound(good_crx,
1775 &correct_version,
1776 path,
1777 Manifest::EXTERNAL_PREF,
1778 Extension::NO_FLAGS,
1779 false,
1780 false)) {
1781 observer2.Wait();
1783 ASSERT_TRUE(service()->GetExtensionById(good_crx, false));
1786 // Install a user script (they get converted automatically to an extension)
1787 TEST_F(ExtensionServiceTest, InstallUserScript) {
1788 // The details of script conversion are tested elsewhere, this just tests
1789 // integration with ExtensionService.
1790 InitializeEmptyExtensionService();
1792 base::FilePath path = data_dir().AppendASCII("user_script_basic.user.js");
1794 ASSERT_TRUE(base::PathExists(path));
1795 scoped_refptr<CrxInstaller> installer(CrxInstaller::CreateSilent(service()));
1796 installer->set_allow_silent_install(true);
1797 installer->InstallUserScript(
1798 path,
1799 GURL("http://www.aaronboodman.com/scripts/user_script_basic.user.js"));
1801 base::RunLoop().RunUntilIdle();
1802 std::vector<base::string16> errors = GetErrors();
1803 EXPECT_TRUE(installed_) << "Nothing was installed.";
1804 EXPECT_FALSE(was_update_) << path.value();
1805 ASSERT_EQ(1u, loaded_.size()) << "Nothing was loaded.";
1806 EXPECT_EQ(0u, errors.size())
1807 << "There were errors: "
1808 << base::JoinString(errors, base::ASCIIToUTF16(","));
1809 EXPECT_TRUE(service()->GetExtensionById(loaded_[0]->id(), false))
1810 << path.value();
1812 installed_ = NULL;
1813 was_update_ = false;
1814 loaded_.clear();
1815 ExtensionErrorReporter::GetInstance()->ClearErrors();
1818 // Extensions don't install during shutdown.
1819 TEST_F(ExtensionServiceTest, InstallExtensionDuringShutdown) {
1820 InitializeEmptyExtensionService();
1822 // Simulate shutdown.
1823 service()->set_browser_terminating_for_test(true);
1825 base::FilePath path = data_dir().AppendASCII("good.crx");
1826 scoped_refptr<CrxInstaller> installer(CrxInstaller::CreateSilent(service()));
1827 installer->set_allow_silent_install(true);
1828 installer->InstallCrx(path);
1829 base::RunLoop().RunUntilIdle();
1831 EXPECT_FALSE(installed_) << "Extension installed during shutdown.";
1832 ASSERT_EQ(0u, loaded_.size()) << "Extension loaded during shutdown.";
1835 // This tests that the granted permissions preferences are correctly set when
1836 // installing an extension.
1837 TEST_F(ExtensionServiceTest, GrantedPermissions) {
1838 InitializeEmptyExtensionService();
1839 base::FilePath path = data_dir().AppendASCII("permissions");
1841 base::FilePath pem_path = path.AppendASCII("unknown.pem");
1842 path = path.AppendASCII("unknown");
1844 ASSERT_TRUE(base::PathExists(pem_path));
1845 ASSERT_TRUE(base::PathExists(path));
1847 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
1849 APIPermissionSet expected_api_perms;
1850 URLPatternSet expected_host_perms;
1852 // Make sure there aren't any granted permissions before the
1853 // extension is installed.
1854 scoped_refptr<PermissionSet> known_perms(
1855 prefs->GetGrantedPermissions(permissions_crx));
1856 EXPECT_FALSE(known_perms.get());
1858 const Extension* extension = PackAndInstallCRX(path, pem_path, INSTALL_NEW);
1860 EXPECT_EQ(0u, GetErrors().size());
1861 ASSERT_EQ(1u, registry()->enabled_extensions().size());
1862 EXPECT_EQ(permissions_crx, extension->id());
1864 // Verify that the valid API permissions have been recognized.
1865 expected_api_perms.insert(APIPermission::kTab);
1867 AddPattern(&expected_host_perms, "http://*.google.com/*");
1868 AddPattern(&expected_host_perms, "https://*.google.com/*");
1869 AddPattern(&expected_host_perms, "http://*.google.com.hk/*");
1870 AddPattern(&expected_host_perms, "http://www.example.com/*");
1872 known_perms = prefs->GetGrantedPermissions(extension->id());
1873 EXPECT_TRUE(known_perms.get());
1874 EXPECT_FALSE(known_perms->IsEmpty());
1875 EXPECT_EQ(expected_api_perms, known_perms->apis());
1876 EXPECT_FALSE(known_perms->HasEffectiveFullAccess());
1877 EXPECT_EQ(expected_host_perms, known_perms->effective_hosts());
1881 #if !defined(OS_CHROMEOS)
1882 // This tests that the granted permissions preferences are correctly set for
1883 // default apps.
1884 TEST_F(ExtensionServiceTest, DefaultAppsGrantedPermissions) {
1885 InitializeEmptyExtensionService();
1886 base::FilePath path = data_dir().AppendASCII("permissions");
1888 base::FilePath pem_path = path.AppendASCII("unknown.pem");
1889 path = path.AppendASCII("unknown");
1891 ASSERT_TRUE(base::PathExists(pem_path));
1892 ASSERT_TRUE(base::PathExists(path));
1894 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
1896 APIPermissionSet expected_api_perms;
1897 URLPatternSet expected_host_perms;
1899 // Make sure there aren't any granted permissions before the
1900 // extension is installed.
1901 scoped_refptr<PermissionSet> known_perms(
1902 prefs->GetGrantedPermissions(permissions_crx));
1903 EXPECT_FALSE(known_perms.get());
1905 const Extension* extension = PackAndInstallCRX(
1906 path, pem_path, INSTALL_NEW, Extension::WAS_INSTALLED_BY_DEFAULT);
1908 EXPECT_EQ(0u, GetErrors().size());
1909 ASSERT_EQ(1u, registry()->enabled_extensions().size());
1910 EXPECT_EQ(permissions_crx, extension->id());
1912 // Verify that the valid API permissions have been recognized.
1913 expected_api_perms.insert(APIPermission::kTab);
1915 known_perms = prefs->GetGrantedPermissions(extension->id());
1916 EXPECT_TRUE(known_perms.get());
1917 EXPECT_FALSE(known_perms->IsEmpty());
1918 EXPECT_EQ(expected_api_perms, known_perms->apis());
1919 EXPECT_FALSE(known_perms->HasEffectiveFullAccess());
1921 #endif
1923 #if !defined(OS_POSIX) || defined(OS_MACOSX)
1924 // Tests that the granted permissions full_access bit gets set correctly when
1925 // an extension contains an NPAPI plugin.
1926 // Only run this on platforms that support NPAPI plugins.
1927 TEST_F(ExtensionServiceTest, GrantedFullAccessPermissions) {
1928 InitPluginService();
1930 InitializeEmptyExtensionService();
1932 ASSERT_TRUE(base::PathExists(good1_path()));
1933 const Extension* extension = PackAndInstallCRX(good1_path(), INSTALL_NEW);
1934 EXPECT_EQ(0u, GetErrors().size());
1935 EXPECT_EQ(1u, registry()->enabled_extensions().size());
1936 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
1938 scoped_refptr<PermissionSet> permissions(
1939 prefs->GetGrantedPermissions(extension->id()));
1940 EXPECT_FALSE(permissions->IsEmpty());
1941 EXPECT_TRUE(permissions->HasEffectiveFullAccess());
1942 EXPECT_FALSE(permissions->apis().empty());
1943 EXPECT_TRUE(permissions->HasAPIPermission(APIPermission::kPlugin));
1945 // Full access implies full host access too...
1946 EXPECT_TRUE(permissions->HasEffectiveAccessToAllHosts());
1948 #endif
1950 // Tests that the extension is disabled when permissions are missing from
1951 // the extension's granted permissions preferences. (This simulates updating
1952 // the browser to a version which recognizes more permissions).
1953 TEST_F(ExtensionServiceTest, GrantedAPIAndHostPermissions) {
1954 InitializeEmptyExtensionService();
1956 base::FilePath path =
1957 data_dir().AppendASCII("permissions").AppendASCII("unknown");
1959 ASSERT_TRUE(base::PathExists(path));
1961 const Extension* extension = PackAndInstallCRX(path, INSTALL_NEW);
1963 EXPECT_EQ(0u, GetErrors().size());
1964 EXPECT_EQ(1u, registry()->enabled_extensions().size());
1965 std::string extension_id = extension->id();
1967 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
1969 APIPermissionSet expected_api_permissions;
1970 URLPatternSet expected_host_permissions;
1972 expected_api_permissions.insert(APIPermission::kTab);
1973 AddPattern(&expected_host_permissions, "http://*.google.com/*");
1974 AddPattern(&expected_host_permissions, "https://*.google.com/*");
1975 AddPattern(&expected_host_permissions, "http://*.google.com.hk/*");
1976 AddPattern(&expected_host_permissions, "http://www.example.com/*");
1978 std::set<std::string> host_permissions;
1980 // Test that the extension is disabled when an API permission is missing from
1981 // the extension's granted api permissions preference. (This simulates
1982 // updating the browser to a version which recognizes a new API permission).
1983 SetPref(extension_id, "granted_permissions.api",
1984 new base::ListValue(), "granted_permissions.api");
1985 service()->ReloadExtensionsForTest();
1987 EXPECT_EQ(1u, registry()->disabled_extensions().size());
1988 extension = registry()->disabled_extensions().begin()->get();
1990 ASSERT_TRUE(prefs->IsExtensionDisabled(extension_id));
1991 ASSERT_FALSE(service()->IsExtensionEnabled(extension_id));
1992 ASSERT_TRUE(prefs->DidExtensionEscalatePermissions(extension_id));
1994 // Now grant and re-enable the extension, making sure the prefs are updated.
1995 service()->GrantPermissionsAndEnableExtension(extension);
1997 ASSERT_FALSE(prefs->IsExtensionDisabled(extension_id));
1998 ASSERT_TRUE(service()->IsExtensionEnabled(extension_id));
1999 ASSERT_FALSE(prefs->DidExtensionEscalatePermissions(extension_id));
2001 scoped_refptr<PermissionSet> current_perms(
2002 prefs->GetGrantedPermissions(extension_id));
2003 ASSERT_TRUE(current_perms.get());
2004 ASSERT_FALSE(current_perms->IsEmpty());
2005 ASSERT_FALSE(current_perms->HasEffectiveFullAccess());
2006 ASSERT_EQ(expected_api_permissions, current_perms->apis());
2007 ASSERT_EQ(expected_host_permissions, current_perms->effective_hosts());
2009 // Tests that the extension is disabled when a host permission is missing from
2010 // the extension's granted host permissions preference. (This simulates
2011 // updating the browser to a version which recognizes additional host
2012 // permissions).
2013 host_permissions.clear();
2014 current_perms = NULL;
2016 host_permissions.insert("http://*.google.com/*");
2017 host_permissions.insert("https://*.google.com/*");
2018 host_permissions.insert("http://*.google.com.hk/*");
2020 base::ListValue* api_permissions = new base::ListValue();
2021 api_permissions->Append(
2022 new base::StringValue("tabs"));
2023 SetPref(extension_id, "granted_permissions.api",
2024 api_permissions, "granted_permissions.api");
2025 SetPrefStringSet(
2026 extension_id, "granted_permissions.scriptable_host", host_permissions);
2028 service()->ReloadExtensionsForTest();
2030 EXPECT_EQ(1u, registry()->disabled_extensions().size());
2031 extension = registry()->disabled_extensions().begin()->get();
2033 ASSERT_TRUE(prefs->IsExtensionDisabled(extension_id));
2034 ASSERT_FALSE(service()->IsExtensionEnabled(extension_id));
2035 ASSERT_TRUE(prefs->DidExtensionEscalatePermissions(extension_id));
2037 // Now grant and re-enable the extension, making sure the prefs are updated.
2038 service()->GrantPermissionsAndEnableExtension(extension);
2040 ASSERT_TRUE(service()->IsExtensionEnabled(extension_id));
2041 ASSERT_FALSE(prefs->DidExtensionEscalatePermissions(extension_id));
2043 current_perms = prefs->GetGrantedPermissions(extension_id);
2044 ASSERT_TRUE(current_perms.get());
2045 ASSERT_FALSE(current_perms->IsEmpty());
2046 ASSERT_FALSE(current_perms->HasEffectiveFullAccess());
2047 ASSERT_EQ(expected_api_permissions, current_perms->apis());
2048 ASSERT_EQ(expected_host_permissions, current_perms->effective_hosts());
2051 // Test Packaging and installing an extension.
2052 TEST_F(ExtensionServiceTest, PackExtension) {
2053 InitializeEmptyExtensionService();
2054 base::FilePath input_directory =
2055 data_dir()
2056 .AppendASCII("good")
2057 .AppendASCII("Extensions")
2058 .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
2059 .AppendASCII("1.0.0.0");
2061 base::ScopedTempDir temp_dir;
2062 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
2063 base::FilePath output_directory = temp_dir.path();
2065 base::FilePath crx_path(output_directory.AppendASCII("ex1.crx"));
2066 base::FilePath privkey_path(output_directory.AppendASCII("privkey.pem"));
2068 scoped_ptr<ExtensionCreator> creator(new ExtensionCreator());
2069 ASSERT_TRUE(creator->Run(input_directory, crx_path, base::FilePath(),
2070 privkey_path, ExtensionCreator::kNoRunFlags));
2071 ASSERT_TRUE(base::PathExists(crx_path));
2072 ASSERT_TRUE(base::PathExists(privkey_path));
2074 // Repeat the run with the pem file gone, and no special flags
2075 // Should refuse to overwrite the existing crx.
2076 base::DeleteFile(privkey_path, false);
2077 ASSERT_FALSE(creator->Run(input_directory, crx_path, base::FilePath(),
2078 privkey_path, ExtensionCreator::kNoRunFlags));
2080 // OK, now try it with a flag to overwrite existing crx. Should work.
2081 ASSERT_TRUE(creator->Run(input_directory, crx_path, base::FilePath(),
2082 privkey_path, ExtensionCreator::kOverwriteCRX));
2084 // Repeat the run allowing existing crx, but the existing pem is still
2085 // an error. Should fail.
2086 ASSERT_FALSE(creator->Run(input_directory, crx_path, base::FilePath(),
2087 privkey_path, ExtensionCreator::kOverwriteCRX));
2089 ASSERT_TRUE(base::PathExists(privkey_path));
2090 InstallCRX(crx_path, INSTALL_NEW);
2092 // Try packing with invalid paths.
2093 creator.reset(new ExtensionCreator());
2094 ASSERT_FALSE(
2095 creator->Run(base::FilePath(), base::FilePath(), base::FilePath(),
2096 base::FilePath(), ExtensionCreator::kOverwriteCRX));
2098 // Try packing an empty directory. Should fail because an empty directory is
2099 // not a valid extension.
2100 base::ScopedTempDir temp_dir2;
2101 ASSERT_TRUE(temp_dir2.CreateUniqueTempDir());
2102 creator.reset(new ExtensionCreator());
2103 ASSERT_FALSE(creator->Run(temp_dir2.path(), crx_path, privkey_path,
2104 base::FilePath(), ExtensionCreator::kOverwriteCRX));
2106 // Try packing with an invalid manifest.
2107 std::string invalid_manifest_content = "I am not a manifest.";
2108 ASSERT_TRUE(base::WriteFile(
2109 temp_dir2.path().Append(extensions::kManifestFilename),
2110 invalid_manifest_content.c_str(), invalid_manifest_content.size()));
2111 creator.reset(new ExtensionCreator());
2112 ASSERT_FALSE(creator->Run(temp_dir2.path(), crx_path, privkey_path,
2113 base::FilePath(), ExtensionCreator::kOverwriteCRX));
2115 // Try packing with a private key that is a valid key, but invalid for the
2116 // extension.
2117 base::FilePath bad_private_key_dir =
2118 data_dir().AppendASCII("bad_private_key");
2119 crx_path = output_directory.AppendASCII("bad_private_key.crx");
2120 privkey_path = data_dir().AppendASCII("bad_private_key.pem");
2121 ASSERT_FALSE(creator->Run(bad_private_key_dir, crx_path, base::FilePath(),
2122 privkey_path, ExtensionCreator::kOverwriteCRX));
2125 // Test Packaging and installing an extension whose name contains punctuation.
2126 TEST_F(ExtensionServiceTest, PackPunctuatedExtension) {
2127 InitializeEmptyExtensionService();
2128 base::FilePath input_directory = data_dir()
2129 .AppendASCII("good")
2130 .AppendASCII("Extensions")
2131 .AppendASCII(good0)
2132 .AppendASCII("1.0.0.0");
2134 base::ScopedTempDir temp_dir;
2135 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
2137 // Extension names containing punctuation, and the expected names for the
2138 // packed extensions.
2139 const base::FilePath punctuated_names[] = {
2140 base::FilePath(FILE_PATH_LITERAL("this.extensions.name.has.periods")),
2141 base::FilePath(FILE_PATH_LITERAL(".thisextensionsnamestartswithaperiod")),
2142 base::FilePath(FILE_PATH_LITERAL("thisextensionhasaslashinitsname/")).
2143 NormalizePathSeparators(),
2145 const base::FilePath expected_crx_names[] = {
2146 base::FilePath(FILE_PATH_LITERAL("this.extensions.name.has.periods.crx")),
2147 base::FilePath(
2148 FILE_PATH_LITERAL(".thisextensionsnamestartswithaperiod.crx")),
2149 base::FilePath(FILE_PATH_LITERAL("thisextensionhasaslashinitsname.crx")),
2151 const base::FilePath expected_private_key_names[] = {
2152 base::FilePath(FILE_PATH_LITERAL("this.extensions.name.has.periods.pem")),
2153 base::FilePath(
2154 FILE_PATH_LITERAL(".thisextensionsnamestartswithaperiod.pem")),
2155 base::FilePath(FILE_PATH_LITERAL("thisextensionhasaslashinitsname.pem")),
2158 for (size_t i = 0; i < arraysize(punctuated_names); ++i) {
2159 SCOPED_TRACE(punctuated_names[i].value().c_str());
2160 base::FilePath output_dir = temp_dir.path().Append(punctuated_names[i]);
2162 // Copy the extension into the output directory, as PackExtensionJob doesn't
2163 // let us choose where to output the packed extension.
2164 ASSERT_TRUE(base::CopyDirectory(input_directory, output_dir, true));
2166 base::FilePath expected_crx_path =
2167 temp_dir.path().Append(expected_crx_names[i]);
2168 base::FilePath expected_private_key_path =
2169 temp_dir.path().Append(expected_private_key_names[i]);
2170 PackExtensionTestClient pack_client(expected_crx_path,
2171 expected_private_key_path);
2172 scoped_refptr<extensions::PackExtensionJob> packer(
2173 new extensions::PackExtensionJob(&pack_client, output_dir,
2174 base::FilePath(),
2175 ExtensionCreator::kOverwriteCRX));
2176 packer->Start();
2178 // The packer will post a notification task to the current thread's message
2179 // loop when it is finished. We manually run the loop here so that we
2180 // block and catch the notification; otherwise, the process would exit.
2181 // This call to |Run()| is matched by a call to |Quit()| in the
2182 // |PackExtensionTestClient|'s notification handling code.
2183 base::MessageLoop::current()->Run();
2185 if (HasFatalFailure())
2186 return;
2188 InstallCRX(expected_crx_path, INSTALL_NEW);
2192 TEST_F(ExtensionServiceTest, PackExtensionContainingKeyFails) {
2193 InitializeEmptyExtensionService();
2195 base::ScopedTempDir extension_temp_dir;
2196 ASSERT_TRUE(extension_temp_dir.CreateUniqueTempDir());
2197 base::FilePath input_directory = extension_temp_dir.path().AppendASCII("ext");
2198 ASSERT_TRUE(
2199 base::CopyDirectory(data_dir()
2200 .AppendASCII("good")
2201 .AppendASCII("Extensions")
2202 .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
2203 .AppendASCII("1.0.0.0"),
2204 input_directory,
2205 /*recursive=*/true));
2207 base::ScopedTempDir output_temp_dir;
2208 ASSERT_TRUE(output_temp_dir.CreateUniqueTempDir());
2209 base::FilePath output_directory = output_temp_dir.path();
2211 base::FilePath crx_path(output_directory.AppendASCII("ex1.crx"));
2212 base::FilePath privkey_path(output_directory.AppendASCII("privkey.pem"));
2214 // Pack the extension once to get a private key.
2215 scoped_ptr<ExtensionCreator> creator(new ExtensionCreator());
2216 ASSERT_TRUE(creator->Run(input_directory, crx_path, base::FilePath(),
2217 privkey_path, ExtensionCreator::kNoRunFlags))
2218 << creator->error_message();
2219 ASSERT_TRUE(base::PathExists(crx_path));
2220 ASSERT_TRUE(base::PathExists(privkey_path));
2222 base::DeleteFile(crx_path, false);
2223 // Move the pem file into the extension.
2224 base::Move(privkey_path,
2225 input_directory.AppendASCII("privkey.pem"));
2227 // This pack should fail because of the contained private key.
2228 EXPECT_FALSE(creator->Run(input_directory, crx_path, base::FilePath(),
2229 privkey_path, ExtensionCreator::kNoRunFlags));
2230 EXPECT_THAT(creator->error_message(),
2231 testing::ContainsRegex(
2232 "extension includes the key file.*privkey.pem"));
2235 // Test Packaging and installing an extension using an openssl generated key.
2236 // The openssl is generated with the following:
2237 // > openssl genrsa -out privkey.pem 1024
2238 // > openssl pkcs8 -topk8 -nocrypt -in privkey.pem -out privkey_asn1.pem
2239 // The privkey.pem is a PrivateKey, and the pcks8 -topk8 creates a
2240 // PrivateKeyInfo ASN.1 structure, we our RSAPrivateKey expects.
2241 TEST_F(ExtensionServiceTest, PackExtensionOpenSSLKey) {
2242 InitializeEmptyExtensionService();
2243 base::FilePath input_directory =
2244 data_dir()
2245 .AppendASCII("good")
2246 .AppendASCII("Extensions")
2247 .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
2248 .AppendASCII("1.0.0.0");
2249 base::FilePath privkey_path(
2250 data_dir().AppendASCII("openssl_privkey_asn1.pem"));
2251 ASSERT_TRUE(base::PathExists(privkey_path));
2253 base::ScopedTempDir temp_dir;
2254 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
2255 base::FilePath output_directory = temp_dir.path();
2257 base::FilePath crx_path(output_directory.AppendASCII("ex1.crx"));
2259 scoped_ptr<ExtensionCreator> creator(new ExtensionCreator());
2260 ASSERT_TRUE(creator->Run(input_directory, crx_path, privkey_path,
2261 base::FilePath(), ExtensionCreator::kOverwriteCRX));
2263 InstallCRX(crx_path, INSTALL_NEW);
2266 #if defined(THREAD_SANITIZER)
2267 // Flaky under Tsan. http://crbug.com/377702
2268 #define MAYBE_InstallTheme DISABLED_InstallTheme
2269 #else
2270 #define MAYBE_InstallTheme InstallTheme
2271 #endif
2273 TEST_F(ExtensionServiceTest, MAYBE_InstallTheme) {
2274 InitializeEmptyExtensionService();
2275 service()->Init();
2277 // A theme.
2278 base::FilePath path = data_dir().AppendASCII("theme.crx");
2279 InstallCRX(path, INSTALL_NEW);
2280 int pref_count = 0;
2281 ValidatePrefKeyCount(++pref_count);
2282 ValidateIntegerPref(theme_crx, "state", Extension::ENABLED);
2283 ValidateIntegerPref(theme_crx, "location", Manifest::INTERNAL);
2285 // A theme when extensions are disabled. Themes can be installed, even when
2286 // extensions are disabled.
2287 service()->set_extensions_enabled(false);
2288 path = data_dir().AppendASCII("theme2.crx");
2289 InstallCRX(path, INSTALL_NEW);
2290 ValidatePrefKeyCount(++pref_count);
2291 ValidateIntegerPref(theme2_crx, "state", Extension::ENABLED);
2292 ValidateIntegerPref(theme2_crx, "location", Manifest::INTERNAL);
2294 // A theme with extension elements. Themes cannot have extension elements,
2295 // so any such elements (like content scripts) should be ignored.
2296 service()->set_extensions_enabled(true);
2298 path = data_dir().AppendASCII("theme_with_extension.crx");
2299 const Extension* extension = InstallCRX(path, INSTALL_NEW);
2300 ValidatePrefKeyCount(++pref_count);
2301 ASSERT_TRUE(extension);
2302 EXPECT_TRUE(extension->is_theme());
2303 EXPECT_EQ(
2305 extensions::ContentScriptsInfo::GetContentScripts(extension).size());
2308 // A theme with image resources missing (misspelt path).
2309 path = data_dir().AppendASCII("theme_missing_image.crx");
2310 InstallCRX(path, INSTALL_FAILED);
2311 ValidatePrefKeyCount(pref_count);
2314 TEST_F(ExtensionServiceTest, LoadLocalizedTheme) {
2315 // Load.
2316 InitializeEmptyExtensionService();
2317 service()->Init();
2319 base::FilePath extension_path = data_dir().AppendASCII("theme_i18n");
2321 extensions::UnpackedInstaller::Create(service())->Load(extension_path);
2322 base::RunLoop().RunUntilIdle();
2323 EXPECT_EQ(0u, GetErrors().size());
2324 ASSERT_EQ(1u, loaded_.size());
2325 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2326 const Extension* theme = registry()->enabled_extensions().begin()->get();
2327 EXPECT_EQ("name", theme->name());
2328 EXPECT_EQ("description", theme->description());
2330 // Cleanup the "Cached Theme.pak" file. Ideally, this would be installed in a
2331 // temporary directory, but it automatically installs to the extension's
2332 // directory, and we don't want to copy the whole extension for a unittest.
2333 base::FilePath theme_file = extension_path.Append(chrome::kThemePackFilename);
2334 ASSERT_TRUE(base::PathExists(theme_file));
2335 ASSERT_TRUE(base::DeleteFile(theme_file, false)); // Not recursive.
2338 #if defined(OS_POSIX)
2339 TEST_F(ExtensionServiceTest, UnpackedExtensionMayContainSymlinkedFiles) {
2340 base::FilePath source_data_dir =
2341 data_dir().AppendASCII("unpacked").AppendASCII("symlinks_allowed");
2343 // Paths to test data files.
2344 base::FilePath source_manifest = source_data_dir.AppendASCII("manifest.json");
2345 ASSERT_TRUE(base::PathExists(source_manifest));
2346 base::FilePath source_icon = source_data_dir.AppendASCII("icon.png");
2347 ASSERT_TRUE(base::PathExists(source_icon));
2349 // Set up the temporary extension directory.
2350 base::ScopedTempDir temp;
2351 ASSERT_TRUE(temp.CreateUniqueTempDir());
2352 base::FilePath extension_path = temp.path();
2353 base::FilePath manifest = extension_path.Append(
2354 extensions::kManifestFilename);
2355 base::FilePath icon_symlink = extension_path.AppendASCII("icon.png");
2356 base::CopyFile(source_manifest, manifest);
2357 base::CreateSymbolicLink(source_icon, icon_symlink);
2359 // Load extension.
2360 InitializeEmptyExtensionService();
2361 extensions::UnpackedInstaller::Create(service())->Load(extension_path);
2362 base::RunLoop().RunUntilIdle();
2364 EXPECT_TRUE(GetErrors().empty());
2365 ASSERT_EQ(1u, loaded_.size());
2366 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2368 #endif
2370 TEST_F(ExtensionServiceTest, UnpackedExtensionMayNotHaveUnderscore) {
2371 InitializeEmptyExtensionService();
2372 base::FilePath extension_path = data_dir().AppendASCII("underscore_name");
2373 extensions::UnpackedInstaller::Create(service())->Load(extension_path);
2374 base::RunLoop().RunUntilIdle();
2375 EXPECT_EQ(1u, GetErrors().size());
2376 EXPECT_EQ(0u, registry()->enabled_extensions().size());
2379 TEST_F(ExtensionServiceTest, InstallLocalizedTheme) {
2380 InitializeEmptyExtensionService();
2381 service()->Init();
2383 base::FilePath theme_path = data_dir().AppendASCII("theme_i18n");
2385 const Extension* theme = PackAndInstallCRX(theme_path, INSTALL_NEW);
2387 EXPECT_EQ(0u, GetErrors().size());
2388 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2389 EXPECT_EQ("name", theme->name());
2390 EXPECT_EQ("description", theme->description());
2393 TEST_F(ExtensionServiceTest, InstallApps) {
2394 InitializeEmptyExtensionService();
2396 // An empty app.
2397 const Extension* app =
2398 PackAndInstallCRX(data_dir().AppendASCII("app1"), INSTALL_NEW);
2399 int pref_count = 0;
2400 ValidatePrefKeyCount(++pref_count);
2401 ASSERT_EQ(1u, registry()->enabled_extensions().size());
2402 ValidateIntegerPref(app->id(), "state", Extension::ENABLED);
2403 ValidateIntegerPref(app->id(), "location", Manifest::INTERNAL);
2405 // Another app with non-overlapping extent. Should succeed.
2406 PackAndInstallCRX(data_dir().AppendASCII("app2"), INSTALL_NEW);
2407 ValidatePrefKeyCount(++pref_count);
2409 // A third app whose extent overlaps the first. Should fail.
2410 PackAndInstallCRX(data_dir().AppendASCII("app3"), INSTALL_FAILED);
2411 ValidatePrefKeyCount(pref_count);
2414 // Tests that file access is OFF by default.
2415 TEST_F(ExtensionServiceTest, DefaultFileAccess) {
2416 InitializeEmptyExtensionService();
2417 const Extension* extension = PackAndInstallCRX(
2418 data_dir().AppendASCII("permissions").AppendASCII("files"), INSTALL_NEW);
2419 EXPECT_EQ(0u, GetErrors().size());
2420 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2421 EXPECT_FALSE(
2422 ExtensionPrefs::Get(profile())->AllowFileAccess(extension->id()));
2425 TEST_F(ExtensionServiceTest, UpdateApps) {
2426 InitializeEmptyExtensionService();
2427 base::FilePath extensions_path = data_dir().AppendASCII("app_update");
2429 // First install v1 of a hosted app.
2430 const Extension* extension =
2431 InstallCRX(extensions_path.AppendASCII("v1.crx"), INSTALL_NEW);
2432 ASSERT_EQ(1u, registry()->enabled_extensions().size());
2433 std::string id = extension->id();
2434 ASSERT_EQ(std::string("1"), extension->version()->GetString());
2436 // Now try updating to v2.
2437 UpdateExtension(id,
2438 extensions_path.AppendASCII("v2.crx"),
2439 ENABLED);
2440 ASSERT_EQ(std::string("2"),
2441 service()->GetExtensionById(id, false)->version()->GetString());
2444 // Verifies that the NTP page and launch ordinals are kept when updating apps.
2445 TEST_F(ExtensionServiceTest, UpdateAppsRetainOrdinals) {
2446 InitializeEmptyExtensionService();
2447 AppSorting* sorting = ExtensionPrefs::Get(profile())->app_sorting();
2448 base::FilePath extensions_path = data_dir().AppendASCII("app_update");
2450 // First install v1 of a hosted app.
2451 const Extension* extension =
2452 InstallCRX(extensions_path.AppendASCII("v1.crx"), INSTALL_NEW);
2453 ASSERT_EQ(1u, registry()->enabled_extensions().size());
2454 std::string id = extension->id();
2455 ASSERT_EQ(std::string("1"), extension->version()->GetString());
2457 // Modify the ordinals so we can distinguish them from the defaults.
2458 syncer::StringOrdinal new_page_ordinal =
2459 sorting->GetPageOrdinal(id).CreateAfter();
2460 syncer::StringOrdinal new_launch_ordinal =
2461 sorting->GetAppLaunchOrdinal(id).CreateBefore();
2463 sorting->SetPageOrdinal(id, new_page_ordinal);
2464 sorting->SetAppLaunchOrdinal(id, new_launch_ordinal);
2466 // Now try updating to v2.
2467 UpdateExtension(id, extensions_path.AppendASCII("v2.crx"), ENABLED);
2468 ASSERT_EQ(std::string("2"),
2469 service()->GetExtensionById(id, false)->version()->GetString());
2471 // Verify that the ordinals match.
2472 ASSERT_TRUE(new_page_ordinal.Equals(sorting->GetPageOrdinal(id)));
2473 ASSERT_TRUE(new_launch_ordinal.Equals(sorting->GetAppLaunchOrdinal(id)));
2476 // Ensures that the CWS has properly initialized ordinals.
2477 TEST_F(ExtensionServiceTest, EnsureCWSOrdinalsInitialized) {
2478 InitializeEmptyExtensionService();
2479 service()->component_loader()->Add(
2480 IDR_WEBSTORE_MANIFEST, base::FilePath(FILE_PATH_LITERAL("web_store")));
2481 service()->Init();
2483 AppSorting* sorting = ExtensionPrefs::Get(profile())->app_sorting();
2484 EXPECT_TRUE(
2485 sorting->GetPageOrdinal(extensions::kWebStoreAppId).IsValid());
2486 EXPECT_TRUE(
2487 sorting->GetAppLaunchOrdinal(extensions::kWebStoreAppId).IsValid());
2490 TEST_F(ExtensionServiceTest, InstallAppsWithUnlimitedStorage) {
2491 InitializeEmptyExtensionService();
2492 EXPECT_TRUE(registry()->enabled_extensions().is_empty());
2494 int pref_count = 0;
2496 // Install app1 with unlimited storage.
2497 const Extension* extension =
2498 PackAndInstallCRX(data_dir().AppendASCII("app1"), INSTALL_NEW);
2499 ValidatePrefKeyCount(++pref_count);
2500 ASSERT_EQ(1u, registry()->enabled_extensions().size());
2501 const std::string id1 = extension->id();
2502 EXPECT_TRUE(extension->permissions_data()->HasAPIPermission(
2503 APIPermission::kUnlimitedStorage));
2504 EXPECT_TRUE(extension->web_extent().MatchesURL(
2505 extensions::AppLaunchInfo::GetFullLaunchURL(extension)));
2506 const GURL origin1(
2507 extensions::AppLaunchInfo::GetFullLaunchURL(extension).GetOrigin());
2508 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
2509 origin1));
2511 // Install app2 from the same origin with unlimited storage.
2512 extension = PackAndInstallCRX(data_dir().AppendASCII("app2"), INSTALL_NEW);
2513 ValidatePrefKeyCount(++pref_count);
2514 ASSERT_EQ(2u, registry()->enabled_extensions().size());
2515 const std::string id2 = extension->id();
2516 EXPECT_TRUE(extension->permissions_data()->HasAPIPermission(
2517 APIPermission::kUnlimitedStorage));
2518 EXPECT_TRUE(extension->web_extent().MatchesURL(
2519 extensions::AppLaunchInfo::GetFullLaunchURL(extension)));
2520 const GURL origin2(
2521 extensions::AppLaunchInfo::GetFullLaunchURL(extension).GetOrigin());
2522 EXPECT_EQ(origin1, origin2);
2523 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
2524 origin2));
2526 // Uninstall one of them, unlimited storage should still be granted
2527 // to the origin.
2528 UninstallExtension(id1, false);
2529 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2530 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
2531 origin1));
2533 // Uninstall the other, unlimited storage should be revoked.
2534 UninstallExtension(id2, false);
2535 EXPECT_EQ(0u, registry()->enabled_extensions().size());
2536 EXPECT_FALSE(
2537 profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
2538 origin2));
2541 TEST_F(ExtensionServiceTest, InstallAppsAndCheckStorageProtection) {
2542 InitializeEmptyExtensionService();
2543 EXPECT_TRUE(registry()->enabled_extensions().is_empty());
2545 int pref_count = 0;
2547 const Extension* extension =
2548 PackAndInstallCRX(data_dir().AppendASCII("app1"), INSTALL_NEW);
2549 ValidatePrefKeyCount(++pref_count);
2550 ASSERT_EQ(1u, registry()->enabled_extensions().size());
2551 EXPECT_TRUE(extension->is_app());
2552 const std::string id1 = extension->id();
2553 const GURL origin1(
2554 extensions::AppLaunchInfo::GetFullLaunchURL(extension).GetOrigin());
2555 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageProtected(
2556 origin1));
2558 // App 4 has a different origin (maps.google.com).
2559 extension = PackAndInstallCRX(data_dir().AppendASCII("app4"), INSTALL_NEW);
2560 ValidatePrefKeyCount(++pref_count);
2561 ASSERT_EQ(2u, registry()->enabled_extensions().size());
2562 const std::string id2 = extension->id();
2563 const GURL origin2(
2564 extensions::AppLaunchInfo::GetFullLaunchURL(extension).GetOrigin());
2565 ASSERT_NE(origin1, origin2);
2566 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageProtected(
2567 origin2));
2569 UninstallExtension(id1, false);
2570 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2572 UninstallExtension(id2, false);
2574 EXPECT_TRUE(registry()->enabled_extensions().is_empty());
2575 EXPECT_FALSE(
2576 profile()->GetExtensionSpecialStoragePolicy()->IsStorageProtected(
2577 origin1));
2578 EXPECT_FALSE(
2579 profile()->GetExtensionSpecialStoragePolicy()->IsStorageProtected(
2580 origin2));
2583 // Test that when an extension version is reinstalled, nothing happens.
2584 TEST_F(ExtensionServiceTest, Reinstall) {
2585 InitializeEmptyExtensionService();
2587 // A simple extension that should install without error.
2588 base::FilePath path = data_dir().AppendASCII("good.crx");
2589 InstallCRX(path, INSTALL_NEW);
2591 ValidatePrefKeyCount(1);
2592 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
2593 ValidateIntegerPref(good_crx, "location", Manifest::INTERNAL);
2595 // Reinstall the same version, it should overwrite the previous one.
2596 InstallCRX(path, INSTALL_UPDATED);
2598 ValidatePrefKeyCount(1);
2599 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
2600 ValidateIntegerPref(good_crx, "location", Manifest::INTERNAL);
2603 // Test that we can determine if extensions came from the
2604 // Chrome web store.
2605 TEST_F(ExtensionServiceTest, FromWebStore) {
2606 InitializeEmptyExtensionService();
2608 // A simple extension that should install without error.
2609 base::FilePath path = data_dir().AppendASCII("good.crx");
2610 // Not from web store.
2611 const Extension* extension = InstallCRX(path, INSTALL_NEW);
2612 std::string id = extension->id();
2614 ValidatePrefKeyCount(1);
2615 ASSERT_TRUE(ValidateBooleanPref(good_crx, "from_webstore", false));
2616 ASSERT_FALSE(extension->from_webstore());
2618 // Test install from web store.
2619 InstallCRXFromWebStore(path, INSTALL_UPDATED); // From web store.
2621 ValidatePrefKeyCount(1);
2622 ASSERT_TRUE(ValidateBooleanPref(good_crx, "from_webstore", true));
2624 // Reload so extension gets reinitialized with new value.
2625 service()->ReloadExtensionsForTest();
2626 extension = service()->GetExtensionById(id, false);
2627 ASSERT_TRUE(extension->from_webstore());
2629 // Upgrade to version 2.0
2630 path = data_dir().AppendASCII("good2.crx");
2631 UpdateExtension(good_crx, path, ENABLED);
2632 ValidatePrefKeyCount(1);
2633 ASSERT_TRUE(ValidateBooleanPref(good_crx, "from_webstore", true));
2636 // Test upgrading a signed extension.
2637 TEST_F(ExtensionServiceTest, UpgradeSignedGood) {
2638 InitializeEmptyExtensionService();
2640 base::FilePath path = data_dir().AppendASCII("good.crx");
2641 const Extension* extension = InstallCRX(path, INSTALL_NEW);
2642 std::string id = extension->id();
2644 ASSERT_EQ("1.0.0.0", extension->version()->GetString());
2645 ASSERT_EQ(0u, GetErrors().size());
2647 // Upgrade to version 1.0.0.1.
2648 // Also test that the extension's old and new title are correctly retrieved.
2649 path = data_dir().AppendASCII("good2.crx");
2650 InstallCRX(path, INSTALL_UPDATED, Extension::NO_FLAGS, "My extension 1");
2651 extension = service()->GetExtensionById(id, false);
2653 ASSERT_EQ("1.0.0.1", extension->version()->GetString());
2654 ASSERT_EQ("My updated extension 1", extension->name());
2655 ASSERT_EQ(0u, GetErrors().size());
2658 // Test upgrading a signed extension with a bad signature.
2659 TEST_F(ExtensionServiceTest, UpgradeSignedBad) {
2660 InitializeEmptyExtensionService();
2662 base::FilePath path = data_dir().AppendASCII("good.crx");
2663 InstallCRX(path, INSTALL_NEW);
2665 // Try upgrading with a bad signature. This should fail during the unpack,
2666 // because the key will not match the signature.
2667 path = data_dir().AppendASCII("bad_signature.crx");
2668 InstallCRX(path, INSTALL_FAILED);
2671 // Test a normal update via the UpdateExtension API
2672 TEST_F(ExtensionServiceTest, UpdateExtension) {
2673 InitializeEmptyExtensionService();
2675 base::FilePath path = data_dir().AppendASCII("good.crx");
2677 const Extension* good = InstallCRX(path, INSTALL_NEW);
2678 ASSERT_EQ("1.0.0.0", good->VersionString());
2679 ASSERT_EQ(good_crx, good->id());
2681 path = data_dir().AppendASCII("good2.crx");
2682 UpdateExtension(good_crx, path, ENABLED);
2683 ASSERT_EQ(
2684 "1.0.0.1",
2685 service()->GetExtensionById(good_crx, false)->version()->GetString());
2688 // Extensions should not be updated during browser shutdown.
2689 TEST_F(ExtensionServiceTest, UpdateExtensionDuringShutdown) {
2690 InitializeEmptyExtensionService();
2692 // Install an extension.
2693 base::FilePath path = data_dir().AppendASCII("good.crx");
2694 const Extension* good = InstallCRX(path, INSTALL_NEW);
2695 ASSERT_EQ(good_crx, good->id());
2697 // Simulate shutdown.
2698 service()->set_browser_terminating_for_test(true);
2700 // Update should fail and extension should not be updated.
2701 path = data_dir().AppendASCII("good2.crx");
2702 bool updated = service()->UpdateExtension(
2703 extensions::CRXFileInfo(good_crx, path), true, NULL);
2704 ASSERT_FALSE(updated);
2705 ASSERT_EQ(
2706 "1.0.0.0",
2707 service()->GetExtensionById(good_crx, false)->version()->GetString());
2710 // Test updating a not-already-installed extension - this should fail
2711 TEST_F(ExtensionServiceTest, UpdateNotInstalledExtension) {
2712 InitializeEmptyExtensionService();
2714 base::FilePath path = data_dir().AppendASCII("good.crx");
2715 UpdateExtension(good_crx, path, UPDATED);
2716 base::RunLoop().RunUntilIdle();
2718 ASSERT_EQ(0u, registry()->enabled_extensions().size());
2719 ASSERT_FALSE(installed_);
2720 ASSERT_EQ(0u, loaded_.size());
2723 // Makes sure you can't downgrade an extension via UpdateExtension
2724 TEST_F(ExtensionServiceTest, UpdateWillNotDowngrade) {
2725 InitializeEmptyExtensionService();
2727 base::FilePath path = data_dir().AppendASCII("good2.crx");
2729 const Extension* good = InstallCRX(path, INSTALL_NEW);
2730 ASSERT_EQ("1.0.0.1", good->VersionString());
2731 ASSERT_EQ(good_crx, good->id());
2733 // Change path from good2.crx -> good.crx
2734 path = data_dir().AppendASCII("good.crx");
2735 UpdateExtension(good_crx, path, FAILED);
2736 ASSERT_EQ(
2737 "1.0.0.1",
2738 service()->GetExtensionById(good_crx, false)->version()->GetString());
2741 // Make sure calling update with an identical version does nothing
2742 TEST_F(ExtensionServiceTest, UpdateToSameVersionIsNoop) {
2743 InitializeEmptyExtensionService();
2745 base::FilePath path = data_dir().AppendASCII("good.crx");
2747 const Extension* good = InstallCRX(path, INSTALL_NEW);
2748 ASSERT_EQ(good_crx, good->id());
2749 UpdateExtension(good_crx, path, FAILED_SILENTLY);
2752 // Tests that updating an extension does not clobber old state.
2753 TEST_F(ExtensionServiceTest, UpdateExtensionPreservesState) {
2754 InitializeEmptyExtensionService();
2756 base::FilePath path = data_dir().AppendASCII("good.crx");
2758 const Extension* good = InstallCRX(path, INSTALL_NEW);
2759 ASSERT_EQ("1.0.0.0", good->VersionString());
2760 ASSERT_EQ(good_crx, good->id());
2762 // Disable it and allow it to run in incognito. These settings should carry
2763 // over to the updated version.
2764 service()->DisableExtension(good->id(), Extension::DISABLE_USER_ACTION);
2765 extensions::util::SetIsIncognitoEnabled(good->id(), profile(), true);
2767 path = data_dir().AppendASCII("good2.crx");
2768 UpdateExtension(good_crx, path, INSTALLED);
2769 ASSERT_EQ(1u, registry()->disabled_extensions().size());
2770 const Extension* good2 = service()->GetExtensionById(good_crx, true);
2771 ASSERT_EQ("1.0.0.1", good2->version()->GetString());
2772 EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good2->id(), profile()));
2773 EXPECT_EQ(Extension::DISABLE_USER_ACTION,
2774 ExtensionPrefs::Get(profile())->GetDisableReasons(good2->id()));
2777 // Tests that updating preserves extension location.
2778 TEST_F(ExtensionServiceTest, UpdateExtensionPreservesLocation) {
2779 InitializeEmptyExtensionService();
2781 base::FilePath path = data_dir().AppendASCII("good.crx");
2783 const Extension* good =
2784 InstallCRXWithLocation(path, Manifest::EXTERNAL_PREF, INSTALL_NEW);
2786 ASSERT_EQ("1.0.0.0", good->VersionString());
2787 ASSERT_EQ(good_crx, good->id());
2789 path = data_dir().AppendASCII("good2.crx");
2790 UpdateExtension(good_crx, path, ENABLED);
2791 const Extension* good2 = service()->GetExtensionById(good_crx, false);
2792 ASSERT_EQ("1.0.0.1", good2->version()->GetString());
2793 EXPECT_EQ(good2->location(), Manifest::EXTERNAL_PREF);
2796 // Makes sure that LOAD extension types can downgrade.
2797 TEST_F(ExtensionServiceTest, LoadExtensionsCanDowngrade) {
2798 InitializeEmptyExtensionService();
2800 base::ScopedTempDir temp;
2801 ASSERT_TRUE(temp.CreateUniqueTempDir());
2803 // We'll write the extension manifest dynamically to a temporary path
2804 // to make it easier to change the version number.
2805 base::FilePath extension_path = temp.path();
2806 base::FilePath manifest_path =
2807 extension_path.Append(extensions::kManifestFilename);
2808 ASSERT_FALSE(base::PathExists(manifest_path));
2810 // Start with version 2.0.
2811 base::DictionaryValue manifest;
2812 manifest.SetString("version", "2.0");
2813 manifest.SetString("name", "LOAD Downgrade Test");
2814 manifest.SetInteger("manifest_version", 2);
2816 JSONFileValueSerializer serializer(manifest_path);
2817 ASSERT_TRUE(serializer.Serialize(manifest));
2819 extensions::UnpackedInstaller::Create(service())->Load(extension_path);
2820 base::RunLoop().RunUntilIdle();
2822 EXPECT_EQ(0u, GetErrors().size());
2823 ASSERT_EQ(1u, loaded_.size());
2824 EXPECT_EQ(Manifest::UNPACKED, loaded_[0]->location());
2825 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2826 EXPECT_EQ("2.0", loaded_[0]->VersionString());
2828 // Now set the version number to 1.0, reload the extensions and verify that
2829 // the downgrade was accepted.
2830 manifest.SetString("version", "1.0");
2831 ASSERT_TRUE(serializer.Serialize(manifest));
2833 extensions::UnpackedInstaller::Create(service())->Load(extension_path);
2834 base::RunLoop().RunUntilIdle();
2836 EXPECT_EQ(0u, GetErrors().size());
2837 ASSERT_EQ(1u, loaded_.size());
2838 EXPECT_EQ(Manifest::UNPACKED, loaded_[0]->location());
2839 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2840 EXPECT_EQ("1.0", loaded_[0]->VersionString());
2843 #if !defined(OS_POSIX) || defined(OS_MACOSX)
2844 // LOAD extensions with plugins require approval.
2845 // Only run this on platforms that support NPAPI plugins.
2846 TEST_F(ExtensionServiceTest, LoadExtensionsWithPlugins) {
2847 base::FilePath extension_with_plugin_path = good1_path();
2848 base::FilePath extension_no_plugin_path = good2_path();
2850 InitPluginService();
2851 InitializeEmptyExtensionService();
2852 service()->set_show_extensions_prompts(true);
2854 // Start by canceling any install prompts.
2855 scoped_ptr<extensions::ScopedTestDialogAutoConfirm> auto_confirm(
2856 new extensions::ScopedTestDialogAutoConfirm(
2857 extensions::ScopedTestDialogAutoConfirm::CANCEL));
2859 // The extension that has a plugin should not install.
2860 extensions::UnpackedInstaller::Create(service())
2861 ->Load(extension_with_plugin_path);
2862 base::RunLoop().RunUntilIdle();
2863 EXPECT_EQ(0u, GetErrors().size());
2864 EXPECT_EQ(0u, loaded_.size());
2865 EXPECT_EQ(0u, registry()->enabled_extensions().size());
2866 EXPECT_EQ(0u, registry()->disabled_extensions().size());
2868 // But the extension with no plugin should since there's no prompt.
2869 ExtensionErrorReporter::GetInstance()->ClearErrors();
2870 extensions::UnpackedInstaller::Create(service())
2871 ->Load(extension_no_plugin_path);
2872 base::RunLoop().RunUntilIdle();
2873 EXPECT_EQ(0u, GetErrors().size());
2874 EXPECT_EQ(1u, loaded_.size());
2875 EXPECT_EQ(1u, registry()->enabled_extensions().size());
2876 EXPECT_EQ(0u, registry()->disabled_extensions().size());
2877 EXPECT_TRUE(registry()->enabled_extensions().Contains(good2));
2879 // The plugin extension should install if we accept the dialog.
2880 auto_confirm.reset();
2881 auto_confirm.reset(new extensions::ScopedTestDialogAutoConfirm(
2882 extensions::ScopedTestDialogAutoConfirm::ACCEPT));
2884 ExtensionErrorReporter::GetInstance()->ClearErrors();
2885 extensions::UnpackedInstaller::Create(service())
2886 ->Load(extension_with_plugin_path);
2887 base::RunLoop().RunUntilIdle();
2888 EXPECT_EQ(0u, GetErrors().size());
2889 EXPECT_EQ(2u, loaded_.size());
2890 EXPECT_EQ(2u, registry()->enabled_extensions().size());
2891 EXPECT_EQ(0u, registry()->disabled_extensions().size());
2892 EXPECT_TRUE(registry()->enabled_extensions().Contains(good1));
2893 EXPECT_TRUE(registry()->enabled_extensions().Contains(good2));
2895 // Make sure the granted permissions have been setup.
2896 scoped_refptr<PermissionSet> permissions(
2897 ExtensionPrefs::Get(profile())->GetGrantedPermissions(good1));
2898 EXPECT_FALSE(permissions->IsEmpty());
2899 EXPECT_TRUE(permissions->HasEffectiveFullAccess());
2900 EXPECT_FALSE(permissions->apis().empty());
2901 EXPECT_TRUE(permissions->HasAPIPermission(APIPermission::kPlugin));
2903 // We should be able to reload the extension without getting another prompt.
2904 loaded_.clear();
2905 auto_confirm.reset();
2906 auto_confirm.reset(new extensions::ScopedTestDialogAutoConfirm(
2907 extensions::ScopedTestDialogAutoConfirm::CANCEL));
2909 service()->ReloadExtension(good1);
2910 base::RunLoop().RunUntilIdle();
2911 EXPECT_EQ(1u, loaded_.size());
2912 EXPECT_EQ(2u, registry()->enabled_extensions().size());
2913 EXPECT_EQ(0u, registry()->disabled_extensions().size());
2915 #endif // !defined(OS_POSIX) || defined(OS_MACOSX)
2917 namespace {
2919 bool IsExtension(const Extension* extension) {
2920 return extension->GetType() == Manifest::TYPE_EXTENSION;
2923 #if defined(ENABLE_BLACKLIST_TESTS)
2924 std::set<std::string> StringSet(const std::string& s) {
2925 std::set<std::string> set;
2926 set.insert(s);
2927 return set;
2929 std::set<std::string> StringSet(const std::string& s1, const std::string& s2) {
2930 std::set<std::string> set = StringSet(s1);
2931 set.insert(s2);
2932 return set;
2934 #endif // defined(ENABLE_BLACKLIST_TESTS)
2936 } // namespace
2938 // Test adding a pending extension.
2939 TEST_F(ExtensionServiceTest, AddPendingExtensionFromSync) {
2940 InitializeEmptyExtensionService();
2942 const std::string kFakeId(all_zero);
2943 const GURL kFakeUpdateURL("http:://fake.update/url");
2944 const bool kFakeRemoteInstall(false);
2945 const bool kFakeInstalledByCustodian(false);
2947 EXPECT_TRUE(
2948 service()->pending_extension_manager()->AddFromSync(
2949 kFakeId,
2950 kFakeUpdateURL,
2951 &IsExtension,
2952 kFakeRemoteInstall,
2953 kFakeInstalledByCustodian));
2955 const extensions::PendingExtensionInfo* pending_extension_info;
2956 ASSERT_TRUE((pending_extension_info =
2957 service()->pending_extension_manager()->GetById(kFakeId)));
2958 EXPECT_EQ(kFakeUpdateURL, pending_extension_info->update_url());
2959 EXPECT_EQ(&IsExtension, pending_extension_info->should_allow_install_);
2960 // Use
2961 // EXPECT_TRUE(kFakeRemoteInstall == pending_extension_info->remote_install())
2962 // instead of
2963 // EXPECT_EQ(kFakeRemoteInstall, pending_extension_info->remote_install())
2964 // as gcc 4.7 issues the following warning on EXPECT_EQ(false, x), which is
2965 // turned into an error with -Werror=conversion-null:
2966 // converting 'false' to pointer type for argument 1 of
2967 // 'char testing::internal::IsNullLiteralHelper(testing::internal::Secret*)'
2968 // https://code.google.com/p/googletest/issues/detail?id=458
2969 EXPECT_TRUE(kFakeRemoteInstall == pending_extension_info->remote_install());
2972 namespace {
2973 const char kGoodId[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
2974 const char kGoodUpdateURL[] = "http://good.update/url";
2975 const bool kGoodIsFromSync = true;
2976 const bool kGoodRemoteInstall = false;
2977 const bool kGoodInstalledByCustodian = false;
2978 } // namespace
2980 // Test updating a pending extension.
2981 TEST_F(ExtensionServiceTest, UpdatePendingExtension) {
2982 InitializeEmptyExtensionService();
2983 EXPECT_TRUE(
2984 service()->pending_extension_manager()->AddFromSync(
2985 kGoodId,
2986 GURL(kGoodUpdateURL),
2987 &IsExtension,
2988 kGoodRemoteInstall,
2989 kGoodInstalledByCustodian));
2990 EXPECT_TRUE(service()->pending_extension_manager()->IsIdPending(kGoodId));
2992 base::FilePath path = data_dir().AppendASCII("good.crx");
2993 UpdateExtension(kGoodId, path, ENABLED);
2995 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(kGoodId));
2997 const Extension* extension = service()->GetExtensionById(kGoodId, true);
2998 ASSERT_TRUE(extension);
3001 namespace {
3003 bool IsTheme(const Extension* extension) {
3004 return extension->is_theme();
3007 } // namespace
3009 // Test updating a pending theme.
3010 // Disabled due to ASAN failure. http://crbug.com/108320
3011 TEST_F(ExtensionServiceTest, DISABLED_UpdatePendingTheme) {
3012 InitializeEmptyExtensionService();
3013 EXPECT_TRUE(service()->pending_extension_manager()->AddFromSync(
3014 theme_crx, GURL(), &IsTheme, false, false));
3015 EXPECT_TRUE(service()->pending_extension_manager()->IsIdPending(theme_crx));
3017 base::FilePath path = data_dir().AppendASCII("theme.crx");
3018 UpdateExtension(theme_crx, path, ENABLED);
3020 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(theme_crx));
3022 const Extension* extension = service()->GetExtensionById(theme_crx, true);
3023 ASSERT_TRUE(extension);
3025 EXPECT_FALSE(
3026 ExtensionPrefs::Get(profile())->IsExtensionDisabled(extension->id()));
3027 EXPECT_TRUE(service()->IsExtensionEnabled(theme_crx));
3030 #if defined(OS_CHROMEOS)
3031 // Always fails on ChromeOS: http://crbug.com/79737
3032 #define MAYBE_UpdatePendingExternalCrx DISABLED_UpdatePendingExternalCrx
3033 #else
3034 #define MAYBE_UpdatePendingExternalCrx UpdatePendingExternalCrx
3035 #endif
3036 // Test updating a pending CRX as if the source is an external extension
3037 // with an update URL. In this case we don't know if the CRX is a theme
3038 // or not.
3039 TEST_F(ExtensionServiceTest, MAYBE_UpdatePendingExternalCrx) {
3040 InitializeEmptyExtensionService();
3041 EXPECT_TRUE(service()->pending_extension_manager()->AddFromExternalUpdateUrl(
3042 theme_crx,
3043 std::string(),
3044 GURL(),
3045 Manifest::EXTERNAL_PREF_DOWNLOAD,
3046 Extension::NO_FLAGS,
3047 false));
3049 EXPECT_TRUE(service()->pending_extension_manager()->IsIdPending(theme_crx));
3051 base::FilePath path = data_dir().AppendASCII("theme.crx");
3052 UpdateExtension(theme_crx, path, ENABLED);
3054 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(theme_crx));
3056 const Extension* extension = service()->GetExtensionById(theme_crx, true);
3057 ASSERT_TRUE(extension);
3059 EXPECT_FALSE(
3060 ExtensionPrefs::Get(profile())->IsExtensionDisabled(extension->id()));
3061 EXPECT_TRUE(service()->IsExtensionEnabled(extension->id()));
3062 EXPECT_FALSE(
3063 extensions::util::IsIncognitoEnabled(extension->id(), profile()));
3066 // Test updating a pending CRX as if the source is an external extension
3067 // with an update URL. The external update should overwrite a sync update,
3068 // but a sync update should not overwrite a non-sync update.
3069 TEST_F(ExtensionServiceTest, UpdatePendingExternalCrxWinsOverSync) {
3070 InitializeEmptyExtensionService();
3072 // Add a crx to be installed from the update mechanism.
3073 EXPECT_TRUE(
3074 service()->pending_extension_manager()->AddFromSync(
3075 kGoodId,
3076 GURL(kGoodUpdateURL),
3077 &IsExtension,
3078 kGoodRemoteInstall,
3079 kGoodInstalledByCustodian));
3081 // Check that there is a pending crx, with is_from_sync set to true.
3082 const extensions::PendingExtensionInfo* pending_extension_info;
3083 ASSERT_TRUE((pending_extension_info =
3084 service()->pending_extension_manager()->GetById(kGoodId)));
3085 EXPECT_TRUE(pending_extension_info->is_from_sync());
3087 // Add a crx to be updated, with the same ID, from a non-sync source.
3088 EXPECT_TRUE(service()->pending_extension_manager()->AddFromExternalUpdateUrl(
3089 kGoodId,
3090 std::string(),
3091 GURL(kGoodUpdateURL),
3092 Manifest::EXTERNAL_PREF_DOWNLOAD,
3093 Extension::NO_FLAGS,
3094 false));
3096 // Check that there is a pending crx, with is_from_sync set to false.
3097 ASSERT_TRUE((pending_extension_info =
3098 service()->pending_extension_manager()->GetById(kGoodId)));
3099 EXPECT_FALSE(pending_extension_info->is_from_sync());
3100 EXPECT_EQ(Manifest::EXTERNAL_PREF_DOWNLOAD,
3101 pending_extension_info->install_source());
3103 // Add a crx to be installed from the update mechanism.
3104 EXPECT_FALSE(
3105 service()->pending_extension_manager()->AddFromSync(
3106 kGoodId,
3107 GURL(kGoodUpdateURL),
3108 &IsExtension,
3109 kGoodRemoteInstall,
3110 kGoodInstalledByCustodian));
3112 // Check that the external, non-sync update was not overridden.
3113 ASSERT_TRUE((pending_extension_info =
3114 service()->pending_extension_manager()->GetById(kGoodId)));
3115 EXPECT_FALSE(pending_extension_info->is_from_sync());
3116 EXPECT_EQ(Manifest::EXTERNAL_PREF_DOWNLOAD,
3117 pending_extension_info->install_source());
3120 // Updating a theme should fail if the updater is explicitly told that
3121 // the CRX is not a theme.
3122 TEST_F(ExtensionServiceTest, UpdatePendingCrxThemeMismatch) {
3123 InitializeEmptyExtensionService();
3124 EXPECT_TRUE(service()->pending_extension_manager()->AddFromSync(
3125 theme_crx, GURL(), &IsExtension, false, false));
3127 EXPECT_TRUE(service()->pending_extension_manager()->IsIdPending(theme_crx));
3129 base::FilePath path = data_dir().AppendASCII("theme.crx");
3130 UpdateExtension(theme_crx, path, FAILED_SILENTLY);
3132 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(theme_crx));
3134 const Extension* extension = service()->GetExtensionById(theme_crx, true);
3135 ASSERT_FALSE(extension);
3138 // TODO(akalin): Test updating a pending extension non-silently once
3139 // we can mock out ExtensionInstallUI and inject our version into
3140 // UpdateExtension().
3142 // Test updating a pending extension which fails the should-install test.
3143 TEST_F(ExtensionServiceTest, UpdatePendingExtensionFailedShouldInstallTest) {
3144 InitializeEmptyExtensionService();
3145 // Add pending extension with a flipped is_theme.
3146 EXPECT_TRUE(
3147 service()->pending_extension_manager()->AddFromSync(
3148 kGoodId,
3149 GURL(kGoodUpdateURL),
3150 &IsTheme,
3151 kGoodRemoteInstall,
3152 kGoodInstalledByCustodian));
3153 EXPECT_TRUE(service()->pending_extension_manager()->IsIdPending(kGoodId));
3155 base::FilePath path = data_dir().AppendASCII("good.crx");
3156 UpdateExtension(kGoodId, path, UPDATED);
3158 // TODO(akalin): Figure out how to check that the extensions
3159 // directory is cleaned up properly in OnExtensionInstalled().
3161 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(kGoodId));
3164 // TODO(akalin): Figure out how to test that installs of pending
3165 // unsyncable extensions are blocked.
3167 // Test updating a pending extension for one that is not pending.
3168 TEST_F(ExtensionServiceTest, UpdatePendingExtensionNotPending) {
3169 InitializeEmptyExtensionService();
3171 base::FilePath path = data_dir().AppendASCII("good.crx");
3172 UpdateExtension(kGoodId, path, UPDATED);
3174 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(kGoodId));
3177 // Test updating a pending extension for one that is already
3178 // installed.
3179 TEST_F(ExtensionServiceTest, UpdatePendingExtensionAlreadyInstalled) {
3180 InitializeEmptyExtensionService();
3182 base::FilePath path = data_dir().AppendASCII("good.crx");
3183 const Extension* good = InstallCRX(path, INSTALL_NEW);
3184 ASSERT_EQ(1u, registry()->enabled_extensions().size());
3186 EXPECT_FALSE(good->is_theme());
3188 // Use AddExtensionImpl() as AddFrom*() would balk.
3189 service()->pending_extension_manager()->AddExtensionImpl(
3190 good->id(),
3191 std::string(),
3192 extensions::ManifestURL::GetUpdateURL(good),
3193 Version(),
3194 &IsExtension,
3195 kGoodIsFromSync,
3196 Manifest::INTERNAL,
3197 Extension::NO_FLAGS,
3198 false,
3199 kGoodRemoteInstall);
3200 UpdateExtension(good->id(), path, ENABLED);
3202 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(kGoodId));
3205 #if defined(ENABLE_BLACKLIST_TESTS)
3206 // Tests blacklisting then unblacklisting extensions after the service has been
3207 // initialized.
3208 TEST_F(ExtensionServiceTest, SetUnsetBlacklistInPrefs) {
3209 extensions::TestBlacklist test_blacklist;
3210 // A profile with 3 extensions installed: good0, good1, and good2.
3211 InitializeGoodInstalledExtensionService();
3212 test_blacklist.Attach(service()->blacklist_);
3213 service()->Init();
3215 const extensions::ExtensionSet& enabled_extensions =
3216 registry()->enabled_extensions();
3217 const extensions::ExtensionSet& blacklisted_extensions =
3218 registry()->blacklisted_extensions();
3220 EXPECT_TRUE(enabled_extensions.Contains(good0) &&
3221 !blacklisted_extensions.Contains(good0));
3222 EXPECT_TRUE(enabled_extensions.Contains(good1) &&
3223 !blacklisted_extensions.Contains(good1));
3224 EXPECT_TRUE(enabled_extensions.Contains(good2) &&
3225 !blacklisted_extensions.Contains(good2));
3227 EXPECT_FALSE(IsPrefExist(good0, "blacklist"));
3228 EXPECT_FALSE(IsPrefExist(good1, "blacklist"));
3229 EXPECT_FALSE(IsPrefExist(good2, "blacklist"));
3230 EXPECT_FALSE(IsPrefExist("invalid_id", "blacklist"));
3232 // Blacklist good0 and good1 (and an invalid extension ID).
3233 test_blacklist.SetBlacklistState(
3234 good0, extensions::BLACKLISTED_MALWARE, true);
3235 test_blacklist.SetBlacklistState(
3236 good1, extensions::BLACKLISTED_MALWARE, true);
3237 test_blacklist.SetBlacklistState(
3238 "invalid_id", extensions::BLACKLISTED_MALWARE, true);
3239 base::RunLoop().RunUntilIdle();
3241 EXPECT_TRUE(!enabled_extensions.Contains(good0) &&
3242 blacklisted_extensions.Contains(good0));
3243 EXPECT_TRUE(!enabled_extensions.Contains(good1) &&
3244 blacklisted_extensions.Contains(good1));
3245 EXPECT_TRUE(enabled_extensions.Contains(good2) &&
3246 !blacklisted_extensions.Contains(good2));
3248 EXPECT_TRUE(ValidateBooleanPref(good0, "blacklist", true));
3249 EXPECT_TRUE(ValidateBooleanPref(good1, "blacklist", true));
3250 EXPECT_FALSE(IsPrefExist(good2, "blacklist"));
3251 EXPECT_FALSE(IsPrefExist("invalid_id", "blacklist"));
3253 // Un-blacklist good1 and blacklist good2.
3254 test_blacklist.Clear(false);
3255 test_blacklist.SetBlacklistState(
3256 good0, extensions::BLACKLISTED_MALWARE, true);
3257 test_blacklist.SetBlacklistState(
3258 good2, extensions::BLACKLISTED_MALWARE, true);
3259 test_blacklist.SetBlacklistState(
3260 "invalid_id", extensions::BLACKLISTED_MALWARE, true);
3261 base::RunLoop().RunUntilIdle();
3263 EXPECT_TRUE(!enabled_extensions.Contains(good0) &&
3264 blacklisted_extensions.Contains(good0));
3265 EXPECT_TRUE(enabled_extensions.Contains(good1) &&
3266 !blacklisted_extensions.Contains(good1));
3267 EXPECT_TRUE(!enabled_extensions.Contains(good2) &&
3268 blacklisted_extensions.Contains(good2));
3270 EXPECT_TRUE(ValidateBooleanPref(good0, "blacklist", true));
3271 EXPECT_FALSE(IsPrefExist(good1, "blacklist"));
3272 EXPECT_TRUE(ValidateBooleanPref(good2, "blacklist", true));
3273 EXPECT_FALSE(IsPrefExist("invalid_id", "blacklist"));
3275 #endif // defined(ENABLE_BLACKLIST_TESTS)
3277 #if defined(ENABLE_BLACKLIST_TESTS)
3278 // Tests trying to install a blacklisted extension.
3279 TEST_F(ExtensionServiceTest, BlacklistedExtensionWillNotInstall) {
3280 scoped_refptr<FakeSafeBrowsingDatabaseManager> blacklist_db(
3281 new FakeSafeBrowsingDatabaseManager(true));
3282 Blacklist::ScopedDatabaseManagerForTest scoped_blacklist_db(blacklist_db);
3284 InitializeEmptyExtensionService();
3285 service()->Init();
3287 // After blacklisting good_crx, we cannot install it.
3288 blacklist_db->SetUnsafe(good_crx).NotifyUpdate();
3289 base::RunLoop().RunUntilIdle();
3291 base::FilePath path = data_dir().AppendASCII("good.crx");
3292 // HACK: specify WAS_INSTALLED_BY_DEFAULT so that test machinery doesn't
3293 // decide to install this silently. Somebody should fix these tests, all
3294 // 6,000 lines of them. Hah!
3295 InstallCRX(path, INSTALL_FAILED, Extension::WAS_INSTALLED_BY_DEFAULT);
3296 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3298 #endif // defined(ENABLE_BLACKLIST_TESTS)
3300 #if defined(ENABLE_BLACKLIST_TESTS)
3301 // Unload blacklisted extension on policy change.
3302 TEST_F(ExtensionServiceTest, UnloadBlacklistedExtensionPolicy) {
3303 extensions::TestBlacklist test_blacklist;
3305 // A profile with no extensions installed.
3306 InitializeEmptyExtensionServiceWithTestingPrefs();
3307 test_blacklist.Attach(service()->blacklist_);
3309 base::FilePath path = data_dir().AppendASCII("good.crx");
3311 const Extension* good = InstallCRX(path, INSTALL_NEW);
3312 EXPECT_EQ(good_crx, good->id());
3313 UpdateExtension(good_crx, path, FAILED_SILENTLY);
3314 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3317 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
3318 pref.SetIndividualExtensionInstallationAllowed(good_crx, true);
3321 test_blacklist.SetBlacklistState(
3322 good_crx, extensions::BLACKLISTED_MALWARE, true);
3323 base::RunLoop().RunUntilIdle();
3325 // The good_crx is blacklisted and the whitelist doesn't negate it.
3326 ASSERT_TRUE(ValidateBooleanPref(good_crx, "blacklist", true));
3327 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3329 #endif // defined(ENABLE_BLACKLIST_TESTS)
3331 #if defined(ENABLE_BLACKLIST_TESTS)
3332 // Tests that a blacklisted extension is eventually unloaded on startup, if it
3333 // wasn't already.
3334 TEST_F(ExtensionServiceTest, WillNotLoadBlacklistedExtensionsFromDirectory) {
3335 extensions::TestBlacklist test_blacklist;
3337 // A profile with 3 extensions installed: good0, good1, and good2.
3338 InitializeGoodInstalledExtensionService();
3339 test_blacklist.Attach(service()->blacklist_);
3341 // Blacklist good1 before the service initializes.
3342 test_blacklist.SetBlacklistState(
3343 good1, extensions::BLACKLISTED_MALWARE, false);
3345 // Load extensions.
3346 service()->Init();
3347 ASSERT_EQ(3u, loaded_.size()); // hasn't had time to blacklist yet
3349 base::RunLoop().RunUntilIdle();
3351 ASSERT_EQ(1u, registry()->blacklisted_extensions().size());
3352 ASSERT_EQ(2u, registry()->enabled_extensions().size());
3354 ASSERT_TRUE(registry()->enabled_extensions().Contains(good0));
3355 ASSERT_TRUE(registry()->blacklisted_extensions().Contains(good1));
3356 ASSERT_TRUE(registry()->enabled_extensions().Contains(good2));
3358 #endif // defined(ENABLE_BLACKLIST_TESTS)
3360 #if defined(ENABLE_BLACKLIST_TESTS)
3361 // Tests extensions blacklisted in prefs on startup; one still blacklisted by
3362 // safe browsing, the other not. The not-blacklisted one should recover.
3363 TEST_F(ExtensionServiceTest, BlacklistedInPrefsFromStartup) {
3364 extensions::TestBlacklist test_blacklist;
3366 InitializeGoodInstalledExtensionService();
3367 test_blacklist.Attach(service()->blacklist_);
3368 ExtensionPrefs::Get(profile())->SetExtensionBlacklisted(good0, true);
3369 ExtensionPrefs::Get(profile())->SetExtensionBlacklisted(good1, true);
3371 test_blacklist.SetBlacklistState(
3372 good1, extensions::BLACKLISTED_MALWARE, false);
3374 // Extension service hasn't loaded yet, but IsExtensionEnabled reads out of
3375 // prefs. Ensure it takes into account the blacklist state (crbug.com/373842).
3376 EXPECT_FALSE(service()->IsExtensionEnabled(good0));
3377 EXPECT_FALSE(service()->IsExtensionEnabled(good1));
3378 EXPECT_TRUE(service()->IsExtensionEnabled(good2));
3380 service()->Init();
3382 EXPECT_EQ(2u, registry()->blacklisted_extensions().size());
3383 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3385 EXPECT_TRUE(registry()->blacklisted_extensions().Contains(good0));
3386 EXPECT_TRUE(registry()->blacklisted_extensions().Contains(good1));
3387 EXPECT_TRUE(registry()->enabled_extensions().Contains(good2));
3389 // Give time for the blacklist to update.
3390 base::RunLoop().RunUntilIdle();
3392 EXPECT_EQ(1u, registry()->blacklisted_extensions().size());
3393 EXPECT_EQ(2u, registry()->enabled_extensions().size());
3395 EXPECT_TRUE(registry()->enabled_extensions().Contains(good0));
3396 EXPECT_TRUE(registry()->blacklisted_extensions().Contains(good1));
3397 EXPECT_TRUE(registry()->enabled_extensions().Contains(good2));
3399 #endif // defined(ENABLE_BLACKLIST_TESTS)
3401 #if defined(ENABLE_BLACKLIST_TESTS)
3402 // Extension is added to blacklist with BLACKLISTED_POTENTIALLY_UNWANTED state
3403 // after it is installed. It is then successfully re-enabled by the user.
3404 TEST_F(ExtensionServiceTest, GreylistedExtensionDisabled) {
3405 extensions::TestBlacklist test_blacklist;
3406 // A profile with 3 extensions installed: good0, good1, and good2.
3407 InitializeGoodInstalledExtensionService();
3408 test_blacklist.Attach(service()->blacklist_);
3409 service()->Init();
3411 const extensions::ExtensionSet& enabled_extensions =
3412 registry()->enabled_extensions();
3413 const extensions::ExtensionSet& disabled_extensions =
3414 registry()->disabled_extensions();
3416 EXPECT_TRUE(enabled_extensions.Contains(good0));
3417 EXPECT_TRUE(enabled_extensions.Contains(good1));
3418 EXPECT_TRUE(enabled_extensions.Contains(good2));
3420 // Blacklist good0 and good1 (and an invalid extension ID).
3421 test_blacklist.SetBlacklistState(
3422 good0, extensions::BLACKLISTED_CWS_POLICY_VIOLATION, true);
3423 test_blacklist.SetBlacklistState(
3424 good1, extensions::BLACKLISTED_POTENTIALLY_UNWANTED, true);
3425 test_blacklist.SetBlacklistState(
3426 "invalid_id", extensions::BLACKLISTED_MALWARE, true);
3427 base::RunLoop().RunUntilIdle();
3429 EXPECT_FALSE(enabled_extensions.Contains(good0));
3430 EXPECT_TRUE(disabled_extensions.Contains(good0));
3431 EXPECT_FALSE(enabled_extensions.Contains(good1));
3432 EXPECT_TRUE(disabled_extensions.Contains(good1));
3433 EXPECT_TRUE(enabled_extensions.Contains(good2));
3434 EXPECT_FALSE(disabled_extensions.Contains(good2));
3436 ValidateIntegerPref(
3437 good0, "blacklist_state", extensions::BLACKLISTED_CWS_POLICY_VIOLATION);
3438 ValidateIntegerPref(
3439 good1, "blacklist_state", extensions::BLACKLISTED_POTENTIALLY_UNWANTED);
3441 // Now user enables good0.
3442 service()->EnableExtension(good0);
3444 EXPECT_TRUE(enabled_extensions.Contains(good0));
3445 EXPECT_FALSE(disabled_extensions.Contains(good0));
3446 EXPECT_FALSE(enabled_extensions.Contains(good1));
3447 EXPECT_TRUE(disabled_extensions.Contains(good1));
3449 // Remove extensions from blacklist.
3450 test_blacklist.SetBlacklistState(
3451 good0, extensions::NOT_BLACKLISTED, true);
3452 test_blacklist.SetBlacklistState(
3453 good1, extensions::NOT_BLACKLISTED, true);
3454 base::RunLoop().RunUntilIdle();
3456 // All extensions are enabled.
3457 EXPECT_TRUE(enabled_extensions.Contains(good0));
3458 EXPECT_FALSE(disabled_extensions.Contains(good0));
3459 EXPECT_TRUE(enabled_extensions.Contains(good1));
3460 EXPECT_FALSE(disabled_extensions.Contains(good1));
3461 EXPECT_TRUE(enabled_extensions.Contains(good2));
3462 EXPECT_FALSE(disabled_extensions.Contains(good2));
3464 #endif // defined(ENABLE_BLACKLIST_TESTS)
3466 #if defined(ENABLE_BLACKLIST_TESTS)
3467 // When extension is removed from greylist, do not re-enable it if it is
3468 // disabled by user.
3469 TEST_F(ExtensionServiceTest, GreylistDontEnableManuallyDisabled) {
3470 extensions::TestBlacklist test_blacklist;
3471 // A profile with 3 extensions installed: good0, good1, and good2.
3472 InitializeGoodInstalledExtensionService();
3473 test_blacklist.Attach(service()->blacklist_);
3474 service()->Init();
3476 const extensions::ExtensionSet& enabled_extensions =
3477 registry()->enabled_extensions();
3478 const extensions::ExtensionSet& disabled_extensions =
3479 registry()->disabled_extensions();
3481 // Manually disable.
3482 service()->DisableExtension(good0,
3483 extensions::Extension::DISABLE_USER_ACTION);
3485 test_blacklist.SetBlacklistState(
3486 good0, extensions::BLACKLISTED_CWS_POLICY_VIOLATION, true);
3487 test_blacklist.SetBlacklistState(
3488 good1, extensions::BLACKLISTED_POTENTIALLY_UNWANTED, true);
3489 test_blacklist.SetBlacklistState(
3490 good2, extensions::BLACKLISTED_SECURITY_VULNERABILITY, true);
3491 base::RunLoop().RunUntilIdle();
3493 // All extensions disabled.
3494 EXPECT_FALSE(enabled_extensions.Contains(good0));
3495 EXPECT_TRUE(disabled_extensions.Contains(good0));
3496 EXPECT_FALSE(enabled_extensions.Contains(good1));
3497 EXPECT_TRUE(disabled_extensions.Contains(good1));
3498 EXPECT_FALSE(enabled_extensions.Contains(good2));
3499 EXPECT_TRUE(disabled_extensions.Contains(good2));
3501 // Greylisted extension can be enabled.
3502 service()->EnableExtension(good1);
3503 EXPECT_TRUE(enabled_extensions.Contains(good1));
3504 EXPECT_FALSE(disabled_extensions.Contains(good1));
3506 // good1 is now manually disabled.
3507 service()->DisableExtension(good1,
3508 extensions::Extension::DISABLE_USER_ACTION);
3509 EXPECT_FALSE(enabled_extensions.Contains(good1));
3510 EXPECT_TRUE(disabled_extensions.Contains(good1));
3512 // Remove extensions from blacklist.
3513 test_blacklist.SetBlacklistState(
3514 good0, extensions::NOT_BLACKLISTED, true);
3515 test_blacklist.SetBlacklistState(
3516 good1, extensions::NOT_BLACKLISTED, true);
3517 test_blacklist.SetBlacklistState(
3518 good2, extensions::NOT_BLACKLISTED, true);
3519 base::RunLoop().RunUntilIdle();
3521 // good0 and good1 remain disabled.
3522 EXPECT_FALSE(enabled_extensions.Contains(good0));
3523 EXPECT_TRUE(disabled_extensions.Contains(good0));
3524 EXPECT_FALSE(enabled_extensions.Contains(good1));
3525 EXPECT_TRUE(disabled_extensions.Contains(good1));
3526 EXPECT_TRUE(enabled_extensions.Contains(good2));
3527 EXPECT_FALSE(disabled_extensions.Contains(good2));
3529 #endif // defined(ENABLE_BLACKLIST_TESTS)
3531 #if defined(ENABLE_BLACKLIST_TESTS)
3532 // Blacklisted extension with unknown state are not enabled/disabled.
3533 TEST_F(ExtensionServiceTest, GreylistUnknownDontChange) {
3534 extensions::TestBlacklist test_blacklist;
3535 // A profile with 3 extensions installed: good0, good1, and good2.
3536 InitializeGoodInstalledExtensionService();
3537 test_blacklist.Attach(service()->blacklist_);
3538 service()->Init();
3540 const extensions::ExtensionSet& enabled_extensions =
3541 registry()->enabled_extensions();
3542 const extensions::ExtensionSet& disabled_extensions =
3543 registry()->disabled_extensions();
3545 test_blacklist.SetBlacklistState(
3546 good0, extensions::BLACKLISTED_CWS_POLICY_VIOLATION, true);
3547 test_blacklist.SetBlacklistState(
3548 good1, extensions::BLACKLISTED_POTENTIALLY_UNWANTED, true);
3549 base::RunLoop().RunUntilIdle();
3551 EXPECT_FALSE(enabled_extensions.Contains(good0));
3552 EXPECT_TRUE(disabled_extensions.Contains(good0));
3553 EXPECT_FALSE(enabled_extensions.Contains(good1));
3554 EXPECT_TRUE(disabled_extensions.Contains(good1));
3555 EXPECT_TRUE(enabled_extensions.Contains(good2));
3556 EXPECT_FALSE(disabled_extensions.Contains(good2));
3558 test_blacklist.SetBlacklistState(
3559 good0, extensions::NOT_BLACKLISTED, true);
3560 test_blacklist.SetBlacklistState(
3561 good1, extensions::BLACKLISTED_UNKNOWN, true);
3562 test_blacklist.SetBlacklistState(
3563 good2, extensions::BLACKLISTED_UNKNOWN, true);
3564 base::RunLoop().RunUntilIdle();
3566 // good0 re-enabled, other remain as they were.
3567 EXPECT_TRUE(enabled_extensions.Contains(good0));
3568 EXPECT_FALSE(disabled_extensions.Contains(good0));
3569 EXPECT_FALSE(enabled_extensions.Contains(good1));
3570 EXPECT_TRUE(disabled_extensions.Contains(good1));
3571 EXPECT_TRUE(enabled_extensions.Contains(good2));
3572 EXPECT_FALSE(disabled_extensions.Contains(good2));
3575 // Tests that blacklisted extensions cannot be reloaded, both those loaded
3576 // before and after extension service startup.
3577 TEST_F(ExtensionServiceTest, ReloadBlacklistedExtension) {
3578 extensions::TestBlacklist test_blacklist;
3580 InitializeGoodInstalledExtensionService();
3581 test_blacklist.Attach(service()->blacklist_);
3583 test_blacklist.SetBlacklistState(
3584 good1, extensions::BLACKLISTED_MALWARE, false);
3585 service()->Init();
3586 test_blacklist.SetBlacklistState(
3587 good2, extensions::BLACKLISTED_MALWARE, false);
3588 base::RunLoop().RunUntilIdle();
3590 EXPECT_EQ(StringSet(good0), registry()->enabled_extensions().GetIDs());
3591 EXPECT_EQ(StringSet(good1, good2),
3592 registry()->blacklisted_extensions().GetIDs());
3594 service()->ReloadExtension(good1);
3595 service()->ReloadExtension(good2);
3596 base::RunLoop().RunUntilIdle();
3598 EXPECT_EQ(StringSet(good0), registry()->enabled_extensions().GetIDs());
3599 EXPECT_EQ(StringSet(good1, good2),
3600 registry()->blacklisted_extensions().GetIDs());
3602 #endif // defined(ENABLE_BLACKLIST_TESTS)
3604 // Tests blocking then unblocking enabled extensions after the service has been
3605 // initialized.
3606 TEST_F(ExtensionServiceTest, BlockAndUnblockEnabledExtension) {
3607 InitializeGoodInstalledExtensionService();
3608 service()->Init();
3610 AssertExtensionBlocksAndUnblocks(true, good0);
3613 // Tests blocking then unblocking disabled extensions after the service has been
3614 // initialized.
3615 TEST_F(ExtensionServiceTest, BlockAndUnblockDisabledExtension) {
3616 InitializeGoodInstalledExtensionService();
3617 service()->Init();
3619 service()->DisableExtension(good0, Extension::DISABLE_RELOAD);
3621 AssertExtensionBlocksAndUnblocks(true, good0);
3624 // Tests blocking then unblocking terminated extensions after the service has
3625 // been initialized.
3626 TEST_F(ExtensionServiceTest, BlockAndUnblockTerminatedExtension) {
3627 InitializeGoodInstalledExtensionService();
3628 service()->Init();
3630 TerminateExtension(good0);
3632 AssertExtensionBlocksAndUnblocks(true, good0);
3635 // Tests blocking then unblocking policy-forced extensions after the service has
3636 // been initialized.
3637 TEST_F(ExtensionServiceTest, BlockAndUnblockPolicyExtension) {
3638 InitializeEmptyExtensionServiceWithTestingPrefs();
3641 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
3642 // // Blacklist everything.
3643 // pref.SetBlacklistedByDefault(true);
3644 // Mark good.crx for force-installation.
3645 pref.SetIndividualExtensionAutoInstalled(
3646 good_crx, "http://example.com/update_url", true);
3649 // Have policy force-install an extension.
3650 MockExtensionProvider* provider =
3651 new MockExtensionProvider(service(), Manifest::EXTERNAL_POLICY_DOWNLOAD);
3652 AddMockExternalProvider(provider);
3653 provider->UpdateOrAddExtension(
3654 good_crx, "1.0.0.0", data_dir().AppendASCII("good_crx"));
3656 // Reloading extensions should find our externally registered extension
3657 // and install it.
3658 content::WindowedNotificationObserver observer(
3659 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
3660 content::NotificationService::AllSources());
3661 service()->CheckForExternalUpdates();
3662 observer.Wait();
3664 AssertExtensionBlocksAndUnblocks(false, good_crx);
3668 #if defined(ENABLE_BLACKLIST_TESTS)
3669 // Tests blocking then unblocking extensions that are blacklisted both before
3670 // and after Init().
3671 TEST_F(ExtensionServiceTest, BlockAndUnblockBlacklistedExtension) {
3672 extensions::TestBlacklist test_blacklist;
3674 InitializeGoodInstalledExtensionService();
3675 test_blacklist.Attach(service()->blacklist_);
3677 test_blacklist.SetBlacklistState(
3678 good0, extensions::BLACKLISTED_MALWARE, true);
3679 base::RunLoop().RunUntilIdle();
3681 service()->Init();
3683 test_blacklist.SetBlacklistState(
3684 good1, extensions::BLACKLISTED_MALWARE, true);
3685 base::RunLoop().RunUntilIdle();
3687 // Blacklisted extensions stay blacklisted.
3688 AssertExtensionBlocksAndUnblocks(false, good0);
3689 AssertExtensionBlocksAndUnblocks(false, good1);
3691 service()->BlockAllExtensions();
3693 // Remove an extension from the blacklist while the service is blocked.
3694 test_blacklist.SetBlacklistState(
3695 good0, extensions::NOT_BLACKLISTED, true);
3696 // Add an extension to the blacklist while the service is blocked.
3697 test_blacklist.SetBlacklistState(
3698 good2, extensions::BLACKLISTED_MALWARE, true);
3699 base::RunLoop().RunUntilIdle();
3701 // Go directly to blocked, do not pass go, do not collect $200.
3702 ASSERT_TRUE(IsBlocked(good0));
3703 // Get on the blacklist - even if you were blocked!
3704 ASSERT_FALSE(IsBlocked(good2));
3706 #endif // defined(ENABLE_BLACKLIST_TESTS)
3708 // Tests blocking then unblocking enabled component extensions after the service
3709 // has been initialized.
3710 TEST_F(ExtensionServiceTest, BlockAndUnblockEnabledComponentExtension) {
3711 InitializeEmptyExtensionServiceWithTestingPrefs();
3713 // Install a component extension.
3714 base::FilePath path = data_dir()
3715 .AppendASCII("good")
3716 .AppendASCII("Extensions")
3717 .AppendASCII(good0)
3718 .AppendASCII("1.0.0.0");
3719 std::string manifest;
3720 ASSERT_TRUE(base::ReadFileToString(
3721 path.Append(extensions::kManifestFilename), &manifest));
3722 service()->component_loader()->Add(manifest, path);
3723 service()->Init();
3725 // Component extension should never block.
3726 AssertExtensionBlocksAndUnblocks(false, good0);
3729 // Tests blocking then unblocking a theme after the service has been
3730 // initialized.
3731 TEST_F(ExtensionServiceTest, BlockAndUnblockTheme) {
3732 InitializeEmptyExtensionService();
3733 service()->Init();
3735 base::FilePath path = data_dir().AppendASCII("theme.crx");
3736 InstallCRX(path, INSTALL_NEW);
3738 AssertExtensionBlocksAndUnblocks(true, theme_crx);
3741 // Tests that blocking extensions before Init() results in loading blocked
3742 // extensions.
3743 TEST_F(ExtensionServiceTest, WillNotLoadExtensionsWhenBlocked) {
3744 InitializeGoodInstalledExtensionService();
3746 service()->BlockAllExtensions();
3748 service()->Init();
3750 ASSERT_TRUE(IsBlocked(good0));
3751 ASSERT_TRUE(IsBlocked(good0));
3752 ASSERT_TRUE(IsBlocked(good0));
3755 // Tests that IsEnabledExtension won't crash on an uninstalled extension.
3756 TEST_F(ExtensionServiceTest, IsEnabledExtensionBlockedAndNotInstalled) {
3757 InitializeEmptyExtensionService();
3759 service()->BlockAllExtensions();
3761 service()->IsExtensionEnabled(theme_crx);
3764 // Will not install extension blacklisted by policy.
3765 TEST_F(ExtensionServiceTest, BlacklistedByPolicyWillNotInstall) {
3766 InitializeEmptyExtensionServiceWithTestingPrefs();
3768 // Blacklist everything.
3770 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
3771 pref.SetBlacklistedByDefault(true);
3774 // Blacklist prevents us from installing good_crx.
3775 base::FilePath path = data_dir().AppendASCII("good.crx");
3776 InstallCRX(path, INSTALL_FAILED);
3777 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3779 // Now whitelist this particular extension.
3781 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
3782 pref.SetIndividualExtensionInstallationAllowed(good_crx, true);
3785 // Ensure we can now install good_crx.
3786 InstallCRX(path, INSTALL_NEW);
3787 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3790 // Extension blacklisted by policy get unloaded after installing.
3791 TEST_F(ExtensionServiceTest, BlacklistedByPolicyRemovedIfRunning) {
3792 InitializeEmptyExtensionServiceWithTestingPrefs();
3794 // Install good_crx.
3795 base::FilePath path = data_dir().AppendASCII("good.crx");
3796 InstallCRX(path, INSTALL_NEW);
3797 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3800 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
3801 // Blacklist this extension.
3802 pref.SetIndividualExtensionInstallationAllowed(good_crx, false);
3805 // Extension should not be running now.
3806 base::RunLoop().RunUntilIdle();
3807 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3810 // Tests that component extensions are not blacklisted by policy.
3811 TEST_F(ExtensionServiceTest, ComponentExtensionWhitelisted) {
3812 InitializeEmptyExtensionServiceWithTestingPrefs();
3814 // Blacklist everything.
3816 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
3817 pref.SetBlacklistedByDefault(true);
3820 // Install a component extension.
3821 base::FilePath path = data_dir()
3822 .AppendASCII("good")
3823 .AppendASCII("Extensions")
3824 .AppendASCII(good0)
3825 .AppendASCII("1.0.0.0");
3826 std::string manifest;
3827 ASSERT_TRUE(base::ReadFileToString(
3828 path.Append(extensions::kManifestFilename), &manifest));
3829 service()->component_loader()->Add(manifest, path);
3830 service()->Init();
3832 // Extension should be installed despite blacklist.
3833 ASSERT_EQ(1u, registry()->enabled_extensions().size());
3834 EXPECT_TRUE(service()->GetExtensionById(good0, false));
3836 // Poke external providers and make sure the extension is still present.
3837 service()->CheckForExternalUpdates();
3838 ASSERT_EQ(1u, registry()->enabled_extensions().size());
3839 EXPECT_TRUE(service()->GetExtensionById(good0, false));
3841 // Extension should not be uninstalled on blacklist changes.
3843 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
3844 pref.SetIndividualExtensionInstallationAllowed(good0, false);
3846 base::RunLoop().RunUntilIdle();
3847 ASSERT_EQ(1u, registry()->enabled_extensions().size());
3848 EXPECT_TRUE(service()->GetExtensionById(good0, false));
3851 // Tests that policy-installed extensions are not blacklisted by policy.
3852 TEST_F(ExtensionServiceTest, PolicyInstalledExtensionsWhitelisted) {
3853 InitializeEmptyExtensionServiceWithTestingPrefs();
3856 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
3857 // Blacklist everything.
3858 pref.SetBlacklistedByDefault(true);
3859 // Mark good.crx for force-installation.
3860 pref.SetIndividualExtensionAutoInstalled(
3861 good_crx, "http://example.com/update_url", true);
3864 // Have policy force-install an extension.
3865 MockExtensionProvider* provider =
3866 new MockExtensionProvider(service(), Manifest::EXTERNAL_POLICY_DOWNLOAD);
3867 AddMockExternalProvider(provider);
3868 provider->UpdateOrAddExtension(
3869 good_crx, "1.0.0.0", data_dir().AppendASCII("good.crx"));
3871 // Reloading extensions should find our externally registered extension
3872 // and install it.
3873 content::WindowedNotificationObserver observer(
3874 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
3875 content::NotificationService::AllSources());
3876 service()->CheckForExternalUpdates();
3877 observer.Wait();
3879 // Extension should be installed despite blacklist.
3880 ASSERT_EQ(1u, registry()->enabled_extensions().size());
3881 EXPECT_TRUE(service()->GetExtensionById(good_crx, false));
3883 // Blacklist update should not uninstall the extension.
3885 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
3886 pref.SetIndividualExtensionInstallationAllowed(good0, false);
3888 base::RunLoop().RunUntilIdle();
3889 ASSERT_EQ(1u, registry()->enabled_extensions().size());
3890 EXPECT_TRUE(service()->GetExtensionById(good_crx, false));
3893 // Tests that extensions cannot be installed if the policy provider prohibits
3894 // it. This functionality is implemented in CrxInstaller::ConfirmInstall().
3895 TEST_F(ExtensionServiceTest, ManagementPolicyProhibitsInstall) {
3896 InitializeEmptyExtensionService();
3898 GetManagementPolicy()->UnregisterAllProviders();
3899 extensions::TestManagementPolicyProvider provider_(
3900 extensions::TestManagementPolicyProvider::PROHIBIT_LOAD);
3901 GetManagementPolicy()->RegisterProvider(&provider_);
3903 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_FAILED);
3904 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3907 // Tests that extensions cannot be loaded from prefs if the policy provider
3908 // prohibits it. This functionality is implemented in InstalledLoader::Load().
3909 TEST_F(ExtensionServiceTest, ManagementPolicyProhibitsLoadFromPrefs) {
3910 InitializeEmptyExtensionService();
3912 // Create a fake extension to be loaded as though it were read from prefs.
3913 base::FilePath path =
3914 data_dir().AppendASCII("management").AppendASCII("simple_extension");
3915 base::DictionaryValue manifest;
3916 manifest.SetString(keys::kName, "simple_extension");
3917 manifest.SetString(keys::kVersion, "1");
3918 // UNPACKED is for extensions loaded from a directory. We use it here, even
3919 // though we're testing loading from prefs, so that we don't need to provide
3920 // an extension key.
3921 extensions::ExtensionInfo extension_info(
3922 &manifest, std::string(), path, Manifest::UNPACKED);
3924 // Ensure we can load it with no management policy in place.
3925 GetManagementPolicy()->UnregisterAllProviders();
3926 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3927 extensions::InstalledLoader(service()).Load(extension_info, false);
3928 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3930 const Extension* extension =
3931 (registry()->enabled_extensions().begin())->get();
3932 EXPECT_TRUE(
3933 service()->UninstallExtension(extension->id(),
3934 extensions::UNINSTALL_REASON_FOR_TESTING,
3935 base::Bind(&base::DoNothing),
3936 NULL));
3937 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3939 // Ensure we cannot load it if management policy prohibits installation.
3940 extensions::TestManagementPolicyProvider provider_(
3941 extensions::TestManagementPolicyProvider::PROHIBIT_LOAD);
3942 GetManagementPolicy()->RegisterProvider(&provider_);
3944 extensions::InstalledLoader(service()).Load(extension_info, false);
3945 EXPECT_EQ(0u, registry()->enabled_extensions().size());
3948 // Tests disabling an extension when prohibited by the ManagementPolicy.
3949 TEST_F(ExtensionServiceTest, ManagementPolicyProhibitsDisable) {
3950 InitializeEmptyExtensionService();
3952 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
3953 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3954 EXPECT_EQ(0u, registry()->disabled_extensions().size());
3956 GetManagementPolicy()->UnregisterAllProviders();
3957 extensions::TestManagementPolicyProvider provider(
3958 extensions::TestManagementPolicyProvider::PROHIBIT_MODIFY_STATUS);
3959 GetManagementPolicy()->RegisterProvider(&provider);
3961 // Attempt to disable it.
3962 service()->DisableExtension(good_crx, Extension::DISABLE_USER_ACTION);
3964 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3965 EXPECT_TRUE(service()->GetExtensionById(good_crx, false));
3966 EXPECT_EQ(0u, registry()->disabled_extensions().size());
3969 // Tests uninstalling an extension when prohibited by the ManagementPolicy.
3970 TEST_F(ExtensionServiceTest, ManagementPolicyProhibitsUninstall) {
3971 InitializeEmptyExtensionService();
3973 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
3974 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3975 EXPECT_EQ(0u, registry()->disabled_extensions().size());
3977 GetManagementPolicy()->UnregisterAllProviders();
3978 extensions::TestManagementPolicyProvider provider(
3979 extensions::TestManagementPolicyProvider::PROHIBIT_MODIFY_STATUS);
3980 GetManagementPolicy()->RegisterProvider(&provider);
3982 // Attempt to uninstall it.
3983 EXPECT_FALSE(
3984 service()->UninstallExtension(good_crx,
3985 extensions::UNINSTALL_REASON_FOR_TESTING,
3986 base::Bind(&base::DoNothing),
3987 NULL));
3989 EXPECT_EQ(1u, registry()->enabled_extensions().size());
3990 EXPECT_TRUE(service()->GetExtensionById(good_crx, false));
3993 // Tests that previously installed extensions that are now prohibited from
3994 // being installed are removed.
3995 TEST_F(ExtensionServiceTest, ManagementPolicyUnloadsAllProhibited) {
3996 InitializeEmptyExtensionService();
3998 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
3999 InstallCRX(data_dir().AppendASCII("page_action.crx"), INSTALL_NEW);
4000 EXPECT_EQ(2u, registry()->enabled_extensions().size());
4001 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4003 GetManagementPolicy()->UnregisterAllProviders();
4004 extensions::TestManagementPolicyProvider provider(
4005 extensions::TestManagementPolicyProvider::PROHIBIT_LOAD);
4006 GetManagementPolicy()->RegisterProvider(&provider);
4008 // Run the policy check.
4009 service()->CheckManagementPolicy();
4010 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4011 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4014 // Tests that previously disabled extensions that are now required to be
4015 // enabled are re-enabled on reinstall.
4016 TEST_F(ExtensionServiceTest, ManagementPolicyRequiresEnable) {
4017 InitializeEmptyExtensionService();
4019 // Install, then disable, an extension.
4020 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
4021 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4022 service()->DisableExtension(good_crx, Extension::DISABLE_USER_ACTION);
4023 EXPECT_EQ(1u, registry()->disabled_extensions().size());
4025 // Register an ExtensionManagementPolicy that requires the extension to remain
4026 // enabled.
4027 GetManagementPolicy()->UnregisterAllProviders();
4028 extensions::TestManagementPolicyProvider provider(
4029 extensions::TestManagementPolicyProvider::MUST_REMAIN_ENABLED);
4030 GetManagementPolicy()->RegisterProvider(&provider);
4032 // Reinstall the extension.
4033 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_UPDATED);
4034 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4035 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4038 // Tests that extensions disabled by management policy can be installed but
4039 // will get disabled after installing.
4040 TEST_F(ExtensionServiceTest, ManagementPolicyProhibitsEnableOnInstalled) {
4041 InitializeEmptyExtensionService();
4043 // Register an ExtensionManagementPolicy that disables all extensions, with
4044 // a specified Extension::DisableReason.
4045 GetManagementPolicy()->UnregisterAllProviders();
4046 extensions::TestManagementPolicyProvider provider(
4047 extensions::TestManagementPolicyProvider::MUST_REMAIN_DISABLED);
4048 provider.SetDisableReason(Extension::DISABLE_NOT_VERIFIED);
4049 GetManagementPolicy()->RegisterProvider(&provider);
4051 // Attempts to install an extensions, it should be installed but disabled.
4052 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4053 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4054 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_WITHOUT_LOAD);
4055 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4056 EXPECT_EQ(1u, registry()->disabled_extensions().size());
4058 // Verifies that the disable reason is set properly.
4059 EXPECT_EQ(Extension::DISABLE_NOT_VERIFIED,
4060 service()->extension_prefs_->GetDisableReasons(kGoodId));
4063 // Tests that extensions with conflicting required permissions by enterprise
4064 // policy cannot be installed.
4065 TEST_F(ExtensionServiceTest, PolicyBlockedPermissionNewExtensionInstall) {
4066 InitializeEmptyExtensionServiceWithTestingPrefs();
4067 base::FilePath path = data_dir().AppendASCII("permissions_blocklist");
4070 // Update policy to block one of the required permissions of target.
4071 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
4072 pref.AddBlockedPermission("*", "tabs");
4075 // The extension should be failed to install.
4076 PackAndInstallCRX(path, INSTALL_FAILED);
4079 // Update policy to block one of the optional permissions instead.
4080 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
4081 pref.ClearBlockedPermissions("*");
4082 pref.AddBlockedPermission("*", "history");
4085 // The extension should succeed to install this time.
4086 std::string id = PackAndInstallCRX(path, INSTALL_NEW)->id();
4088 // Uninstall the extension and update policy to block some arbitrary
4089 // unknown permission.
4090 UninstallExtension(id, false);
4092 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
4093 pref.ClearBlockedPermissions("*");
4094 pref.AddBlockedPermission("*", "unknown.permission.for.testing");
4097 // The extension should succeed to install as well.
4098 PackAndInstallCRX(path, INSTALL_NEW);
4101 // Tests that extension supposed to be force installed but with conflicting
4102 // required permissions cannot be installed.
4103 TEST_F(ExtensionServiceTest, PolicyBlockedPermissionConflictsWithForceInstall) {
4104 InitializeEmptyExtensionServiceWithTestingPrefs();
4106 // Pack the crx file.
4107 base::FilePath path = data_dir().AppendASCII("permissions_blocklist");
4108 base::FilePath pem_path = data_dir().AppendASCII("permissions_blocklist.pem");
4109 base::ScopedTempDir temp_dir;
4110 EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
4111 base::FilePath crx_path = temp_dir.path().AppendASCII("temp.crx");
4113 PackCRX(path, pem_path, crx_path);
4116 // Block one of the required permissions.
4117 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
4118 pref.AddBlockedPermission("*", "tabs");
4121 // Use MockExtensionProvider to simulate force installing extension.
4122 MockExtensionProvider* provider =
4123 new MockExtensionProvider(service(), Manifest::EXTERNAL_POLICY_DOWNLOAD);
4124 AddMockExternalProvider(provider);
4125 provider->UpdateOrAddExtension(permissions_blocklist, "1.0", crx_path);
4128 // Attempts to force install this extension.
4129 content::WindowedNotificationObserver observer(
4130 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
4131 content::NotificationService::AllSources());
4132 service()->CheckForExternalUpdates();
4133 observer.Wait();
4136 // The extension should not be installed.
4137 ASSERT_FALSE(service()->GetInstalledExtension(permissions_blocklist));
4139 // Remove this extension from pending extension manager as we would like to
4140 // give another attempt later.
4141 service()->pending_extension_manager()->Remove(permissions_blocklist);
4144 // Clears the permission block list.
4145 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
4146 pref.ClearBlockedPermissions("*");
4150 // Attempts to force install this extension again.
4151 content::WindowedNotificationObserver observer(
4152 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
4153 content::NotificationService::AllSources());
4154 service()->CheckForExternalUpdates();
4155 observer.Wait();
4158 const Extension* installed =
4159 service()->GetInstalledExtension(permissions_blocklist);
4160 ASSERT_TRUE(installed);
4161 EXPECT_EQ(installed->location(), Manifest::EXTERNAL_POLICY_DOWNLOAD);
4164 // Tests that newer versions of an extension with conflicting required
4165 // permissions by enterprise policy cannot be updated to.
4166 TEST_F(ExtensionServiceTest, PolicyBlockedPermissionExtensionUpdate) {
4167 InitializeEmptyExtensionServiceWithTestingPrefs();
4169 base::FilePath path = data_dir().AppendASCII("permissions_blocklist");
4170 base::FilePath path2 = data_dir().AppendASCII("permissions_blocklist2");
4171 base::FilePath pem_path = data_dir().AppendASCII("permissions_blocklist.pem");
4173 // Install 'permissions_blocklist'.
4174 const Extension* installed = PackAndInstallCRX(path, pem_path, INSTALL_NEW);
4175 EXPECT_EQ(installed->id(), permissions_blocklist);
4178 // Block one of the required permissions of 'permissions_blocklist2'.
4179 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
4180 pref.AddBlockedPermission("*", "downloads");
4183 // Install 'permissions_blocklist' again, should be updated.
4184 const Extension* updated = PackAndInstallCRX(path, pem_path, INSTALL_UPDATED);
4185 EXPECT_EQ(updated->id(), permissions_blocklist);
4187 std::string old_version = updated->VersionString();
4189 // Attempts to update to 'permissions_blocklist2' should fail.
4190 PackAndInstallCRX(path2, pem_path, INSTALL_FAILED);
4192 // Verify that the old version is still enabled.
4193 updated = service()->GetExtensionById(permissions_blocklist, false);
4194 ASSERT_TRUE(updated);
4195 EXPECT_EQ(old_version, updated->VersionString());
4198 // Tests that policy update with additional permissions blocked revoke
4199 // conflicting granted optional permissions and unload extensions with
4200 // conflicting required permissions, including the force installed ones.
4201 TEST_F(ExtensionServiceTest, PolicyBlockedPermissionPolicyUpdate) {
4202 InitializeEmptyExtensionServiceWithTestingPrefs();
4204 base::FilePath path = data_dir().AppendASCII("permissions_blocklist");
4205 base::FilePath path2 = data_dir().AppendASCII("permissions_blocklist2");
4206 base::FilePath pem_path = data_dir().AppendASCII("permissions_blocklist.pem");
4208 // Pack the crx file.
4209 base::ScopedTempDir temp_dir;
4210 EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
4211 base::FilePath crx_path = temp_dir.path().AppendASCII("temp.crx");
4213 PackCRX(path2, pem_path, crx_path);
4215 // Install two arbitary extensions with specified manifest.
4216 std::string ext1 = PackAndInstallCRX(path, INSTALL_NEW)->id();
4217 std::string ext2 = PackAndInstallCRX(path2, INSTALL_NEW)->id();
4218 ASSERT_NE(ext1, permissions_blocklist);
4219 ASSERT_NE(ext2, permissions_blocklist);
4220 ASSERT_NE(ext1, ext2);
4222 // Force install another extension with known id and same manifest as 'ext2'.
4223 std::string ext2_forced = permissions_blocklist;
4224 MockExtensionProvider* provider =
4225 new MockExtensionProvider(service(), Manifest::EXTERNAL_POLICY_DOWNLOAD);
4226 AddMockExternalProvider(provider);
4227 provider->UpdateOrAddExtension(ext2_forced, "2.0", crx_path);
4229 content::WindowedNotificationObserver observer(
4230 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
4231 content::NotificationService::AllSources());
4232 service()->CheckForExternalUpdates();
4233 observer.Wait();
4235 extensions::ExtensionRegistry* registry =
4236 extensions::ExtensionRegistry::Get(profile());
4238 // Verify all three extensions are installed and enabled.
4239 ASSERT_TRUE(registry->enabled_extensions().GetByID(ext1));
4240 ASSERT_TRUE(registry->enabled_extensions().GetByID(ext2));
4241 ASSERT_TRUE(registry->enabled_extensions().GetByID(ext2_forced));
4243 // Grant all optional permissions to each extension.
4244 GrantAllOptionalPermissions(ext1);
4245 GrantAllOptionalPermissions(ext2);
4246 GrantAllOptionalPermissions(ext2_forced);
4248 scoped_refptr<const PermissionSet> active_permissions(
4249 ExtensionPrefs::Get(profile())->GetActivePermissions(ext1));
4250 EXPECT_TRUE(active_permissions->HasAPIPermission(
4251 extensions::APIPermission::kDownloads));
4253 // Set policy to block 'downloads' permission.
4255 ManagementPrefUpdater pref(profile_->GetTestingPrefService());
4256 pref.AddBlockedPermission("*", "downloads");
4259 base::RunLoop().RunUntilIdle();
4261 // 'ext1' should still be enabled, but with 'downloads' permission revoked.
4262 EXPECT_TRUE(registry->enabled_extensions().GetByID(ext1));
4263 active_permissions =
4264 ExtensionPrefs::Get(profile())->GetActivePermissions(ext1);
4265 EXPECT_FALSE(active_permissions->HasAPIPermission(
4266 extensions::APIPermission::kDownloads));
4268 // 'ext2' should be disabled because one of its required permissions is
4269 // blocked.
4270 EXPECT_FALSE(registry->enabled_extensions().GetByID(ext2));
4272 // 'ext2_forced' should be handled the same as 'ext2'
4273 EXPECT_FALSE(registry->enabled_extensions().GetByID(ext2_forced));
4276 // Flaky on windows; http://crbug.com/309833
4277 #if defined(OS_WIN)
4278 #define MAYBE_ExternalExtensionAutoAcknowledgement DISABLED_ExternalExtensionAutoAcknowledgement
4279 #else
4280 #define MAYBE_ExternalExtensionAutoAcknowledgement ExternalExtensionAutoAcknowledgement
4281 #endif
4282 TEST_F(ExtensionServiceTest, MAYBE_ExternalExtensionAutoAcknowledgement) {
4283 InitializeEmptyExtensionService();
4284 service()->set_extensions_enabled(true);
4287 // Register and install an external extension.
4288 MockExtensionProvider* provider =
4289 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF);
4290 AddMockExternalProvider(provider);
4291 provider->UpdateOrAddExtension(
4292 good_crx, "1.0.0.0", data_dir().AppendASCII("good.crx"));
4295 // Have policy force-install an extension.
4296 MockExtensionProvider* provider = new MockExtensionProvider(
4297 service(), Manifest::EXTERNAL_POLICY_DOWNLOAD);
4298 AddMockExternalProvider(provider);
4299 provider->UpdateOrAddExtension(
4300 page_action, "1.0.0.0", data_dir().AppendASCII("page_action.crx"));
4303 // Providers are set up. Let them run.
4304 int count = 2;
4305 content::WindowedNotificationObserver observer(
4306 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
4307 base::Bind(&WaitForCountNotificationsCallback, &count));
4308 service()->CheckForExternalUpdates();
4310 observer.Wait();
4312 ASSERT_EQ(2u, registry()->enabled_extensions().size());
4313 EXPECT_TRUE(service()->GetExtensionById(good_crx, false));
4314 EXPECT_TRUE(service()->GetExtensionById(page_action, false));
4315 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
4316 ASSERT_TRUE(!prefs->IsExternalExtensionAcknowledged(good_crx));
4317 ASSERT_TRUE(prefs->IsExternalExtensionAcknowledged(page_action));
4320 #if !defined(OS_CHROMEOS)
4321 // This tests if default apps are installed correctly.
4322 TEST_F(ExtensionServiceTest, DefaultAppsInstall) {
4323 InitializeEmptyExtensionService();
4324 service()->set_extensions_enabled(true);
4327 std::string json_data =
4329 " \"ldnnhddmnhbkjipkidpdiheffobcpfmf\" : {"
4330 " \"external_crx\": \"good.crx\","
4331 " \"external_version\": \"1.0.0.0\","
4332 " \"is_bookmark_app\": false"
4333 " }"
4334 "}";
4335 default_apps::Provider* provider = new default_apps::Provider(
4336 profile(),
4337 service(),
4338 new extensions::ExternalTestingLoader(json_data, data_dir()),
4339 Manifest::INTERNAL,
4340 Manifest::INVALID_LOCATION,
4341 Extension::FROM_WEBSTORE | Extension::WAS_INSTALLED_BY_DEFAULT);
4343 AddMockExternalProvider(provider);
4346 ASSERT_EQ(0u, registry()->enabled_extensions().size());
4347 content::WindowedNotificationObserver observer(
4348 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
4349 content::NotificationService::AllSources());
4350 service()->CheckForExternalUpdates();
4351 observer.Wait();
4353 ASSERT_EQ(1u, registry()->enabled_extensions().size());
4354 EXPECT_TRUE(service()->GetExtensionById(good_crx, false));
4355 const Extension* extension = service()->GetExtensionById(good_crx, false);
4356 EXPECT_TRUE(extension->from_webstore());
4357 EXPECT_TRUE(extension->was_installed_by_default());
4359 #endif
4361 // Tests disabling extensions
4362 TEST_F(ExtensionServiceTest, DisableExtension) {
4363 InitializeEmptyExtensionService();
4365 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
4366 EXPECT_TRUE(service()->GetExtensionById(good_crx, true));
4367 EXPECT_TRUE(service()->GetExtensionById(good_crx, false));
4369 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4370 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4371 EXPECT_EQ(0u, registry()->terminated_extensions().size());
4372 EXPECT_EQ(0u, registry()->blacklisted_extensions().size());
4374 // Disable it.
4375 service()->DisableExtension(good_crx, Extension::DISABLE_USER_ACTION);
4377 EXPECT_TRUE(service()->GetExtensionById(good_crx, true));
4378 EXPECT_FALSE(service()->GetExtensionById(good_crx, false));
4379 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4380 EXPECT_EQ(1u, registry()->disabled_extensions().size());
4381 EXPECT_EQ(0u, registry()->terminated_extensions().size());
4382 EXPECT_EQ(0u, registry()->blacklisted_extensions().size());
4385 TEST_F(ExtensionServiceTest, TerminateExtension) {
4386 InitializeEmptyExtensionService();
4388 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
4389 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4390 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4391 EXPECT_EQ(0u, registry()->terminated_extensions().size());
4392 EXPECT_EQ(0u, registry()->blacklisted_extensions().size());
4394 TerminateExtension(good_crx);
4396 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4397 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4398 EXPECT_EQ(1u, registry()->terminated_extensions().size());
4399 EXPECT_EQ(0u, registry()->blacklisted_extensions().size());
4402 TEST_F(ExtensionServiceTest, DisableTerminatedExtension) {
4403 InitializeEmptyExtensionService();
4405 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
4406 TerminateExtension(good_crx);
4407 EXPECT_TRUE(registry()->GetExtensionById(
4408 good_crx, extensions::ExtensionRegistry::TERMINATED));
4410 // Disable it.
4411 service()->DisableExtension(good_crx, Extension::DISABLE_USER_ACTION);
4413 EXPECT_FALSE(registry()->GetExtensionById(
4414 good_crx, extensions::ExtensionRegistry::TERMINATED));
4415 EXPECT_TRUE(service()->GetExtensionById(good_crx, true));
4417 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4418 EXPECT_EQ(1u, registry()->disabled_extensions().size());
4419 EXPECT_EQ(0u, registry()->terminated_extensions().size());
4420 EXPECT_EQ(0u, registry()->blacklisted_extensions().size());
4423 // Tests disabling all extensions (simulating --disable-extensions flag).
4424 TEST_F(ExtensionServiceTest, DisableAllExtensions) {
4425 InitializeEmptyExtensionService();
4427 base::FilePath path = data_dir().AppendASCII("good.crx");
4428 InstallCRX(path, INSTALL_NEW);
4430 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4431 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4433 // Disable extensions.
4434 service()->set_extensions_enabled(false);
4435 service()->ReloadExtensionsForTest();
4437 // There shouldn't be extensions in either list.
4438 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4439 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4441 // This shouldn't do anything when all extensions are disabled.
4442 service()->EnableExtension(good_crx);
4443 service()->ReloadExtensionsForTest();
4445 // There still shouldn't be extensions in either list.
4446 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4447 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4449 // And then re-enable the extensions.
4450 service()->set_extensions_enabled(true);
4451 service()->ReloadExtensionsForTest();
4453 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4454 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4457 // Tests reloading extensions.
4458 TEST_F(ExtensionServiceTest, ReloadExtensions) {
4459 InitializeEmptyExtensionService();
4461 // Simple extension that should install without error.
4462 base::FilePath path = data_dir().AppendASCII("good.crx");
4463 InstallCRX(path, INSTALL_NEW,
4464 Extension::FROM_WEBSTORE | Extension::WAS_INSTALLED_BY_DEFAULT);
4465 const char* const extension_id = good_crx;
4466 service()->DisableExtension(extension_id, Extension::DISABLE_USER_ACTION);
4468 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4469 EXPECT_EQ(1u, registry()->disabled_extensions().size());
4471 service()->ReloadExtensionsForTest();
4473 // The creation flags should not change when reloading the extension.
4474 const Extension* extension = service()->GetExtensionById(good_crx, true);
4475 EXPECT_TRUE(extension->from_webstore());
4476 EXPECT_TRUE(extension->was_installed_by_default());
4477 EXPECT_FALSE(extension->from_bookmark());
4479 // Extension counts shouldn't change.
4480 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4481 EXPECT_EQ(1u, registry()->disabled_extensions().size());
4483 service()->EnableExtension(extension_id);
4485 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4486 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4488 // Need to clear |loaded_| manually before reloading as the
4489 // EnableExtension() call above inserted into it and
4490 // UnloadAllExtensions() doesn't send out notifications.
4491 loaded_.clear();
4492 service()->ReloadExtensionsForTest();
4494 // Extension counts shouldn't change.
4495 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4496 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4499 // Tests reloading an extension.
4500 TEST_F(ExtensionServiceTest, ReloadExtension) {
4501 InitializeEmptyExtensionService();
4503 // Simple extension that should install without error.
4504 const char extension_id[] = "behllobkkfkfnphdnhnkndlbkcpglgmj";
4505 base::FilePath ext = data_dir()
4506 .AppendASCII("good")
4507 .AppendASCII("Extensions")
4508 .AppendASCII(extension_id)
4509 .AppendASCII("1.0.0.0");
4510 extensions::UnpackedInstaller::Create(service())->Load(ext);
4511 base::RunLoop().RunUntilIdle();
4513 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4514 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4516 service()->ReloadExtension(extension_id);
4518 // Extension should be disabled now, waiting to be reloaded.
4519 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4520 EXPECT_EQ(1u, registry()->disabled_extensions().size());
4521 EXPECT_EQ(Extension::DISABLE_RELOAD,
4522 ExtensionPrefs::Get(profile())->GetDisableReasons(extension_id));
4524 // Reloading again should not crash.
4525 service()->ReloadExtension(extension_id);
4527 // Finish reloading
4528 base::RunLoop().RunUntilIdle();
4530 // Extension should be enabled again.
4531 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4532 EXPECT_EQ(0u, registry()->disabled_extensions().size());
4535 TEST_F(ExtensionServiceTest, UninstallExtension) {
4536 InitializeEmptyExtensionService();
4537 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
4538 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4539 UninstallExtension(good_crx, false);
4540 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4541 EXPECT_EQ(UnloadedExtensionInfo::REASON_UNINSTALL, unloaded_reason_);
4544 TEST_F(ExtensionServiceTest, UninstallTerminatedExtension) {
4545 InitializeEmptyExtensionService();
4546 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
4547 TerminateExtension(good_crx);
4548 UninstallExtension(good_crx, false);
4549 EXPECT_EQ(UnloadedExtensionInfo::REASON_TERMINATE, unloaded_reason_);
4552 // Tests the uninstaller helper.
4553 TEST_F(ExtensionServiceTest, UninstallExtensionHelper) {
4554 InitializeEmptyExtensionService();
4555 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
4556 UninstallExtension(good_crx, true);
4557 EXPECT_EQ(UnloadedExtensionInfo::REASON_UNINSTALL, unloaded_reason_);
4560 TEST_F(ExtensionServiceTest, UninstallExtensionHelperTerminated) {
4561 InitializeEmptyExtensionService();
4562 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
4563 TerminateExtension(good_crx);
4564 UninstallExtension(good_crx, true);
4565 EXPECT_EQ(UnloadedExtensionInfo::REASON_TERMINATE, unloaded_reason_);
4568 // An extension disabled because of unsupported requirements should re-enabled
4569 // if updated to a version with supported requirements as long as there are no
4570 // other disable reasons.
4571 TEST_F(ExtensionServiceTest, UpgradingRequirementsEnabled) {
4572 InitializeEmptyExtensionService();
4573 BlackListWebGL();
4575 base::FilePath path = data_dir().AppendASCII("requirements");
4576 base::FilePath pem_path =
4577 data_dir().AppendASCII("requirements").AppendASCII("v1_good.pem");
4578 const Extension* extension_v1 = PackAndInstallCRX(path.AppendASCII("v1_good"),
4579 pem_path,
4580 INSTALL_NEW);
4581 std::string id = extension_v1->id();
4582 EXPECT_TRUE(service()->IsExtensionEnabled(id));
4584 base::FilePath v2_bad_requirements_crx = GetTemporaryFile();
4586 PackCRX(path.AppendASCII("v2_bad_requirements"),
4587 pem_path,
4588 v2_bad_requirements_crx);
4589 UpdateExtension(id, v2_bad_requirements_crx, INSTALLED);
4590 EXPECT_FALSE(service()->IsExtensionEnabled(id));
4592 base::FilePath v3_good_crx = GetTemporaryFile();
4594 PackCRX(path.AppendASCII("v3_good"), pem_path, v3_good_crx);
4595 UpdateExtension(id, v3_good_crx, ENABLED);
4596 EXPECT_TRUE(service()->IsExtensionEnabled(id));
4599 // Extensions disabled through user action should stay disabled.
4600 TEST_F(ExtensionServiceTest, UpgradingRequirementsDisabled) {
4601 InitializeEmptyExtensionService();
4602 BlackListWebGL();
4604 base::FilePath path = data_dir().AppendASCII("requirements");
4605 base::FilePath pem_path =
4606 data_dir().AppendASCII("requirements").AppendASCII("v1_good.pem");
4607 const Extension* extension_v1 = PackAndInstallCRX(path.AppendASCII("v1_good"),
4608 pem_path,
4609 INSTALL_NEW);
4610 std::string id = extension_v1->id();
4611 service()->DisableExtension(id, Extension::DISABLE_USER_ACTION);
4612 EXPECT_FALSE(service()->IsExtensionEnabled(id));
4614 base::FilePath v2_bad_requirements_crx = GetTemporaryFile();
4616 PackCRX(path.AppendASCII("v2_bad_requirements"),
4617 pem_path,
4618 v2_bad_requirements_crx);
4619 UpdateExtension(id, v2_bad_requirements_crx, INSTALLED);
4620 EXPECT_FALSE(service()->IsExtensionEnabled(id));
4622 base::FilePath v3_good_crx = GetTemporaryFile();
4624 PackCRX(path.AppendASCII("v3_good"), pem_path, v3_good_crx);
4625 UpdateExtension(id, v3_good_crx, INSTALLED);
4626 EXPECT_FALSE(service()->IsExtensionEnabled(id));
4629 // The extension should not re-enabled because it was disabled from a
4630 // permission increase.
4631 TEST_F(ExtensionServiceTest, UpgradingRequirementsPermissions) {
4632 InitializeEmptyExtensionService();
4633 BlackListWebGL();
4635 base::FilePath path = data_dir().AppendASCII("requirements");
4636 base::FilePath pem_path =
4637 data_dir().AppendASCII("requirements").AppendASCII("v1_good.pem");
4638 const Extension* extension_v1 = PackAndInstallCRX(path.AppendASCII("v1_good"),
4639 pem_path,
4640 INSTALL_NEW);
4641 std::string id = extension_v1->id();
4642 EXPECT_TRUE(service()->IsExtensionEnabled(id));
4644 base::FilePath v2_bad_requirements_and_permissions_crx = GetTemporaryFile();
4646 PackCRX(path.AppendASCII("v2_bad_requirements_and_permissions"),
4647 pem_path,
4648 v2_bad_requirements_and_permissions_crx);
4649 UpdateExtension(id, v2_bad_requirements_and_permissions_crx, INSTALLED);
4650 EXPECT_FALSE(service()->IsExtensionEnabled(id));
4652 base::FilePath v3_bad_permissions_crx = GetTemporaryFile();
4654 PackCRX(path.AppendASCII("v3_bad_permissions"),
4655 pem_path,
4656 v3_bad_permissions_crx);
4657 UpdateExtension(id, v3_bad_permissions_crx, INSTALLED);
4658 EXPECT_FALSE(service()->IsExtensionEnabled(id));
4661 // Unpacked extensions are not allowed to be installed if they have unsupported
4662 // requirements.
4663 TEST_F(ExtensionServiceTest, UnpackedRequirements) {
4664 InitializeEmptyExtensionService();
4665 BlackListWebGL();
4667 base::FilePath path =
4668 data_dir().AppendASCII("requirements").AppendASCII("v2_bad_requirements");
4669 extensions::UnpackedInstaller::Create(service())->Load(path);
4670 base::RunLoop().RunUntilIdle();
4671 EXPECT_EQ(1u, GetErrors().size());
4672 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4675 class ExtensionCookieCallback {
4676 public:
4677 ExtensionCookieCallback()
4678 : result_(false),
4679 weak_factory_(base::MessageLoop::current()) {}
4681 void SetCookieCallback(bool result) {
4682 base::ThreadTaskRunnerHandle::Get()->PostTask(
4683 FROM_HERE,
4684 base::Bind(&base::MessageLoop::Quit, weak_factory_.GetWeakPtr()));
4685 result_ = result;
4688 void GetAllCookiesCallback(const net::CookieList& list) {
4689 base::ThreadTaskRunnerHandle::Get()->PostTask(
4690 FROM_HERE,
4691 base::Bind(&base::MessageLoop::Quit, weak_factory_.GetWeakPtr()));
4692 list_ = list;
4694 net::CookieList list_;
4695 bool result_;
4696 base::WeakPtrFactory<base::MessageLoop> weak_factory_;
4699 // Verifies extension state is removed upon uninstall.
4700 TEST_F(ExtensionServiceTest, ClearExtensionData) {
4701 InitializeEmptyExtensionService();
4702 ExtensionCookieCallback callback;
4704 // Load a test extension.
4705 base::FilePath path = data_dir();
4706 path = path.AppendASCII("good.crx");
4707 const Extension* extension = InstallCRX(path, INSTALL_NEW);
4708 ASSERT_TRUE(extension);
4709 GURL ext_url(extension->url());
4710 std::string origin_id = storage::GetIdentifierFromOrigin(ext_url);
4712 // Set a cookie for the extension.
4713 net::CookieMonster* cookie_monster = profile()
4714 ->GetRequestContextForExtensions()
4715 ->GetURLRequestContext()
4716 ->cookie_store()
4717 ->GetCookieMonster();
4718 ASSERT_TRUE(cookie_monster);
4719 net::CookieOptions options;
4720 cookie_monster->SetCookieWithOptionsAsync(
4721 ext_url, "dummy=value", options,
4722 base::Bind(&ExtensionCookieCallback::SetCookieCallback,
4723 base::Unretained(&callback)));
4724 base::RunLoop().RunUntilIdle();
4725 EXPECT_TRUE(callback.result_);
4727 cookie_monster->GetAllCookiesForURLAsync(
4728 ext_url,
4729 base::Bind(&ExtensionCookieCallback::GetAllCookiesCallback,
4730 base::Unretained(&callback)));
4731 base::RunLoop().RunUntilIdle();
4732 EXPECT_EQ(1U, callback.list_.size());
4734 // Open a database.
4735 storage::DatabaseTracker* db_tracker =
4736 BrowserContext::GetDefaultStoragePartition(profile())
4737 ->GetDatabaseTracker();
4738 base::string16 db_name = base::UTF8ToUTF16("db");
4739 base::string16 description = base::UTF8ToUTF16("db_description");
4740 int64 size;
4741 db_tracker->DatabaseOpened(origin_id, db_name, description, 1, &size);
4742 db_tracker->DatabaseClosed(origin_id, db_name);
4743 std::vector<storage::OriginInfo> origins;
4744 db_tracker->GetAllOriginsInfo(&origins);
4745 EXPECT_EQ(1U, origins.size());
4746 EXPECT_EQ(origin_id, origins[0].GetOriginIdentifier());
4748 // Create local storage. We only simulate this by creating the backing files.
4749 // Note: This test depends on details of how the dom_storage library
4750 // stores data in the host file system.
4751 base::FilePath lso_dir_path =
4752 profile()->GetPath().AppendASCII("Local Storage");
4753 base::FilePath lso_file_path = lso_dir_path.AppendASCII(origin_id)
4754 .AddExtension(FILE_PATH_LITERAL(".localstorage"));
4755 EXPECT_TRUE(base::CreateDirectory(lso_dir_path));
4756 EXPECT_EQ(0, base::WriteFile(lso_file_path, NULL, 0));
4757 EXPECT_TRUE(base::PathExists(lso_file_path));
4759 // Create indexed db. Similarly, it is enough to only simulate this by
4760 // creating the directory on the disk.
4761 IndexedDBContext* idb_context = BrowserContext::GetDefaultStoragePartition(
4762 profile())->GetIndexedDBContext();
4763 idb_context->SetTaskRunnerForTesting(
4764 base::MessageLoop::current()->task_runner().get());
4765 base::FilePath idb_path = idb_context->GetFilePathForTesting(origin_id);
4766 EXPECT_TRUE(base::CreateDirectory(idb_path));
4767 EXPECT_TRUE(base::DirectoryExists(idb_path));
4769 // Uninstall the extension.
4770 base::RunLoop run_loop;
4771 ASSERT_TRUE(
4772 service()->UninstallExtension(good_crx,
4773 extensions::UNINSTALL_REASON_FOR_TESTING,
4774 run_loop.QuitClosure(),
4775 NULL));
4776 // The data deletion happens on the IO thread.
4777 run_loop.Run();
4779 // Check that the cookie is gone.
4780 cookie_monster->GetAllCookiesForURLAsync(
4781 ext_url,
4782 base::Bind(&ExtensionCookieCallback::GetAllCookiesCallback,
4783 base::Unretained(&callback)));
4784 base::RunLoop().RunUntilIdle();
4785 EXPECT_EQ(0U, callback.list_.size());
4787 // The database should have vanished as well.
4788 origins.clear();
4789 db_tracker->GetAllOriginsInfo(&origins);
4790 EXPECT_EQ(0U, origins.size());
4792 // Check that the LSO file has been removed.
4793 EXPECT_FALSE(base::PathExists(lso_file_path));
4795 // Check if the indexed db has disappeared too.
4796 EXPECT_FALSE(base::DirectoryExists(idb_path));
4799 // Verifies app state is removed upon uninstall.
4800 TEST_F(ExtensionServiceTest, ClearAppData) {
4801 InitializeEmptyExtensionService();
4802 ExtensionCookieCallback callback;
4804 int pref_count = 0;
4806 // Install app1 with unlimited storage.
4807 const Extension* extension =
4808 PackAndInstallCRX(data_dir().AppendASCII("app1"), INSTALL_NEW);
4809 ValidatePrefKeyCount(++pref_count);
4810 ASSERT_EQ(1u, registry()->enabled_extensions().size());
4811 const std::string id1 = extension->id();
4812 EXPECT_TRUE(extension->permissions_data()->HasAPIPermission(
4813 APIPermission::kUnlimitedStorage));
4814 const GURL origin1(
4815 extensions::AppLaunchInfo::GetFullLaunchURL(extension).GetOrigin());
4816 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
4817 origin1));
4818 std::string origin_id = storage::GetIdentifierFromOrigin(origin1);
4820 // Install app2 from the same origin with unlimited storage.
4821 extension = PackAndInstallCRX(data_dir().AppendASCII("app2"), INSTALL_NEW);
4822 ValidatePrefKeyCount(++pref_count);
4823 ASSERT_EQ(2u, registry()->enabled_extensions().size());
4824 const std::string id2 = extension->id();
4825 EXPECT_TRUE(extension->permissions_data()->HasAPIPermission(
4826 APIPermission::kUnlimitedStorage));
4827 EXPECT_TRUE(extension->web_extent().MatchesURL(
4828 extensions::AppLaunchInfo::GetFullLaunchURL(extension)));
4829 const GURL origin2(
4830 extensions::AppLaunchInfo::GetFullLaunchURL(extension).GetOrigin());
4831 EXPECT_EQ(origin1, origin2);
4832 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
4833 origin2));
4835 // Set a cookie for the extension.
4836 net::CookieMonster* cookie_monster = profile()
4837 ->GetRequestContext()
4838 ->GetURLRequestContext()
4839 ->cookie_store()
4840 ->GetCookieMonster();
4841 ASSERT_TRUE(cookie_monster);
4842 net::CookieOptions options;
4843 cookie_monster->SetCookieWithOptionsAsync(
4844 origin1, "dummy=value", options,
4845 base::Bind(&ExtensionCookieCallback::SetCookieCallback,
4846 base::Unretained(&callback)));
4847 base::RunLoop().RunUntilIdle();
4848 EXPECT_TRUE(callback.result_);
4850 cookie_monster->GetAllCookiesForURLAsync(
4851 origin1,
4852 base::Bind(&ExtensionCookieCallback::GetAllCookiesCallback,
4853 base::Unretained(&callback)));
4854 base::RunLoop().RunUntilIdle();
4855 EXPECT_EQ(1U, callback.list_.size());
4857 // Open a database.
4858 storage::DatabaseTracker* db_tracker =
4859 BrowserContext::GetDefaultStoragePartition(profile())
4860 ->GetDatabaseTracker();
4861 base::string16 db_name = base::UTF8ToUTF16("db");
4862 base::string16 description = base::UTF8ToUTF16("db_description");
4863 int64 size;
4864 db_tracker->DatabaseOpened(origin_id, db_name, description, 1, &size);
4865 db_tracker->DatabaseClosed(origin_id, db_name);
4866 std::vector<storage::OriginInfo> origins;
4867 db_tracker->GetAllOriginsInfo(&origins);
4868 EXPECT_EQ(1U, origins.size());
4869 EXPECT_EQ(origin_id, origins[0].GetOriginIdentifier());
4871 // Create local storage. We only simulate this by creating the backing files.
4872 // Note: This test depends on details of how the dom_storage library
4873 // stores data in the host file system.
4874 base::FilePath lso_dir_path =
4875 profile()->GetPath().AppendASCII("Local Storage");
4876 base::FilePath lso_file_path = lso_dir_path.AppendASCII(origin_id)
4877 .AddExtension(FILE_PATH_LITERAL(".localstorage"));
4878 EXPECT_TRUE(base::CreateDirectory(lso_dir_path));
4879 EXPECT_EQ(0, base::WriteFile(lso_file_path, NULL, 0));
4880 EXPECT_TRUE(base::PathExists(lso_file_path));
4882 // Create indexed db. Similarly, it is enough to only simulate this by
4883 // creating the directory on the disk.
4884 IndexedDBContext* idb_context = BrowserContext::GetDefaultStoragePartition(
4885 profile())->GetIndexedDBContext();
4886 idb_context->SetTaskRunnerForTesting(
4887 base::MessageLoop::current()->task_runner().get());
4888 base::FilePath idb_path = idb_context->GetFilePathForTesting(origin_id);
4889 EXPECT_TRUE(base::CreateDirectory(idb_path));
4890 EXPECT_TRUE(base::DirectoryExists(idb_path));
4892 // Uninstall one of them, unlimited storage should still be granted
4893 // to the origin.
4894 UninstallExtension(id1, false);
4895 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4896 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
4897 origin1));
4899 // Check that the cookie is still there.
4900 cookie_monster->GetAllCookiesForURLAsync(
4901 origin1,
4902 base::Bind(&ExtensionCookieCallback::GetAllCookiesCallback,
4903 base::Unretained(&callback)));
4904 base::RunLoop().RunUntilIdle();
4905 EXPECT_EQ(1U, callback.list_.size());
4907 // Now uninstall the other. Storage should be cleared for the apps.
4908 UninstallExtension(id2, false);
4909 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4910 EXPECT_FALSE(
4911 profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
4912 origin1));
4914 // Check that the cookie is gone.
4915 cookie_monster->GetAllCookiesForURLAsync(
4916 origin1,
4917 base::Bind(&ExtensionCookieCallback::GetAllCookiesCallback,
4918 base::Unretained(&callback)));
4919 base::RunLoop().RunUntilIdle();
4920 EXPECT_EQ(0U, callback.list_.size());
4922 // The database should have vanished as well.
4923 origins.clear();
4924 db_tracker->GetAllOriginsInfo(&origins);
4925 EXPECT_EQ(0U, origins.size());
4927 // Check that the LSO file has been removed.
4928 EXPECT_FALSE(base::PathExists(lso_file_path));
4930 // Check if the indexed db has disappeared too.
4931 EXPECT_FALSE(base::DirectoryExists(idb_path));
4934 // Tests loading single extensions (like --load-extension)
4935 // Flaky crashes. http://crbug.com/231806
4936 TEST_F(ExtensionServiceTest, DISABLED_LoadExtension) {
4937 InitializeEmptyExtensionService();
4939 base::FilePath ext1 = data_dir()
4940 .AppendASCII("good")
4941 .AppendASCII("Extensions")
4942 .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
4943 .AppendASCII("1.0.0.0");
4944 extensions::UnpackedInstaller::Create(service())->Load(ext1);
4945 base::RunLoop().RunUntilIdle();
4946 EXPECT_EQ(0u, GetErrors().size());
4947 ASSERT_EQ(1u, loaded_.size());
4948 EXPECT_EQ(Manifest::UNPACKED, loaded_[0]->location());
4949 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4951 ValidatePrefKeyCount(1);
4953 base::FilePath no_manifest =
4954 data_dir()
4955 .AppendASCII("bad")
4956 // .AppendASCII("Extensions")
4957 .AppendASCII("cccccccccccccccccccccccccccccccc")
4958 .AppendASCII("1");
4959 extensions::UnpackedInstaller::Create(service())->Load(no_manifest);
4960 base::RunLoop().RunUntilIdle();
4961 EXPECT_EQ(1u, GetErrors().size());
4962 ASSERT_EQ(1u, loaded_.size());
4963 EXPECT_EQ(1u, registry()->enabled_extensions().size());
4965 // Test uninstall.
4966 std::string id = loaded_[0]->id();
4967 EXPECT_FALSE(unloaded_id_.length());
4968 service()->UninstallExtension(id,
4969 extensions::UNINSTALL_REASON_FOR_TESTING,
4970 base::Bind(&base::DoNothing),
4971 NULL);
4972 base::RunLoop().RunUntilIdle();
4973 EXPECT_EQ(id, unloaded_id_);
4974 ASSERT_EQ(0u, loaded_.size());
4975 EXPECT_EQ(0u, registry()->enabled_extensions().size());
4978 // Tests that we generate IDs when they are not specified in the manifest for
4979 // --load-extension.
4980 TEST_F(ExtensionServiceTest, GenerateID) {
4981 InitializeEmptyExtensionService();
4983 base::FilePath no_id_ext = data_dir().AppendASCII("no_id");
4984 extensions::UnpackedInstaller::Create(service())->Load(no_id_ext);
4985 base::RunLoop().RunUntilIdle();
4986 EXPECT_EQ(0u, GetErrors().size());
4987 ASSERT_EQ(1u, loaded_.size());
4988 ASSERT_TRUE(crx_file::id_util::IdIsValid(loaded_[0]->id()));
4989 EXPECT_EQ(loaded_[0]->location(), Manifest::UNPACKED);
4991 ValidatePrefKeyCount(1);
4993 std::string previous_id = loaded_[0]->id();
4995 // If we reload the same path, we should get the same extension ID.
4996 extensions::UnpackedInstaller::Create(service())->Load(no_id_ext);
4997 base::RunLoop().RunUntilIdle();
4998 ASSERT_EQ(1u, loaded_.size());
4999 ASSERT_EQ(previous_id, loaded_[0]->id());
5002 TEST_F(ExtensionServiceTest, UnpackedValidatesLocales) {
5003 InitializeEmptyExtensionService();
5005 base::FilePath bad_locale =
5006 data_dir().AppendASCII("unpacked").AppendASCII("bad_messages_file");
5007 extensions::UnpackedInstaller::Create(service())->Load(bad_locale);
5008 base::RunLoop().RunUntilIdle();
5009 EXPECT_EQ(1u, GetErrors().size());
5010 base::FilePath ms_messages_file = bad_locale.AppendASCII("_locales")
5011 .AppendASCII("ms")
5012 .AppendASCII("messages.json");
5013 EXPECT_THAT(base::UTF16ToUTF8(GetErrors()[0]), testing::AllOf(
5014 testing::HasSubstr(
5015 base::UTF16ToUTF8(ms_messages_file.LossyDisplayName())),
5016 testing::HasSubstr("Dictionary keys must be quoted.")));
5017 ASSERT_EQ(0u, loaded_.size());
5020 void ExtensionServiceTest::TestExternalProvider(
5021 MockExtensionProvider* provider, Manifest::Location location) {
5022 // Verify that starting with no providers loads no extensions.
5023 service()->Init();
5024 ASSERT_EQ(0u, loaded_.size());
5026 provider->set_visit_count(0);
5028 // Register a test extension externally using the mock registry provider.
5029 base::FilePath source_path = data_dir().AppendASCII("good.crx");
5031 // Add the extension.
5032 provider->UpdateOrAddExtension(good_crx, "1.0.0.0", source_path);
5034 // Reloading extensions should find our externally registered extension
5035 // and install it.
5036 content::WindowedNotificationObserver observer(
5037 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
5038 content::NotificationService::AllSources());
5039 service()->CheckForExternalUpdates();
5040 observer.Wait();
5042 ASSERT_EQ(0u, GetErrors().size());
5043 ASSERT_EQ(1u, loaded_.size());
5044 ASSERT_EQ(location, loaded_[0]->location());
5045 ASSERT_EQ("1.0.0.0", loaded_[0]->version()->GetString());
5046 ValidatePrefKeyCount(1);
5047 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
5048 ValidateIntegerPref(good_crx, "location", location);
5050 // Reload extensions without changing anything. The extension should be
5051 // loaded again.
5052 loaded_.clear();
5053 service()->ReloadExtensionsForTest();
5054 base::RunLoop().RunUntilIdle();
5055 ASSERT_EQ(0u, GetErrors().size());
5056 ASSERT_EQ(1u, loaded_.size());
5057 ValidatePrefKeyCount(1);
5058 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
5059 ValidateIntegerPref(good_crx, "location", location);
5061 // Now update the extension with a new version. We should get upgraded.
5062 source_path = source_path.DirName().AppendASCII("good2.crx");
5063 provider->UpdateOrAddExtension(good_crx, "1.0.0.1", source_path);
5065 loaded_.clear();
5066 content::WindowedNotificationObserver observer_2(
5067 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
5068 content::NotificationService::AllSources());
5069 service()->CheckForExternalUpdates();
5070 observer_2.Wait();
5071 ASSERT_EQ(0u, GetErrors().size());
5072 ASSERT_EQ(1u, loaded_.size());
5073 ASSERT_EQ("1.0.0.1", loaded_[0]->version()->GetString());
5074 ValidatePrefKeyCount(1);
5075 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
5076 ValidateIntegerPref(good_crx, "location", location);
5078 // Uninstall the extension and reload. Nothing should happen because the
5079 // preference should prevent us from reinstalling.
5080 std::string id = loaded_[0]->id();
5081 bool no_uninstall =
5082 GetManagementPolicy()->MustRemainEnabled(loaded_[0].get(), NULL);
5083 service()->UninstallExtension(id,
5084 extensions::UNINSTALL_REASON_FOR_TESTING,
5085 base::Bind(&base::DoNothing),
5086 NULL);
5087 base::RunLoop().RunUntilIdle();
5089 base::FilePath install_path = extensions_install_dir().AppendASCII(id);
5090 if (no_uninstall) {
5091 // Policy controlled extensions should not have been touched by uninstall.
5092 ASSERT_TRUE(base::PathExists(install_path));
5093 } else {
5094 // The extension should also be gone from the install directory.
5095 ASSERT_FALSE(base::PathExists(install_path));
5096 loaded_.clear();
5097 service()->CheckForExternalUpdates();
5098 base::RunLoop().RunUntilIdle();
5099 ASSERT_EQ(0u, loaded_.size());
5100 ValidatePrefKeyCount(1);
5101 ValidateIntegerPref(good_crx, "state",
5102 Extension::EXTERNAL_EXTENSION_UNINSTALLED);
5103 ValidateIntegerPref(good_crx, "location", location);
5105 // Now clear the preference and reinstall.
5106 SetPrefInteg(good_crx, "state", Extension::ENABLED);
5108 loaded_.clear();
5109 content::WindowedNotificationObserver observer(
5110 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
5111 content::NotificationService::AllSources());
5112 service()->CheckForExternalUpdates();
5113 observer.Wait();
5114 ASSERT_EQ(1u, loaded_.size());
5116 ValidatePrefKeyCount(1);
5117 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
5118 ValidateIntegerPref(good_crx, "location", location);
5120 if (GetManagementPolicy()->MustRemainEnabled(loaded_[0].get(), NULL)) {
5121 EXPECT_EQ(2, provider->visit_count());
5122 } else {
5123 // Now test an externally triggered uninstall (deleting the registry key or
5124 // the pref entry).
5125 provider->RemoveExtension(good_crx);
5127 loaded_.clear();
5128 service()->OnExternalProviderReady(provider);
5129 base::RunLoop().RunUntilIdle();
5130 ASSERT_EQ(0u, loaded_.size());
5131 ValidatePrefKeyCount(0);
5133 // The extension should also be gone from the install directory.
5134 ASSERT_FALSE(base::PathExists(install_path));
5136 // Now test the case where user uninstalls and then the extension is removed
5137 // from the external provider.
5138 content::WindowedNotificationObserver observer(
5139 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
5140 content::NotificationService::AllSources());
5141 provider->UpdateOrAddExtension(good_crx, "1.0.0.1", source_path);
5142 service()->CheckForExternalUpdates();
5143 observer.Wait();
5145 ASSERT_EQ(1u, loaded_.size());
5146 ASSERT_EQ(0u, GetErrors().size());
5148 // User uninstalls.
5149 loaded_.clear();
5150 service()->UninstallExtension(id,
5151 extensions::UNINSTALL_REASON_FOR_TESTING,
5152 base::Bind(&base::DoNothing),
5153 NULL);
5154 base::RunLoop().RunUntilIdle();
5155 ASSERT_EQ(0u, loaded_.size());
5157 // Then remove the extension from the extension provider.
5158 provider->RemoveExtension(good_crx);
5160 // Should still be at 0.
5161 loaded_.clear();
5162 extensions::InstalledLoader(service()).LoadAllExtensions();
5163 base::RunLoop().RunUntilIdle();
5164 ASSERT_EQ(0u, loaded_.size());
5165 ValidatePrefKeyCount(1);
5167 EXPECT_EQ(5, provider->visit_count());
5171 // Tests the external installation feature
5172 #if defined(OS_WIN)
5173 TEST_F(ExtensionServiceTest, ExternalInstallRegistry) {
5174 // This should all work, even when normal extension installation is disabled.
5175 InitializeEmptyExtensionService();
5176 service()->set_extensions_enabled(false);
5178 // Now add providers. Extension system takes ownership of the objects.
5179 MockExtensionProvider* reg_provider =
5180 new MockExtensionProvider(service(), Manifest::EXTERNAL_REGISTRY);
5181 AddMockExternalProvider(reg_provider);
5182 TestExternalProvider(reg_provider, Manifest::EXTERNAL_REGISTRY);
5184 #endif
5186 TEST_F(ExtensionServiceTest, ExternalInstallPref) {
5187 InitializeEmptyExtensionService();
5189 // Now add providers. Extension system takes ownership of the objects.
5190 MockExtensionProvider* pref_provider =
5191 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF);
5193 AddMockExternalProvider(pref_provider);
5194 TestExternalProvider(pref_provider, Manifest::EXTERNAL_PREF);
5197 TEST_F(ExtensionServiceTest, ExternalInstallPrefUpdateUrl) {
5198 // This should all work, even when normal extension installation is disabled.
5199 InitializeEmptyExtensionService();
5200 service()->set_extensions_enabled(false);
5202 // TODO(skerner): The mock provider is not a good model of a provider
5203 // that works with update URLs, because it adds file and version info.
5204 // Extend the mock to work with update URLs. This test checks the
5205 // behavior that is common to all external extension visitors. The
5206 // browser test ExtensionManagementTest.ExternalUrlUpdate tests that
5207 // what the visitor does results in an extension being downloaded and
5208 // installed.
5209 MockExtensionProvider* pref_provider =
5210 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF_DOWNLOAD);
5211 AddMockExternalProvider(pref_provider);
5212 TestExternalProvider(pref_provider, Manifest::EXTERNAL_PREF_DOWNLOAD);
5215 TEST_F(ExtensionServiceTest, ExternalInstallPolicyUpdateUrl) {
5216 // This should all work, even when normal extension installation is disabled.
5217 InitializeEmptyExtensionService();
5218 service()->set_extensions_enabled(false);
5220 // TODO(skerner): The mock provider is not a good model of a provider
5221 // that works with update URLs, because it adds file and version info.
5222 // Extend the mock to work with update URLs. This test checks the
5223 // behavior that is common to all external extension visitors. The
5224 // browser test ExtensionManagementTest.ExternalUrlUpdate tests that
5225 // what the visitor does results in an extension being downloaded and
5226 // installed.
5227 MockExtensionProvider* pref_provider =
5228 new MockExtensionProvider(service(), Manifest::EXTERNAL_POLICY_DOWNLOAD);
5229 AddMockExternalProvider(pref_provider);
5230 TestExternalProvider(pref_provider, Manifest::EXTERNAL_POLICY_DOWNLOAD);
5233 // Tests that external extensions get uninstalled when the external extension
5234 // providers can't account for them.
5235 TEST_F(ExtensionServiceTest, ExternalUninstall) {
5236 // Start the extensions service with one external extension already installed.
5237 base::FilePath source_install_dir =
5238 data_dir().AppendASCII("good").AppendASCII("Extensions");
5239 base::FilePath pref_path = source_install_dir
5240 .DirName()
5241 .AppendASCII("PreferencesExternal");
5243 // This initializes the extensions service with no ExternalProviders.
5244 InitializeInstalledExtensionService(pref_path, source_install_dir);
5245 service()->set_extensions_enabled(false);
5247 service()->Init();
5249 ASSERT_EQ(0u, GetErrors().size());
5250 ASSERT_EQ(0u, loaded_.size());
5252 // Verify that it's not the disabled extensions flag causing it not to load.
5253 service()->set_extensions_enabled(true);
5254 service()->ReloadExtensionsForTest();
5255 base::RunLoop().RunUntilIdle();
5257 ASSERT_EQ(0u, GetErrors().size());
5258 ASSERT_EQ(0u, loaded_.size());
5261 // Test that running multiple update checks simultaneously does not
5262 // keep the update from succeeding.
5263 TEST_F(ExtensionServiceTest, MultipleExternalUpdateCheck) {
5264 InitializeEmptyExtensionService();
5266 MockExtensionProvider* provider =
5267 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF);
5268 AddMockExternalProvider(provider);
5270 // Verify that starting with no providers loads no extensions.
5271 service()->Init();
5272 ASSERT_EQ(0u, loaded_.size());
5274 // Start two checks for updates.
5275 provider->set_visit_count(0);
5276 service()->CheckForExternalUpdates();
5277 service()->CheckForExternalUpdates();
5278 base::RunLoop().RunUntilIdle();
5280 // Two calls should cause two checks for external extensions.
5281 EXPECT_EQ(2, provider->visit_count());
5282 EXPECT_EQ(0u, GetErrors().size());
5283 EXPECT_EQ(0u, loaded_.size());
5285 // Register a test extension externally using the mock registry provider.
5286 base::FilePath source_path = data_dir().AppendASCII("good.crx");
5287 provider->UpdateOrAddExtension(good_crx, "1.0.0.0", source_path);
5289 // Two checks for external updates should find the extension, and install it
5290 // once.
5291 content::WindowedNotificationObserver observer(
5292 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
5293 content::NotificationService::AllSources());
5294 provider->set_visit_count(0);
5295 service()->CheckForExternalUpdates();
5296 service()->CheckForExternalUpdates();
5297 observer.Wait();
5298 EXPECT_EQ(2, provider->visit_count());
5299 ASSERT_EQ(0u, GetErrors().size());
5300 ASSERT_EQ(1u, loaded_.size());
5301 ASSERT_EQ(Manifest::EXTERNAL_PREF, loaded_[0]->location());
5302 ASSERT_EQ("1.0.0.0", loaded_[0]->version()->GetString());
5303 ValidatePrefKeyCount(1);
5304 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
5305 ValidateIntegerPref(good_crx, "location", Manifest::EXTERNAL_PREF);
5307 provider->RemoveExtension(good_crx);
5308 provider->set_visit_count(0);
5309 service()->CheckForExternalUpdates();
5310 service()->CheckForExternalUpdates();
5311 base::RunLoop().RunUntilIdle();
5313 // Two calls should cause two checks for external extensions.
5314 // Because the external source no longer includes good_crx,
5315 // good_crx will be uninstalled. So, expect that no extensions
5316 // are loaded.
5317 EXPECT_EQ(2, provider->visit_count());
5318 EXPECT_EQ(0u, GetErrors().size());
5319 EXPECT_EQ(0u, loaded_.size());
5322 TEST_F(ExtensionServiceTest, ExternalPrefProvider) {
5323 InitializeEmptyExtensionService();
5325 // Test some valid extension records.
5326 // Set a base path to avoid erroring out on relative paths.
5327 // Paths starting with // are absolute on every platform we support.
5328 base::FilePath base_path(FILE_PATH_LITERAL("//base/path"));
5329 ASSERT_TRUE(base_path.IsAbsolute());
5330 MockProviderVisitor visitor(base_path);
5331 std::string json_data =
5333 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5334 " \"external_crx\": \"RandomExtension.crx\","
5335 " \"external_version\": \"1.0\""
5336 " },"
5337 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\": {"
5338 " \"external_crx\": \"RandomExtension2.crx\","
5339 " \"external_version\": \"2.0\""
5340 " },"
5341 " \"cccccccccccccccccccccccccccccccc\": {"
5342 " \"external_update_url\": \"http:\\\\foo.com/update\","
5343 " \"install_parameter\": \"id\""
5344 " }"
5345 "}";
5346 EXPECT_EQ(3, visitor.Visit(json_data));
5348 // Simulate an external_extensions.json file that contains seven invalid
5349 // records:
5350 // - One that is missing the 'external_crx' key.
5351 // - One that is missing the 'external_version' key.
5352 // - One that is specifying .. in the path.
5353 // - One that specifies both a file and update URL.
5354 // - One that specifies no file or update URL.
5355 // - One that has an update URL that is not well formed.
5356 // - One that contains a malformed version.
5357 // - One that has an invalid id.
5358 // - One that has a non-dictionary value.
5359 // - One that has an integer 'external_version' instead of a string.
5360 // The final extension is valid, and we check that it is read to make sure
5361 // failures don't stop valid records from being read.
5362 json_data =
5364 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5365 " \"external_version\": \"1.0\""
5366 " },"
5367 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\": {"
5368 " \"external_crx\": \"RandomExtension.crx\""
5369 " },"
5370 " \"cccccccccccccccccccccccccccccccc\": {"
5371 " \"external_crx\": \"..\\\\foo\\\\RandomExtension2.crx\","
5372 " \"external_version\": \"2.0\""
5373 " },"
5374 " \"dddddddddddddddddddddddddddddddd\": {"
5375 " \"external_crx\": \"RandomExtension2.crx\","
5376 " \"external_version\": \"2.0\","
5377 " \"external_update_url\": \"http:\\\\foo.com/update\""
5378 " },"
5379 " \"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\": {"
5380 " },"
5381 " \"ffffffffffffffffffffffffffffffff\": {"
5382 " \"external_update_url\": \"This string is not a valid URL\""
5383 " },"
5384 " \"gggggggggggggggggggggggggggggggg\": {"
5385 " \"external_crx\": \"RandomExtension3.crx\","
5386 " \"external_version\": \"This is not a valid version!\""
5387 " },"
5388 " \"This is not a valid id!\": {},"
5389 " \"hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh\": true,"
5390 " \"iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii\": {"
5391 " \"external_crx\": \"RandomExtension4.crx\","
5392 " \"external_version\": 1.0"
5393 " },"
5394 " \"pppppppppppppppppppppppppppppppp\": {"
5395 " \"external_crx\": \"RandomValidExtension.crx\","
5396 " \"external_version\": \"1.0\""
5397 " }"
5398 "}";
5399 EXPECT_EQ(1, visitor.Visit(json_data));
5401 // Check that if a base path is not provided, use of a relative
5402 // path fails.
5403 base::FilePath empty;
5404 MockProviderVisitor visitor_no_relative_paths(empty);
5406 // Use absolute paths. Expect success.
5407 json_data =
5409 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5410 " \"external_crx\": \"//RandomExtension1.crx\","
5411 " \"external_version\": \"3.0\""
5412 " },"
5413 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\": {"
5414 " \"external_crx\": \"//path/to/RandomExtension2.crx\","
5415 " \"external_version\": \"3.0\""
5416 " }"
5417 "}";
5418 EXPECT_EQ(2, visitor_no_relative_paths.Visit(json_data));
5420 // Use a relative path. Expect that it will error out.
5421 json_data =
5423 " \"cccccccccccccccccccccccccccccccc\": {"
5424 " \"external_crx\": \"RandomExtension2.crx\","
5425 " \"external_version\": \"3.0\""
5426 " }"
5427 "}";
5428 EXPECT_EQ(0, visitor_no_relative_paths.Visit(json_data));
5430 // Test supported_locales.
5431 json_data =
5433 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5434 " \"external_crx\": \"RandomExtension.crx\","
5435 " \"external_version\": \"1.0\","
5436 " \"supported_locales\": [ \"en\" ]"
5437 " },"
5438 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\": {"
5439 " \"external_crx\": \"RandomExtension2.crx\","
5440 " \"external_version\": \"2.0\","
5441 " \"supported_locales\": [ \"en-GB\" ]"
5442 " },"
5443 " \"cccccccccccccccccccccccccccccccc\": {"
5444 " \"external_crx\": \"RandomExtension2.crx\","
5445 " \"external_version\": \"3.0\","
5446 " \"supported_locales\": [ \"en_US\", \"fr\" ]"
5447 " }"
5448 "}";
5450 ScopedBrowserLocale guard("en-US");
5451 EXPECT_EQ(2, visitor.Visit(json_data));
5454 // Test keep_if_present.
5455 json_data =
5457 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5458 " \"external_crx\": \"RandomExtension.crx\","
5459 " \"external_version\": \"1.0\","
5460 " \"keep_if_present\": true"
5461 " }"
5462 "}";
5464 EXPECT_EQ(0, visitor.Visit(json_data));
5467 // Test is_bookmark_app.
5468 MockProviderVisitor from_bookmark_visitor(
5469 base_path, Extension::FROM_BOOKMARK);
5470 json_data =
5472 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5473 " \"external_crx\": \"RandomExtension.crx\","
5474 " \"external_version\": \"1.0\","
5475 " \"is_bookmark_app\": true"
5476 " }"
5477 "}";
5478 EXPECT_EQ(1, from_bookmark_visitor.Visit(json_data));
5480 // Test is_from_webstore.
5481 MockProviderVisitor from_webstore_visitor(
5482 base_path, Extension::FROM_WEBSTORE);
5483 json_data =
5485 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5486 " \"external_crx\": \"RandomExtension.crx\","
5487 " \"external_version\": \"1.0\","
5488 " \"is_from_webstore\": true"
5489 " }"
5490 "}";
5491 EXPECT_EQ(1, from_webstore_visitor.Visit(json_data));
5493 // Test was_installed_by_eom.
5494 MockProviderVisitor was_installed_by_eom_visitor(
5495 base_path, Extension::WAS_INSTALLED_BY_OEM);
5496 json_data =
5498 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5499 " \"external_crx\": \"RandomExtension.crx\","
5500 " \"external_version\": \"1.0\","
5501 " \"was_installed_by_oem\": true"
5502 " }"
5503 "}";
5504 EXPECT_EQ(1, was_installed_by_eom_visitor.Visit(json_data));
5506 // Test min_profile_created_by_version.
5507 MockProviderVisitor min_profile_created_by_version_visitor(base_path);
5508 json_data =
5510 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5511 " \"external_crx\": \"RandomExtension.crx\","
5512 " \"external_version\": \"1.0\","
5513 " \"min_profile_created_by_version\": \"42.0.0.1\""
5514 " },"
5515 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\": {"
5516 " \"external_crx\": \"RandomExtension2.crx\","
5517 " \"external_version\": \"1.0\","
5518 " \"min_profile_created_by_version\": \"43.0.0.1\""
5519 " },"
5520 " \"cccccccccccccccccccccccccccccccc\": {"
5521 " \"external_crx\": \"RandomExtension3.crx\","
5522 " \"external_version\": \"3.0\","
5523 " \"min_profile_created_by_version\": \"44.0.0.1\""
5524 " }"
5525 "}";
5526 min_profile_created_by_version_visitor.profile()->GetPrefs()->SetString(
5527 prefs::kProfileCreatedByVersion, "40.0.0.1");
5528 EXPECT_EQ(0, min_profile_created_by_version_visitor.Visit(json_data));
5529 min_profile_created_by_version_visitor.profile()->GetPrefs()->SetString(
5530 prefs::kProfileCreatedByVersion, "43.0.0.1");
5531 EXPECT_EQ(2, min_profile_created_by_version_visitor.Visit(json_data));
5532 min_profile_created_by_version_visitor.profile()->GetPrefs()->SetString(
5533 prefs::kProfileCreatedByVersion, "45.0.0.1");
5534 EXPECT_EQ(3, min_profile_created_by_version_visitor.Visit(json_data));
5537 TEST_F(ExtensionServiceTest, DoNotInstallForEnterprise) {
5538 InitializeEmptyExtensionService();
5540 const base::FilePath base_path(FILE_PATH_LITERAL("//base/path"));
5541 ASSERT_TRUE(base_path.IsAbsolute());
5542 MockProviderVisitor visitor(base_path);
5543 policy::ProfilePolicyConnector* const connector =
5544 policy::ProfilePolicyConnectorFactory::GetForBrowserContext(
5545 visitor.profile());
5546 connector->OverrideIsManagedForTesting(true);
5547 EXPECT_TRUE(connector->IsManaged());
5549 std::string json_data =
5551 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5552 " \"external_crx\": \"RandomExtension.crx\","
5553 " \"external_version\": \"1.0\","
5554 " \"do_not_install_for_enterprise\": true"
5555 " },"
5556 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\": {"
5557 " \"external_crx\": \"RandomExtension2.crx\","
5558 " \"external_version\": \"1.0\""
5559 " }"
5560 "}";
5561 EXPECT_EQ(1, visitor.Visit(json_data));
5564 // Test loading good extensions from the profile directory.
5565 TEST_F(ExtensionServiceTest, LoadAndRelocalizeExtensions) {
5566 // Ensure we're testing in "en" and leave global state untouched.
5567 extension_l10n_util::ScopedLocaleForTest testLocale("en");
5569 // Initialize the test dir with a good Preferences/extensions.
5570 base::FilePath source_install_dir = data_dir().AppendASCII("l10n");
5571 base::FilePath pref_path =
5572 source_install_dir.Append(chrome::kPreferencesFilename);
5573 InitializeInstalledExtensionService(pref_path, source_install_dir);
5575 service()->Init();
5577 ASSERT_EQ(3u, loaded_.size());
5579 // This was equal to "sr" on load.
5580 ValidateStringPref(loaded_[0]->id(), keys::kCurrentLocale, "en");
5582 // These are untouched by re-localization.
5583 ValidateStringPref(loaded_[1]->id(), keys::kCurrentLocale, "en");
5584 EXPECT_FALSE(IsPrefExist(loaded_[1]->id(), keys::kCurrentLocale));
5586 // This one starts with Serbian name, and gets re-localized into English.
5587 EXPECT_EQ("My name is simple.", loaded_[0]->name());
5589 // These are untouched by re-localization.
5590 EXPECT_EQ("My name is simple.", loaded_[1]->name());
5591 EXPECT_EQ("no l10n", loaded_[2]->name());
5594 class ExtensionsReadyRecorder : public content::NotificationObserver {
5595 public:
5596 ExtensionsReadyRecorder() : ready_(false) {
5597 registrar_.Add(this,
5598 extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED,
5599 content::NotificationService::AllSources());
5602 void set_ready(bool value) { ready_ = value; }
5603 bool ready() { return ready_; }
5605 private:
5606 void Observe(int type,
5607 const content::NotificationSource& source,
5608 const content::NotificationDetails& details) override {
5609 switch (type) {
5610 case extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED:
5611 ready_ = true;
5612 break;
5613 default:
5614 NOTREACHED();
5618 content::NotificationRegistrar registrar_;
5619 bool ready_;
5622 // Test that we get enabled/disabled correctly for all the pref/command-line
5623 // combinations. We don't want to derive from the ExtensionServiceTest class
5624 // for this test, so we use ExtensionServiceTestSimple.
5626 // Also tests that we always fire EXTENSIONS_READY, no matter whether we are
5627 // enabled or not.
5628 class ExtensionServiceTestSimple : public testing::Test {
5629 content::TestBrowserThreadBundle thread_bundle_;
5632 TEST_F(ExtensionServiceTestSimple, Enabledness) {
5633 // Make sure the PluginService singleton is destroyed at the end of the test.
5634 base::ShadowingAtExitManager at_exit_manager;
5635 #if defined(ENABLE_PLUGINS)
5636 content::PluginService::GetInstance()->Init();
5637 content::PluginService::GetInstance()->DisablePluginsDiscoveryForTesting();
5638 #endif
5640 ExtensionErrorReporter::Init(false); // no noisy errors
5641 ExtensionsReadyRecorder recorder;
5642 scoped_ptr<TestingProfile> profile(new TestingProfile());
5643 #if defined OS_CHROMEOS
5644 chromeos::ScopedTestDeviceSettingsService device_settings_service;
5645 chromeos::ScopedTestCrosSettings cros_settings;
5646 scoped_ptr<chromeos::ScopedTestUserManager> user_manager(
5647 new chromeos::ScopedTestUserManager);
5648 #endif
5649 scoped_ptr<base::CommandLine> command_line;
5650 base::FilePath install_dir = profile->GetPath()
5651 .AppendASCII(extensions::kInstallDirectoryName);
5653 // By default, we are enabled.
5654 command_line.reset(new base::CommandLine(base::CommandLine::NO_PROGRAM));
5655 ExtensionService* service = static_cast<extensions::TestExtensionSystem*>(
5656 ExtensionSystem::Get(profile.get()))->
5657 CreateExtensionService(
5658 command_line.get(),
5659 install_dir,
5660 false);
5661 EXPECT_TRUE(service->extensions_enabled());
5662 service->Init();
5663 base::RunLoop().RunUntilIdle();
5664 EXPECT_TRUE(recorder.ready());
5665 #if defined OS_CHROMEOS
5666 user_manager.reset();
5667 #endif
5669 // If either the command line or pref is set, we are disabled.
5670 recorder.set_ready(false);
5671 profile.reset(new TestingProfile());
5672 command_line->AppendSwitch(switches::kDisableExtensions);
5673 service = static_cast<extensions::TestExtensionSystem*>(
5674 ExtensionSystem::Get(profile.get()))->
5675 CreateExtensionService(
5676 command_line.get(),
5677 install_dir,
5678 false);
5679 EXPECT_FALSE(service->extensions_enabled());
5680 service->Init();
5681 base::RunLoop().RunUntilIdle();
5682 EXPECT_TRUE(recorder.ready());
5684 recorder.set_ready(false);
5685 profile.reset(new TestingProfile());
5686 profile->GetPrefs()->SetBoolean(prefs::kDisableExtensions, true);
5687 service = static_cast<extensions::TestExtensionSystem*>(
5688 ExtensionSystem::Get(profile.get()))->
5689 CreateExtensionService(
5690 command_line.get(),
5691 install_dir,
5692 false);
5693 EXPECT_FALSE(service->extensions_enabled());
5694 service->Init();
5695 base::RunLoop().RunUntilIdle();
5696 EXPECT_TRUE(recorder.ready());
5698 recorder.set_ready(false);
5699 profile.reset(new TestingProfile());
5700 profile->GetPrefs()->SetBoolean(prefs::kDisableExtensions, true);
5701 command_line.reset(new base::CommandLine(base::CommandLine::NO_PROGRAM));
5702 service = static_cast<extensions::TestExtensionSystem*>(
5703 ExtensionSystem::Get(profile.get()))->
5704 CreateExtensionService(
5705 command_line.get(),
5706 install_dir,
5707 false);
5708 EXPECT_FALSE(service->extensions_enabled());
5709 service->Init();
5710 base::RunLoop().RunUntilIdle();
5711 EXPECT_TRUE(recorder.ready());
5713 // Explicitly delete all the resources used in this test.
5714 profile.reset();
5715 service = NULL;
5716 // Execute any pending deletion tasks.
5717 base::RunLoop().RunUntilIdle();
5720 // Test loading extensions that require limited and unlimited storage quotas.
5721 TEST_F(ExtensionServiceTest, StorageQuota) {
5722 InitializeEmptyExtensionService();
5724 base::FilePath extensions_path = data_dir().AppendASCII("storage_quota");
5726 base::FilePath limited_quota_ext =
5727 extensions_path.AppendASCII("limited_quota")
5728 .AppendASCII("1.0");
5730 // The old permission name for unlimited quota was "unlimited_storage", but
5731 // we changed it to "unlimitedStorage". This tests both versions.
5732 base::FilePath unlimited_quota_ext =
5733 extensions_path.AppendASCII("unlimited_quota")
5734 .AppendASCII("1.0");
5735 base::FilePath unlimited_quota_ext2 =
5736 extensions_path.AppendASCII("unlimited_quota")
5737 .AppendASCII("2.0");
5738 extensions::UnpackedInstaller::Create(service())->Load(limited_quota_ext);
5739 extensions::UnpackedInstaller::Create(service())->Load(unlimited_quota_ext);
5740 extensions::UnpackedInstaller::Create(service())->Load(unlimited_quota_ext2);
5741 base::RunLoop().RunUntilIdle();
5743 ASSERT_EQ(3u, loaded_.size());
5744 EXPECT_TRUE(profile());
5745 EXPECT_FALSE(profile()->IsOffTheRecord());
5746 EXPECT_FALSE(
5747 profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
5748 loaded_[0]->url()));
5749 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
5750 loaded_[1]->url()));
5751 EXPECT_TRUE(profile()->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
5752 loaded_[2]->url()));
5755 // Tests ComponentLoader::Add().
5756 TEST_F(ExtensionServiceTest, ComponentExtensions) {
5757 InitializeEmptyExtensionService();
5759 // Component extensions should work even when extensions are disabled.
5760 service()->set_extensions_enabled(false);
5762 base::FilePath path = data_dir()
5763 .AppendASCII("good")
5764 .AppendASCII("Extensions")
5765 .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
5766 .AppendASCII("1.0.0.0");
5768 std::string manifest;
5769 ASSERT_TRUE(base::ReadFileToString(
5770 path.Append(extensions::kManifestFilename), &manifest));
5772 service()->component_loader()->Add(manifest, path);
5773 service()->Init();
5775 // Note that we do not pump messages -- the extension should be loaded
5776 // immediately.
5778 EXPECT_EQ(0u, GetErrors().size());
5779 ASSERT_EQ(1u, loaded_.size());
5780 EXPECT_EQ(Manifest::COMPONENT, loaded_[0]->location());
5781 EXPECT_EQ(1u, registry()->enabled_extensions().size());
5783 // Component extensions get a prefs entry on first install.
5784 ValidatePrefKeyCount(1);
5786 // Reload all extensions, and make sure it comes back.
5787 std::string extension_id = (*registry()->enabled_extensions().begin())->id();
5788 loaded_.clear();
5789 service()->ReloadExtensionsForTest();
5790 ASSERT_EQ(1u, registry()->enabled_extensions().size());
5791 EXPECT_EQ(extension_id, (*registry()->enabled_extensions().begin())->id());
5794 TEST_F(ExtensionServiceTest, DeferredSyncStartupPreInstalledComponent) {
5795 InitializeEmptyExtensionService();
5797 bool flare_was_called = false;
5798 syncer::ModelType triggered_type(syncer::UNSPECIFIED);
5799 base::WeakPtrFactory<ExtensionServiceTest> factory(this);
5800 extension_sync_service()->SetSyncStartFlareForTesting(
5801 base::Bind(&ExtensionServiceTest::MockSyncStartFlare,
5802 factory.GetWeakPtr(),
5803 &flare_was_called, // Safe due to WeakPtrFactory scope.
5804 &triggered_type)); // Safe due to WeakPtrFactory scope.
5806 // Install a component extension.
5807 std::string manifest;
5808 ASSERT_TRUE(base::ReadFileToString(
5809 good0_path().Append(extensions::kManifestFilename), &manifest));
5810 service()->component_loader()->Add(manifest, good0_path());
5811 ASSERT_FALSE(service()->is_ready());
5812 service()->Init();
5813 ASSERT_TRUE(service()->is_ready());
5815 // Extensions added before service is_ready() don't trigger sync startup.
5816 EXPECT_FALSE(flare_was_called);
5817 ASSERT_EQ(syncer::UNSPECIFIED, triggered_type);
5820 TEST_F(ExtensionServiceTest, DeferredSyncStartupPreInstalledNormal) {
5821 InitializeGoodInstalledExtensionService();
5823 bool flare_was_called = false;
5824 syncer::ModelType triggered_type(syncer::UNSPECIFIED);
5825 base::WeakPtrFactory<ExtensionServiceTest> factory(this);
5826 extension_sync_service()->SetSyncStartFlareForTesting(
5827 base::Bind(&ExtensionServiceTest::MockSyncStartFlare,
5828 factory.GetWeakPtr(),
5829 &flare_was_called, // Safe due to WeakPtrFactory scope.
5830 &triggered_type)); // Safe due to WeakPtrFactory scope.
5832 ASSERT_FALSE(service()->is_ready());
5833 service()->Init();
5834 ASSERT_EQ(3u, loaded_.size());
5835 ASSERT_TRUE(service()->is_ready());
5837 // Extensions added before service is_ready() don't trigger sync startup.
5838 EXPECT_FALSE(flare_was_called);
5839 ASSERT_EQ(syncer::UNSPECIFIED, triggered_type);
5842 TEST_F(ExtensionServiceTest, DeferredSyncStartupOnInstall) {
5843 InitializeEmptyExtensionService();
5844 service()->Init();
5845 ASSERT_TRUE(service()->is_ready());
5847 bool flare_was_called = false;
5848 syncer::ModelType triggered_type(syncer::UNSPECIFIED);
5849 base::WeakPtrFactory<ExtensionServiceTest> factory(this);
5850 extension_sync_service()->SetSyncStartFlareForTesting(
5851 base::Bind(&ExtensionServiceTest::MockSyncStartFlare,
5852 factory.GetWeakPtr(),
5853 &flare_was_called, // Safe due to WeakPtrFactory scope.
5854 &triggered_type)); // Safe due to WeakPtrFactory scope.
5856 base::FilePath path = data_dir().AppendASCII("good.crx");
5857 InstallCRX(path, INSTALL_NEW);
5859 EXPECT_TRUE(flare_was_called);
5860 EXPECT_EQ(syncer::EXTENSIONS, triggered_type);
5862 // Reset.
5863 flare_was_called = false;
5864 triggered_type = syncer::UNSPECIFIED;
5866 // Once sync starts, flare should no longer be invoked.
5867 extension_sync_service()->MergeDataAndStartSyncing(
5868 syncer::EXTENSIONS,
5869 syncer::SyncDataList(),
5870 scoped_ptr<syncer::SyncChangeProcessor>(
5871 new syncer::FakeSyncChangeProcessor),
5872 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5873 path = data_dir().AppendASCII("page_action.crx");
5874 InstallCRX(path, INSTALL_NEW);
5875 EXPECT_FALSE(flare_was_called);
5876 ASSERT_EQ(syncer::UNSPECIFIED, triggered_type);
5879 TEST_F(ExtensionServiceTest, DisableExtensionFromSync) {
5880 // Start the extensions service with one external extension already installed.
5881 base::FilePath source_install_dir =
5882 data_dir().AppendASCII("good").AppendASCII("Extensions");
5883 base::FilePath pref_path =
5884 source_install_dir.DirName().Append(chrome::kPreferencesFilename);
5886 InitializeInstalledExtensionService(pref_path, source_install_dir);
5888 // The user has enabled sync.
5889 ProfileSyncService* sync_service =
5890 ProfileSyncServiceFactory::GetForProfile(profile());
5891 sync_service->SetSyncSetupCompleted();
5893 service()->Init();
5894 ASSERT_TRUE(service()->is_ready());
5896 ASSERT_EQ(3u, loaded_.size());
5898 // We start enabled.
5899 const Extension* extension = service()->GetExtensionById(good0, true);
5900 ASSERT_TRUE(extension);
5901 ASSERT_TRUE(service()->IsExtensionEnabled(good0));
5903 // Sync starts up.
5904 extension_sync_service()->MergeDataAndStartSyncing(
5905 syncer::EXTENSIONS,
5906 syncer::SyncDataList(),
5907 make_scoped_ptr(new syncer::FakeSyncChangeProcessor),
5908 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5910 // Then sync data arrives telling us to disable |good0|.
5911 ExtensionSyncData disable_good_crx(*extension, false,
5912 Extension::DISABLE_USER_ACTION, false,
5913 false, ExtensionSyncData::BOOLEAN_UNSET);
5914 syncer::SyncChange sync_change(FROM_HERE,
5915 syncer::SyncChange::ACTION_UPDATE,
5916 disable_good_crx.GetSyncData());
5917 syncer::SyncChangeList list(1, sync_change);
5918 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
5920 ASSERT_FALSE(service()->IsExtensionEnabled(good0));
5923 TEST_F(ExtensionServiceTest, IgnoreSyncChangesWhenLocalStateIsMoreRecent) {
5924 // Start the extension service with three extensions already installed.
5925 base::FilePath source_install_dir =
5926 data_dir().AppendASCII("good").AppendASCII("Extensions");
5927 base::FilePath pref_path =
5928 source_install_dir.DirName().Append(chrome::kPreferencesFilename);
5930 InitializeInstalledExtensionService(pref_path, source_install_dir);
5932 // The user has enabled sync.
5933 ProfileSyncService* sync_service =
5934 ProfileSyncServiceFactory::GetForProfile(profile());
5935 sync_service->SetSyncSetupCompleted();
5936 // Make sure ExtensionSyncService is created, so it'll be notified of changes.
5937 extension_sync_service();
5939 service()->Init();
5940 ASSERT_TRUE(service()->is_ready());
5941 ASSERT_EQ(3u, loaded_.size());
5943 ASSERT_TRUE(service()->IsExtensionEnabled(good0));
5944 ASSERT_TRUE(service()->IsExtensionEnabled(good2));
5946 // Disable and re-enable good0 before first sync data arrives.
5947 service()->DisableExtension(good0, Extension::DISABLE_USER_ACTION);
5948 ASSERT_FALSE(service()->IsExtensionEnabled(good0));
5949 service()->EnableExtension(good0);
5950 ASSERT_TRUE(service()->IsExtensionEnabled(good0));
5951 // Disable good2 before first sync data arrives (good1 is considered
5952 // non-syncable because it has plugin permission).
5953 service()->DisableExtension(good2, Extension::DISABLE_USER_ACTION);
5954 ASSERT_FALSE(service()->IsExtensionEnabled(good2));
5956 const Extension* extension0 = service()->GetExtensionById(good0, true);
5957 const Extension* extension2 = service()->GetExtensionById(good2, true);
5958 ASSERT_TRUE(extensions::sync_helper::IsSyncable(extension0));
5959 ASSERT_TRUE(extensions::sync_helper::IsSyncable(extension2));
5961 // Now sync data comes in that says to disable good0 and enable good2.
5962 ExtensionSyncData disable_good0(*extension0, false,
5963 Extension::DISABLE_USER_ACTION, false, false,
5964 ExtensionSyncData::BOOLEAN_UNSET);
5965 ExtensionSyncData enable_good2(*extension2, true, Extension::DISABLE_NONE,
5966 false, false,
5967 ExtensionSyncData::BOOLEAN_UNSET);
5968 syncer::SyncDataList sync_data;
5969 sync_data.push_back(disable_good0.GetSyncData());
5970 sync_data.push_back(enable_good2.GetSyncData());
5971 extension_sync_service()->MergeDataAndStartSyncing(
5972 syncer::EXTENSIONS,
5973 sync_data,
5974 make_scoped_ptr(new syncer::FakeSyncChangeProcessor),
5975 make_scoped_ptr(new syncer::SyncErrorFactoryMock));
5977 // Both sync changes should be ignored, since the local state was changed
5978 // before sync started, and so the local state is considered more recent.
5979 EXPECT_TRUE(service()->IsExtensionEnabled(good0));
5980 EXPECT_FALSE(service()->IsExtensionEnabled(good2));
5983 TEST_F(ExtensionServiceTest, GetSyncData) {
5984 InitializeEmptyExtensionService();
5985 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
5986 const Extension* extension = service()->GetInstalledExtension(good_crx);
5987 ASSERT_TRUE(extension);
5989 extension_sync_service()->MergeDataAndStartSyncing(
5990 syncer::EXTENSIONS,
5991 syncer::SyncDataList(),
5992 scoped_ptr<syncer::SyncChangeProcessor>(
5993 new syncer::FakeSyncChangeProcessor),
5994 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5996 syncer::SyncDataList list =
5997 extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS);
5998 ASSERT_EQ(list.size(), 1U);
5999 scoped_ptr<ExtensionSyncData> data =
6000 ExtensionSyncData::CreateFromSyncData(list[0]);
6001 ASSERT_TRUE(data.get());
6002 EXPECT_EQ(extension->id(), data->id());
6003 EXPECT_FALSE(data->uninstalled());
6004 EXPECT_EQ(service()->IsExtensionEnabled(good_crx), data->enabled());
6005 EXPECT_EQ(extensions::util::IsIncognitoEnabled(good_crx, profile()),
6006 data->incognito_enabled());
6007 EXPECT_EQ(ExtensionSyncData::BOOLEAN_UNSET, data->all_urls_enabled());
6008 EXPECT_TRUE(data->version().Equals(*extension->version()));
6009 EXPECT_EQ(extensions::ManifestURL::GetUpdateURL(extension),
6010 data->update_url());
6011 EXPECT_EQ(extension->name(), data->name());
6014 TEST_F(ExtensionServiceTest, GetSyncDataTerminated) {
6015 InitializeEmptyExtensionService();
6016 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
6017 TerminateExtension(good_crx);
6018 const Extension* extension = service()->GetInstalledExtension(good_crx);
6019 ASSERT_TRUE(extension);
6021 syncer::FakeSyncChangeProcessor processor;
6022 extension_sync_service()->MergeDataAndStartSyncing(
6023 syncer::EXTENSIONS,
6024 syncer::SyncDataList(),
6025 scoped_ptr<syncer::SyncChangeProcessor>(
6026 new syncer::FakeSyncChangeProcessor),
6027 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6029 syncer::SyncDataList list =
6030 extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS);
6031 ASSERT_EQ(list.size(), 1U);
6032 scoped_ptr<ExtensionSyncData> data =
6033 ExtensionSyncData::CreateFromSyncData(list[0]);
6034 ASSERT_TRUE(data.get());
6035 EXPECT_EQ(extension->id(), data->id());
6036 EXPECT_FALSE(data->uninstalled());
6037 EXPECT_EQ(service()->IsExtensionEnabled(good_crx), data->enabled());
6038 EXPECT_EQ(extensions::util::IsIncognitoEnabled(good_crx, profile()),
6039 data->incognito_enabled());
6040 EXPECT_EQ(ExtensionSyncData::BOOLEAN_UNSET, data->all_urls_enabled());
6041 EXPECT_TRUE(data->version().Equals(*extension->version()));
6042 EXPECT_EQ(extensions::ManifestURL::GetUpdateURL(extension),
6043 data->update_url());
6044 EXPECT_EQ(extension->name(), data->name());
6047 TEST_F(ExtensionServiceTest, GetSyncDataFilter) {
6048 InitializeEmptyExtensionService();
6049 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
6050 const Extension* extension = service()->GetInstalledExtension(good_crx);
6051 ASSERT_TRUE(extension);
6053 syncer::FakeSyncChangeProcessor processor;
6054 extension_sync_service()->MergeDataAndStartSyncing(
6055 syncer::APPS,
6056 syncer::SyncDataList(),
6057 scoped_ptr<syncer::SyncChangeProcessor>(
6058 new syncer::FakeSyncChangeProcessor),
6059 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6061 syncer::SyncDataList list =
6062 extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS);
6063 ASSERT_EQ(list.size(), 0U);
6066 TEST_F(ExtensionServiceTest, GetSyncExtensionDataUserSettings) {
6067 InitializeEmptyExtensionService();
6068 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
6069 const Extension* extension = service()->GetInstalledExtension(good_crx);
6070 ASSERT_TRUE(extension);
6072 syncer::FakeSyncChangeProcessor processor;
6073 extension_sync_service()->MergeDataAndStartSyncing(
6074 syncer::EXTENSIONS,
6075 syncer::SyncDataList(),
6076 scoped_ptr<syncer::SyncChangeProcessor>(
6077 new syncer::FakeSyncChangeProcessor),
6078 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6081 syncer::SyncDataList list =
6082 extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS);
6083 ASSERT_EQ(list.size(), 1U);
6084 scoped_ptr<ExtensionSyncData> data =
6085 ExtensionSyncData::CreateFromSyncData(list[0]);
6086 ASSERT_TRUE(data.get());
6087 EXPECT_TRUE(data->enabled());
6088 EXPECT_FALSE(data->incognito_enabled());
6089 EXPECT_EQ(ExtensionSyncData::BOOLEAN_UNSET, data->all_urls_enabled());
6092 service()->DisableExtension(good_crx, Extension::DISABLE_USER_ACTION);
6094 syncer::SyncDataList list =
6095 extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS);
6096 ASSERT_EQ(list.size(), 1U);
6097 scoped_ptr<ExtensionSyncData> data =
6098 ExtensionSyncData::CreateFromSyncData(list[0]);
6099 ASSERT_TRUE(data.get());
6100 EXPECT_FALSE(data->enabled());
6101 EXPECT_FALSE(data->incognito_enabled());
6102 EXPECT_EQ(ExtensionSyncData::BOOLEAN_UNSET, data->all_urls_enabled());
6105 extensions::util::SetIsIncognitoEnabled(good_crx, profile(), true);
6106 extensions::util::SetAllowedScriptingOnAllUrls(
6107 good_crx, profile(), false);
6109 syncer::SyncDataList list =
6110 extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS);
6111 ASSERT_EQ(list.size(), 1U);
6112 scoped_ptr<ExtensionSyncData> data =
6113 ExtensionSyncData::CreateFromSyncData(list[0]);
6114 ASSERT_TRUE(data.get());
6115 EXPECT_FALSE(data->enabled());
6116 EXPECT_TRUE(data->incognito_enabled());
6117 EXPECT_EQ(ExtensionSyncData::BOOLEAN_FALSE, data->all_urls_enabled());
6120 service()->EnableExtension(good_crx);
6121 extensions::util::SetAllowedScriptingOnAllUrls(
6122 good_crx, profile(), true);
6124 syncer::SyncDataList list =
6125 extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS);
6126 ASSERT_EQ(list.size(), 1U);
6127 scoped_ptr<ExtensionSyncData> data =
6128 ExtensionSyncData::CreateFromSyncData(list[0]);
6129 ASSERT_TRUE(data.get());
6130 EXPECT_TRUE(data->enabled());
6131 EXPECT_TRUE(data->incognito_enabled());
6132 EXPECT_EQ(ExtensionSyncData::BOOLEAN_TRUE, data->all_urls_enabled());
6136 TEST_F(ExtensionServiceTest, SyncForUninstalledExternalExtension) {
6137 InitializeEmptyExtensionService();
6138 InstallCRXWithLocation(
6139 data_dir().AppendASCII("good.crx"), Manifest::EXTERNAL_PREF, INSTALL_NEW);
6140 const Extension* extension = service()->GetInstalledExtension(good_crx);
6141 ASSERT_TRUE(extension);
6143 syncer::FakeSyncChangeProcessor processor;
6144 extension_sync_service()->MergeDataAndStartSyncing(
6145 syncer::EXTENSIONS,
6146 syncer::SyncDataList(),
6147 scoped_ptr<syncer::SyncChangeProcessor>(
6148 new syncer::FakeSyncChangeProcessor),
6149 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6151 UninstallExtension(good_crx, false);
6152 EXPECT_TRUE(
6153 ExtensionPrefs::Get(profile())->IsExternalExtensionUninstalled(good_crx));
6155 sync_pb::EntitySpecifics specifics;
6156 sync_pb::AppSpecifics* app_specifics = specifics.mutable_app();
6157 sync_pb::ExtensionSpecifics* extension_specifics =
6158 app_specifics->mutable_extension();
6159 extension_specifics->set_id(good_crx);
6160 extension_specifics->set_version("1.0");
6161 extension_specifics->set_enabled(true);
6163 syncer::SyncData sync_data =
6164 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6165 syncer::SyncChange sync_change(FROM_HERE,
6166 syncer::SyncChange::ACTION_UPDATE,
6167 sync_data);
6168 syncer::SyncChangeList list(1);
6169 list[0] = sync_change;
6171 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6172 EXPECT_TRUE(
6173 ExtensionPrefs::Get(profile())->IsExternalExtensionUninstalled(good_crx));
6176 TEST_F(ExtensionServiceTest, GetSyncAppDataUserSettings) {
6177 InitializeEmptyExtensionService();
6178 const Extension* app =
6179 PackAndInstallCRX(data_dir().AppendASCII("app"), INSTALL_NEW);
6180 ASSERT_TRUE(app);
6181 ASSERT_TRUE(app->is_app());
6183 syncer::FakeSyncChangeProcessor processor;
6184 extension_sync_service()->MergeDataAndStartSyncing(
6185 syncer::APPS,
6186 syncer::SyncDataList(),
6187 scoped_ptr<syncer::SyncChangeProcessor>(
6188 new syncer::FakeSyncChangeProcessor),
6189 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6191 syncer::StringOrdinal initial_ordinal =
6192 syncer::StringOrdinal::CreateInitialOrdinal();
6194 syncer::SyncDataList list =
6195 extension_sync_service()->GetAllSyncData(syncer::APPS);
6196 ASSERT_EQ(list.size(), 1U);
6198 scoped_ptr<ExtensionSyncData> app_sync_data =
6199 ExtensionSyncData::CreateFromSyncData(list[0]);
6200 EXPECT_TRUE(initial_ordinal.Equals(app_sync_data->app_launch_ordinal()));
6201 EXPECT_TRUE(initial_ordinal.Equals(app_sync_data->page_ordinal()));
6204 AppSorting* sorting = ExtensionPrefs::Get(profile())->app_sorting();
6205 sorting->SetAppLaunchOrdinal(app->id(), initial_ordinal.CreateAfter());
6207 syncer::SyncDataList list =
6208 extension_sync_service()->GetAllSyncData(syncer::APPS);
6209 ASSERT_EQ(list.size(), 1U);
6211 scoped_ptr<ExtensionSyncData> app_sync_data =
6212 ExtensionSyncData::CreateFromSyncData(list[0]);
6213 ASSERT_TRUE(app_sync_data.get());
6214 EXPECT_TRUE(initial_ordinal.LessThan(app_sync_data->app_launch_ordinal()));
6215 EXPECT_TRUE(initial_ordinal.Equals(app_sync_data->page_ordinal()));
6218 sorting->SetPageOrdinal(app->id(), initial_ordinal.CreateAfter());
6220 syncer::SyncDataList list =
6221 extension_sync_service()->GetAllSyncData(syncer::APPS);
6222 ASSERT_EQ(list.size(), 1U);
6224 scoped_ptr<ExtensionSyncData> app_sync_data =
6225 ExtensionSyncData::CreateFromSyncData(list[0]);
6226 ASSERT_TRUE(app_sync_data.get());
6227 EXPECT_TRUE(initial_ordinal.LessThan(app_sync_data->app_launch_ordinal()));
6228 EXPECT_TRUE(initial_ordinal.LessThan(app_sync_data->page_ordinal()));
6232 // TODO (rdevlin.cronin): The OnExtensionMoved() method has been removed from
6233 // ExtensionService, so this test probably needs a new home. Unfortunately, it
6234 // relies pretty heavily on things like InitializeExtension[Sync]Service() and
6235 // PackAndInstallCRX(). When we clean up a bit more, this should move out.
6236 TEST_F(ExtensionServiceTest, GetSyncAppDataUserSettingsOnExtensionMoved) {
6237 InitializeEmptyExtensionService();
6238 const size_t kAppCount = 3;
6239 const Extension* apps[kAppCount];
6240 apps[0] = PackAndInstallCRX(data_dir().AppendASCII("app1"), INSTALL_NEW);
6241 apps[1] = PackAndInstallCRX(data_dir().AppendASCII("app2"), INSTALL_NEW);
6242 apps[2] = PackAndInstallCRX(data_dir().AppendASCII("app4"), INSTALL_NEW);
6243 for (size_t i = 0; i < kAppCount; ++i) {
6244 ASSERT_TRUE(apps[i]);
6245 ASSERT_TRUE(apps[i]->is_app());
6248 syncer::FakeSyncChangeProcessor processor;
6249 extension_sync_service()->MergeDataAndStartSyncing(
6250 syncer::APPS,
6251 syncer::SyncDataList(),
6252 scoped_ptr<syncer::SyncChangeProcessor>(
6253 new syncer::FakeSyncChangeProcessor),
6254 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6256 ExtensionPrefs::Get(service()->GetBrowserContext())
6257 ->app_sorting()
6258 ->OnExtensionMoved(apps[0]->id(), apps[1]->id(), apps[2]->id());
6260 syncer::SyncDataList list =
6261 extension_sync_service()->GetAllSyncData(syncer::APPS);
6262 ASSERT_EQ(list.size(), 3U);
6264 scoped_ptr<ExtensionSyncData> data[kAppCount];
6265 for (size_t i = 0; i < kAppCount; ++i) {
6266 data[i] = ExtensionSyncData::CreateFromSyncData(list[i]);
6267 ASSERT_TRUE(data[i].get());
6270 // The sync data is not always in the same order our apps were installed in,
6271 // so we do that sorting here so we can make sure the values are changed as
6272 // expected.
6273 syncer::StringOrdinal app_launch_ordinals[kAppCount];
6274 for (size_t i = 0; i < kAppCount; ++i) {
6275 for (size_t j = 0; j < kAppCount; ++j) {
6276 if (apps[i]->id() == data[j]->id())
6277 app_launch_ordinals[i] = data[j]->app_launch_ordinal();
6281 EXPECT_TRUE(app_launch_ordinals[1].LessThan(app_launch_ordinals[0]));
6282 EXPECT_TRUE(app_launch_ordinals[0].LessThan(app_launch_ordinals[2]));
6286 TEST_F(ExtensionServiceTest, GetSyncDataList) {
6287 InitializeEmptyExtensionService();
6288 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
6289 InstallCRX(data_dir().AppendASCII("page_action.crx"), INSTALL_NEW);
6290 InstallCRX(data_dir().AppendASCII("theme.crx"), INSTALL_NEW);
6291 InstallCRX(data_dir().AppendASCII("theme2.crx"), INSTALL_NEW);
6293 syncer::FakeSyncChangeProcessor processor;
6294 extension_sync_service()->MergeDataAndStartSyncing(
6295 syncer::APPS,
6296 syncer::SyncDataList(),
6297 scoped_ptr<syncer::SyncChangeProcessor>(
6298 new syncer::FakeSyncChangeProcessor),
6299 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6300 extension_sync_service()->MergeDataAndStartSyncing(
6301 syncer::EXTENSIONS,
6302 syncer::SyncDataList(),
6303 scoped_ptr<syncer::SyncChangeProcessor>(
6304 new syncer::FakeSyncChangeProcessor),
6305 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6307 service()->DisableExtension(page_action, Extension::DISABLE_USER_ACTION);
6308 TerminateExtension(theme2_crx);
6310 EXPECT_EQ(0u, extension_sync_service()->GetAllSyncData(syncer::APPS).size());
6311 EXPECT_EQ(
6312 2u, extension_sync_service()->GetAllSyncData(syncer::EXTENSIONS).size());
6315 TEST_F(ExtensionServiceTest, ProcessSyncDataUninstall) {
6316 InitializeEmptyExtensionService();
6317 syncer::FakeSyncChangeProcessor processor;
6318 extension_sync_service()->MergeDataAndStartSyncing(
6319 syncer::EXTENSIONS,
6320 syncer::SyncDataList(),
6321 scoped_ptr<syncer::SyncChangeProcessor>(
6322 new syncer::FakeSyncChangeProcessor),
6323 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6325 sync_pb::EntitySpecifics specifics;
6326 sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension();
6327 ext_specifics->set_id(good_crx);
6328 ext_specifics->set_version("1.0");
6329 syncer::SyncData sync_data =
6330 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6331 syncer::SyncChange sync_change(FROM_HERE,
6332 syncer::SyncChange::ACTION_DELETE,
6333 sync_data);
6334 syncer::SyncChangeList list(1);
6335 list[0] = sync_change;
6337 // Should do nothing.
6338 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6339 EXPECT_FALSE(service()->GetExtensionById(good_crx, true));
6341 // Install the extension.
6342 base::FilePath extension_path = data_dir().AppendASCII("good.crx");
6343 InstallCRX(extension_path, INSTALL_NEW);
6344 EXPECT_TRUE(service()->GetExtensionById(good_crx, true));
6346 // Should uninstall the extension.
6347 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6348 EXPECT_FALSE(service()->GetExtensionById(good_crx, true));
6350 // Should again do nothing.
6351 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6352 EXPECT_FALSE(service()->GetExtensionById(good_crx, true));
6355 TEST_F(ExtensionServiceTest, ProcessSyncDataWrongType) {
6356 InitializeEmptyExtensionService();
6358 // Install the extension.
6359 base::FilePath extension_path = data_dir().AppendASCII("good.crx");
6360 InstallCRX(extension_path, INSTALL_NEW);
6361 EXPECT_TRUE(service()->GetExtensionById(good_crx, true));
6363 sync_pb::EntitySpecifics specifics;
6364 sync_pb::AppSpecifics* app_specifics = specifics.mutable_app();
6365 sync_pb::ExtensionSpecifics* extension_specifics =
6366 app_specifics->mutable_extension();
6367 extension_specifics->set_id(good_crx);
6368 extension_specifics->set_version(
6369 service()->GetInstalledExtension(good_crx)->version()->GetString());
6372 extension_specifics->set_enabled(true);
6373 syncer::SyncData sync_data =
6374 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6375 syncer::SyncChange sync_change(FROM_HERE,
6376 syncer::SyncChange::ACTION_DELETE,
6377 sync_data);
6378 syncer::SyncChangeList list(1);
6379 list[0] = sync_change;
6381 // Should do nothing
6382 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6383 EXPECT_TRUE(service()->GetExtensionById(good_crx, true));
6387 extension_specifics->set_enabled(false);
6388 syncer::SyncData sync_data =
6389 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6390 syncer::SyncChange sync_change(FROM_HERE,
6391 syncer::SyncChange::ACTION_UPDATE,
6392 sync_data);
6393 syncer::SyncChangeList list(1);
6394 list[0] = sync_change;
6396 // Should again do nothing.
6397 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6398 EXPECT_TRUE(service()->GetExtensionById(good_crx, false));
6402 TEST_F(ExtensionServiceTest, ProcessSyncDataSettings) {
6403 InitializeEmptyExtensionService();
6404 syncer::FakeSyncChangeProcessor processor;
6405 extension_sync_service()->MergeDataAndStartSyncing(
6406 syncer::EXTENSIONS,
6407 syncer::SyncDataList(),
6408 scoped_ptr<syncer::SyncChangeProcessor>(
6409 new syncer::FakeSyncChangeProcessor),
6410 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6412 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
6413 EXPECT_TRUE(service()->IsExtensionEnabled(good_crx));
6414 EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
6415 EXPECT_FALSE(extensions::util::HasSetAllowedScriptingOnAllUrls(
6416 good_crx, profile()));
6417 const bool kDefaultAllowedScripting =
6418 extensions::util::DefaultAllowedScriptingOnAllUrls();
6419 EXPECT_EQ(kDefaultAllowedScripting,
6420 extensions::util::AllowedScriptingOnAllUrls(good_crx, profile()));
6422 sync_pb::EntitySpecifics specifics;
6423 sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension();
6424 ext_specifics->set_id(good_crx);
6425 ext_specifics->set_version(
6426 service()->GetInstalledExtension(good_crx)->version()->GetString());
6427 ext_specifics->set_enabled(false);
6430 syncer::SyncData sync_data =
6431 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6432 syncer::SyncChange sync_change(FROM_HERE,
6433 syncer::SyncChange::ACTION_UPDATE,
6434 sync_data);
6435 syncer::SyncChangeList list(1);
6436 list[0] = sync_change;
6437 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6438 EXPECT_FALSE(service()->IsExtensionEnabled(good_crx));
6439 EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
6440 EXPECT_FALSE(extensions::util::HasSetAllowedScriptingOnAllUrls(
6441 good_crx, profile()));
6442 EXPECT_EQ(kDefaultAllowedScripting,
6443 extensions::util::AllowedScriptingOnAllUrls(good_crx, profile()));
6447 ext_specifics->set_enabled(true);
6448 ext_specifics->set_incognito_enabled(true);
6449 syncer::SyncData sync_data =
6450 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6451 syncer::SyncChange sync_change(FROM_HERE,
6452 syncer::SyncChange::ACTION_UPDATE,
6453 sync_data);
6454 syncer::SyncChangeList list(1);
6455 list[0] = sync_change;
6456 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6457 EXPECT_TRUE(service()->IsExtensionEnabled(good_crx));
6458 EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
6462 ext_specifics->set_enabled(false);
6463 ext_specifics->set_incognito_enabled(true);
6464 syncer::SyncData sync_data =
6465 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6466 syncer::SyncChange sync_change(FROM_HERE,
6467 syncer::SyncChange::ACTION_UPDATE,
6468 sync_data);
6469 syncer::SyncChangeList list(1);
6470 list[0] = sync_change;
6471 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6472 EXPECT_FALSE(service()->IsExtensionEnabled(good_crx));
6473 EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
6477 ext_specifics->set_enabled(true);
6478 ext_specifics->set_all_urls_enabled(!kDefaultAllowedScripting);
6479 syncer::SyncData sync_data =
6480 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6481 syncer::SyncChange sync_change(FROM_HERE,
6482 syncer::SyncChange::ACTION_UPDATE,
6483 sync_data);
6484 syncer::SyncChangeList list(1);
6485 list[0] = sync_change;
6486 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6487 EXPECT_TRUE(service()->IsExtensionEnabled(good_crx));
6488 EXPECT_TRUE(extensions::util::HasSetAllowedScriptingOnAllUrls(
6489 good_crx, profile()));
6490 EXPECT_EQ(!kDefaultAllowedScripting,
6491 extensions::util::AllowedScriptingOnAllUrls(good_crx, profile()));
6495 ext_specifics->set_all_urls_enabled(kDefaultAllowedScripting);
6496 syncer::SyncData sync_data =
6497 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6498 syncer::SyncChange sync_change(FROM_HERE,
6499 syncer::SyncChange::ACTION_UPDATE,
6500 sync_data);
6501 syncer::SyncChangeList list(1);
6502 list[0] = sync_change;
6503 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6504 EXPECT_TRUE(service()->IsExtensionEnabled(good_crx));
6505 EXPECT_TRUE(extensions::util::HasSetAllowedScriptingOnAllUrls(
6506 good_crx, profile()));
6507 EXPECT_EQ(kDefaultAllowedScripting,
6508 extensions::util::AllowedScriptingOnAllUrls(good_crx, profile()));
6511 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(good_crx));
6514 TEST_F(ExtensionServiceTest, ProcessSyncDataNewExtension) {
6515 InitializeEmptyExtensionService();
6516 syncer::FakeSyncChangeProcessor processor;
6517 extension_sync_service()->MergeDataAndStartSyncing(
6518 syncer::EXTENSIONS,
6519 syncer::SyncDataList(),
6520 scoped_ptr<syncer::SyncChangeProcessor>(
6521 new syncer::FakeSyncChangeProcessor),
6522 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6524 const base::FilePath path = data_dir().AppendASCII("good.crx");
6525 const ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
6527 struct TestCase {
6528 const char* name; // For failure output only.
6529 bool sync_enabled; // The "enabled" flag coming in from Sync.
6530 // The disable reason(s) coming in from Sync, or -1 for "not set".
6531 int sync_disable_reasons;
6532 // The disable reason(s) that should be set on the installed extension.
6533 // This will usually be the same as |sync_disable_reasons|, but see the
6534 // "Legacy" case.
6535 int expect_disable_reasons;
6536 // Whether the extension's permissions should be auto-granted during
6537 // installation.
6538 bool expect_permissions_granted;
6539 } test_cases[] = {
6540 // Standard case: Extension comes in enabled; permissions should be granted
6541 // during installation.
6542 { "Standard", true, 0, 0, true },
6543 // If the extension comes in disabled, its permissions should still be
6544 // granted (the user already approved them on another machine).
6545 { "Disabled", false, Extension::DISABLE_USER_ACTION,
6546 Extension::DISABLE_USER_ACTION, true },
6547 // Legacy case (<M45): No disable reasons come in from Sync (see
6548 // crbug.com/484214). After installation, the reason should be set to
6549 // DISABLE_UNKNOWN_FROM_SYNC.
6550 { "Legacy", false, -1, Extension::DISABLE_UNKNOWN_FROM_SYNC, true },
6551 // If the extension came in disabled due to a permissions increase, then the
6552 // user has *not* approved the permissions, and they shouldn't be granted.
6553 // crbug.com/484214
6554 { "PermissionsIncrease", false, Extension::DISABLE_PERMISSIONS_INCREASE,
6555 Extension::DISABLE_PERMISSIONS_INCREASE, false },
6558 for (const TestCase& test_case : test_cases) {
6559 SCOPED_TRACE(test_case.name);
6561 sync_pb::EntitySpecifics specifics;
6562 sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension();
6563 ext_specifics->set_id(good_crx);
6564 ext_specifics->set_version(base::Version("1").GetString());
6565 ext_specifics->set_enabled(test_case.sync_enabled);
6566 if (test_case.sync_disable_reasons != -1)
6567 ext_specifics->set_disable_reasons(test_case.sync_disable_reasons);
6569 syncer::SyncData sync_data =
6570 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6571 syncer::SyncChange sync_change(FROM_HERE,
6572 syncer::SyncChange::ACTION_UPDATE,
6573 sync_data);
6574 syncer::SyncChangeList list(1, sync_change);
6575 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6577 ASSERT_TRUE(service()->pending_extension_manager()->IsIdPending(good_crx));
6578 UpdateExtension(good_crx, path, test_case.sync_enabled ? ENABLED
6579 : DISABLED);
6580 EXPECT_EQ(test_case.expect_disable_reasons,
6581 prefs->GetDisableReasons(good_crx));
6582 scoped_refptr<PermissionSet> permissions(
6583 prefs->GetGrantedPermissions(good_crx));
6584 EXPECT_EQ(test_case.expect_permissions_granted, !permissions->IsEmpty());
6585 ASSERT_FALSE(service()->pending_extension_manager()->IsIdPending(good_crx));
6587 // Remove the extension again, so we can install it again for the next case.
6588 UninstallExtension(good_crx, false,
6589 test_case.sync_enabled ? Extension::ENABLED
6590 : Extension::DISABLED);
6594 TEST_F(ExtensionServiceTest, ProcessSyncDataTerminatedExtension) {
6595 InitializeExtensionServiceWithUpdater();
6596 syncer::FakeSyncChangeProcessor processor;
6597 extension_sync_service()->MergeDataAndStartSyncing(
6598 syncer::EXTENSIONS,
6599 syncer::SyncDataList(),
6600 scoped_ptr<syncer::SyncChangeProcessor>(
6601 new syncer::FakeSyncChangeProcessor),
6602 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6604 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
6605 TerminateExtension(good_crx);
6606 EXPECT_TRUE(service()->IsExtensionEnabled(good_crx));
6607 EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
6609 sync_pb::EntitySpecifics specifics;
6610 sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension();
6611 ext_specifics->set_id(good_crx);
6612 ext_specifics->set_version(
6613 service()->GetInstalledExtension(good_crx)->version()->GetString());
6614 ext_specifics->set_enabled(false);
6615 ext_specifics->set_incognito_enabled(true);
6616 syncer::SyncData sync_data =
6617 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6618 syncer::SyncChange sync_change(FROM_HERE,
6619 syncer::SyncChange::ACTION_UPDATE,
6620 sync_data);
6621 syncer::SyncChangeList list(1);
6622 list[0] = sync_change;
6624 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6625 EXPECT_FALSE(service()->IsExtensionEnabled(good_crx));
6626 EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
6628 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(good_crx));
6631 TEST_F(ExtensionServiceTest, ProcessSyncDataVersionCheck) {
6632 InitializeExtensionServiceWithUpdater();
6633 syncer::FakeSyncChangeProcessor processor;
6634 extension_sync_service()->MergeDataAndStartSyncing(
6635 syncer::EXTENSIONS,
6636 syncer::SyncDataList(),
6637 scoped_ptr<syncer::SyncChangeProcessor>(
6638 new syncer::FakeSyncChangeProcessor),
6639 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6641 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
6642 EXPECT_TRUE(service()->IsExtensionEnabled(good_crx));
6643 EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
6645 sync_pb::EntitySpecifics specifics;
6646 sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension();
6647 ext_specifics->set_id(good_crx);
6648 ext_specifics->set_enabled(true);
6651 ext_specifics->set_version(
6652 service()->GetInstalledExtension(good_crx)->version()->GetString());
6653 syncer::SyncData sync_data =
6654 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6655 syncer::SyncChange sync_change(FROM_HERE,
6656 syncer::SyncChange::ACTION_UPDATE,
6657 sync_data);
6658 syncer::SyncChangeList list(1);
6659 list[0] = sync_change;
6661 // Should do nothing if extension version == sync version.
6662 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6663 EXPECT_FALSE(service()->updater()->WillCheckSoon());
6666 // Should do nothing if extension version > sync version (but see
6667 // the TODO in ProcessExtensionSyncData).
6669 ext_specifics->set_version("0.0.0.0");
6670 syncer::SyncData sync_data =
6671 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6672 syncer::SyncChange sync_change(FROM_HERE,
6673 syncer::SyncChange::ACTION_UPDATE,
6674 sync_data);
6675 syncer::SyncChangeList list(1);
6676 list[0] = sync_change;
6678 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6679 EXPECT_FALSE(service()->updater()->WillCheckSoon());
6682 // Should kick off an update if extension version < sync version.
6684 ext_specifics->set_version("9.9.9.9");
6685 syncer::SyncData sync_data =
6686 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6687 syncer::SyncChange sync_change(FROM_HERE,
6688 syncer::SyncChange::ACTION_UPDATE,
6689 sync_data);
6690 syncer::SyncChangeList list(1);
6691 list[0] = sync_change;
6693 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6694 EXPECT_TRUE(service()->updater()->WillCheckSoon());
6697 EXPECT_FALSE(service()->pending_extension_manager()->IsIdPending(good_crx));
6700 TEST_F(ExtensionServiceTest, ProcessSyncDataNotInstalled) {
6701 InitializeExtensionServiceWithUpdater();
6702 syncer::FakeSyncChangeProcessor processor;
6703 extension_sync_service()->MergeDataAndStartSyncing(
6704 syncer::EXTENSIONS,
6705 syncer::SyncDataList(),
6706 scoped_ptr<syncer::SyncChangeProcessor>(
6707 new syncer::FakeSyncChangeProcessor),
6708 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6710 sync_pb::EntitySpecifics specifics;
6711 sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension();
6712 ext_specifics->set_id(good_crx);
6713 ext_specifics->set_enabled(false);
6714 ext_specifics->set_incognito_enabled(true);
6715 ext_specifics->set_update_url("http://www.google.com/");
6716 ext_specifics->set_version("1.2.3.4");
6717 syncer::SyncData sync_data =
6718 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6719 syncer::SyncChange sync_change(FROM_HERE,
6720 syncer::SyncChange::ACTION_UPDATE,
6721 sync_data);
6722 syncer::SyncChangeList list(1);
6723 list[0] = sync_change;
6725 EXPECT_TRUE(service()->IsExtensionEnabled(good_crx));
6726 EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
6727 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6728 EXPECT_TRUE(service()->updater()->WillCheckSoon());
6729 EXPECT_FALSE(service()->IsExtensionEnabled(good_crx));
6730 EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good_crx, profile()));
6732 const extensions::PendingExtensionInfo* info;
6733 EXPECT_TRUE(
6734 (info = service()->pending_extension_manager()->GetById(good_crx)));
6735 EXPECT_EQ(ext_specifics->update_url(), info->update_url().spec());
6736 EXPECT_TRUE(info->is_from_sync());
6737 EXPECT_EQ(Manifest::INTERNAL, info->install_source());
6738 // TODO(akalin): Figure out a way to test |info.ShouldAllowInstall()|.
6741 TEST_F(ExtensionServiceTest, ProcessSyncDataEnableDisable) {
6742 InitializeEmptyExtensionService();
6743 extension_sync_service()->MergeDataAndStartSyncing(
6744 syncer::EXTENSIONS,
6745 syncer::SyncDataList(),
6746 scoped_ptr<syncer::SyncChangeProcessor>(
6747 new syncer::FakeSyncChangeProcessor),
6748 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6750 const ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
6752 struct TestCase {
6753 const char* name; // For failure output only.
6754 // Set of disable reasons before any Sync data comes in. If this is != 0,
6755 // the extension is disabled.
6756 int previous_disable_reasons;
6757 bool sync_enable; // The enabled flag coming in from Sync.
6758 // The disable reason(s) coming in from Sync, or -1 for "not set".
6759 int sync_disable_reasons;
6760 // The expected set of disable reasons after processing the Sync update. The
6761 // extension should be disabled iff this is != 0.
6762 int expect_disable_reasons;
6763 } test_cases[] = {
6764 { "NopEnable", 0, true, 0, 0 },
6765 { "NopDisable", Extension::DISABLE_USER_ACTION, false,
6766 Extension::DISABLE_USER_ACTION, Extension::DISABLE_USER_ACTION },
6767 { "Disable", 0, false, Extension::DISABLE_USER_ACTION,
6768 Extension::DISABLE_USER_ACTION },
6769 { "DisableLegacy", 0, false, -1, Extension::DISABLE_UNKNOWN_FROM_SYNC },
6770 { "AddDisableReason", Extension::DISABLE_REMOTE_INSTALL, false,
6771 Extension::DISABLE_REMOTE_INSTALL | Extension::DISABLE_USER_ACTION,
6772 Extension::DISABLE_REMOTE_INSTALL | Extension::DISABLE_USER_ACTION },
6773 { "AddDisableReasonLegacy", Extension::DISABLE_USER_ACTION, false, -1,
6774 Extension::DISABLE_USER_ACTION | Extension::DISABLE_UNKNOWN_FROM_SYNC},
6775 { "RemoveDisableReason",
6776 Extension::DISABLE_REMOTE_INSTALL | Extension::DISABLE_USER_ACTION, false,
6777 Extension::DISABLE_USER_ACTION, Extension::DISABLE_USER_ACTION },
6778 { "Enable", Extension::DISABLE_USER_ACTION, true, 0, 0 },
6779 { "EnableLegacy", Extension::DISABLE_USER_ACTION, true, -1, 0 },
6782 for (const TestCase& test_case : test_cases) {
6783 SCOPED_TRACE(test_case.name);
6785 std::string id;
6786 std::string version;
6787 // Don't keep |extension| around longer than necessary.
6789 const Extension* extension =
6790 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
6791 // The extension should now be installed and enabled.
6792 ASSERT_TRUE(extension);
6793 id = extension->id();
6794 version = extension->VersionString();
6796 ASSERT_TRUE(registry()->enabled_extensions().Contains(id));
6798 // Disable it if the test case says so.
6799 if (test_case.previous_disable_reasons) {
6800 service()->DisableExtension(id, test_case.previous_disable_reasons);
6801 ASSERT_TRUE(registry()->disabled_extensions().Contains(id));
6804 // Now a sync update comes in.
6805 sync_pb::EntitySpecifics specifics;
6806 sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension();
6807 ext_specifics->set_id(id);
6808 ext_specifics->set_enabled(test_case.sync_enable);
6809 ext_specifics->set_version(version);
6810 if (test_case.sync_disable_reasons != -1)
6811 ext_specifics->set_disable_reasons(test_case.sync_disable_reasons);
6813 syncer::SyncData sync_data =
6814 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6815 syncer::SyncChange sync_change(FROM_HERE,
6816 syncer::SyncChange::ACTION_UPDATE,
6817 sync_data);
6818 syncer::SyncChangeList list(1, sync_change);
6819 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6821 // Check expectations.
6822 const bool expect_enabled = !test_case.expect_disable_reasons;
6823 EXPECT_EQ(expect_enabled, service()->IsExtensionEnabled(id));
6824 EXPECT_EQ(test_case.expect_disable_reasons, prefs->GetDisableReasons(id));
6826 // Remove the extension again, so we can install it again for the next case.
6827 UninstallExtension(id, false, expect_enabled ? Extension::ENABLED
6828 : Extension::DISABLED);
6832 TEST_F(ExtensionServiceTest, ProcessSyncDataPermissionApproval) {
6833 // This is the update URL specified in the test extension. Setting it here is
6834 // necessary to make it considered syncable.
6835 base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
6836 switches::kAppsGalleryUpdateURL,
6837 "http://localhost/autoupdate/updates.xml");
6839 InitializeEmptyExtensionService();
6840 extension_sync_service()->MergeDataAndStartSyncing(
6841 syncer::EXTENSIONS,
6842 syncer::SyncDataList(),
6843 scoped_ptr<syncer::SyncChangeProcessor>(
6844 new syncer::FakeSyncChangeProcessor),
6845 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6847 const base::FilePath base_path =
6848 data_dir().AppendASCII("permissions_increase");
6849 const base::FilePath pem_path = base_path.AppendASCII("permissions.pem");
6850 const base::FilePath path_v1 = base_path.AppendASCII("v1");
6851 const base::FilePath path_v2 = base_path.AppendASCII("v2");
6853 base::ScopedTempDir crx_dir;
6854 ASSERT_TRUE(crx_dir.CreateUniqueTempDir());
6855 const base::FilePath crx_path_v1 = crx_dir.path().AppendASCII("temp1.crx");
6856 PackCRX(path_v1, pem_path, crx_path_v1);
6857 const base::FilePath crx_path_v2 = crx_dir.path().AppendASCII("temp2.crx");
6858 PackCRX(path_v2, pem_path, crx_path_v2);
6860 const std::string v1("1");
6861 const std::string v2("2");
6863 const ExtensionPrefs* prefs = ExtensionPrefs::Get(profile());
6865 struct TestCase {
6866 const char* name; // For failure output only.
6867 const std::string& sync_version; // The version coming in from Sync.
6868 // The disable reason(s) coming in from Sync, or -1 for "not set".
6869 int sync_disable_reasons;
6870 // Whether the extension's permissions should be auto-granted.
6871 bool expect_permissions_granted;
6872 } test_cases[] = {
6873 // Sync tells us to re-enable an older version. No permissions should be
6874 // granted, since we can't be sure if the user actually approved the right
6875 // set of permissions. Note that the extension will get disabled again the
6876 // next time ExtensionService::CheckPermissionsIncrease runs because of the
6877 // extra permissions.
6878 { "OldVersion", v1, 0, false },
6879 // Legacy case: Sync tells us to re-enable the extension, but doesn't
6880 // specify disable reasons. No permissions should be granted.
6881 { "Legacy", v2, -1, false },
6882 // Sync tells us to re-enable the extension and explicitly removes the
6883 // disable reasons. Now the extension should have its permissions granted.
6884 { "GrantPermissions", v2, 0, true },
6887 for (const TestCase& test_case : test_cases) {
6888 SCOPED_TRACE(test_case.name);
6890 std::string id;
6891 // Don't keep |extension| around longer than necessary (it'll be destroyed
6892 // during updating).
6894 const Extension* extension = InstallCRX(crx_path_v1, INSTALL_NEW);
6895 // The extension should now be installed and enabled.
6896 ASSERT_TRUE(extension);
6897 ASSERT_EQ(v1, extension->VersionString());
6898 id = extension->id();
6900 ASSERT_TRUE(registry()->enabled_extensions().Contains(id));
6902 scoped_refptr<PermissionSet> granted_permissions_v1(
6903 prefs->GetGrantedPermissions(id));
6905 // Update to a new version with increased permissions.
6906 UpdateExtension(id, crx_path_v2, DISABLED);
6908 // Now the extension should be disabled due to a permissions increase.
6910 const Extension* extension =
6911 registry()->disabled_extensions().GetByID(id);
6912 ASSERT_TRUE(extension);
6913 ASSERT_EQ(v2, extension->VersionString());
6915 ASSERT_TRUE(prefs->HasDisableReason(
6916 id, Extension::DISABLE_PERMISSIONS_INCREASE));
6918 // No new permissions should have been granted.
6919 scoped_refptr<PermissionSet> granted_permissions_v2(
6920 prefs->GetGrantedPermissions(id));
6921 ASSERT_EQ(*granted_permissions_v1, *granted_permissions_v2);
6923 // Now a sync update comes in.
6924 sync_pb::EntitySpecifics specifics;
6925 sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension();
6926 ext_specifics->set_id(id);
6927 ext_specifics->set_enabled(true);
6928 ext_specifics->set_version(test_case.sync_version);
6929 if (test_case.sync_disable_reasons != -1)
6930 ext_specifics->set_disable_reasons(test_case.sync_disable_reasons);
6932 syncer::SyncData sync_data =
6933 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6934 syncer::SyncChange sync_change(FROM_HERE,
6935 syncer::SyncChange::ACTION_UPDATE,
6936 sync_data);
6937 syncer::SyncChangeList list(1, sync_change);
6938 extension_sync_service()->ProcessSyncChanges(FROM_HERE, list);
6940 // Check expectations.
6941 EXPECT_TRUE(registry()->GetExtensionById(id, ExtensionRegistry::ENABLED));
6942 scoped_refptr<PermissionSet> granted_permissions(
6943 prefs->GetGrantedPermissions(id));
6944 if (test_case.expect_permissions_granted) {
6945 scoped_refptr<PermissionSet> active_permissions(
6946 prefs->GetActivePermissions(id));
6947 EXPECT_EQ(*granted_permissions, *active_permissions);
6948 } else {
6949 EXPECT_EQ(*granted_permissions, *granted_permissions_v1);
6951 EXPECT_EQ(Extension::DISABLE_NONE, prefs->GetDisableReasons(id));
6953 // Remove the extension again, so we can install it again for the next case.
6954 UninstallExtension(id, false);
6958 #if defined(ENABLE_SUPERVISED_USERS)
6959 class ScopedSupervisedUserServiceDelegate
6960 : public SupervisedUserService::Delegate {
6961 public:
6962 explicit ScopedSupervisedUserServiceDelegate(SupervisedUserService* service)
6963 : service_(service) {
6964 service_->SetDelegate(this);
6966 ~ScopedSupervisedUserServiceDelegate() override {
6967 service_->SetDelegate(nullptr);
6970 // This prevents the legacy supervised user init code from running.
6971 bool SetActive(bool active) override { return true; }
6973 private:
6974 SupervisedUserService* service_;
6977 class MockPermissionRequestCreator : public PermissionRequestCreator {
6978 public:
6979 MockPermissionRequestCreator() {}
6980 ~MockPermissionRequestCreator() override {}
6982 bool IsEnabled() const override { return true; }
6984 void CreateURLAccessRequest(const GURL& url_requested,
6985 const SuccessCallback& callback) override {
6986 FAIL();
6989 MOCK_METHOD2(CreateExtensionUpdateRequest,
6990 void(const std::string& id,
6991 const SupervisedUserService::SuccessCallback& callback));
6993 private:
6994 DISALLOW_COPY_AND_ASSIGN(MockPermissionRequestCreator);
6997 TEST_F(ExtensionServiceTest, SupervisedUserInstallOnlyAllowedByCustodian) {
6998 ExtensionServiceInitParams params = CreateDefaultInitParams();
6999 params.profile_is_supervised = true;
7000 InitializeExtensionService(params);
7002 SupervisedUserService* supervised_user_service =
7003 SupervisedUserServiceFactory::GetForProfile(profile());
7004 ScopedSupervisedUserServiceDelegate delegate(supervised_user_service);
7005 supervised_user_service->Init();
7007 base::FilePath path1 = data_dir().AppendASCII("good.crx");
7008 base::FilePath path2 = data_dir().AppendASCII("good2048.crx");
7009 const Extension* extensions[] = {
7010 InstallCRX(path1, INSTALL_FAILED),
7011 InstallCRX(path2, INSTALL_NEW, Extension::WAS_INSTALLED_BY_CUSTODIAN)
7014 // Only the extension with the "installed by custodian" flag should have been
7015 // installed and enabled.
7016 EXPECT_FALSE(extensions[0]);
7017 ASSERT_TRUE(extensions[1]);
7018 EXPECT_TRUE(registry()->enabled_extensions().Contains(extensions[1]->id()));
7021 TEST_F(ExtensionServiceTest, SupervisedUserPreinstalledExtension) {
7022 ExtensionServiceInitParams params = CreateDefaultInitParams();
7023 // Do *not* set the profile to supervised here!
7024 InitializeExtensionService(params);
7026 SupervisedUserService* supervised_user_service =
7027 SupervisedUserServiceFactory::GetForProfile(profile());
7028 ScopedSupervisedUserServiceDelegate delegate(supervised_user_service);
7029 supervised_user_service->Init();
7031 // Install an extension.
7032 base::FilePath path = data_dir().AppendASCII("good.crx");
7033 const Extension* extension = InstallCRX(path, INSTALL_NEW);
7034 std::string id = extension->id();
7036 // Now make the profile supervised.
7037 profile()->AsTestingProfile()->SetSupervisedUserId(
7038 supervised_users::kChildAccountSUID);
7040 // The extension should not be enabled anymore.
7041 EXPECT_FALSE(registry()->enabled_extensions().Contains(id));
7044 TEST_F(ExtensionServiceTest, SupervisedUserUpdateWithoutPermissionIncrease) {
7045 ExtensionServiceInitParams params = CreateDefaultInitParams();
7046 params.profile_is_supervised = true;
7047 InitializeExtensionService(params);
7049 SupervisedUserService* supervised_user_service =
7050 SupervisedUserServiceFactory::GetForProfile(profile());
7051 ScopedSupervisedUserServiceDelegate delegate(supervised_user_service);
7052 supervised_user_service->Init();
7054 base::FilePath base_path = data_dir().AppendASCII("autoupdate");
7055 base::FilePath pem_path = base_path.AppendASCII("key.pem");
7057 base::FilePath path = base_path.AppendASCII("v1");
7058 const Extension* extension =
7059 PackAndInstallCRX(path, pem_path, INSTALL_NEW,
7060 Extension::WAS_INSTALLED_BY_CUSTODIAN);
7061 // The extension must now be installed and enabled.
7062 ASSERT_TRUE(extension);
7063 ASSERT_TRUE(registry()->enabled_extensions().Contains(extension->id()));
7065 // Save the id, as the extension object will be destroyed during updating.
7066 std::string id = extension->id();
7068 std::string old_version = extension->VersionString();
7070 // Update to a new version.
7071 path = base_path.AppendASCII("v2");
7072 PackCRXAndUpdateExtension(id, path, pem_path, ENABLED);
7074 // The extension should still be there and enabled.
7075 extension = registry()->enabled_extensions().GetByID(id);
7076 ASSERT_TRUE(extension);
7077 // The version should have changed.
7078 EXPECT_NE(extension->VersionString(), old_version);
7081 // Helper class that allows us to parameterize the UpdateWithPermissionIncrease
7082 // test over |bool need_custodian_approval|.
7083 class ExtensionServiceTestSupervisedUserPermissionIncrease :
7084 public ExtensionServiceTest, public testing::WithParamInterface<bool> {};
7086 TEST_P(ExtensionServiceTestSupervisedUserPermissionIncrease,
7087 UpdateWithPermissionIncrease) {
7088 bool need_custodian_approval = GetParam();
7089 base::FieldTrialList field_trial_list(new base::MockEntropyProvider());
7090 base::FieldTrialList::CreateFieldTrial(
7091 "SupervisedUserExtensionPermissionIncrease",
7092 need_custodian_approval ? "NeedCustodianApproval" : "");
7094 ExtensionServiceInitParams params = CreateDefaultInitParams();
7095 params.profile_is_supervised = true;
7096 InitializeExtensionService(params);
7098 SupervisedUserService* supervised_user_service =
7099 SupervisedUserServiceFactory::GetForProfile(profile());
7100 ScopedSupervisedUserServiceDelegate delegate(supervised_user_service);
7101 supervised_user_service->Init();
7102 MockPermissionRequestCreator* creator = new MockPermissionRequestCreator;
7103 supervised_user_service->AddPermissionRequestCreator(
7104 make_scoped_ptr(creator));
7106 base::FilePath base_path = data_dir().AppendASCII("permissions_increase");
7107 base::FilePath pem_path = base_path.AppendASCII("permissions.pem");
7109 base::FilePath path = base_path.AppendASCII("v1");
7110 const Extension* extension =
7111 PackAndInstallCRX(path, pem_path, INSTALL_NEW,
7112 Extension::WAS_INSTALLED_BY_CUSTODIAN);
7113 // The extension must now be installed and enabled.
7114 ASSERT_TRUE(extension);
7115 ASSERT_TRUE(registry()->enabled_extensions().Contains(extension->id()));
7117 // Save the id, as the extension object will be destroyed during updating.
7118 std::string id = extension->id();
7120 std::string old_version = extension->VersionString();
7122 // Update to a new version with increased permissions.
7123 EXPECT_CALL(*creator, CreateExtensionUpdateRequest(id + ":2", testing::_))
7124 .Times(need_custodian_approval ? 1 : 0);
7125 path = base_path.AppendASCII("v2");
7126 PackCRXAndUpdateExtension(id, path, pem_path, DISABLED);
7128 // The extension should still be there, but disabled.
7129 EXPECT_FALSE(registry()->enabled_extensions().Contains(id));
7130 extension = registry()->disabled_extensions().GetByID(id);
7131 ASSERT_TRUE(extension);
7132 // The version should have changed.
7133 EXPECT_NE(extension->VersionString(), old_version);
7135 INSTANTIATE_TEST_CASE_P(NeedCustodianApproval,
7136 ExtensionServiceTestSupervisedUserPermissionIncrease,
7137 testing::Bool());
7139 TEST_F(ExtensionServiceTest,
7140 SupervisedUserSyncUninstallByCustodianSkipsPolicy) {
7141 InitializeEmptyExtensionService();
7142 extension_sync_service()->MergeDataAndStartSyncing(
7143 syncer::EXTENSIONS,
7144 syncer::SyncDataList(),
7145 scoped_ptr<syncer::SyncChangeProcessor>(
7146 new syncer::FakeSyncChangeProcessor),
7147 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
7149 // Install two extensions.
7150 base::FilePath path1 = data_dir().AppendASCII("good.crx");
7151 base::FilePath path2 = data_dir().AppendASCII("good2048.crx");
7152 const Extension* extensions[] = {
7153 InstallCRX(path1, INSTALL_NEW),
7154 InstallCRX(path2, INSTALL_NEW, Extension::WAS_INSTALLED_BY_CUSTODIAN)
7157 // Add a policy provider that will disallow any changes.
7158 extensions::TestManagementPolicyProvider provider(
7159 extensions::TestManagementPolicyProvider::PROHIBIT_MODIFY_STATUS);
7160 GetManagementPolicy()->RegisterProvider(&provider);
7162 // Create a sync deletion for each extension.
7163 syncer::SyncChangeList change_list;
7164 for (size_t i = 0; i < arraysize(extensions); i++) {
7165 const std::string& id = extensions[i]->id();
7166 sync_pb::EntitySpecifics specifics;
7167 sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension();
7168 ext_specifics->set_id(id);
7169 ext_specifics->set_version("1.0");
7170 ext_specifics->set_installed_by_custodian(
7171 extensions[i]->was_installed_by_custodian());
7172 syncer::SyncData sync_data =
7173 syncer::SyncData::CreateLocalData(id, "Name", specifics);
7174 change_list.push_back(syncer::SyncChange(FROM_HERE,
7175 syncer::SyncChange::ACTION_DELETE,
7176 sync_data));
7179 // Save the extension ids, as uninstalling destroys the Extension instance.
7180 std::string extension_ids[] = {
7181 extensions[0]->id(),
7182 extensions[1]->id()
7185 // Now apply the uninstallations.
7186 extension_sync_service()->ProcessSyncChanges(FROM_HERE, change_list);
7188 // Uninstalling the extension without installed_by_custodian should have been
7189 // blocked by policy, so it should still be there.
7190 EXPECT_TRUE(registry()->enabled_extensions().Contains(extension_ids[0]));
7192 // But installed_by_custodian should result in bypassing the policy check.
7193 EXPECT_FALSE(
7194 registry()->GenerateInstalledExtensionsSet()->Contains(extension_ids[1]));
7196 #endif // defined(ENABLE_SUPERVISED_USERS)
7198 TEST_F(ExtensionServiceTest, InstallPriorityExternalUpdateUrl) {
7199 InitializeEmptyExtensionService();
7201 base::FilePath path = data_dir().AppendASCII("good.crx");
7202 InstallCRX(path, INSTALL_NEW);
7203 ValidatePrefKeyCount(1u);
7204 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
7205 ValidateIntegerPref(good_crx, "location", Manifest::INTERNAL);
7207 extensions::PendingExtensionManager* pending =
7208 service()->pending_extension_manager();
7209 EXPECT_FALSE(pending->IsIdPending(kGoodId));
7211 // Skip install when the location is the same.
7212 EXPECT_FALSE(
7213 service()->OnExternalExtensionUpdateUrlFound(kGoodId,
7214 std::string(),
7215 GURL(kGoodUpdateURL),
7216 Manifest::INTERNAL,
7217 Extension::NO_FLAGS,
7218 false));
7219 EXPECT_FALSE(pending->IsIdPending(kGoodId));
7221 // Install when the location has higher priority.
7222 EXPECT_TRUE(service()->OnExternalExtensionUpdateUrlFound(
7223 kGoodId,
7224 std::string(),
7225 GURL(kGoodUpdateURL),
7226 Manifest::EXTERNAL_POLICY_DOWNLOAD,
7227 Extension::NO_FLAGS,
7228 false));
7229 EXPECT_TRUE(pending->IsIdPending(kGoodId));
7231 // Try the low priority again. Should be rejected.
7232 EXPECT_FALSE(service()->OnExternalExtensionUpdateUrlFound(
7233 kGoodId,
7234 std::string(),
7235 GURL(kGoodUpdateURL),
7236 Manifest::EXTERNAL_PREF_DOWNLOAD,
7237 Extension::NO_FLAGS,
7238 false));
7239 // The existing record should still be present in the pending extension
7240 // manager.
7241 EXPECT_TRUE(pending->IsIdPending(kGoodId));
7243 pending->Remove(kGoodId);
7245 // Skip install when the location has the same priority as the installed
7246 // location.
7247 EXPECT_FALSE(
7248 service()->OnExternalExtensionUpdateUrlFound(kGoodId,
7249 std::string(),
7250 GURL(kGoodUpdateURL),
7251 Manifest::INTERNAL,
7252 Extension::NO_FLAGS,
7253 false));
7255 EXPECT_FALSE(pending->IsIdPending(kGoodId));
7258 TEST_F(ExtensionServiceTest, InstallPriorityExternalLocalFile) {
7259 Version older_version("0.1.0.0");
7260 Version newer_version("2.0.0.0");
7262 // We don't want the extension to be installed. A path that doesn't
7263 // point to a valid CRX ensures this.
7264 const base::FilePath kInvalidPathToCrx(FILE_PATH_LITERAL("invalid_path"));
7266 const int kCreationFlags = 0;
7267 const bool kDontMarkAcknowledged = false;
7268 const bool kDontInstallImmediately = false;
7270 InitializeEmptyExtensionService();
7272 // The test below uses install source constants to test that
7273 // priority is enforced. It assumes a specific ranking of install
7274 // sources: Registry (EXTERNAL_REGISTRY) overrides external pref
7275 // (EXTERNAL_PREF), and external pref overrides user install (INTERNAL).
7276 // The following assertions verify these assumptions:
7277 ASSERT_EQ(Manifest::EXTERNAL_REGISTRY,
7278 Manifest::GetHigherPriorityLocation(Manifest::EXTERNAL_REGISTRY,
7279 Manifest::EXTERNAL_PREF));
7280 ASSERT_EQ(Manifest::EXTERNAL_REGISTRY,
7281 Manifest::GetHigherPriorityLocation(Manifest::EXTERNAL_REGISTRY,
7282 Manifest::INTERNAL));
7283 ASSERT_EQ(Manifest::EXTERNAL_PREF,
7284 Manifest::GetHigherPriorityLocation(Manifest::EXTERNAL_PREF,
7285 Manifest::INTERNAL));
7287 extensions::PendingExtensionManager* pending =
7288 service()->pending_extension_manager();
7289 EXPECT_FALSE(pending->IsIdPending(kGoodId));
7292 // Simulate an external source adding the extension as INTERNAL.
7293 content::WindowedNotificationObserver observer(
7294 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
7295 content::NotificationService::AllSources());
7296 EXPECT_TRUE(service()->OnExternalExtensionFileFound(
7297 kGoodId,
7298 &older_version,
7299 kInvalidPathToCrx,
7300 Manifest::INTERNAL,
7301 kCreationFlags,
7302 kDontMarkAcknowledged,
7303 kDontInstallImmediately));
7304 EXPECT_TRUE(pending->IsIdPending(kGoodId));
7305 observer.Wait();
7306 VerifyCrxInstall(kInvalidPathToCrx, INSTALL_FAILED);
7310 // Simulate an external source adding the extension as EXTERNAL_PREF.
7311 content::WindowedNotificationObserver observer(
7312 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
7313 content::NotificationService::AllSources());
7314 EXPECT_TRUE(service()->OnExternalExtensionFileFound(
7315 kGoodId,
7316 &older_version,
7317 kInvalidPathToCrx,
7318 Manifest::EXTERNAL_PREF,
7319 kCreationFlags,
7320 kDontMarkAcknowledged,
7321 kDontInstallImmediately));
7322 EXPECT_TRUE(pending->IsIdPending(kGoodId));
7323 observer.Wait();
7324 VerifyCrxInstall(kInvalidPathToCrx, INSTALL_FAILED);
7327 // Simulate an external source adding as EXTERNAL_PREF again.
7328 // This is rejected because the version and the location are the same as
7329 // the previous installation, which is still pending.
7330 EXPECT_FALSE(service()->OnExternalExtensionFileFound(
7331 kGoodId,
7332 &older_version,
7333 kInvalidPathToCrx,
7334 Manifest::EXTERNAL_PREF,
7335 kCreationFlags,
7336 kDontMarkAcknowledged,
7337 kDontInstallImmediately));
7338 EXPECT_TRUE(pending->IsIdPending(kGoodId));
7340 // Try INTERNAL again. Should fail.
7341 EXPECT_FALSE(service()->OnExternalExtensionFileFound(
7342 kGoodId,
7343 &older_version,
7344 kInvalidPathToCrx,
7345 Manifest::INTERNAL,
7346 kCreationFlags,
7347 kDontMarkAcknowledged,
7348 kDontInstallImmediately));
7349 EXPECT_TRUE(pending->IsIdPending(kGoodId));
7352 // Now the registry adds the extension.
7353 content::WindowedNotificationObserver observer(
7354 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
7355 content::NotificationService::AllSources());
7356 EXPECT_TRUE(service()->OnExternalExtensionFileFound(
7357 kGoodId,
7358 &older_version,
7359 kInvalidPathToCrx,
7360 Manifest::EXTERNAL_REGISTRY,
7361 kCreationFlags,
7362 kDontMarkAcknowledged,
7363 kDontInstallImmediately));
7364 EXPECT_TRUE(pending->IsIdPending(kGoodId));
7365 observer.Wait();
7366 VerifyCrxInstall(kInvalidPathToCrx, INSTALL_FAILED);
7369 // Registry outranks both external pref and internal, so both fail.
7370 EXPECT_FALSE(service()->OnExternalExtensionFileFound(
7371 kGoodId,
7372 &older_version,
7373 kInvalidPathToCrx,
7374 Manifest::EXTERNAL_PREF,
7375 kCreationFlags,
7376 kDontMarkAcknowledged,
7377 kDontInstallImmediately));
7378 EXPECT_TRUE(pending->IsIdPending(kGoodId));
7380 EXPECT_FALSE(service()->OnExternalExtensionFileFound(
7381 kGoodId,
7382 &older_version,
7383 kInvalidPathToCrx,
7384 Manifest::INTERNAL,
7385 kCreationFlags,
7386 kDontMarkAcknowledged,
7387 kDontInstallImmediately));
7388 EXPECT_TRUE(pending->IsIdPending(kGoodId));
7390 pending->Remove(kGoodId);
7392 // Install the extension.
7393 base::FilePath path = data_dir().AppendASCII("good.crx");
7394 const Extension* ext = InstallCRX(path, INSTALL_NEW);
7395 ValidatePrefKeyCount(1u);
7396 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
7397 ValidateIntegerPref(good_crx, "location", Manifest::INTERNAL);
7399 // Now test the logic of OnExternalExtensionFileFound() when the extension
7400 // being added is already installed.
7402 // Tests assume |older_version| is less than the installed version, and
7403 // |newer_version| is greater. Verify this:
7404 ASSERT_TRUE(older_version.IsOlderThan(ext->VersionString()));
7405 ASSERT_TRUE(ext->version()->IsOlderThan(newer_version.GetString()));
7407 // An external install for the same location should fail if the version is
7408 // older, or the same, and succeed if the version is newer.
7410 // Older than the installed version...
7411 EXPECT_FALSE(service()->OnExternalExtensionFileFound(
7412 kGoodId,
7413 &older_version,
7414 kInvalidPathToCrx,
7415 Manifest::INTERNAL,
7416 kCreationFlags,
7417 kDontMarkAcknowledged,
7418 kDontInstallImmediately));
7419 EXPECT_FALSE(pending->IsIdPending(kGoodId));
7421 // Same version as the installed version...
7422 EXPECT_FALSE(service()->OnExternalExtensionFileFound(
7423 kGoodId,
7424 ext->version(),
7425 kInvalidPathToCrx,
7426 Manifest::INTERNAL,
7427 kCreationFlags,
7428 kDontMarkAcknowledged,
7429 kDontInstallImmediately));
7430 EXPECT_FALSE(pending->IsIdPending(kGoodId));
7432 // Newer than the installed version...
7433 EXPECT_TRUE(service()->OnExternalExtensionFileFound(
7434 kGoodId,
7435 &newer_version,
7436 kInvalidPathToCrx,
7437 Manifest::INTERNAL,
7438 kCreationFlags,
7439 kDontMarkAcknowledged,
7440 kDontInstallImmediately));
7441 EXPECT_TRUE(pending->IsIdPending(kGoodId));
7443 // An external install for a higher priority install source should succeed
7444 // if the version is greater. |older_version| is not...
7445 EXPECT_FALSE(service()->OnExternalExtensionFileFound(
7446 kGoodId,
7447 &older_version,
7448 kInvalidPathToCrx,
7449 Manifest::EXTERNAL_PREF,
7450 kCreationFlags,
7451 kDontMarkAcknowledged,
7452 kDontInstallImmediately));
7453 EXPECT_TRUE(pending->IsIdPending(kGoodId));
7455 // |newer_version| is newer.
7456 EXPECT_TRUE(service()->OnExternalExtensionFileFound(
7457 kGoodId,
7458 &newer_version,
7459 kInvalidPathToCrx,
7460 Manifest::EXTERNAL_PREF,
7461 kCreationFlags,
7462 kDontMarkAcknowledged,
7463 kDontInstallImmediately));
7464 EXPECT_TRUE(pending->IsIdPending(kGoodId));
7466 // An external install for an even higher priority install source should
7467 // succeed if the version is greater.
7468 EXPECT_TRUE(service()->OnExternalExtensionFileFound(
7469 kGoodId,
7470 &newer_version,
7471 kInvalidPathToCrx,
7472 Manifest::EXTERNAL_REGISTRY,
7473 kCreationFlags,
7474 kDontMarkAcknowledged,
7475 kDontInstallImmediately));
7476 EXPECT_TRUE(pending->IsIdPending(kGoodId));
7478 // Because EXTERNAL_PREF is a lower priority source than EXTERNAL_REGISTRY,
7479 // adding from external pref will now fail.
7480 EXPECT_FALSE(service()->OnExternalExtensionFileFound(
7481 kGoodId,
7482 &newer_version,
7483 kInvalidPathToCrx,
7484 Manifest::EXTERNAL_PREF,
7485 kCreationFlags,
7486 kDontMarkAcknowledged,
7487 kDontInstallImmediately));
7488 EXPECT_TRUE(pending->IsIdPending(kGoodId));
7491 TEST_F(ExtensionServiceTest, ConcurrentExternalLocalFile) {
7492 Version kVersion123("1.2.3");
7493 Version kVersion124("1.2.4");
7494 Version kVersion125("1.2.5");
7495 const base::FilePath kInvalidPathToCrx(FILE_PATH_LITERAL("invalid_path"));
7496 const int kCreationFlags = 0;
7497 const bool kDontMarkAcknowledged = false;
7498 const bool kDontInstallImmediately = false;
7500 InitializeEmptyExtensionService();
7502 extensions::PendingExtensionManager* pending =
7503 service()->pending_extension_manager();
7504 EXPECT_FALSE(pending->IsIdPending(kGoodId));
7506 // An external provider starts installing from a local crx.
7507 EXPECT_TRUE(service()->OnExternalExtensionFileFound(
7508 kGoodId,
7509 &kVersion123,
7510 kInvalidPathToCrx,
7511 Manifest::EXTERNAL_PREF,
7512 kCreationFlags,
7513 kDontMarkAcknowledged,
7514 kDontInstallImmediately));
7515 const extensions::PendingExtensionInfo* info;
7516 EXPECT_TRUE((info = pending->GetById(kGoodId)));
7517 EXPECT_TRUE(info->version().IsValid());
7518 EXPECT_TRUE(info->version().Equals(kVersion123));
7520 // Adding a newer version overrides the currently pending version.
7521 EXPECT_TRUE(service()->OnExternalExtensionFileFound(
7522 kGoodId,
7523 &kVersion124,
7524 kInvalidPathToCrx,
7525 Manifest::EXTERNAL_PREF,
7526 kCreationFlags,
7527 kDontMarkAcknowledged,
7528 kDontInstallImmediately));
7529 EXPECT_TRUE((info = pending->GetById(kGoodId)));
7530 EXPECT_TRUE(info->version().IsValid());
7531 EXPECT_TRUE(info->version().Equals(kVersion124));
7533 // Adding an older version fails.
7534 EXPECT_FALSE(service()->OnExternalExtensionFileFound(
7535 kGoodId,
7536 &kVersion123,
7537 kInvalidPathToCrx,
7538 Manifest::EXTERNAL_PREF,
7539 kCreationFlags,
7540 kDontMarkAcknowledged,
7541 kDontInstallImmediately));
7542 EXPECT_TRUE((info = pending->GetById(kGoodId)));
7543 EXPECT_TRUE(info->version().IsValid());
7544 EXPECT_TRUE(info->version().Equals(kVersion124));
7546 // Adding an older version fails even when coming from a higher-priority
7547 // location.
7548 EXPECT_FALSE(service()->OnExternalExtensionFileFound(
7549 kGoodId,
7550 &kVersion123,
7551 kInvalidPathToCrx,
7552 Manifest::EXTERNAL_REGISTRY,
7553 kCreationFlags,
7554 kDontMarkAcknowledged,
7555 kDontInstallImmediately));
7556 EXPECT_TRUE((info = pending->GetById(kGoodId)));
7557 EXPECT_TRUE(info->version().IsValid());
7558 EXPECT_TRUE(info->version().Equals(kVersion124));
7560 // Adding the latest version from the webstore overrides a specific version.
7561 GURL kUpdateUrl("http://example.com/update");
7562 EXPECT_TRUE(service()->OnExternalExtensionUpdateUrlFound(
7563 kGoodId,
7564 std::string(),
7565 kUpdateUrl,
7566 Manifest::EXTERNAL_POLICY_DOWNLOAD,
7567 Extension::NO_FLAGS,
7568 false));
7569 EXPECT_TRUE((info = pending->GetById(kGoodId)));
7570 EXPECT_FALSE(info->version().IsValid());
7573 // This makes sure we can package and install CRX files that use whitelisted
7574 // permissions.
7575 TEST_F(ExtensionServiceTest, InstallWhitelistedExtension) {
7576 std::string test_id = "hdkklepkcpckhnpgjnmbdfhehckloojk";
7577 base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
7578 extensions::switches::kWhitelistedExtensionID, test_id);
7580 InitializeEmptyExtensionService();
7581 base::FilePath path = data_dir().AppendASCII("permissions");
7582 base::FilePath pem_path = path
7583 .AppendASCII("whitelist.pem");
7584 path = path
7585 .AppendASCII("whitelist");
7587 const Extension* extension = PackAndInstallCRX(path, pem_path, INSTALL_NEW);
7588 EXPECT_EQ(0u, GetErrors().size());
7589 ASSERT_EQ(1u, registry()->enabled_extensions().size());
7590 EXPECT_EQ(test_id, extension->id());
7593 // Test that when multiple sources try to install an extension,
7594 // we consistently choose the right one. To make tests easy to read,
7595 // methods that fake requests to install crx files in several ways
7596 // are provided.
7597 class ExtensionSourcePriorityTest : public ExtensionServiceTest {
7598 public:
7599 void SetUp() override {
7600 ExtensionServiceTest::SetUp();
7602 // All tests use a single extension. Put the id and path in member vars
7603 // that all methods can read.
7604 crx_id_ = kGoodId;
7605 crx_path_ = data_dir().AppendASCII("good.crx");
7608 // Fake an external source adding a URL to fetch an extension from.
7609 bool AddPendingExternalPrefUrl() {
7610 return service()->pending_extension_manager()->AddFromExternalUpdateUrl(
7611 crx_id_,
7612 std::string(),
7613 GURL(),
7614 Manifest::EXTERNAL_PREF_DOWNLOAD,
7615 Extension::NO_FLAGS,
7616 false);
7619 // Fake an external file from external_extensions.json.
7620 bool AddPendingExternalPrefFileInstall() {
7621 Version version("1.0.0.0");
7623 return service()->OnExternalExtensionFileFound(crx_id_,
7624 &version,
7625 crx_path_,
7626 Manifest::EXTERNAL_PREF,
7627 Extension::NO_FLAGS,
7628 false,
7629 false);
7632 // Fake a request from sync to install an extension.
7633 bool AddPendingSyncInstall() {
7634 return service()->pending_extension_manager()->AddFromSync(
7635 crx_id_,
7636 GURL(kGoodUpdateURL),
7637 &IsExtension,
7638 kGoodRemoteInstall,
7639 kGoodInstalledByCustodian);
7642 // Fake a policy install.
7643 bool AddPendingPolicyInstall() {
7644 // Get path to the CRX with id |kGoodId|.
7645 return service()->OnExternalExtensionUpdateUrlFound(
7646 crx_id_,
7647 std::string(),
7648 GURL(),
7649 Manifest::EXTERNAL_POLICY_DOWNLOAD,
7650 Extension::NO_FLAGS,
7651 false);
7654 // Get the install source of a pending extension.
7655 Manifest::Location GetPendingLocation() {
7656 const extensions::PendingExtensionInfo* info;
7657 EXPECT_TRUE(
7658 (info = service()->pending_extension_manager()->GetById(crx_id_)));
7659 return info->install_source();
7662 // Is an extension pending from a sync request?
7663 bool GetPendingIsFromSync() {
7664 const extensions::PendingExtensionInfo* info;
7665 EXPECT_TRUE(
7666 (info = service()->pending_extension_manager()->GetById(crx_id_)));
7667 return info->is_from_sync();
7670 // Is the CRX id these tests use pending?
7671 bool IsCrxPending() {
7672 return service()->pending_extension_manager()->IsIdPending(crx_id_);
7675 // Is an extension installed?
7676 bool IsCrxInstalled() {
7677 return (service()->GetExtensionById(crx_id_, true) != NULL);
7680 protected:
7681 // All tests use a single extension. Making the id and path member
7682 // vars avoids pasing the same argument to every method.
7683 std::string crx_id_;
7684 base::FilePath crx_path_;
7687 // Test that a pending request for installation of an external CRX from
7688 // an update URL overrides a pending request to install the same extension
7689 // from sync.
7690 TEST_F(ExtensionSourcePriorityTest, PendingExternalFileOverSync) {
7691 InitializeEmptyExtensionService();
7693 ASSERT_FALSE(IsCrxInstalled());
7695 // Install pending extension from sync.
7696 content::WindowedNotificationObserver observer(
7697 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
7698 content::NotificationService::AllSources());
7699 EXPECT_TRUE(AddPendingSyncInstall());
7700 ASSERT_EQ(Manifest::INTERNAL, GetPendingLocation());
7701 EXPECT_TRUE(GetPendingIsFromSync());
7702 ASSERT_FALSE(IsCrxInstalled());
7704 // Install pending as external prefs json would.
7705 AddPendingExternalPrefFileInstall();
7706 ASSERT_EQ(Manifest::EXTERNAL_PREF, GetPendingLocation());
7707 ASSERT_FALSE(IsCrxInstalled());
7709 // Another request from sync should be ignored.
7710 EXPECT_FALSE(AddPendingSyncInstall());
7711 ASSERT_EQ(Manifest::EXTERNAL_PREF, GetPendingLocation());
7712 ASSERT_FALSE(IsCrxInstalled());
7714 observer.Wait();
7715 VerifyCrxInstall(crx_path_, INSTALL_NEW);
7716 ASSERT_TRUE(IsCrxInstalled());
7719 // Test that an install of an external CRX from an update overrides
7720 // an install of the same extension from sync.
7721 TEST_F(ExtensionSourcePriorityTest, PendingExternalUrlOverSync) {
7722 InitializeEmptyExtensionService();
7723 ASSERT_FALSE(IsCrxInstalled());
7725 EXPECT_TRUE(AddPendingSyncInstall());
7726 ASSERT_EQ(Manifest::INTERNAL, GetPendingLocation());
7727 EXPECT_TRUE(GetPendingIsFromSync());
7728 ASSERT_FALSE(IsCrxInstalled());
7730 ASSERT_TRUE(AddPendingExternalPrefUrl());
7731 ASSERT_EQ(Manifest::EXTERNAL_PREF_DOWNLOAD, GetPendingLocation());
7732 EXPECT_FALSE(GetPendingIsFromSync());
7733 ASSERT_FALSE(IsCrxInstalled());
7735 EXPECT_FALSE(AddPendingSyncInstall());
7736 ASSERT_EQ(Manifest::EXTERNAL_PREF_DOWNLOAD, GetPendingLocation());
7737 EXPECT_FALSE(GetPendingIsFromSync());
7738 ASSERT_FALSE(IsCrxInstalled());
7741 // Test that an external install request stops sync from installing
7742 // the same extension.
7743 TEST_F(ExtensionSourcePriorityTest, InstallExternalBlocksSyncRequest) {
7744 InitializeEmptyExtensionService();
7745 ASSERT_FALSE(IsCrxInstalled());
7747 // External prefs starts an install.
7748 AddPendingExternalPrefFileInstall();
7750 // Crx installer was made, but has not yet run.
7751 ASSERT_FALSE(IsCrxInstalled());
7753 // Before the CRX installer runs, Sync requests that the same extension
7754 // be installed. Should fail, because an external source is pending.
7755 content::WindowedNotificationObserver observer(
7756 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
7757 content::NotificationService::AllSources());
7758 ASSERT_FALSE(AddPendingSyncInstall());
7760 // Wait for the external source to install.
7761 observer.Wait();
7762 VerifyCrxInstall(crx_path_, INSTALL_NEW);
7763 ASSERT_TRUE(IsCrxInstalled());
7765 // Now that the extension is installed, sync request should fail
7766 // because the extension is already installed.
7767 ASSERT_FALSE(AddPendingSyncInstall());
7770 // Test that installing an external extension displays a GlobalError.
7771 TEST_F(ExtensionServiceTest, ExternalInstallGlobalError) {
7772 FeatureSwitch::ScopedOverride prompt(
7773 FeatureSwitch::prompt_for_external_extensions(), true);
7775 InitializeEmptyExtensionService();
7776 MockExtensionProvider* provider =
7777 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF);
7778 AddMockExternalProvider(provider);
7780 service()->external_install_manager()->UpdateExternalExtensionAlert();
7781 // Should return false, meaning there aren't any extensions that the user
7782 // needs to know about.
7783 EXPECT_FALSE(
7784 service()->external_install_manager()->HasExternalInstallError());
7786 // This is a normal extension, installed normally.
7787 // This should NOT trigger an alert.
7788 service()->set_extensions_enabled(true);
7789 base::FilePath path = data_dir().AppendASCII("good.crx");
7790 InstallCRX(path, INSTALL_NEW);
7792 service()->CheckForExternalUpdates();
7793 base::RunLoop().RunUntilIdle();
7794 EXPECT_FALSE(
7795 service()->external_install_manager()->HasExternalInstallError());
7797 // A hosted app, installed externally.
7798 // This should NOT trigger an alert.
7799 provider->UpdateOrAddExtension(
7800 hosted_app, "1.0.0.0", data_dir().AppendASCII("hosted_app.crx"));
7802 content::WindowedNotificationObserver observer(
7803 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
7804 content::NotificationService::AllSources());
7805 service()->CheckForExternalUpdates();
7806 observer.Wait();
7807 EXPECT_FALSE(
7808 service()->external_install_manager()->HasExternalInstallError());
7810 // Another normal extension, but installed externally.
7811 // This SHOULD trigger an alert.
7812 provider->UpdateOrAddExtension(
7813 page_action, "1.0.0.0", data_dir().AppendASCII("page_action.crx"));
7815 content::WindowedNotificationObserver observer2(
7816 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
7817 content::NotificationService::AllSources());
7818 service()->CheckForExternalUpdates();
7819 observer2.Wait();
7820 EXPECT_TRUE(service()->external_install_manager()->HasExternalInstallError());
7823 // Test that external extensions are initially disabled, and that enabling
7824 // them clears the prompt.
7825 TEST_F(ExtensionServiceTest, ExternalInstallInitiallyDisabled) {
7826 FeatureSwitch::ScopedOverride prompt(
7827 FeatureSwitch::prompt_for_external_extensions(), true);
7829 InitializeEmptyExtensionService();
7830 MockExtensionProvider* provider =
7831 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF);
7832 AddMockExternalProvider(provider);
7834 provider->UpdateOrAddExtension(
7835 page_action, "1.0.0.0", data_dir().AppendASCII("page_action.crx"));
7837 content::WindowedNotificationObserver observer(
7838 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
7839 content::NotificationService::AllSources());
7840 service()->CheckForExternalUpdates();
7841 observer.Wait();
7842 EXPECT_TRUE(service()->external_install_manager()->HasExternalInstallError());
7843 EXPECT_FALSE(service()->IsExtensionEnabled(page_action));
7845 const Extension* extension =
7846 registry()->disabled_extensions().GetByID(page_action);
7847 EXPECT_TRUE(extension);
7848 EXPECT_EQ(page_action, extension->id());
7850 service()->EnableExtension(page_action);
7851 EXPECT_FALSE(
7852 service()->external_install_manager()->HasExternalInstallError());
7853 EXPECT_TRUE(service()->IsExtensionEnabled(page_action));
7856 // Test that installing multiple external extensions works.
7857 // Flaky on windows; http://crbug.com/295757 .
7858 // Causes race conditions with an in-process utility thread, so disable under
7859 // TSan: https://crbug.com/518957
7860 #if defined(OS_WIN) || defined(THREAD_SANITIZER)
7861 #define MAYBE_ExternalInstallMultiple DISABLED_ExternalInstallMultiple
7862 #else
7863 #define MAYBE_ExternalInstallMultiple ExternalInstallMultiple
7864 #endif
7865 TEST_F(ExtensionServiceTest, MAYBE_ExternalInstallMultiple) {
7866 FeatureSwitch::ScopedOverride prompt(
7867 FeatureSwitch::prompt_for_external_extensions(), true);
7869 InitializeEmptyExtensionService();
7870 MockExtensionProvider* provider =
7871 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF);
7872 AddMockExternalProvider(provider);
7874 provider->UpdateOrAddExtension(
7875 page_action, "1.0.0.0", data_dir().AppendASCII("page_action.crx"));
7876 provider->UpdateOrAddExtension(
7877 good_crx, "1.0.0.0", data_dir().AppendASCII("good.crx"));
7878 provider->UpdateOrAddExtension(
7879 theme_crx, "2.0", data_dir().AppendASCII("theme.crx"));
7881 int count = 3;
7882 content::WindowedNotificationObserver observer(
7883 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
7884 base::Bind(&WaitForCountNotificationsCallback, &count));
7885 service()->CheckForExternalUpdates();
7886 observer.Wait();
7887 EXPECT_TRUE(service()->external_install_manager()->HasExternalInstallError());
7888 EXPECT_FALSE(service()->IsExtensionEnabled(page_action));
7889 EXPECT_FALSE(service()->IsExtensionEnabled(good_crx));
7890 EXPECT_FALSE(service()->IsExtensionEnabled(theme_crx));
7892 service()->EnableExtension(page_action);
7893 EXPECT_TRUE(service()->external_install_manager()->HasExternalInstallError());
7894 EXPECT_FALSE(service()
7895 ->external_install_manager()
7896 ->HasExternalInstallBubbleForTesting());
7898 service()->EnableExtension(theme_crx);
7899 EXPECT_TRUE(service()->external_install_manager()->HasExternalInstallError());
7900 EXPECT_FALSE(service()
7901 ->external_install_manager()
7902 ->HasExternalInstallBubbleForTesting());
7904 service()->EnableExtension(good_crx);
7905 EXPECT_FALSE(
7906 service()->external_install_manager()->HasExternalInstallError());
7907 EXPECT_FALSE(service()
7908 ->external_install_manager()
7909 ->HasExternalInstallBubbleForTesting());
7912 // Test that there is a bubble for external extensions that update
7913 // from the webstore if the profile is not new.
7914 TEST_F(ExtensionServiceTest, ExternalInstallUpdatesFromWebstoreOldProfile) {
7915 FeatureSwitch::ScopedOverride prompt(
7916 FeatureSwitch::prompt_for_external_extensions(), true);
7918 // This sets up the ExtensionPrefs used by our ExtensionService to be
7919 // post-first run.
7920 ExtensionServiceInitParams params = CreateDefaultInitParams();
7921 params.is_first_run = false;
7922 InitializeExtensionService(params);
7924 base::FilePath crx_path = temp_dir().path().AppendASCII("webstore.crx");
7925 PackCRX(data_dir().AppendASCII("update_from_webstore"),
7926 data_dir().AppendASCII("update_from_webstore.pem"),
7927 crx_path);
7929 MockExtensionProvider* provider =
7930 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF);
7931 AddMockExternalProvider(provider);
7932 provider->UpdateOrAddExtension(updates_from_webstore, "1", crx_path);
7934 content::WindowedNotificationObserver observer(
7935 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
7936 content::NotificationService::AllSources());
7937 service()->CheckForExternalUpdates();
7938 observer.Wait();
7939 EXPECT_TRUE(service()->external_install_manager()->HasExternalInstallError());
7940 EXPECT_TRUE(service()
7941 ->external_install_manager()
7942 ->HasExternalInstallBubbleForTesting());
7943 EXPECT_FALSE(service()->IsExtensionEnabled(updates_from_webstore));
7946 // Test that there is no bubble for external extensions if the profile is new.
7947 TEST_F(ExtensionServiceTest, ExternalInstallUpdatesFromWebstoreNewProfile) {
7948 FeatureSwitch::ScopedOverride prompt(
7949 FeatureSwitch::prompt_for_external_extensions(), true);
7951 InitializeEmptyExtensionService();
7953 base::FilePath crx_path = temp_dir().path().AppendASCII("webstore.crx");
7954 PackCRX(data_dir().AppendASCII("update_from_webstore"),
7955 data_dir().AppendASCII("update_from_webstore.pem"),
7956 crx_path);
7958 MockExtensionProvider* provider =
7959 new MockExtensionProvider(service(), Manifest::EXTERNAL_PREF);
7960 AddMockExternalProvider(provider);
7961 provider->UpdateOrAddExtension(updates_from_webstore, "1", crx_path);
7963 content::WindowedNotificationObserver observer(
7964 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
7965 content::NotificationService::AllSources());
7966 service()->CheckForExternalUpdates();
7967 observer.Wait();
7968 EXPECT_TRUE(service()->external_install_manager()->HasExternalInstallError());
7969 EXPECT_FALSE(service()
7970 ->external_install_manager()
7971 ->HasExternalInstallBubbleForTesting());
7972 EXPECT_FALSE(service()->IsExtensionEnabled(updates_from_webstore));
7975 // Test that clicking to remove the extension on an external install warning
7976 // uninstalls the extension.
7977 TEST_F(ExtensionServiceTest, ExternalInstallClickToRemove) {
7978 FeatureSwitch::ScopedOverride prompt(
7979 FeatureSwitch::prompt_for_external_extensions(), true);
7981 ExtensionServiceInitParams params = CreateDefaultInitParams();
7982 params.is_first_run = false;
7983 InitializeExtensionService(params);
7985 base::FilePath crx_path = temp_dir().path().AppendASCII("webstore.crx");
7986 PackCRX(data_dir().AppendASCII("update_from_webstore"),
7987 data_dir().AppendASCII("update_from_webstore.pem"),
7988 crx_path);
7990 MockExtensionProvider* provider =
7991 new MockExtensionProvider(service_, Manifest::EXTERNAL_PREF);
7992 AddMockExternalProvider(provider);
7993 provider->UpdateOrAddExtension(updates_from_webstore, "1", crx_path);
7995 content::WindowedNotificationObserver observer(
7996 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
7997 content::NotificationService::AllSources());
7998 service_->CheckForExternalUpdates();
7999 observer.Wait();
8000 EXPECT_TRUE(service_->external_install_manager()->HasExternalInstallError());
8002 // We check both enabled and disabled, since these are "eventually exclusive"
8003 // sets.
8004 EXPECT_TRUE(registry()->disabled_extensions().GetByID(updates_from_webstore));
8005 EXPECT_FALSE(registry()->enabled_extensions().GetByID(updates_from_webstore));
8007 // Click the negative response.
8008 service_->external_install_manager()->error_for_testing()->InstallUIAbort(
8009 true);
8010 // The Extension should be uninstalled.
8011 EXPECT_FALSE(registry()->GetExtensionById(updates_from_webstore,
8012 ExtensionRegistry::EVERYTHING));
8013 // The error should be removed.
8014 EXPECT_FALSE(service_->external_install_manager()->HasExternalInstallError());
8017 // Test that clicking to keep the extension on an external install warning
8018 // re-enables the extension.
8019 TEST_F(ExtensionServiceTest, ExternalInstallClickToKeep) {
8020 FeatureSwitch::ScopedOverride prompt(
8021 FeatureSwitch::prompt_for_external_extensions(), true);
8023 ExtensionServiceInitParams params = CreateDefaultInitParams();
8024 params.is_first_run = false;
8025 InitializeExtensionService(params);
8027 base::FilePath crx_path = temp_dir().path().AppendASCII("webstore.crx");
8028 PackCRX(data_dir().AppendASCII("update_from_webstore"),
8029 data_dir().AppendASCII("update_from_webstore.pem"),
8030 crx_path);
8032 MockExtensionProvider* provider =
8033 new MockExtensionProvider(service_, Manifest::EXTERNAL_PREF);
8034 AddMockExternalProvider(provider);
8035 provider->UpdateOrAddExtension(updates_from_webstore, "1", crx_path);
8037 content::WindowedNotificationObserver observer(
8038 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
8039 content::NotificationService::AllSources());
8040 service_->CheckForExternalUpdates();
8041 observer.Wait();
8042 EXPECT_TRUE(service_->external_install_manager()->HasExternalInstallError());
8044 // We check both enabled and disabled, since these are "eventually exclusive"
8045 // sets.
8046 EXPECT_TRUE(registry()->disabled_extensions().GetByID(updates_from_webstore));
8047 EXPECT_FALSE(registry()->enabled_extensions().GetByID(updates_from_webstore));
8049 // Accept the extension.
8050 service_->external_install_manager()->error_for_testing()->InstallUIProceed();
8052 // It should be enabled again.
8053 EXPECT_TRUE(registry()->enabled_extensions().GetByID(updates_from_webstore));
8054 EXPECT_FALSE(
8055 registry()->disabled_extensions().GetByID(updates_from_webstore));
8057 // The error should be removed.
8058 EXPECT_FALSE(service_->external_install_manager()->HasExternalInstallError());
8061 TEST_F(ExtensionServiceTest, InstallBlacklistedExtension) {
8062 InitializeEmptyExtensionService();
8064 scoped_refptr<Extension> extension = extensions::ExtensionBuilder()
8065 .SetManifest(extensions::DictionaryBuilder()
8066 .Set("name", "extension")
8067 .Set("version", "1.0")
8068 .Set("manifest_version", 2).Build())
8069 .Build();
8070 ASSERT_TRUE(extension.get());
8071 const std::string& id = extension->id();
8073 std::set<std::string> id_set;
8074 id_set.insert(id);
8075 extensions::ExtensionNotificationObserver notifications(
8076 content::NotificationService::AllSources(), id_set);
8078 // Installation should be allowed but the extension should never have been
8079 // loaded and it should be blacklisted in prefs.
8080 service()->OnExtensionInstalled(
8081 extension.get(),
8082 syncer::StringOrdinal(),
8083 (extensions::kInstallFlagIsBlacklistedForMalware |
8084 extensions::kInstallFlagInstallImmediately));
8085 base::RunLoop().RunUntilIdle();
8087 // Extension was installed but not loaded.
8088 EXPECT_TRUE(notifications.CheckNotifications(
8089 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED));
8090 EXPECT_TRUE(service()->GetInstalledExtension(id));
8092 EXPECT_FALSE(registry()->enabled_extensions().Contains(id));
8093 EXPECT_TRUE(registry()->blacklisted_extensions().Contains(id));
8095 EXPECT_TRUE(ExtensionPrefs::Get(profile())->IsExtensionBlacklisted(id));
8096 EXPECT_TRUE(
8097 ExtensionPrefs::Get(profile())->IsBlacklistedExtensionAcknowledged(id));
8100 // Tests a profile being destroyed correctly disables extensions.
8101 TEST_F(ExtensionServiceTest, DestroyingProfileClearsExtensions) {
8102 InitializeEmptyExtensionService();
8104 InstallCRX(data_dir().AppendASCII("good.crx"), INSTALL_NEW);
8105 EXPECT_NE(UnloadedExtensionInfo::REASON_PROFILE_SHUTDOWN, unloaded_reason_);
8106 EXPECT_EQ(1u, registry()->enabled_extensions().size());
8107 EXPECT_EQ(0u, registry()->disabled_extensions().size());
8108 EXPECT_EQ(0u, registry()->terminated_extensions().size());
8109 EXPECT_EQ(0u, registry()->blacklisted_extensions().size());
8111 service()->Observe(chrome::NOTIFICATION_PROFILE_DESTRUCTION_STARTED,
8112 content::Source<Profile>(profile()),
8113 content::NotificationService::NoDetails());
8114 EXPECT_EQ(UnloadedExtensionInfo::REASON_PROFILE_SHUTDOWN, unloaded_reason_);
8115 EXPECT_EQ(0u, registry()->enabled_extensions().size());
8116 EXPECT_EQ(0u, registry()->disabled_extensions().size());
8117 EXPECT_EQ(0u, registry()->terminated_extensions().size());
8118 EXPECT_EQ(0u, registry()->blacklisted_extensions().size());