Cast: Stop logging kVideoFrameSentToEncoder and rename a couple events.
[chromium-blink-merge.git] / chrome / browser / extensions / extension_service_unittest.cc
blobbbbff27cd49548bf7c9fbfc000b7342a6c604ee7
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 "chrome/browser/extensions/extension_service_unittest.h"
7 #include <algorithm>
8 #include <set>
9 #include <vector>
11 #include "base/at_exit.h"
12 #include "base/basictypes.h"
13 #include "base/bind.h"
14 #include "base/command_line.h"
15 #include "base/file_util.h"
16 #include "base/files/file_enumerator.h"
17 #include "base/files/scoped_temp_dir.h"
18 #include "base/json/json_file_value_serializer.h"
19 #include "base/json/json_reader.h"
20 #include "base/json/json_string_value_serializer.h"
21 #include "base/memory/scoped_ptr.h"
22 #include "base/memory/weak_ptr.h"
23 #include "base/message_loop/message_loop.h"
24 #include "base/path_service.h"
25 #include "base/prefs/scoped_user_pref_update.h"
26 #include "base/stl_util.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/version.h"
32 #include "chrome/browser/browser_process.h"
33 #include "chrome/browser/chrome_notification_types.h"
34 #include "chrome/browser/extensions/app_sync_data.h"
35 #include "chrome/browser/extensions/blacklist.h"
36 #include "chrome/browser/extensions/chrome_app_sorting.h"
37 #include "chrome/browser/extensions/component_loader.h"
38 #include "chrome/browser/extensions/crx_installer.h"
39 #include "chrome/browser/extensions/default_apps.h"
40 #include "chrome/browser/extensions/extension_creator.h"
41 #include "chrome/browser/extensions/extension_error_reporter.h"
42 #include "chrome/browser/extensions/extension_error_ui.h"
43 #include "chrome/browser/extensions/extension_garbage_collector_factory.h"
44 #include "chrome/browser/extensions/extension_notification_observer.h"
45 #include "chrome/browser/extensions/extension_service.h"
46 #include "chrome/browser/extensions/extension_special_storage_policy.h"
47 #include "chrome/browser/extensions/extension_sync_data.h"
48 #include "chrome/browser/extensions/extension_util.h"
49 #include "chrome/browser/extensions/external_install_ui.h"
50 #include "chrome/browser/extensions/external_policy_loader.h"
51 #include "chrome/browser/extensions/external_pref_loader.h"
52 #include "chrome/browser/extensions/external_provider_impl.h"
53 #include "chrome/browser/extensions/fake_safe_browsing_database_manager.h"
54 #include "chrome/browser/extensions/install_observer.h"
55 #include "chrome/browser/extensions/install_tracker.h"
56 #include "chrome/browser/extensions/install_tracker_factory.h"
57 #include "chrome/browser/extensions/installed_loader.h"
58 #include "chrome/browser/extensions/pack_extension_job.h"
59 #include "chrome/browser/extensions/pending_extension_info.h"
60 #include "chrome/browser/extensions/pending_extension_manager.h"
61 #include "chrome/browser/extensions/test_blacklist.h"
62 #include "chrome/browser/extensions/test_extension_system.h"
63 #include "chrome/browser/extensions/unpacked_installer.h"
64 #include "chrome/browser/extensions/updater/extension_updater.h"
65 #include "chrome/browser/prefs/browser_prefs.h"
66 #include "chrome/browser/prefs/pref_service_mock_factory.h"
67 #include "chrome/browser/prefs/pref_service_syncable.h"
68 #include "chrome/browser/sync/profile_sync_service.h"
69 #include "chrome/browser/sync/profile_sync_service_factory.h"
70 #include "chrome/common/chrome_constants.h"
71 #include "chrome/common/chrome_paths.h"
72 #include "chrome/common/chrome_switches.h"
73 #include "chrome/common/extensions/api/plugins/plugins_handler.h"
74 #include "chrome/common/extensions/manifest_handlers/app_launch_info.h"
75 #include "chrome/common/extensions/manifest_handlers/content_scripts_handler.h"
76 #include "chrome/common/extensions/manifest_url_handler.h"
77 #include "chrome/common/pref_names.h"
78 #include "chrome/common/url_constants.h"
79 #include "chrome/test/base/scoped_browser_locale.h"
80 #include "chrome/test/base/testing_profile.h"
81 #include "components/user_prefs/pref_registry_syncable.h"
82 #include "content/public/browser/dom_storage_context.h"
83 #include "content/public/browser/gpu_data_manager.h"
84 #include "content/public/browser/indexed_db_context.h"
85 #include "content/public/browser/notification_registrar.h"
86 #include "content/public/browser/notification_service.h"
87 #include "content/public/browser/plugin_service.h"
88 #include "content/public/browser/render_process_host.h"
89 #include "content/public/browser/storage_partition.h"
90 #include "content/public/common/content_constants.h"
91 #include "content/public/test/test_utils.h"
92 #include "extensions/browser/extension_registry.h"
93 #include "extensions/browser/extension_system.h"
94 #include "extensions/browser/external_provider_interface.h"
95 #include "extensions/browser/management_policy.h"
96 #include "extensions/browser/pref_names.h"
97 #include "extensions/browser/test_management_policy.h"
98 #include "extensions/common/constants.h"
99 #include "extensions/common/extension.h"
100 #include "extensions/common/extension_builder.h"
101 #include "extensions/common/extension_l10n_util.h"
102 #include "extensions/common/extension_resource.h"
103 #include "extensions/common/manifest_constants.h"
104 #include "extensions/common/manifest_handlers/background_info.h"
105 #include "extensions/common/permissions/permission_set.h"
106 #include "extensions/common/switches.h"
107 #include "extensions/common/url_pattern.h"
108 #include "extensions/common/value_builder.h"
109 #include "gpu/config/gpu_info.h"
110 #include "grit/browser_resources.h"
111 #include "net/cookies/canonical_cookie.h"
112 #include "net/cookies/cookie_monster.h"
113 #include "net/cookies/cookie_options.h"
114 #include "net/url_request/url_request_context.h"
115 #include "net/url_request/url_request_context_getter.h"
116 #include "sync/api/fake_sync_change_processor.h"
117 #include "sync/api/string_ordinal.h"
118 #include "sync/api/sync_data.h"
119 #include "sync/api/sync_error_factory.h"
120 #include "sync/api/sync_error_factory_mock.h"
121 #include "sync/api/syncable_service.h"
122 #include "sync/protocol/app_specifics.pb.h"
123 #include "sync/protocol/extension_specifics.pb.h"
124 #include "sync/protocol/sync.pb.h"
125 #include "testing/gtest/include/gtest/gtest.h"
126 #include "testing/platform_test.h"
127 #include "url/gurl.h"
128 #include "webkit/browser/database/database_tracker.h"
129 #include "webkit/browser/quota/quota_manager.h"
130 #include "webkit/common/database/database_identifier.h"
132 #if defined(OS_CHROMEOS)
133 #include "chrome/browser/chromeos/extensions/install_limiter.h"
134 #include "chrome/browser/chromeos/login/user_manager.h"
135 #include "chrome/browser/chromeos/settings/cros_settings.h"
136 #include "chrome/browser/chromeos/settings/device_settings_service.h"
137 #endif
139 // The blacklist tests rely on safe browsing.
140 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
141 #define ENABLE_BLACKLIST_TESTS
142 #endif
144 using base::DictionaryValue;
145 using base::ListValue;
146 using base::Value;
147 using content::BrowserContext;
148 using content::BrowserThread;
149 using content::DOMStorageContext;
150 using content::IndexedDBContext;
151 using content::PluginService;
152 using extensions::APIPermission;
153 using extensions::APIPermissionSet;
154 using extensions::AppSorting;
155 using extensions::Blacklist;
156 using extensions::CrxInstaller;
157 using extensions::Extension;
158 using extensions::ExtensionCreator;
159 using extensions::ExtensionPrefs;
160 using extensions::ExtensionRegistry;
161 using extensions::ExtensionResource;
162 using extensions::ExtensionSystem;
163 using extensions::FakeSafeBrowsingDatabaseManager;
164 using extensions::FeatureSwitch;
165 using extensions::Manifest;
166 using extensions::PermissionSet;
167 using extensions::TestExtensionSystem;
168 using extensions::URLPatternSet;
170 namespace keys = extensions::manifest_keys;
172 namespace {
174 // Extension ids used during testing.
175 const char good0[] = "behllobkkfkfnphdnhnkndlbkcpglgmj";
176 const char good1[] = "hpiknbiabeeppbpihjehijgoemciehgk";
177 const char good2[] = "bjafgdebaacbbbecmhlhpofkepfkgcpa";
178 const char all_zero[] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
179 const char good2048[] = "nmgjhmhbleinmjpbdhgajfjkbijcmgbh";
180 const char good_crx[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
181 const char hosted_app[] = "kbmnembihfiondgfjekmnmcbddelicoi";
182 const char page_action[] = "obcimlgaoabeegjmmpldobjndiealpln";
183 const char theme_crx[] = "iamefpfkojoapidjnbafmgkgncegbkad";
184 const char theme2_crx[] = "pjpgmfcmabopnnfonnhmdjglfpjjfkbf";
185 const char permissions_crx[] = "eagpmdpfmaekmmcejjbmjoecnejeiiin";
186 const char unpacked[] = "cbcdidchbppangcjoddlpdjlenngjldk";
187 const char updates_from_webstore[] = "akjooamlhcgeopfifcmlggaebeocgokj";
189 struct ExtensionsOrder {
190 bool operator()(const scoped_refptr<const Extension>& a,
191 const scoped_refptr<const Extension>& b) {
192 return a->name() < b->name();
196 static std::vector<base::string16> GetErrors() {
197 const std::vector<base::string16>* errors =
198 ExtensionErrorReporter::GetInstance()->GetErrors();
199 std::vector<base::string16> ret_val;
201 for (std::vector<base::string16>::const_iterator iter = errors->begin();
202 iter != errors->end(); ++iter) {
203 std::string utf8_error = base::UTF16ToUTF8(*iter);
204 if (utf8_error.find(".svn") == std::string::npos) {
205 ret_val.push_back(*iter);
209 // The tests rely on the errors being in a certain order, which can vary
210 // depending on how filesystem iteration works.
211 std::stable_sort(ret_val.begin(), ret_val.end());
213 return ret_val;
216 static void AddPattern(URLPatternSet* extent, const std::string& pattern) {
217 int schemes = URLPattern::SCHEME_ALL;
218 extent->AddPattern(URLPattern(schemes, pattern));
221 base::FilePath GetTemporaryFile() {
222 base::FilePath temp_file;
223 CHECK(base::CreateTemporaryFile(&temp_file));
224 return temp_file;
227 bool WaitForCountNotificationsCallback(int *count) {
228 return --(*count) == 0;
231 } // namespace
233 class MockExtensionProvider : public extensions::ExternalProviderInterface {
234 public:
235 MockExtensionProvider(
236 VisitorInterface* visitor,
237 Manifest::Location location)
238 : location_(location), visitor_(visitor), visit_count_(0) {
241 virtual ~MockExtensionProvider() {}
243 void UpdateOrAddExtension(const std::string& id,
244 const std::string& version,
245 const base::FilePath& path) {
246 extension_map_[id] = std::make_pair(version, path);
249 void RemoveExtension(const std::string& id) {
250 extension_map_.erase(id);
253 // ExternalProvider implementation:
254 virtual void VisitRegisteredExtension() OVERRIDE {
255 visit_count_++;
256 for (DataMap::const_iterator i = extension_map_.begin();
257 i != extension_map_.end(); ++i) {
258 Version version(i->second.first);
260 visitor_->OnExternalExtensionFileFound(
261 i->first, &version, i->second.second, location_,
262 Extension::NO_FLAGS, false);
264 visitor_->OnExternalProviderReady(this);
267 virtual bool HasExtension(const std::string& id) const OVERRIDE {
268 return extension_map_.find(id) != extension_map_.end();
271 virtual bool GetExtensionDetails(
272 const std::string& id,
273 Manifest::Location* location,
274 scoped_ptr<Version>* version) const OVERRIDE {
275 DataMap::const_iterator it = extension_map_.find(id);
276 if (it == extension_map_.end())
277 return false;
279 if (version)
280 version->reset(new Version(it->second.first));
282 if (location)
283 *location = location_;
285 return true;
288 virtual bool IsReady() const OVERRIDE {
289 return true;
292 virtual void ServiceShutdown() OVERRIDE {
295 int visit_count() const { return visit_count_; }
296 void set_visit_count(int visit_count) {
297 visit_count_ = visit_count;
300 private:
301 typedef std::map< std::string, std::pair<std::string, base::FilePath> >
302 DataMap;
303 DataMap extension_map_;
304 Manifest::Location location_;
305 VisitorInterface* visitor_;
307 // visit_count_ tracks the number of calls to VisitRegisteredExtension().
308 // Mutable because it must be incremented on each call to
309 // VisitRegisteredExtension(), which must be a const method to inherit
310 // from the class being mocked.
311 mutable int visit_count_;
313 DISALLOW_COPY_AND_ASSIGN(MockExtensionProvider);
316 class MockProviderVisitor
317 : public extensions::ExternalProviderInterface::VisitorInterface {
318 public:
319 // The provider will return |fake_base_path| from
320 // GetBaseCrxFilePath(). User can test the behavior with
321 // and without an empty path using this parameter.
322 explicit MockProviderVisitor(base::FilePath fake_base_path)
323 : ids_found_(0),
324 fake_base_path_(fake_base_path),
325 expected_creation_flags_(Extension::NO_FLAGS) {
326 profile_.reset(new TestingProfile);
329 MockProviderVisitor(base::FilePath fake_base_path,
330 int expected_creation_flags)
331 : ids_found_(0),
332 fake_base_path_(fake_base_path),
333 expected_creation_flags_(expected_creation_flags) {
336 int Visit(const std::string& json_data) {
337 // Give the test json file to the provider for parsing.
338 provider_.reset(new extensions::ExternalProviderImpl(
339 this,
340 new extensions::ExternalTestingLoader(json_data, fake_base_path_),
341 profile_.get(),
342 Manifest::EXTERNAL_PREF,
343 Manifest::EXTERNAL_PREF_DOWNLOAD,
344 Extension::NO_FLAGS));
346 // We also parse the file into a dictionary to compare what we get back
347 // from the provider.
348 JSONStringValueSerializer serializer(json_data);
349 base::Value* json_value = serializer.Deserialize(NULL, NULL);
351 if (!json_value || !json_value->IsType(base::Value::TYPE_DICTIONARY)) {
352 NOTREACHED() << "Unable to deserialize json data";
353 return -1;
354 } else {
355 base::DictionaryValue* external_extensions =
356 static_cast<base::DictionaryValue*>(json_value);
357 prefs_.reset(external_extensions);
360 // Reset our counter.
361 ids_found_ = 0;
362 // Ask the provider to look up all extensions and return them.
363 provider_->VisitRegisteredExtension();
365 return ids_found_;
368 virtual bool OnExternalExtensionFileFound(const std::string& id,
369 const Version* version,
370 const base::FilePath& path,
371 Manifest::Location unused,
372 int creation_flags,
373 bool mark_acknowledged) OVERRIDE {
374 EXPECT_EQ(expected_creation_flags_, creation_flags);
376 ++ids_found_;
377 base::DictionaryValue* pref;
378 // This tests is to make sure that the provider only notifies us of the
379 // values we gave it. So if the id we doesn't exist in our internal
380 // dictionary then something is wrong.
381 EXPECT_TRUE(prefs_->GetDictionary(id, &pref))
382 << "Got back ID (" << id.c_str() << ") we weren't expecting";
384 EXPECT_TRUE(path.IsAbsolute());
385 if (!fake_base_path_.empty())
386 EXPECT_TRUE(fake_base_path_.IsParent(path));
388 if (pref) {
389 EXPECT_TRUE(provider_->HasExtension(id));
391 // Ask provider if the extension we got back is registered.
392 Manifest::Location location = Manifest::INVALID_LOCATION;
393 scoped_ptr<Version> v1;
394 base::FilePath crx_path;
396 EXPECT_TRUE(provider_->GetExtensionDetails(id, NULL, &v1));
397 EXPECT_STREQ(version->GetString().c_str(), v1->GetString().c_str());
399 scoped_ptr<Version> v2;
400 EXPECT_TRUE(provider_->GetExtensionDetails(id, &location, &v2));
401 EXPECT_STREQ(version->GetString().c_str(), v1->GetString().c_str());
402 EXPECT_STREQ(version->GetString().c_str(), v2->GetString().c_str());
403 EXPECT_EQ(Manifest::EXTERNAL_PREF, location);
405 // Remove it so we won't count it ever again.
406 prefs_->Remove(id, NULL);
408 return true;
411 virtual bool OnExternalExtensionUpdateUrlFound(
412 const std::string& id,
413 const std::string& install_parameter,
414 const GURL& update_url,
415 Manifest::Location location,
416 int creation_flags,
417 bool mark_acknowledged) OVERRIDE {
418 ++ids_found_;
419 base::DictionaryValue* pref;
420 // This tests is to make sure that the provider only notifies us of the
421 // values we gave it. So if the id we doesn't exist in our internal
422 // dictionary then something is wrong.
423 EXPECT_TRUE(prefs_->GetDictionary(id, &pref))
424 << L"Got back ID (" << id.c_str() << ") we weren't expecting";
425 EXPECT_EQ(Manifest::EXTERNAL_PREF_DOWNLOAD, location);
427 if (pref) {
428 EXPECT_TRUE(provider_->HasExtension(id));
430 // External extensions with update URLs do not have versions.
431 scoped_ptr<Version> v1;
432 Manifest::Location location1 = Manifest::INVALID_LOCATION;
433 EXPECT_TRUE(provider_->GetExtensionDetails(id, &location1, &v1));
434 EXPECT_FALSE(v1.get());
435 EXPECT_EQ(Manifest::EXTERNAL_PREF_DOWNLOAD, location1);
437 std::string parsed_install_parameter;
438 pref->GetString("install_parameter", &parsed_install_parameter);
439 EXPECT_EQ(parsed_install_parameter, install_parameter);
441 // Remove it so we won't count it again.
442 prefs_->Remove(id, NULL);
444 return true;
447 virtual void OnExternalProviderReady(
448 const extensions::ExternalProviderInterface* provider) OVERRIDE {
449 EXPECT_EQ(provider, provider_.get());
450 EXPECT_TRUE(provider->IsReady());
453 private:
454 int ids_found_;
455 base::FilePath fake_base_path_;
456 int expected_creation_flags_;
457 scoped_ptr<extensions::ExternalProviderImpl> provider_;
458 scoped_ptr<base::DictionaryValue> prefs_;
459 scoped_ptr<TestingProfile> profile_;
461 DISALLOW_COPY_AND_ASSIGN(MockProviderVisitor);
464 ExtensionServiceTestBase::ExtensionServiceInitParams::
465 ExtensionServiceInitParams()
466 : autoupdate_enabled(false), is_first_run(true), profile_is_managed(false) {
469 // Our message loop may be used in tests which require it to be an IO loop.
470 ExtensionServiceTestBase::ExtensionServiceTestBase()
471 : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP),
472 service_(NULL),
473 management_policy_(NULL),
474 expected_extensions_count_(0),
475 registry_(NULL) {
476 base::FilePath test_data_dir;
477 if (!PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir)) {
478 ADD_FAILURE();
479 return;
481 data_dir_ = test_data_dir.AppendASCII("extensions");
484 ExtensionServiceTestBase::~ExtensionServiceTestBase() {
485 service_ = NULL;
488 void ExtensionServiceTestBase::InitializeExtensionService(
489 const ExtensionServiceTestBase::ExtensionServiceInitParams& params) {
490 profile_ = CreateTestingProfile(params);
491 service_ = InitializeExtensionServiceForProfile(params, profile_.get());
492 management_policy_ =
493 ExtensionSystem::Get(profile_.get())->management_policy();
494 extensions_install_dir_ = params.extensions_install_dir;
495 expected_extensions_count_ = 0;
496 registry_ = extensions::ExtensionRegistry::Get(profile_.get());
497 extensions::ExtensionGarbageCollectorFactory::GetInstance()
498 ->SetTestingFactoryAndUse(
499 profile_.get(),
500 &extensions::ExtensionGarbageCollectorFactory::BuildInstanceFor);
503 // static
504 scoped_ptr<TestingProfile> ExtensionServiceTestBase::CreateTestingProfile(
505 const ExtensionServiceInitParams& params) {
506 TestingProfile::Builder profile_builder;
507 // Create a PrefService that only contains user defined preference values.
508 PrefServiceMockFactory factory;
509 // If pref_file is empty, TestingProfile automatically creates
510 // TestingPrefServiceSyncable instance.
511 if (!params.pref_file.empty()) {
512 factory.SetUserPrefsFile(params.pref_file,
513 base::MessageLoopProxy::current().get());
514 scoped_refptr<user_prefs::PrefRegistrySyncable> registry(
515 new user_prefs::PrefRegistrySyncable);
516 scoped_ptr<PrefServiceSyncable> prefs(
517 factory.CreateSyncable(registry.get()));
518 chrome::RegisterUserProfilePrefs(registry.get());
519 profile_builder.SetPrefService(prefs.Pass());
522 if (params.profile_is_managed)
523 profile_builder.SetManagedUserId("asdf");
525 profile_builder.SetPath(params.profile_path);
526 return profile_builder.Build();
529 // static
530 ExtensionService*
531 ExtensionServiceTestBase::InitializeExtensionServiceForProfile(
532 const ExtensionServiceInitParams& params,
533 Profile* profile) {
534 TestExtensionSystem* system = static_cast<TestExtensionSystem*>(
535 ExtensionSystem::Get(profile));
536 if (!params.is_first_run) {
537 ExtensionPrefs* prefs = system->CreateExtensionPrefs(
538 CommandLine::ForCurrentProcess(),
539 params.extensions_install_dir);
540 prefs->SetAlertSystemFirstRun();
543 ExtensionService* service = system->CreateExtensionService(
544 CommandLine::ForCurrentProcess(),
545 params.extensions_install_dir,
546 params.autoupdate_enabled);
548 service->SetFileTaskRunnerForTesting(
549 base::MessageLoopProxy::current().get());
550 service->set_extensions_enabled(true);
551 service->set_show_extensions_prompts(false);
552 service->set_install_updates_when_idle_for_test(false);
554 // When we start up, we want to make sure there is no external provider,
555 // since the ExtensionService on Windows will use the Registry as a default
556 // provider and if there is something already registered there then it will
557 // interfere with the tests. Those tests that need an external provider
558 // will register one specifically.
559 service->ClearProvidersForTesting();
561 #if defined(OS_CHROMEOS)
562 extensions::InstallLimiter::Get(profile)->DisableForTest();
563 #endif
564 return service;
567 void ExtensionServiceTestBase::InitializeInstalledExtensionService(
568 const base::FilePath& prefs_file,
569 const base::FilePath& source_install_dir) {
570 EXPECT_TRUE(temp_dir_.CreateUniqueTempDir());
571 base::FilePath path = temp_dir_.path();
572 path = path.Append(FILE_PATH_LITERAL("TestingExtensionsPath"));
573 EXPECT_TRUE(base::DeleteFile(path, true));
574 base::File::Error error = base::File::FILE_OK;
575 EXPECT_TRUE(base::CreateDirectoryAndGetError(path, &error)) << error;
576 base::FilePath temp_prefs = path.Append(chrome::kPreferencesFilename);
577 EXPECT_TRUE(base::CopyFile(prefs_file, temp_prefs));
579 base::FilePath extensions_install_dir =
580 path.Append(FILE_PATH_LITERAL("Extensions"));
581 EXPECT_TRUE(base::DeleteFile(extensions_install_dir, true));
582 EXPECT_TRUE(
583 base::CopyDirectory(source_install_dir, extensions_install_dir, true));
585 ExtensionServiceInitParams params;
586 params.profile_path = path;
587 params.pref_file = temp_prefs;
588 params.extensions_install_dir = extensions_install_dir;
589 InitializeExtensionService(params);
592 void ExtensionServiceTestBase::InitializeGoodInstalledExtensionService() {
593 base::FilePath source_install_dir = data_dir_
594 .AppendASCII("good")
595 .AppendASCII("Extensions");
596 base::FilePath pref_path =
597 source_install_dir.DirName().Append(chrome::kPreferencesFilename);
598 InitializeInstalledExtensionService(pref_path, source_install_dir);
601 void ExtensionServiceTestBase::InitializeEmptyExtensionService() {
602 InitializeExtensionService(CreateDefaultInitParams());
605 void ExtensionServiceTestBase::InitializeProcessManager() {
606 static_cast<extensions::TestExtensionSystem*>(
607 ExtensionSystem::Get(profile_.get()))->
608 CreateProcessManager();
611 void ExtensionServiceTestBase::InitializeExtensionServiceWithUpdater() {
612 ExtensionServiceInitParams params = CreateDefaultInitParams();
613 params.autoupdate_enabled = true;
614 InitializeExtensionService(params);
615 service_->updater()->Start();
618 void ExtensionServiceTestBase::InitializeExtensionSyncService() {
619 extension_sync_service_.reset(new ExtensionSyncService(
620 profile_.get(), ExtensionPrefs::Get(profile_.get()), service_));
623 // static
624 void ExtensionServiceTestBase::SetUpTestCase() {
625 ExtensionErrorReporter::Init(false); // no noisy errors
628 void ExtensionServiceTestBase::SetUp() {
629 ExtensionErrorReporter::GetInstance()->ClearErrors();
632 void ExtensionServiceTestBase::TearDown() {
635 ExtensionServiceTestBase::ExtensionServiceInitParams
636 ExtensionServiceTestBase::CreateDefaultInitParams() {
637 return CreateDefaultInitParamsInTempDir(&temp_dir_);
640 // static
641 ExtensionServiceTestBase::ExtensionServiceInitParams
642 ExtensionServiceTestBase::CreateDefaultInitParamsInTempDir(
643 base::ScopedTempDir* temp_dir) {
644 ExtensionServiceInitParams params;
645 EXPECT_TRUE(temp_dir->CreateUniqueTempDir());
646 base::FilePath path = temp_dir->path();
647 path = path.Append(FILE_PATH_LITERAL("TestingExtensionsPath"));
648 EXPECT_TRUE(base::DeleteFile(path, true));
649 base::File::Error error = base::File::FILE_OK;
650 EXPECT_TRUE(base::CreateDirectoryAndGetError(path, &error)) << error;
651 base::FilePath prefs_filename =
652 path.Append(FILE_PATH_LITERAL("TestPreferences"));
653 base::FilePath extensions_install_dir =
654 path.Append(FILE_PATH_LITERAL("Extensions"));
655 EXPECT_TRUE(base::DeleteFile(extensions_install_dir, true));
656 EXPECT_TRUE(base::CreateDirectoryAndGetError(extensions_install_dir,
657 &error)) << error;
659 params.profile_path = path;
660 params.pref_file = prefs_filename;
661 params.extensions_install_dir = extensions_install_dir;
662 return params;
665 class ExtensionServiceTest
666 : public ExtensionServiceTestBase, public content::NotificationObserver {
667 public:
668 ExtensionServiceTest()
669 : installed_(NULL),
670 was_update_(false),
671 override_external_install_prompt_(
672 FeatureSwitch::prompt_for_external_extensions(), false) {
673 registrar_.Add(this,
674 chrome::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
675 content::NotificationService::AllSources());
676 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
677 content::NotificationService::AllSources());
678 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_INSTALLED,
679 content::NotificationService::AllSources());
682 virtual void Observe(int type,
683 const content::NotificationSource& source,
684 const content::NotificationDetails& details) OVERRIDE {
685 switch (type) {
686 case chrome::NOTIFICATION_EXTENSION_LOADED_DEPRECATED: {
687 const Extension* extension =
688 content::Details<const Extension>(details).ptr();
689 loaded_.push_back(make_scoped_refptr(extension));
690 // The tests rely on the errors being in a certain order, which can vary
691 // depending on how filesystem iteration works.
692 std::stable_sort(loaded_.begin(), loaded_.end(), ExtensionsOrder());
693 break;
696 case chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED: {
697 const Extension* e =
698 content::Details<extensions::UnloadedExtensionInfo>(
699 details)->extension;
700 unloaded_id_ = e->id();
701 extensions::ExtensionList::iterator i =
702 std::find(loaded_.begin(), loaded_.end(), e);
703 // TODO(erikkay) fix so this can be an assert. Right now the tests
704 // are manually calling clear() on loaded_, so this isn't doable.
705 if (i == loaded_.end())
706 return;
707 loaded_.erase(i);
708 break;
710 case chrome::NOTIFICATION_EXTENSION_INSTALLED: {
711 const extensions::InstalledExtensionInfo* installed_info =
712 content::Details<const extensions::InstalledExtensionInfo>(details)
713 .ptr();
714 installed_ = installed_info->extension;
715 was_update_ = installed_info->is_update;
716 old_name_ = installed_info->old_name;
717 break;
720 default:
721 DCHECK(false);
725 void AddMockExternalProvider(
726 extensions::ExternalProviderInterface* provider) {
727 service_->AddProviderForTesting(provider);
730 void MockSyncStartFlare(bool* was_called,
731 syncer::ModelType* model_type_passed_in,
732 syncer::ModelType model_type) {
733 *was_called = true;
734 *model_type_passed_in = model_type;
737 protected:
738 // Paths to some of the fake extensions.
739 base::FilePath good0_path() {
740 return data_dir_.AppendASCII("good").AppendASCII("Extensions")
741 .AppendASCII(good0).AppendASCII("1.0.0.0");
744 base::FilePath good1_path() {
745 return data_dir_.AppendASCII("good").AppendASCII("Extensions")
746 .AppendASCII(good1).AppendASCII("2");
749 base::FilePath good2_path() {
750 return data_dir_.AppendASCII("good").AppendASCII("Extensions")
751 .AppendASCII(good2).AppendASCII("1.0");
754 void TestExternalProvider(MockExtensionProvider* provider,
755 Manifest::Location location);
757 void PackCRX(const base::FilePath& dir_path,
758 const base::FilePath& pem_path,
759 const base::FilePath& crx_path) {
760 // Use the existing pem key, if provided.
761 base::FilePath pem_output_path;
762 if (pem_path.value().empty()) {
763 pem_output_path = crx_path.DirName().AppendASCII("temp.pem");
764 } else {
765 ASSERT_TRUE(base::PathExists(pem_path));
768 ASSERT_TRUE(base::DeleteFile(crx_path, false));
770 scoped_ptr<ExtensionCreator> creator(new ExtensionCreator());
771 ASSERT_TRUE(creator->Run(dir_path,
772 crx_path,
773 pem_path,
774 pem_output_path,
775 ExtensionCreator::kOverwriteCRX));
777 ASSERT_TRUE(base::PathExists(crx_path));
780 enum InstallState {
781 INSTALL_FAILED,
782 INSTALL_UPDATED,
783 INSTALL_NEW,
784 INSTALL_WITHOUT_LOAD,
787 const Extension* PackAndInstallCRX(const base::FilePath& dir_path,
788 const base::FilePath& pem_path,
789 InstallState install_state,
790 int creation_flags) {
791 base::FilePath crx_path;
792 base::ScopedTempDir temp_dir;
793 EXPECT_TRUE(temp_dir.CreateUniqueTempDir());
794 crx_path = temp_dir.path().AppendASCII("temp.crx");
796 PackCRX(dir_path, pem_path, crx_path);
797 return InstallCRX(crx_path, install_state, creation_flags);
800 const Extension* PackAndInstallCRX(const base::FilePath& dir_path,
801 const base::FilePath& pem_path,
802 InstallState install_state) {
803 return PackAndInstallCRX(dir_path, pem_path, install_state,
804 Extension::NO_FLAGS);
807 const Extension* PackAndInstallCRX(const base::FilePath& dir_path,
808 InstallState install_state) {
809 return PackAndInstallCRX(dir_path, base::FilePath(), install_state,
810 Extension::NO_FLAGS);
813 // Attempts to install an extension. Use INSTALL_FAILED if the installation
814 // is expected to fail.
815 // If |install_state| is INSTALL_UPDATED, and |expected_old_name| is
816 // non-empty, expects that the existing extension's title was
817 // |expected_old_name|.
818 const Extension* InstallCRX(const base::FilePath& path,
819 InstallState install_state,
820 int creation_flags,
821 const std::string& expected_old_name) {
822 InstallCRXInternal(path, creation_flags);
823 return VerifyCrxInstall(path, install_state, expected_old_name);
826 // Attempts to install an extension. Use INSTALL_FAILED if the installation
827 // is expected to fail.
828 const Extension* InstallCRX(const base::FilePath& path,
829 InstallState install_state,
830 int creation_flags) {
831 return InstallCRX(path, install_state, creation_flags, std::string());
834 // Attempts to install an extension. Use INSTALL_FAILED if the installation
835 // is expected to fail.
836 const Extension* InstallCRX(const base::FilePath& path,
837 InstallState install_state) {
838 return InstallCRX(path, install_state, Extension::NO_FLAGS);
841 const Extension* InstallCRXFromWebStore(const base::FilePath& path,
842 InstallState install_state) {
843 InstallCRXInternal(path, Extension::FROM_WEBSTORE);
844 return VerifyCrxInstall(path, install_state);
847 const Extension* InstallCRXWithLocation(const base::FilePath& crx_path,
848 Manifest::Location install_location,
849 InstallState install_state) {
850 EXPECT_TRUE(base::PathExists(crx_path))
851 << "Path does not exist: "<< crx_path.value().c_str();
852 // no client (silent install)
853 scoped_refptr<CrxInstaller> installer(CrxInstaller::CreateSilent(service_));
854 installer->set_install_source(install_location);
856 content::WindowedNotificationObserver observer(
857 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
858 content::NotificationService::AllSources());
859 installer->InstallCrx(crx_path);
860 observer.Wait();
862 return VerifyCrxInstall(crx_path, install_state);
865 // Verifies the result of a CRX installation. Used by InstallCRX. Set the
866 // |install_state| to INSTALL_FAILED if the installation is expected to fail.
867 // Returns an Extension pointer if the install succeeded, NULL otherwise.
868 const Extension* VerifyCrxInstall(const base::FilePath& path,
869 InstallState install_state) {
870 return VerifyCrxInstall(path, install_state, std::string());
873 // Verifies the result of a CRX installation. Used by InstallCRX. Set the
874 // |install_state| to INSTALL_FAILED if the installation is expected to fail.
875 // If |install_state| is INSTALL_UPDATED, and |expected_old_name| is
876 // non-empty, expects that the existing extension's title was
877 // |expected_old_name|.
878 // Returns an Extension pointer if the install succeeded, NULL otherwise.
879 const Extension* VerifyCrxInstall(const base::FilePath& path,
880 InstallState install_state,
881 const std::string& expected_old_name) {
882 std::vector<base::string16> errors = GetErrors();
883 const Extension* extension = NULL;
884 if (install_state != INSTALL_FAILED) {
885 if (install_state == INSTALL_NEW)
886 ++expected_extensions_count_;
888 EXPECT_TRUE(installed_) << path.value();
889 // If and only if INSTALL_UPDATED, it should have the is_update flag.
890 EXPECT_EQ(install_state == INSTALL_UPDATED, was_update_)
891 << path.value();
892 // If INSTALL_UPDATED, old_name_ should match the given string.
893 if (install_state == INSTALL_UPDATED && !expected_old_name.empty())
894 EXPECT_EQ(expected_old_name, old_name_);
895 EXPECT_EQ(0u, errors.size()) << path.value();
897 if (install_state == INSTALL_WITHOUT_LOAD) {
898 EXPECT_EQ(0u, loaded_.size()) << path.value();
899 } else {
900 EXPECT_EQ(1u, loaded_.size()) << path.value();
901 size_t actual_extension_count = registry_->enabled_extensions().size() +
902 registry_->disabled_extensions().size();
903 EXPECT_EQ(expected_extensions_count_, actual_extension_count) <<
904 path.value();
905 extension = loaded_[0].get();
906 EXPECT_TRUE(service_->GetExtensionById(extension->id(), false))
907 << path.value();
910 for (std::vector<base::string16>::iterator err = errors.begin();
911 err != errors.end(); ++err) {
912 LOG(ERROR) << *err;
914 } else {
915 EXPECT_FALSE(installed_) << path.value();
916 EXPECT_EQ(0u, loaded_.size()) << path.value();
917 EXPECT_EQ(1u, errors.size()) << path.value();
920 installed_ = NULL;
921 was_update_ = false;
922 old_name_ = "";
923 loaded_.clear();
924 ExtensionErrorReporter::GetInstance()->ClearErrors();
925 return extension;
928 enum UpdateState {
929 FAILED_SILENTLY,
930 FAILED,
931 UPDATED,
932 INSTALLED,
933 ENABLED
936 void BlackListWebGL() {
937 static const std::string json_blacklist =
938 "{\n"
939 " \"name\": \"gpu blacklist\",\n"
940 " \"version\": \"1.0\",\n"
941 " \"entries\": [\n"
942 " {\n"
943 " \"id\": 1,\n"
944 " \"features\": [\"webgl\"]\n"
945 " }\n"
946 " ]\n"
947 "}";
948 gpu::GPUInfo gpu_info;
949 content::GpuDataManager::GetInstance()->InitializeForTesting(
950 json_blacklist, gpu_info);
953 // Helper method to set up a WindowedNotificationObserver to wait for a
954 // specific CrxInstaller to finish if we don't know the value of the
955 // |installer| yet.
956 static bool IsCrxInstallerDone(extensions::CrxInstaller** installer,
957 const content::NotificationSource& source,
958 const content::NotificationDetails& details) {
959 return content::Source<extensions::CrxInstaller>(source).ptr() ==
960 *installer;
963 void UpdateExtension(const std::string& id,
964 const base::FilePath& in_path,
965 UpdateState expected_state) {
966 ASSERT_TRUE(base::PathExists(in_path));
968 // We need to copy this to a temporary location because Update() will delete
969 // it.
970 base::FilePath path = temp_dir_.path();
971 path = path.Append(in_path.BaseName());
972 ASSERT_TRUE(base::CopyFile(in_path, path));
974 int previous_enabled_extension_count =
975 registry_->enabled_extensions().size();
976 int previous_installed_extension_count =
977 previous_enabled_extension_count +
978 registry_->disabled_extensions().size();
980 extensions::CrxInstaller* installer = NULL;
981 content::WindowedNotificationObserver observer(
982 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
983 base::Bind(&IsCrxInstallerDone, &installer));
984 service_->UpdateExtension(id, path, true, &installer);
986 if (installer)
987 observer.Wait();
988 else
989 base::RunLoop().RunUntilIdle();
991 std::vector<base::string16> errors = GetErrors();
992 int error_count = errors.size();
993 int enabled_extension_count = registry_->enabled_extensions().size();
994 int installed_extension_count =
995 enabled_extension_count + registry_->disabled_extensions().size();
997 int expected_error_count = (expected_state == FAILED) ? 1 : 0;
998 EXPECT_EQ(expected_error_count, error_count) << path.value();
1000 if (expected_state <= FAILED) {
1001 EXPECT_EQ(previous_enabled_extension_count,
1002 enabled_extension_count);
1003 EXPECT_EQ(previous_installed_extension_count,
1004 installed_extension_count);
1005 } else {
1006 int expected_installed_extension_count =
1007 (expected_state >= INSTALLED) ? 1 : 0;
1008 int expected_enabled_extension_count =
1009 (expected_state >= ENABLED) ? 1 : 0;
1010 EXPECT_EQ(expected_installed_extension_count,
1011 installed_extension_count);
1012 EXPECT_EQ(expected_enabled_extension_count,
1013 enabled_extension_count);
1016 // Update() should the temporary input file.
1017 EXPECT_FALSE(base::PathExists(path));
1020 void TerminateExtension(const std::string& id) {
1021 const Extension* extension = service_->GetInstalledExtension(id);
1022 if (!extension) {
1023 ADD_FAILURE();
1024 return;
1026 service_->TrackTerminatedExtensionForTest(extension);
1029 size_t GetPrefKeyCount() {
1030 const base::DictionaryValue* dict =
1031 profile_->GetPrefs()->GetDictionary("extensions.settings");
1032 if (!dict) {
1033 ADD_FAILURE();
1034 return 0;
1036 return dict->size();
1039 void UninstallExtension(const std::string& id, bool use_helper) {
1040 // Verify that the extension is installed.
1041 base::FilePath extension_path = extensions_install_dir_.AppendASCII(id);
1042 EXPECT_TRUE(base::PathExists(extension_path));
1043 size_t pref_key_count = GetPrefKeyCount();
1044 EXPECT_GT(pref_key_count, 0u);
1045 ValidateIntegerPref(id, "state", Extension::ENABLED);
1047 // Uninstall it.
1048 if (use_helper) {
1049 EXPECT_TRUE(ExtensionService::UninstallExtensionHelper(service_, id));
1050 } else {
1051 EXPECT_TRUE(service_->UninstallExtension(id, false, NULL));
1053 --expected_extensions_count_;
1055 // We should get an unload notification.
1056 EXPECT_FALSE(unloaded_id_.empty());
1057 EXPECT_EQ(id, unloaded_id_);
1059 // Verify uninstalled state.
1060 size_t new_pref_key_count = GetPrefKeyCount();
1061 if (new_pref_key_count == pref_key_count) {
1062 ValidateIntegerPref(id, "location",
1063 Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1064 } else {
1065 EXPECT_EQ(new_pref_key_count, pref_key_count - 1);
1068 // The extension should not be in the service anymore.
1069 EXPECT_FALSE(service_->GetInstalledExtension(id));
1070 base::RunLoop().RunUntilIdle();
1072 // The directory should be gone.
1073 EXPECT_FALSE(base::PathExists(extension_path));
1076 void ValidatePrefKeyCount(size_t count) {
1077 EXPECT_EQ(count, GetPrefKeyCount());
1080 testing::AssertionResult ValidateBooleanPref(
1081 const std::string& extension_id,
1082 const std::string& pref_path,
1083 bool expected_val) {
1084 std::string msg = "while checking: ";
1085 msg += extension_id;
1086 msg += " ";
1087 msg += pref_path;
1088 msg += " == ";
1089 msg += expected_val ? "true" : "false";
1091 PrefService* prefs = profile_->GetPrefs();
1092 const base::DictionaryValue* dict =
1093 prefs->GetDictionary("extensions.settings");
1094 if (!dict) {
1095 return testing::AssertionFailure()
1096 << "extension.settings does not exist " << msg;
1099 const base::DictionaryValue* pref = NULL;
1100 if (!dict->GetDictionary(extension_id, &pref)) {
1101 return testing::AssertionFailure()
1102 << "extension pref does not exist " << msg;
1105 bool val;
1106 if (!pref->GetBoolean(pref_path, &val)) {
1107 return testing::AssertionFailure()
1108 << pref_path << " pref not found " << msg;
1111 return expected_val == val
1112 ? testing::AssertionSuccess()
1113 : testing::AssertionFailure() << "base::Value is incorrect " << msg;
1116 bool IsPrefExist(const std::string& extension_id,
1117 const std::string& pref_path) {
1118 const base::DictionaryValue* dict =
1119 profile_->GetPrefs()->GetDictionary("extensions.settings");
1120 if (dict == NULL) return false;
1121 const base::DictionaryValue* pref = NULL;
1122 if (!dict->GetDictionary(extension_id, &pref)) {
1123 return false;
1125 if (pref == NULL) {
1126 return false;
1128 bool val;
1129 if (!pref->GetBoolean(pref_path, &val)) {
1130 return false;
1132 return true;
1135 void ValidateIntegerPref(const std::string& extension_id,
1136 const std::string& pref_path,
1137 int expected_val) {
1138 std::string msg = " while checking: ";
1139 msg += extension_id;
1140 msg += " ";
1141 msg += pref_path;
1142 msg += " == ";
1143 msg += base::IntToString(expected_val);
1145 PrefService* prefs = profile_->GetPrefs();
1146 const base::DictionaryValue* dict =
1147 prefs->GetDictionary("extensions.settings");
1148 ASSERT_TRUE(dict != NULL) << msg;
1149 const base::DictionaryValue* pref = NULL;
1150 ASSERT_TRUE(dict->GetDictionary(extension_id, &pref)) << msg;
1151 EXPECT_TRUE(pref != NULL) << msg;
1152 int val;
1153 ASSERT_TRUE(pref->GetInteger(pref_path, &val)) << msg;
1154 EXPECT_EQ(expected_val, val) << msg;
1157 void ValidateStringPref(const std::string& extension_id,
1158 const std::string& pref_path,
1159 const std::string& expected_val) {
1160 std::string msg = " while checking: ";
1161 msg += extension_id;
1162 msg += ".manifest.";
1163 msg += pref_path;
1164 msg += " == ";
1165 msg += expected_val;
1167 const base::DictionaryValue* dict =
1168 profile_->GetPrefs()->GetDictionary("extensions.settings");
1169 ASSERT_TRUE(dict != NULL) << msg;
1170 const base::DictionaryValue* pref = NULL;
1171 std::string manifest_path = extension_id + ".manifest";
1172 ASSERT_TRUE(dict->GetDictionary(manifest_path, &pref)) << msg;
1173 EXPECT_TRUE(pref != NULL) << msg;
1174 std::string val;
1175 ASSERT_TRUE(pref->GetString(pref_path, &val)) << msg;
1176 EXPECT_EQ(expected_val, val) << msg;
1179 void SetPref(const std::string& extension_id,
1180 const std::string& pref_path,
1181 base::Value* value,
1182 const std::string& msg) {
1183 DictionaryPrefUpdate update(profile_->GetPrefs(), "extensions.settings");
1184 base::DictionaryValue* dict = update.Get();
1185 ASSERT_TRUE(dict != NULL) << msg;
1186 base::DictionaryValue* pref = NULL;
1187 ASSERT_TRUE(dict->GetDictionary(extension_id, &pref)) << msg;
1188 EXPECT_TRUE(pref != NULL) << msg;
1189 pref->Set(pref_path, value);
1192 void SetPrefInteg(const std::string& extension_id,
1193 const std::string& pref_path,
1194 int value) {
1195 std::string msg = " while setting: ";
1196 msg += extension_id;
1197 msg += " ";
1198 msg += pref_path;
1199 msg += " = ";
1200 msg += base::IntToString(value);
1202 SetPref(extension_id, pref_path, new base::FundamentalValue(value), msg);
1205 void SetPrefBool(const std::string& extension_id,
1206 const std::string& pref_path,
1207 bool value) {
1208 std::string msg = " while setting: ";
1209 msg += extension_id + " " + pref_path;
1210 msg += " = ";
1211 msg += (value ? "true" : "false");
1213 SetPref(extension_id, pref_path, new base::FundamentalValue(value), msg);
1216 void ClearPref(const std::string& extension_id,
1217 const std::string& pref_path) {
1218 std::string msg = " while clearing: ";
1219 msg += extension_id + " " + pref_path;
1221 DictionaryPrefUpdate update(profile_->GetPrefs(), "extensions.settings");
1222 base::DictionaryValue* dict = update.Get();
1223 ASSERT_TRUE(dict != NULL) << msg;
1224 base::DictionaryValue* pref = NULL;
1225 ASSERT_TRUE(dict->GetDictionary(extension_id, &pref)) << msg;
1226 EXPECT_TRUE(pref != NULL) << msg;
1227 pref->Remove(pref_path, NULL);
1230 void SetPrefStringSet(const std::string& extension_id,
1231 const std::string& pref_path,
1232 const std::set<std::string>& value) {
1233 std::string msg = " while setting: ";
1234 msg += extension_id + " " + pref_path;
1236 base::ListValue* list_value = new base::ListValue();
1237 for (std::set<std::string>::const_iterator iter = value.begin();
1238 iter != value.end(); ++iter)
1239 list_value->Append(new base::StringValue(*iter));
1241 SetPref(extension_id, pref_path, list_value, msg);
1244 void InitPluginService() {
1245 #if defined(ENABLE_PLUGINS)
1246 PluginService::GetInstance()->Init();
1247 #endif
1250 protected:
1251 extensions::ExtensionList loaded_;
1252 std::string unloaded_id_;
1253 const Extension* installed_;
1254 bool was_update_;
1255 std::string old_name_;
1256 FeatureSwitch::ScopedOverride override_external_install_prompt_;
1258 private:
1259 // Create a CrxInstaller and install the CRX file.
1260 // Instead of calling this method yourself, use InstallCRX(), which does extra
1261 // error checking.
1262 void InstallCRXInternal(const base::FilePath& crx_path) {
1263 InstallCRXInternal(crx_path, Extension::NO_FLAGS);
1266 void InstallCRXInternal(const base::FilePath& crx_path, int creation_flags) {
1267 ASSERT_TRUE(base::PathExists(crx_path))
1268 << "Path does not exist: "<< crx_path.value().c_str();
1269 scoped_refptr<CrxInstaller> installer(CrxInstaller::CreateSilent(service_));
1270 installer->set_creation_flags(creation_flags);
1271 if (!(creation_flags & Extension::WAS_INSTALLED_BY_DEFAULT))
1272 installer->set_allow_silent_install(true);
1274 content::WindowedNotificationObserver observer(
1275 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
1276 content::Source<extensions::CrxInstaller>(installer));
1278 installer->InstallCrx(crx_path);
1280 observer.Wait();
1283 content::NotificationRegistrar registrar_;
1286 // Receives notifications from a PackExtensionJob, indicating either that
1287 // packing succeeded or that there was some error.
1288 class PackExtensionTestClient : public extensions::PackExtensionJob::Client {
1289 public:
1290 PackExtensionTestClient(const base::FilePath& expected_crx_path,
1291 const base::FilePath& expected_private_key_path);
1292 virtual void OnPackSuccess(const base::FilePath& crx_path,
1293 const base::FilePath& private_key_path) OVERRIDE;
1294 virtual void OnPackFailure(const std::string& error_message,
1295 ExtensionCreator::ErrorType type) OVERRIDE;
1297 private:
1298 const base::FilePath expected_crx_path_;
1299 const base::FilePath expected_private_key_path_;
1300 DISALLOW_COPY_AND_ASSIGN(PackExtensionTestClient);
1303 PackExtensionTestClient::PackExtensionTestClient(
1304 const base::FilePath& expected_crx_path,
1305 const base::FilePath& expected_private_key_path)
1306 : expected_crx_path_(expected_crx_path),
1307 expected_private_key_path_(expected_private_key_path) {}
1309 // If packing succeeded, we make sure that the package names match our
1310 // expectations.
1311 void PackExtensionTestClient::OnPackSuccess(
1312 const base::FilePath& crx_path,
1313 const base::FilePath& private_key_path) {
1314 // We got the notification and processed it; we don't expect any further tasks
1315 // to be posted to the current thread, so we should stop blocking and continue
1316 // on with the rest of the test.
1317 // This call to |Quit()| matches the call to |Run()| in the
1318 // |PackPunctuatedExtension| test.
1319 base::MessageLoop::current()->Quit();
1320 EXPECT_EQ(expected_crx_path_.value(), crx_path.value());
1321 EXPECT_EQ(expected_private_key_path_.value(), private_key_path.value());
1322 ASSERT_TRUE(base::PathExists(private_key_path));
1325 // The tests are designed so that we never expect to see a packing error.
1326 void PackExtensionTestClient::OnPackFailure(const std::string& error_message,
1327 ExtensionCreator::ErrorType type) {
1328 if (type == ExtensionCreator::kCRXExists)
1329 FAIL() << "Packing should not fail.";
1330 else
1331 FAIL() << "Existing CRX should have been overwritten.";
1334 // Test loading good extensions from the profile directory.
1335 TEST_F(ExtensionServiceTest, LoadAllExtensionsFromDirectorySuccess) {
1336 InitPluginService();
1337 InitializeGoodInstalledExtensionService();
1338 service_->Init();
1340 uint32 expected_num_extensions = 3u;
1341 ASSERT_EQ(expected_num_extensions, loaded_.size());
1343 EXPECT_EQ(std::string(good0), loaded_[0]->id());
1344 EXPECT_EQ(std::string("My extension 1"),
1345 loaded_[0]->name());
1346 EXPECT_EQ(std::string("The first extension that I made."),
1347 loaded_[0]->description());
1348 EXPECT_EQ(Manifest::INTERNAL, loaded_[0]->location());
1349 EXPECT_TRUE(service_->GetExtensionById(loaded_[0]->id(), false));
1350 EXPECT_EQ(expected_num_extensions, registry_->enabled_extensions().size());
1352 ValidatePrefKeyCount(3);
1353 ValidateIntegerPref(good0, "state", Extension::ENABLED);
1354 ValidateIntegerPref(good0, "location", Manifest::INTERNAL);
1355 ValidateIntegerPref(good1, "state", Extension::ENABLED);
1356 ValidateIntegerPref(good1, "location", Manifest::INTERNAL);
1357 ValidateIntegerPref(good2, "state", Extension::ENABLED);
1358 ValidateIntegerPref(good2, "location", Manifest::INTERNAL);
1360 URLPatternSet expected_patterns;
1361 AddPattern(&expected_patterns, "file:///*");
1362 AddPattern(&expected_patterns, "http://*.google.com/*");
1363 AddPattern(&expected_patterns, "https://*.google.com/*");
1364 const Extension* extension = loaded_[0].get();
1365 const extensions::UserScriptList& scripts =
1366 extensions::ContentScriptsInfo::GetContentScripts(extension);
1367 ASSERT_EQ(2u, scripts.size());
1368 EXPECT_EQ(expected_patterns, scripts[0].url_patterns());
1369 EXPECT_EQ(2u, scripts[0].js_scripts().size());
1370 ExtensionResource resource00(extension->id(),
1371 scripts[0].js_scripts()[0].extension_root(),
1372 scripts[0].js_scripts()[0].relative_path());
1373 base::FilePath expected_path =
1374 base::MakeAbsoluteFilePath(extension->path().AppendASCII("script1.js"));
1375 EXPECT_TRUE(resource00.ComparePathWithDefault(expected_path));
1376 ExtensionResource resource01(extension->id(),
1377 scripts[0].js_scripts()[1].extension_root(),
1378 scripts[0].js_scripts()[1].relative_path());
1379 expected_path =
1380 base::MakeAbsoluteFilePath(extension->path().AppendASCII("script2.js"));
1381 EXPECT_TRUE(resource01.ComparePathWithDefault(expected_path));
1382 EXPECT_TRUE(!extensions::PluginInfo::HasPlugins(extension));
1383 EXPECT_EQ(1u, scripts[1].url_patterns().patterns().size());
1384 EXPECT_EQ("http://*.news.com/*",
1385 scripts[1].url_patterns().begin()->GetAsString());
1386 ExtensionResource resource10(extension->id(),
1387 scripts[1].js_scripts()[0].extension_root(),
1388 scripts[1].js_scripts()[0].relative_path());
1389 expected_path =
1390 extension->path().AppendASCII("js_files").AppendASCII("script3.js");
1391 expected_path = base::MakeAbsoluteFilePath(expected_path);
1392 EXPECT_TRUE(resource10.ComparePathWithDefault(expected_path));
1394 expected_patterns.ClearPatterns();
1395 AddPattern(&expected_patterns, "http://*.google.com/*");
1396 AddPattern(&expected_patterns, "https://*.google.com/*");
1397 EXPECT_EQ(expected_patterns,
1398 extension->GetActivePermissions()->explicit_hosts());
1400 EXPECT_EQ(std::string(good1), loaded_[1]->id());
1401 EXPECT_EQ(std::string("My extension 2"), loaded_[1]->name());
1402 EXPECT_EQ(std::string(), loaded_[1]->description());
1403 EXPECT_EQ(loaded_[1]->GetResourceURL("background.html"),
1404 extensions::BackgroundInfo::GetBackgroundURL(loaded_[1].get()));
1405 EXPECT_EQ(0u,
1406 extensions::ContentScriptsInfo::GetContentScripts(loaded_[1].get())
1407 .size());
1409 // We don't parse the plugins section on Chrome OS.
1410 #if defined(OS_CHROMEOS)
1411 EXPECT_TRUE(!extensions::PluginInfo::HasPlugins(loaded_[1].get()));
1412 #else
1413 ASSERT_TRUE(extensions::PluginInfo::HasPlugins(loaded_[1].get()));
1414 const std::vector<extensions::PluginInfo>* plugins =
1415 extensions::PluginInfo::GetPlugins(loaded_[1].get());
1416 ASSERT_TRUE(plugins);
1417 ASSERT_EQ(2u, plugins->size());
1418 EXPECT_EQ(loaded_[1]->path().AppendASCII("content_plugin.dll").value(),
1419 plugins->at(0).path.value());
1420 EXPECT_TRUE(plugins->at(0).is_public);
1421 EXPECT_EQ(loaded_[1]->path().AppendASCII("extension_plugin.dll").value(),
1422 plugins->at(1).path.value());
1423 EXPECT_FALSE(plugins->at(1).is_public);
1424 #endif
1426 EXPECT_EQ(Manifest::INTERNAL, loaded_[1]->location());
1428 int index = expected_num_extensions - 1;
1429 EXPECT_EQ(std::string(good2), loaded_[index]->id());
1430 EXPECT_EQ(std::string("My extension 3"), loaded_[index]->name());
1431 EXPECT_EQ(std::string(), loaded_[index]->description());
1432 EXPECT_EQ(0u,
1433 extensions::ContentScriptsInfo::GetContentScripts(
1434 loaded_[index].get()).size());
1435 EXPECT_EQ(Manifest::INTERNAL, loaded_[index]->location());
1438 // Test loading bad extensions from the profile directory.
1439 TEST_F(ExtensionServiceTest, LoadAllExtensionsFromDirectoryFail) {
1440 // Initialize the test dir with a bad Preferences/extensions.
1441 base::FilePath source_install_dir = data_dir_
1442 .AppendASCII("bad")
1443 .AppendASCII("Extensions");
1444 base::FilePath pref_path =
1445 source_install_dir.DirName().Append(chrome::kPreferencesFilename);
1447 InitializeInstalledExtensionService(pref_path, source_install_dir);
1449 service_->Init();
1451 ASSERT_EQ(4u, GetErrors().size());
1452 ASSERT_EQ(0u, loaded_.size());
1454 EXPECT_TRUE(MatchPattern(base::UTF16ToUTF8(GetErrors()[0]),
1455 std::string("Could not load extension from '*'. ") +
1456 extensions::manifest_errors::kManifestUnreadable)) <<
1457 base::UTF16ToUTF8(GetErrors()[0]);
1459 EXPECT_TRUE(MatchPattern(base::UTF16ToUTF8(GetErrors()[1]),
1460 std::string("Could not load extension from '*'. ") +
1461 extensions::manifest_errors::kManifestUnreadable)) <<
1462 base::UTF16ToUTF8(GetErrors()[1]);
1464 EXPECT_TRUE(MatchPattern(base::UTF16ToUTF8(GetErrors()[2]),
1465 std::string("Could not load extension from '*'. ") +
1466 extensions::manifest_errors::kMissingFile)) <<
1467 base::UTF16ToUTF8(GetErrors()[2]);
1469 EXPECT_TRUE(MatchPattern(base::UTF16ToUTF8(GetErrors()[3]),
1470 std::string("Could not load extension from '*'. ") +
1471 extensions::manifest_errors::kManifestUnreadable)) <<
1472 base::UTF16ToUTF8(GetErrors()[3]);
1475 // Test various cases for delayed install because of missing imports.
1476 TEST_F(ExtensionServiceTest, PendingImports) {
1477 InitPluginService();
1479 base::FilePath source_install_dir = data_dir_
1480 .AppendASCII("pending_updates_with_imports")
1481 .AppendASCII("Extensions");
1482 base::FilePath pref_path =
1483 source_install_dir.DirName().Append(chrome::kPreferencesFilename);
1485 InitializeInstalledExtensionService(pref_path, source_install_dir);
1487 // Verify there are no pending extensions initially.
1488 EXPECT_FALSE(service_->pending_extension_manager()->HasPendingExtensions());
1490 service_->Init();
1491 // Wait for GarbageCollectExtensions task to complete.
1492 base::RunLoop().RunUntilIdle();
1494 // These extensions are used by the extensions we test below, they must be
1495 // installed.
1496 EXPECT_TRUE(base::PathExists(extensions_install_dir_.AppendASCII(
1497 "bjafgdebaacbbbecmhlhpofkepfkgcpa/1.0")));
1498 EXPECT_TRUE(base::PathExists(extensions_install_dir_.AppendASCII(
1499 "hpiknbiabeeppbpihjehijgoemciehgk/2")));
1501 // Each of these extensions should have been rejected because of dependencies
1502 // that cannot be satisfied.
1503 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile_.get());
1504 EXPECT_FALSE(
1505 prefs->GetDelayedInstallInfo("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
1506 EXPECT_FALSE(
1507 prefs->GetInstalledExtensionInfo("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
1508 EXPECT_FALSE(
1509 prefs->GetDelayedInstallInfo("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"));
1510 EXPECT_FALSE(
1511 prefs->GetInstalledExtensionInfo("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"));
1512 EXPECT_FALSE(
1513 prefs->GetDelayedInstallInfo("cccccccccccccccccccccccccccccccc"));
1514 EXPECT_FALSE(
1515 prefs->GetInstalledExtensionInfo("cccccccccccccccccccccccccccccccc"));
1517 // Make sure the import started for the extension with a dependency.
1518 EXPECT_TRUE(
1519 prefs->GetDelayedInstallInfo("behllobkkfkfnphdnhnkndlbkcpglgmj"));
1520 EXPECT_EQ(ExtensionPrefs::DELAY_REASON_WAIT_FOR_IMPORTS,
1521 prefs->GetDelayedInstallReason("behllobkkfkfnphdnhnkndlbkcpglgmj"));
1523 EXPECT_FALSE(base::PathExists(extensions_install_dir_.AppendASCII(
1524 "behllobkkfkfnphdnhnkndlbkcpglgmj/1.0.0.0")));
1526 EXPECT_TRUE(service_->pending_extension_manager()->HasPendingExtensions());
1527 std::string pending_id("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
1528 EXPECT_TRUE(service_->pending_extension_manager()->IsIdPending(pending_id));
1529 // Remove it because we are not testing the pending extension manager's
1530 // ability to download and install extensions.
1531 EXPECT_TRUE(service_->pending_extension_manager()->Remove(pending_id));
1534 // Test installing extensions. This test tries to install few extensions using
1535 // crx files. If you need to change those crx files, feel free to repackage
1536 // them, throw away the key used and change the id's above.
1537 TEST_F(ExtensionServiceTest, InstallExtension) {
1538 InitializeEmptyExtensionService();
1540 // Extensions not enabled.
1541 set_extensions_enabled(false);
1542 base::FilePath path = data_dir_.AppendASCII("good.crx");
1543 InstallCRX(path, INSTALL_FAILED);
1544 set_extensions_enabled(true);
1546 ValidatePrefKeyCount(0);
1548 // A simple extension that should install without error.
1549 path = data_dir_.AppendASCII("good.crx");
1550 InstallCRX(path, INSTALL_NEW);
1551 // TODO(erikkay): verify the contents of the installed extension.
1553 int pref_count = 0;
1554 ValidatePrefKeyCount(++pref_count);
1555 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
1556 ValidateIntegerPref(good_crx, "location", Manifest::INTERNAL);
1558 // An extension with page actions.
1559 path = data_dir_.AppendASCII("page_action.crx");
1560 InstallCRX(path, INSTALL_NEW);
1561 ValidatePrefKeyCount(++pref_count);
1562 ValidateIntegerPref(page_action, "state", Extension::ENABLED);
1563 ValidateIntegerPref(page_action, "location", Manifest::INTERNAL);
1565 // Bad signature.
1566 path = data_dir_.AppendASCII("bad_signature.crx");
1567 InstallCRX(path, INSTALL_FAILED);
1568 ValidatePrefKeyCount(pref_count);
1570 // 0-length extension file.
1571 path = data_dir_.AppendASCII("not_an_extension.crx");
1572 InstallCRX(path, INSTALL_FAILED);
1573 ValidatePrefKeyCount(pref_count);
1575 // Bad magic number.
1576 path = data_dir_.AppendASCII("bad_magic.crx");
1577 InstallCRX(path, INSTALL_FAILED);
1578 ValidatePrefKeyCount(pref_count);
1580 // Packed extensions may have folders or files that have underscores.
1581 // This will only cause a warning, rather than a fatal error.
1582 path = data_dir_.AppendASCII("bad_underscore.crx");
1583 InstallCRX(path, INSTALL_NEW);
1584 ValidatePrefKeyCount(++pref_count);
1586 // A test for an extension with a 2048-bit public key.
1587 path = data_dir_.AppendASCII("good2048.crx");
1588 InstallCRX(path, INSTALL_NEW);
1589 ValidatePrefKeyCount(++pref_count);
1590 ValidateIntegerPref(good2048, "state", Extension::ENABLED);
1591 ValidateIntegerPref(good2048, "location", Manifest::INTERNAL);
1593 // TODO(erikkay): add more tests for many of the failure cases.
1594 // TODO(erikkay): add tests for upgrade cases.
1597 struct MockInstallObserver : public extensions::InstallObserver {
1598 MockInstallObserver() {
1601 virtual ~MockInstallObserver() {
1604 virtual void OnExtensionInstalled(const Extension* extension) OVERRIDE {
1605 last_extension_installed = extension->id();
1608 virtual void OnExtensionUninstalled(const Extension* extension) OVERRIDE {
1609 last_extension_uninstalled = extension->id();
1612 std::string last_extension_installed;
1613 std::string last_extension_uninstalled;
1616 // Test that correct notifications are sent to InstallTracker observers on
1617 // extension install and uninstall.
1618 TEST_F(ExtensionServiceTest, InstallObserverNotified) {
1619 InitializeEmptyExtensionService();
1621 extensions::InstallTracker* tracker(
1622 extensions::InstallTrackerFactory::GetForProfile(profile_.get()));
1623 MockInstallObserver observer;
1624 tracker->AddObserver(&observer);
1626 // A simple extension that should install without error.
1627 ASSERT_TRUE(observer.last_extension_installed.empty());
1628 base::FilePath path = data_dir_.AppendASCII("good.crx");
1629 InstallCRX(path, INSTALL_NEW);
1630 ASSERT_EQ(good_crx, observer.last_extension_installed);
1632 // Uninstall the extension.
1633 ASSERT_TRUE(observer.last_extension_uninstalled.empty());
1634 UninstallExtension(good_crx, false);
1635 ASSERT_EQ(good_crx, observer.last_extension_uninstalled);
1637 tracker->RemoveObserver(&observer);
1640 // Tests that flags passed to OnExternalExtensionFileFound() make it to the
1641 // extension object.
1642 TEST_F(ExtensionServiceTest, InstallingExternalExtensionWithFlags) {
1643 const char kPrefFromBookmark[] = "from_bookmark";
1645 InitializeEmptyExtensionService();
1647 base::FilePath path = data_dir_.AppendASCII("good.crx");
1648 set_extensions_enabled(true);
1650 // Register and install an external extension.
1651 Version version("1.0.0.0");
1652 content::WindowedNotificationObserver observer(
1653 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
1654 content::NotificationService::AllSources());
1655 if (service_->OnExternalExtensionFileFound(
1656 good_crx,
1657 &version,
1658 path,
1659 Manifest::EXTERNAL_PREF,
1660 Extension::FROM_BOOKMARK,
1661 false /* mark_acknowledged */)) {
1662 observer.Wait();
1665 const Extension* extension = service_->GetExtensionById(good_crx, false);
1666 ASSERT_TRUE(extension);
1667 ASSERT_TRUE(extension->from_bookmark());
1668 ASSERT_TRUE(ValidateBooleanPref(good_crx, kPrefFromBookmark, true));
1670 // Upgrade to version 2.0, the flag should be preserved.
1671 path = data_dir_.AppendASCII("good2.crx");
1672 UpdateExtension(good_crx, path, ENABLED);
1673 ASSERT_TRUE(ValidateBooleanPref(good_crx, kPrefFromBookmark, true));
1674 extension = service_->GetExtensionById(good_crx, false);
1675 ASSERT_TRUE(extension);
1676 ASSERT_TRUE(extension->from_bookmark());
1679 // Test the handling of Extension::EXTERNAL_EXTENSION_UNINSTALLED
1680 TEST_F(ExtensionServiceTest, UninstallingExternalExtensions) {
1681 InitializeEmptyExtensionService();
1683 base::FilePath path = data_dir_.AppendASCII("good.crx");
1684 set_extensions_enabled(true);
1686 // Install an external extension.
1687 Version version("1.0.0.0");
1688 content::WindowedNotificationObserver observer(
1689 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
1690 content::NotificationService::AllSources());
1691 if (service_->OnExternalExtensionFileFound(good_crx, &version,
1692 path, Manifest::EXTERNAL_PREF,
1693 Extension::NO_FLAGS, false)) {
1694 observer.Wait();
1697 ASSERT_TRUE(service_->GetExtensionById(good_crx, false));
1699 // Uninstall it and check that its killbit gets set.
1700 UninstallExtension(good_crx, false);
1701 ValidateIntegerPref(good_crx, "location",
1702 Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1704 // Try to re-install it externally. This should fail because of the killbit.
1705 service_->OnExternalExtensionFileFound(good_crx, &version,
1706 path, Manifest::EXTERNAL_PREF,
1707 Extension::NO_FLAGS, false);
1708 base::RunLoop().RunUntilIdle();
1709 ASSERT_TRUE(NULL == service_->GetExtensionById(good_crx, false));
1710 ValidateIntegerPref(good_crx, "location",
1711 Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1713 version = Version("1.0.0.1");
1714 // Repeat the same thing with a newer version of the extension.
1715 path = data_dir_.AppendASCII("good2.crx");
1716 service_->OnExternalExtensionFileFound(good_crx, &version,
1717 path, Manifest::EXTERNAL_PREF,
1718 Extension::NO_FLAGS, false);
1719 base::RunLoop().RunUntilIdle();
1720 ASSERT_TRUE(NULL == service_->GetExtensionById(good_crx, false));
1721 ValidateIntegerPref(good_crx, "location",
1722 Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1724 // Try adding the same extension from an external update URL.
1725 ASSERT_FALSE(service_->pending_extension_manager()->AddFromExternalUpdateUrl(
1726 good_crx,
1727 std::string(),
1728 GURL("http:://fake.update/url"),
1729 Manifest::EXTERNAL_PREF_DOWNLOAD,
1730 Extension::NO_FLAGS,
1731 false));
1733 ASSERT_FALSE(service_->pending_extension_manager()->IsIdPending(good_crx));
1736 // Test that uninstalling an external extension does not crash when
1737 // the extension could not be loaded.
1738 // This extension shown in preferences file requires an experimental permission.
1739 // It could not be loaded without such permission.
1740 TEST_F(ExtensionServiceTest, UninstallingNotLoadedExtension) {
1741 base::FilePath source_install_dir = data_dir_
1742 .AppendASCII("good")
1743 .AppendASCII("Extensions");
1744 // The preference contains an external extension
1745 // that requires 'experimental' permission.
1746 base::FilePath pref_path = source_install_dir
1747 .DirName()
1748 .AppendASCII("PreferencesExperimental");
1750 // Aforementioned extension will not be loaded if
1751 // there is no '--enable-experimental-extension-apis' command line flag.
1752 InitializeInstalledExtensionService(pref_path, source_install_dir);
1754 service_->Init();
1756 // Check and try to uninstall it.
1757 // If we don't check whether the extension is loaded before we uninstall it
1758 // in CheckExternalUninstall, a crash will happen here because we will get or
1759 // dereference a NULL pointer (extension) inside UninstallExtension.
1760 MockExtensionProvider provider(NULL, Manifest::EXTERNAL_REGISTRY);
1761 service_->OnExternalProviderReady(&provider);
1764 // Test that external extensions with incorrect IDs are not installed.
1765 TEST_F(ExtensionServiceTest, FailOnWrongId) {
1766 InitializeEmptyExtensionService();
1767 base::FilePath path = data_dir_.AppendASCII("good.crx");
1768 set_extensions_enabled(true);
1770 Version version("1.0.0.0");
1772 const std::string wrong_id = all_zero;
1773 const std::string correct_id = good_crx;
1774 ASSERT_NE(correct_id, wrong_id);
1776 // Install an external extension with an ID from the external
1777 // source that is not equal to the ID in the extension manifest.
1778 content::WindowedNotificationObserver observer(
1779 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
1780 content::NotificationService::AllSources());
1781 service_->OnExternalExtensionFileFound(
1782 wrong_id, &version, path, Manifest::EXTERNAL_PREF,
1783 Extension::NO_FLAGS, false);
1785 observer.Wait();
1786 ASSERT_FALSE(service_->GetExtensionById(good_crx, false));
1788 // Try again with the right ID. Expect success.
1789 content::WindowedNotificationObserver observer2(
1790 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
1791 content::NotificationService::AllSources());
1792 if (service_->OnExternalExtensionFileFound(
1793 correct_id, &version, path, Manifest::EXTERNAL_PREF,
1794 Extension::NO_FLAGS, false)) {
1795 observer2.Wait();
1797 ASSERT_TRUE(service_->GetExtensionById(good_crx, false));
1800 // Test that external extensions with incorrect versions are not installed.
1801 TEST_F(ExtensionServiceTest, FailOnWrongVersion) {
1802 InitializeEmptyExtensionService();
1803 base::FilePath path = data_dir_.AppendASCII("good.crx");
1804 set_extensions_enabled(true);
1806 // Install an external extension with a version from the external
1807 // source that is not equal to the version in the extension manifest.
1808 Version wrong_version("1.2.3.4");
1809 content::WindowedNotificationObserver observer(
1810 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
1811 content::NotificationService::AllSources());
1812 service_->OnExternalExtensionFileFound(
1813 good_crx, &wrong_version, path, Manifest::EXTERNAL_PREF,
1814 Extension::NO_FLAGS, false);
1816 observer.Wait();
1817 ASSERT_FALSE(service_->GetExtensionById(good_crx, false));
1819 // Try again with the right version. Expect success.
1820 service_->pending_extension_manager()->Remove(good_crx);
1821 Version correct_version("1.0.0.0");
1822 content::WindowedNotificationObserver observer2(
1823 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
1824 content::NotificationService::AllSources());
1825 if (service_->OnExternalExtensionFileFound(
1826 good_crx, &correct_version, path, Manifest::EXTERNAL_PREF,
1827 Extension::NO_FLAGS, false)) {
1828 observer2.Wait();
1830 ASSERT_TRUE(service_->GetExtensionById(good_crx, false));
1833 // Install a user script (they get converted automatically to an extension)
1834 TEST_F(ExtensionServiceTest, InstallUserScript) {
1835 // The details of script conversion are tested elsewhere, this just tests
1836 // integration with ExtensionService.
1837 InitializeEmptyExtensionService();
1839 base::FilePath path = data_dir_
1840 .AppendASCII("user_script_basic.user.js");
1842 ASSERT_TRUE(base::PathExists(path));
1843 scoped_refptr<CrxInstaller> installer(CrxInstaller::CreateSilent(service_));
1844 installer->set_allow_silent_install(true);
1845 installer->InstallUserScript(
1846 path,
1847 GURL("http://www.aaronboodman.com/scripts/user_script_basic.user.js"));
1849 base::RunLoop().RunUntilIdle();
1850 std::vector<base::string16> errors = GetErrors();
1851 EXPECT_TRUE(installed_) << "Nothing was installed.";
1852 EXPECT_FALSE(was_update_) << path.value();
1853 ASSERT_EQ(1u, loaded_.size()) << "Nothing was loaded.";
1854 EXPECT_EQ(0u, errors.size()) << "There were errors: "
1855 << JoinString(errors, ',');
1856 EXPECT_TRUE(service_->GetExtensionById(loaded_[0]->id(), false)) <<
1857 path.value();
1859 installed_ = NULL;
1860 was_update_ = false;
1861 loaded_.clear();
1862 ExtensionErrorReporter::GetInstance()->ClearErrors();
1865 // Extensions don't install during shutdown.
1866 TEST_F(ExtensionServiceTest, InstallExtensionDuringShutdown) {
1867 InitializeEmptyExtensionService();
1869 // Simulate shutdown.
1870 service_->set_browser_terminating_for_test(true);
1872 base::FilePath path = data_dir_.AppendASCII("good.crx");
1873 scoped_refptr<CrxInstaller> installer(CrxInstaller::CreateSilent(service_));
1874 installer->set_allow_silent_install(true);
1875 installer->InstallCrx(path);
1876 base::RunLoop().RunUntilIdle();
1878 EXPECT_FALSE(installed_) << "Extension installed during shutdown.";
1879 ASSERT_EQ(0u, loaded_.size()) << "Extension loaded during shutdown.";
1882 // This tests that the granted permissions preferences are correctly set when
1883 // installing an extension.
1884 TEST_F(ExtensionServiceTest, GrantedPermissions) {
1885 InitializeEmptyExtensionService();
1886 base::FilePath path = data_dir_
1887 .AppendASCII("permissions");
1889 base::FilePath pem_path = path.AppendASCII("unknown.pem");
1890 path = path.AppendASCII("unknown");
1892 ASSERT_TRUE(base::PathExists(pem_path));
1893 ASSERT_TRUE(base::PathExists(path));
1895 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile_.get());
1897 APIPermissionSet expected_api_perms;
1898 URLPatternSet expected_host_perms;
1900 // Make sure there aren't any granted permissions before the
1901 // extension is installed.
1902 scoped_refptr<PermissionSet> known_perms(
1903 prefs->GetGrantedPermissions(permissions_crx));
1904 EXPECT_FALSE(known_perms.get());
1906 const Extension* extension = PackAndInstallCRX(path, pem_path, INSTALL_NEW);
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 AddPattern(&expected_host_perms, "http://*.google.com/*");
1916 AddPattern(&expected_host_perms, "https://*.google.com/*");
1917 AddPattern(&expected_host_perms, "http://*.google.com.hk/*");
1918 AddPattern(&expected_host_perms, "http://www.example.com/*");
1920 known_perms = prefs->GetGrantedPermissions(extension->id());
1921 EXPECT_TRUE(known_perms.get());
1922 EXPECT_FALSE(known_perms->IsEmpty());
1923 EXPECT_EQ(expected_api_perms, known_perms->apis());
1924 EXPECT_FALSE(known_perms->HasEffectiveFullAccess());
1925 EXPECT_EQ(expected_host_perms, known_perms->effective_hosts());
1929 #if !defined(OS_CHROMEOS)
1930 // This tests that the granted permissions preferences are correctly set for
1931 // default apps.
1932 TEST_F(ExtensionServiceTest, DefaultAppsGrantedPermissions) {
1933 InitializeEmptyExtensionService();
1934 base::FilePath path = data_dir_
1935 .AppendASCII("permissions");
1937 base::FilePath pem_path = path.AppendASCII("unknown.pem");
1938 path = path.AppendASCII("unknown");
1940 ASSERT_TRUE(base::PathExists(pem_path));
1941 ASSERT_TRUE(base::PathExists(path));
1943 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile_.get());
1945 APIPermissionSet expected_api_perms;
1946 URLPatternSet expected_host_perms;
1948 // Make sure there aren't any granted permissions before the
1949 // extension is installed.
1950 scoped_refptr<PermissionSet> known_perms(
1951 prefs->GetGrantedPermissions(permissions_crx));
1952 EXPECT_FALSE(known_perms.get());
1954 const Extension* extension = PackAndInstallCRX(
1955 path, pem_path, INSTALL_NEW, Extension::WAS_INSTALLED_BY_DEFAULT);
1957 EXPECT_EQ(0u, GetErrors().size());
1958 ASSERT_EQ(1u, registry_->enabled_extensions().size());
1959 EXPECT_EQ(permissions_crx, extension->id());
1961 // Verify that the valid API permissions have been recognized.
1962 expected_api_perms.insert(APIPermission::kTab);
1964 known_perms = prefs->GetGrantedPermissions(extension->id());
1965 EXPECT_TRUE(known_perms.get());
1966 EXPECT_FALSE(known_perms->IsEmpty());
1967 EXPECT_EQ(expected_api_perms, known_perms->apis());
1968 EXPECT_FALSE(known_perms->HasEffectiveFullAccess());
1970 #endif
1972 #if !defined(OS_CHROMEOS)
1973 // Tests that the granted permissions full_access bit gets set correctly when
1974 // an extension contains an NPAPI plugin. Don't run this test on Chrome OS
1975 // since they don't support plugins.
1976 TEST_F(ExtensionServiceTest, GrantedFullAccessPermissions) {
1977 InitPluginService();
1979 InitializeEmptyExtensionService();
1981 ASSERT_TRUE(base::PathExists(good1_path()));
1982 const Extension* extension = PackAndInstallCRX(good1_path(), INSTALL_NEW);
1983 EXPECT_EQ(0u, GetErrors().size());
1984 EXPECT_EQ(1u, registry_->enabled_extensions().size());
1985 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile_.get());
1987 scoped_refptr<PermissionSet> permissions(
1988 prefs->GetGrantedPermissions(extension->id()));
1989 EXPECT_FALSE(permissions->IsEmpty());
1990 EXPECT_TRUE(permissions->HasEffectiveFullAccess());
1991 EXPECT_FALSE(permissions->apis().empty());
1992 EXPECT_TRUE(permissions->HasAPIPermission(APIPermission::kPlugin));
1994 // Full access implies full host access too...
1995 EXPECT_TRUE(permissions->HasEffectiveAccessToAllHosts());
1997 #endif
1999 // Tests that the extension is disabled when permissions are missing from
2000 // the extension's granted permissions preferences. (This simulates updating
2001 // the browser to a version which recognizes more permissions).
2002 TEST_F(ExtensionServiceTest, GrantedAPIAndHostPermissions) {
2003 InitializeEmptyExtensionService();
2005 base::FilePath path = data_dir_
2006 .AppendASCII("permissions")
2007 .AppendASCII("unknown");
2009 ASSERT_TRUE(base::PathExists(path));
2011 const Extension* extension = PackAndInstallCRX(path, INSTALL_NEW);
2013 EXPECT_EQ(0u, GetErrors().size());
2014 EXPECT_EQ(1u, registry_->enabled_extensions().size());
2015 std::string extension_id = extension->id();
2017 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile_.get());
2019 APIPermissionSet expected_api_permissions;
2020 URLPatternSet expected_host_permissions;
2022 expected_api_permissions.insert(APIPermission::kTab);
2023 AddPattern(&expected_host_permissions, "http://*.google.com/*");
2024 AddPattern(&expected_host_permissions, "https://*.google.com/*");
2025 AddPattern(&expected_host_permissions, "http://*.google.com.hk/*");
2026 AddPattern(&expected_host_permissions, "http://www.example.com/*");
2028 std::set<std::string> host_permissions;
2030 // Test that the extension is disabled when an API permission is missing from
2031 // the extension's granted api permissions preference. (This simulates
2032 // updating the browser to a version which recognizes a new API permission).
2033 SetPref(extension_id, "granted_permissions.api",
2034 new base::ListValue(), "granted_permissions.api");
2035 service_->ReloadExtensionsForTest();
2037 EXPECT_EQ(1u, registry_->disabled_extensions().size());
2038 extension = registry_->disabled_extensions().begin()->get();
2040 ASSERT_TRUE(prefs->IsExtensionDisabled(extension_id));
2041 ASSERT_FALSE(service_->IsExtensionEnabled(extension_id));
2042 ASSERT_TRUE(prefs->DidExtensionEscalatePermissions(extension_id));
2044 // Now grant and re-enable the extension, making sure the prefs are updated.
2045 service_->GrantPermissionsAndEnableExtension(extension);
2047 ASSERT_FALSE(prefs->IsExtensionDisabled(extension_id));
2048 ASSERT_TRUE(service_->IsExtensionEnabled(extension_id));
2049 ASSERT_FALSE(prefs->DidExtensionEscalatePermissions(extension_id));
2051 scoped_refptr<PermissionSet> current_perms(
2052 prefs->GetGrantedPermissions(extension_id));
2053 ASSERT_TRUE(current_perms.get());
2054 ASSERT_FALSE(current_perms->IsEmpty());
2055 ASSERT_FALSE(current_perms->HasEffectiveFullAccess());
2056 ASSERT_EQ(expected_api_permissions, current_perms->apis());
2057 ASSERT_EQ(expected_host_permissions, current_perms->effective_hosts());
2059 // Tests that the extension is disabled when a host permission is missing from
2060 // the extension's granted host permissions preference. (This simulates
2061 // updating the browser to a version which recognizes additional host
2062 // permissions).
2063 host_permissions.clear();
2064 current_perms = NULL;
2066 host_permissions.insert("http://*.google.com/*");
2067 host_permissions.insert("https://*.google.com/*");
2068 host_permissions.insert("http://*.google.com.hk/*");
2070 base::ListValue* api_permissions = new base::ListValue();
2071 api_permissions->Append(
2072 new base::StringValue("tabs"));
2073 SetPref(extension_id, "granted_permissions.api",
2074 api_permissions, "granted_permissions.api");
2075 SetPrefStringSet(
2076 extension_id, "granted_permissions.scriptable_host", host_permissions);
2078 service_->ReloadExtensionsForTest();
2080 EXPECT_EQ(1u, registry_->disabled_extensions().size());
2081 extension = registry_->disabled_extensions().begin()->get();
2083 ASSERT_TRUE(prefs->IsExtensionDisabled(extension_id));
2084 ASSERT_FALSE(service_->IsExtensionEnabled(extension_id));
2085 ASSERT_TRUE(prefs->DidExtensionEscalatePermissions(extension_id));
2087 // Now grant and re-enable the extension, making sure the prefs are updated.
2088 service_->GrantPermissionsAndEnableExtension(extension);
2090 ASSERT_TRUE(service_->IsExtensionEnabled(extension_id));
2091 ASSERT_FALSE(prefs->DidExtensionEscalatePermissions(extension_id));
2093 current_perms = prefs->GetGrantedPermissions(extension_id);
2094 ASSERT_TRUE(current_perms.get());
2095 ASSERT_FALSE(current_perms->IsEmpty());
2096 ASSERT_FALSE(current_perms->HasEffectiveFullAccess());
2097 ASSERT_EQ(expected_api_permissions, current_perms->apis());
2098 ASSERT_EQ(expected_host_permissions, current_perms->effective_hosts());
2101 // Test Packaging and installing an extension.
2102 TEST_F(ExtensionServiceTest, PackExtension) {
2103 InitializeEmptyExtensionService();
2104 base::FilePath input_directory = data_dir_
2105 .AppendASCII("good")
2106 .AppendASCII("Extensions")
2107 .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
2108 .AppendASCII("1.0.0.0");
2110 base::ScopedTempDir temp_dir;
2111 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
2112 base::FilePath output_directory = temp_dir.path();
2114 base::FilePath crx_path(output_directory.AppendASCII("ex1.crx"));
2115 base::FilePath privkey_path(output_directory.AppendASCII("privkey.pem"));
2117 scoped_ptr<ExtensionCreator> creator(new ExtensionCreator());
2118 ASSERT_TRUE(creator->Run(input_directory, crx_path, base::FilePath(),
2119 privkey_path, ExtensionCreator::kNoRunFlags));
2120 ASSERT_TRUE(base::PathExists(crx_path));
2121 ASSERT_TRUE(base::PathExists(privkey_path));
2123 // Repeat the run with the pem file gone, and no special flags
2124 // Should refuse to overwrite the existing crx.
2125 base::DeleteFile(privkey_path, false);
2126 ASSERT_FALSE(creator->Run(input_directory, crx_path, base::FilePath(),
2127 privkey_path, ExtensionCreator::kNoRunFlags));
2129 // OK, now try it with a flag to overwrite existing crx. Should work.
2130 ASSERT_TRUE(creator->Run(input_directory, crx_path, base::FilePath(),
2131 privkey_path, ExtensionCreator::kOverwriteCRX));
2133 // Repeat the run allowing existing crx, but the existing pem is still
2134 // an error. Should fail.
2135 ASSERT_FALSE(creator->Run(input_directory, crx_path, base::FilePath(),
2136 privkey_path, ExtensionCreator::kOverwriteCRX));
2138 ASSERT_TRUE(base::PathExists(privkey_path));
2139 InstallCRX(crx_path, INSTALL_NEW);
2141 // Try packing with invalid paths.
2142 creator.reset(new ExtensionCreator());
2143 ASSERT_FALSE(
2144 creator->Run(base::FilePath(), base::FilePath(), base::FilePath(),
2145 base::FilePath(), ExtensionCreator::kOverwriteCRX));
2147 // Try packing an empty directory. Should fail because an empty directory is
2148 // not a valid extension.
2149 base::ScopedTempDir temp_dir2;
2150 ASSERT_TRUE(temp_dir2.CreateUniqueTempDir());
2151 creator.reset(new ExtensionCreator());
2152 ASSERT_FALSE(creator->Run(temp_dir2.path(), crx_path, privkey_path,
2153 base::FilePath(), ExtensionCreator::kOverwriteCRX));
2155 // Try packing with an invalid manifest.
2156 std::string invalid_manifest_content = "I am not a manifest.";
2157 ASSERT_TRUE(base::WriteFile(
2158 temp_dir2.path().Append(extensions::kManifestFilename),
2159 invalid_manifest_content.c_str(), invalid_manifest_content.size()));
2160 creator.reset(new ExtensionCreator());
2161 ASSERT_FALSE(creator->Run(temp_dir2.path(), crx_path, privkey_path,
2162 base::FilePath(), ExtensionCreator::kOverwriteCRX));
2164 // Try packing with a private key that is a valid key, but invalid for the
2165 // extension.
2166 base::FilePath bad_private_key_dir = data_dir_.AppendASCII("bad_private_key");
2167 crx_path = output_directory.AppendASCII("bad_private_key.crx");
2168 privkey_path = data_dir_.AppendASCII("bad_private_key.pem");
2169 ASSERT_FALSE(creator->Run(bad_private_key_dir, crx_path, base::FilePath(),
2170 privkey_path, ExtensionCreator::kOverwriteCRX));
2173 // Test Packaging and installing an extension whose name contains punctuation.
2174 TEST_F(ExtensionServiceTest, PackPunctuatedExtension) {
2175 InitializeEmptyExtensionService();
2176 base::FilePath input_directory = data_dir_
2177 .AppendASCII("good")
2178 .AppendASCII("Extensions")
2179 .AppendASCII(good0)
2180 .AppendASCII("1.0.0.0");
2182 base::ScopedTempDir temp_dir;
2183 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
2185 // Extension names containing punctuation, and the expected names for the
2186 // packed extensions.
2187 const base::FilePath punctuated_names[] = {
2188 base::FilePath(FILE_PATH_LITERAL("this.extensions.name.has.periods")),
2189 base::FilePath(FILE_PATH_LITERAL(".thisextensionsnamestartswithaperiod")),
2190 base::FilePath(FILE_PATH_LITERAL("thisextensionhasaslashinitsname/")).
2191 NormalizePathSeparators(),
2193 const base::FilePath expected_crx_names[] = {
2194 base::FilePath(FILE_PATH_LITERAL("this.extensions.name.has.periods.crx")),
2195 base::FilePath(
2196 FILE_PATH_LITERAL(".thisextensionsnamestartswithaperiod.crx")),
2197 base::FilePath(FILE_PATH_LITERAL("thisextensionhasaslashinitsname.crx")),
2199 const base::FilePath expected_private_key_names[] = {
2200 base::FilePath(FILE_PATH_LITERAL("this.extensions.name.has.periods.pem")),
2201 base::FilePath(
2202 FILE_PATH_LITERAL(".thisextensionsnamestartswithaperiod.pem")),
2203 base::FilePath(FILE_PATH_LITERAL("thisextensionhasaslashinitsname.pem")),
2206 for (size_t i = 0; i < arraysize(punctuated_names); ++i) {
2207 SCOPED_TRACE(punctuated_names[i].value().c_str());
2208 base::FilePath output_dir = temp_dir.path().Append(punctuated_names[i]);
2210 // Copy the extension into the output directory, as PackExtensionJob doesn't
2211 // let us choose where to output the packed extension.
2212 ASSERT_TRUE(base::CopyDirectory(input_directory, output_dir, true));
2214 base::FilePath expected_crx_path =
2215 temp_dir.path().Append(expected_crx_names[i]);
2216 base::FilePath expected_private_key_path =
2217 temp_dir.path().Append(expected_private_key_names[i]);
2218 PackExtensionTestClient pack_client(expected_crx_path,
2219 expected_private_key_path);
2220 scoped_refptr<extensions::PackExtensionJob> packer(
2221 new extensions::PackExtensionJob(&pack_client, output_dir,
2222 base::FilePath(),
2223 ExtensionCreator::kOverwriteCRX));
2224 packer->Start();
2226 // The packer will post a notification task to the current thread's message
2227 // loop when it is finished. We manually run the loop here so that we
2228 // block and catch the notification; otherwise, the process would exit.
2229 // This call to |Run()| is matched by a call to |Quit()| in the
2230 // |PackExtensionTestClient|'s notification handling code.
2231 base::MessageLoop::current()->Run();
2233 if (HasFatalFailure())
2234 return;
2236 InstallCRX(expected_crx_path, INSTALL_NEW);
2240 TEST_F(ExtensionServiceTest, PackExtensionContainingKeyFails) {
2241 InitializeEmptyExtensionService();
2243 base::ScopedTempDir extension_temp_dir;
2244 ASSERT_TRUE(extension_temp_dir.CreateUniqueTempDir());
2245 base::FilePath input_directory = extension_temp_dir.path().AppendASCII("ext");
2246 ASSERT_TRUE(base::CopyDirectory(
2247 data_dir_
2248 .AppendASCII("good")
2249 .AppendASCII("Extensions")
2250 .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
2251 .AppendASCII("1.0.0.0"),
2252 input_directory,
2253 /*recursive=*/true));
2255 base::ScopedTempDir output_temp_dir;
2256 ASSERT_TRUE(output_temp_dir.CreateUniqueTempDir());
2257 base::FilePath output_directory = output_temp_dir.path();
2259 base::FilePath crx_path(output_directory.AppendASCII("ex1.crx"));
2260 base::FilePath privkey_path(output_directory.AppendASCII("privkey.pem"));
2262 // Pack the extension once to get a private key.
2263 scoped_ptr<ExtensionCreator> creator(new ExtensionCreator());
2264 ASSERT_TRUE(creator->Run(input_directory, crx_path, base::FilePath(),
2265 privkey_path, ExtensionCreator::kNoRunFlags))
2266 << creator->error_message();
2267 ASSERT_TRUE(base::PathExists(crx_path));
2268 ASSERT_TRUE(base::PathExists(privkey_path));
2270 base::DeleteFile(crx_path, false);
2271 // Move the pem file into the extension.
2272 base::Move(privkey_path,
2273 input_directory.AppendASCII("privkey.pem"));
2275 // This pack should fail because of the contained private key.
2276 EXPECT_FALSE(creator->Run(input_directory, crx_path, base::FilePath(),
2277 privkey_path, ExtensionCreator::kNoRunFlags));
2278 EXPECT_THAT(creator->error_message(),
2279 testing::ContainsRegex(
2280 "extension includes the key file.*privkey.pem"));
2283 // Test Packaging and installing an extension using an openssl generated key.
2284 // The openssl is generated with the following:
2285 // > openssl genrsa -out privkey.pem 1024
2286 // > openssl pkcs8 -topk8 -nocrypt -in privkey.pem -out privkey_asn1.pem
2287 // The privkey.pem is a PrivateKey, and the pcks8 -topk8 creates a
2288 // PrivateKeyInfo ASN.1 structure, we our RSAPrivateKey expects.
2289 TEST_F(ExtensionServiceTest, PackExtensionOpenSSLKey) {
2290 InitializeEmptyExtensionService();
2291 base::FilePath input_directory = data_dir_
2292 .AppendASCII("good")
2293 .AppendASCII("Extensions")
2294 .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
2295 .AppendASCII("1.0.0.0");
2296 base::FilePath privkey_path(data_dir_.AppendASCII(
2297 "openssl_privkey_asn1.pem"));
2298 ASSERT_TRUE(base::PathExists(privkey_path));
2300 base::ScopedTempDir temp_dir;
2301 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
2302 base::FilePath output_directory = temp_dir.path();
2304 base::FilePath crx_path(output_directory.AppendASCII("ex1.crx"));
2306 scoped_ptr<ExtensionCreator> creator(new ExtensionCreator());
2307 ASSERT_TRUE(creator->Run(input_directory, crx_path, privkey_path,
2308 base::FilePath(), ExtensionCreator::kOverwriteCRX));
2310 InstallCRX(crx_path, INSTALL_NEW);
2313 TEST_F(ExtensionServiceTest, InstallTheme) {
2314 InitializeEmptyExtensionService();
2315 service_->Init();
2317 // A theme.
2318 base::FilePath path = data_dir_.AppendASCII("theme.crx");
2319 InstallCRX(path, INSTALL_NEW);
2320 int pref_count = 0;
2321 ValidatePrefKeyCount(++pref_count);
2322 ValidateIntegerPref(theme_crx, "state", Extension::ENABLED);
2323 ValidateIntegerPref(theme_crx, "location", Manifest::INTERNAL);
2325 // A theme when extensions are disabled. Themes can be installed, even when
2326 // extensions are disabled.
2327 set_extensions_enabled(false);
2328 path = data_dir_.AppendASCII("theme2.crx");
2329 InstallCRX(path, INSTALL_NEW);
2330 ValidatePrefKeyCount(++pref_count);
2331 ValidateIntegerPref(theme2_crx, "state", Extension::ENABLED);
2332 ValidateIntegerPref(theme2_crx, "location", Manifest::INTERNAL);
2334 // A theme with extension elements. Themes cannot have extension elements,
2335 // so any such elements (like content scripts) should be ignored.
2336 set_extensions_enabled(true);
2338 path = data_dir_.AppendASCII("theme_with_extension.crx");
2339 const Extension* extension = InstallCRX(path, INSTALL_NEW);
2340 ValidatePrefKeyCount(++pref_count);
2341 ASSERT_TRUE(extension);
2342 EXPECT_TRUE(extension->is_theme());
2343 EXPECT_EQ(
2345 extensions::ContentScriptsInfo::GetContentScripts(extension).size());
2348 // A theme with image resources missing (misspelt path).
2349 path = data_dir_.AppendASCII("theme_missing_image.crx");
2350 InstallCRX(path, INSTALL_FAILED);
2351 ValidatePrefKeyCount(pref_count);
2354 TEST_F(ExtensionServiceTest, LoadLocalizedTheme) {
2355 // Load.
2356 InitializeEmptyExtensionService();
2357 service_->Init();
2359 base::FilePath extension_path = data_dir_
2360 .AppendASCII("theme_i18n");
2362 extensions::UnpackedInstaller::Create(service_)->Load(extension_path);
2363 base::RunLoop().RunUntilIdle();
2364 EXPECT_EQ(0u, GetErrors().size());
2365 ASSERT_EQ(1u, loaded_.size());
2366 EXPECT_EQ(1u, registry_->enabled_extensions().size());
2367 const Extension* theme = registry_->enabled_extensions().begin()->get();
2368 EXPECT_EQ("name", theme->name());
2369 EXPECT_EQ("description", theme->description());
2371 // Cleanup the "Cached Theme.pak" file. Ideally, this would be installed in a
2372 // temporary directory, but it automatically installs to the extension's
2373 // directory, and we don't want to copy the whole extension for a unittest.
2374 base::FilePath theme_file = extension_path.Append(chrome::kThemePackFilename);
2375 ASSERT_TRUE(base::PathExists(theme_file));
2376 ASSERT_TRUE(base::DeleteFile(theme_file, false)); // Not recursive.
2379 // Tests that we can change the ID of an unpacked extension by adding a key
2380 // to its manifest.
2381 TEST_F(ExtensionServiceTest, UnpackedExtensionCanChangeID) {
2382 InitializeEmptyExtensionService();
2384 base::ScopedTempDir temp;
2385 ASSERT_TRUE(temp.CreateUniqueTempDir());
2387 base::FilePath extension_path = temp.path();
2388 base::FilePath manifest_path =
2389 extension_path.Append(extensions::kManifestFilename);
2390 base::FilePath manifest_no_key = data_dir_.
2391 AppendASCII("unpacked").
2392 AppendASCII("manifest_no_key.json");
2394 base::FilePath manifest_with_key = data_dir_.
2395 AppendASCII("unpacked").
2396 AppendASCII("manifest_with_key.json");
2398 ASSERT_TRUE(base::PathExists(manifest_no_key));
2399 ASSERT_TRUE(base::PathExists(manifest_with_key));
2401 // Load the unpacked extension with no key.
2402 base::CopyFile(manifest_no_key, manifest_path);
2403 extensions::UnpackedInstaller::Create(service_)->Load(extension_path);
2405 base::RunLoop().RunUntilIdle();
2406 EXPECT_EQ(0u, GetErrors().size());
2407 ASSERT_EQ(1u, loaded_.size());
2408 EXPECT_EQ(1u, registry_->enabled_extensions().size());
2410 // Add the key to the manifest.
2411 base::CopyFile(manifest_with_key, manifest_path);
2412 loaded_.clear();
2414 // Reload the extensions.
2415 service_->ReloadExtensionsForTest();
2416 const Extension* extension = service_->GetExtensionById(unpacked, false);
2417 EXPECT_EQ(unpacked, extension->id());
2418 ASSERT_EQ(1u, loaded_.size());
2420 // TODO(jstritar): Right now this just makes sure we don't crash and burn, but
2421 // we should also test that preferences are preserved.
2424 #if defined(OS_POSIX)
2425 TEST_F(ExtensionServiceTest, UnpackedExtensionMayContainSymlinkedFiles) {
2426 base::FilePath source_data_dir = data_dir_.
2427 AppendASCII("unpacked").
2428 AppendASCII("symlinks_allowed");
2430 // Paths to test data files.
2431 base::FilePath source_manifest = source_data_dir.AppendASCII("manifest.json");
2432 ASSERT_TRUE(base::PathExists(source_manifest));
2433 base::FilePath source_icon = source_data_dir.AppendASCII("icon.png");
2434 ASSERT_TRUE(base::PathExists(source_icon));
2436 // Set up the temporary extension directory.
2437 base::ScopedTempDir temp;
2438 ASSERT_TRUE(temp.CreateUniqueTempDir());
2439 base::FilePath extension_path = temp.path();
2440 base::FilePath manifest = extension_path.Append(
2441 extensions::kManifestFilename);
2442 base::FilePath icon_symlink = extension_path.AppendASCII("icon.png");
2443 base::CopyFile(source_manifest, manifest);
2444 base::CreateSymbolicLink(source_icon, icon_symlink);
2446 // Load extension.
2447 InitializeEmptyExtensionService();
2448 extensions::UnpackedInstaller::Create(service_)->Load(extension_path);
2449 base::RunLoop().RunUntilIdle();
2451 EXPECT_TRUE(GetErrors().empty());
2452 ASSERT_EQ(1u, loaded_.size());
2453 EXPECT_EQ(1u, registry_->enabled_extensions().size());
2455 #endif
2457 TEST_F(ExtensionServiceTest, UnpackedExtensionMayNotHaveUnderscore) {
2458 InitializeEmptyExtensionService();
2459 base::FilePath extension_path = data_dir_
2460 .AppendASCII("underscore_name");
2461 extensions::UnpackedInstaller::Create(service_)->Load(extension_path);
2462 base::RunLoop().RunUntilIdle();
2463 EXPECT_EQ(1u, GetErrors().size());
2464 EXPECT_EQ(0u, registry_->enabled_extensions().size());
2467 TEST_F(ExtensionServiceTest, InstallLocalizedTheme) {
2468 InitializeEmptyExtensionService();
2469 service_->Init();
2471 base::FilePath theme_path = data_dir_
2472 .AppendASCII("theme_i18n");
2474 const Extension* theme = PackAndInstallCRX(theme_path, INSTALL_NEW);
2476 EXPECT_EQ(0u, GetErrors().size());
2477 EXPECT_EQ(1u, registry_->enabled_extensions().size());
2478 EXPECT_EQ("name", theme->name());
2479 EXPECT_EQ("description", theme->description());
2482 TEST_F(ExtensionServiceTest, InstallApps) {
2483 InitializeEmptyExtensionService();
2485 // An empty app.
2486 const Extension* app = PackAndInstallCRX(data_dir_.AppendASCII("app1"),
2487 INSTALL_NEW);
2488 int pref_count = 0;
2489 ValidatePrefKeyCount(++pref_count);
2490 ASSERT_EQ(1u, registry_->enabled_extensions().size());
2491 ValidateIntegerPref(app->id(), "state", Extension::ENABLED);
2492 ValidateIntegerPref(app->id(), "location", Manifest::INTERNAL);
2494 // Another app with non-overlapping extent. Should succeed.
2495 PackAndInstallCRX(data_dir_.AppendASCII("app2"), INSTALL_NEW);
2496 ValidatePrefKeyCount(++pref_count);
2498 // A third app whose extent overlaps the first. Should fail.
2499 PackAndInstallCRX(data_dir_.AppendASCII("app3"), INSTALL_FAILED);
2500 ValidatePrefKeyCount(pref_count);
2503 // Tests that file access is OFF by default.
2504 TEST_F(ExtensionServiceTest, DefaultFileAccess) {
2505 InitializeEmptyExtensionService();
2506 const Extension* extension =
2507 PackAndInstallCRX(data_dir_
2508 .AppendASCII("permissions")
2509 .AppendASCII("files"),
2510 INSTALL_NEW);
2511 EXPECT_EQ(0u, GetErrors().size());
2512 EXPECT_EQ(1u, registry_->enabled_extensions().size());
2513 EXPECT_FALSE(
2514 ExtensionPrefs::Get(profile_.get())->AllowFileAccess(extension->id()));
2517 TEST_F(ExtensionServiceTest, UpdateApps) {
2518 InitializeEmptyExtensionService();
2519 base::FilePath extensions_path = data_dir_.AppendASCII("app_update");
2521 // First install v1 of a hosted app.
2522 const Extension* extension =
2523 InstallCRX(extensions_path.AppendASCII("v1.crx"), INSTALL_NEW);
2524 ASSERT_EQ(1u, registry_->enabled_extensions().size());
2525 std::string id = extension->id();
2526 ASSERT_EQ(std::string("1"), extension->version()->GetString());
2528 // Now try updating to v2.
2529 UpdateExtension(id,
2530 extensions_path.AppendASCII("v2.crx"),
2531 ENABLED);
2532 ASSERT_EQ(std::string("2"),
2533 service_->GetExtensionById(id, false)->version()->GetString());
2536 // Verifies that the NTP page and launch ordinals are kept when updating apps.
2537 TEST_F(ExtensionServiceTest, UpdateAppsRetainOrdinals) {
2538 InitializeEmptyExtensionService();
2539 AppSorting* sorting = ExtensionPrefs::Get(profile_.get())->app_sorting();
2540 base::FilePath extensions_path = data_dir_.AppendASCII("app_update");
2542 // First install v1 of a hosted app.
2543 const Extension* extension =
2544 InstallCRX(extensions_path.AppendASCII("v1.crx"), INSTALL_NEW);
2545 ASSERT_EQ(1u, registry_->enabled_extensions().size());
2546 std::string id = extension->id();
2547 ASSERT_EQ(std::string("1"), extension->version()->GetString());
2549 // Modify the ordinals so we can distinguish them from the defaults.
2550 syncer::StringOrdinal new_page_ordinal =
2551 sorting->GetPageOrdinal(id).CreateAfter();
2552 syncer::StringOrdinal new_launch_ordinal =
2553 sorting->GetAppLaunchOrdinal(id).CreateBefore();
2555 sorting->SetPageOrdinal(id, new_page_ordinal);
2556 sorting->SetAppLaunchOrdinal(id, new_launch_ordinal);
2558 // Now try updating to v2.
2559 UpdateExtension(id, extensions_path.AppendASCII("v2.crx"), ENABLED);
2560 ASSERT_EQ(std::string("2"),
2561 service_->GetExtensionById(id, false)->version()->GetString());
2563 // Verify that the ordinals match.
2564 ASSERT_TRUE(new_page_ordinal.Equals(sorting->GetPageOrdinal(id)));
2565 ASSERT_TRUE(new_launch_ordinal.Equals(sorting->GetAppLaunchOrdinal(id)));
2568 // Ensures that the CWS has properly initialized ordinals.
2569 TEST_F(ExtensionServiceTest, EnsureCWSOrdinalsInitialized) {
2570 InitializeEmptyExtensionService();
2571 service_->component_loader()->Add(
2572 IDR_WEBSTORE_MANIFEST, base::FilePath(FILE_PATH_LITERAL("web_store")));
2573 service_->Init();
2575 AppSorting* sorting = ExtensionPrefs::Get(profile_.get())->app_sorting();
2576 EXPECT_TRUE(
2577 sorting->GetPageOrdinal(extension_misc::kWebStoreAppId).IsValid());
2578 EXPECT_TRUE(
2579 sorting->GetAppLaunchOrdinal(extension_misc::kWebStoreAppId).IsValid());
2582 TEST_F(ExtensionServiceTest, InstallAppsWithUnlimitedStorage) {
2583 InitializeEmptyExtensionService();
2584 EXPECT_TRUE(registry_->enabled_extensions().is_empty());
2586 int pref_count = 0;
2588 // Install app1 with unlimited storage.
2589 const Extension* extension =
2590 PackAndInstallCRX(data_dir_.AppendASCII("app1"), INSTALL_NEW);
2591 ValidatePrefKeyCount(++pref_count);
2592 ASSERT_EQ(1u, registry_->enabled_extensions().size());
2593 const std::string id1 = extension->id();
2594 EXPECT_TRUE(extension->HasAPIPermission(
2595 APIPermission::kUnlimitedStorage));
2596 EXPECT_TRUE(extension->web_extent().MatchesURL(
2597 extensions::AppLaunchInfo::GetFullLaunchURL(extension)));
2598 const GURL origin1(
2599 extensions::AppLaunchInfo::GetFullLaunchURL(extension).GetOrigin());
2600 EXPECT_TRUE(profile_->GetExtensionSpecialStoragePolicy()->
2601 IsStorageUnlimited(origin1));
2603 // Install app2 from the same origin with unlimited storage.
2604 extension = PackAndInstallCRX(data_dir_.AppendASCII("app2"), INSTALL_NEW);
2605 ValidatePrefKeyCount(++pref_count);
2606 ASSERT_EQ(2u, registry_->enabled_extensions().size());
2607 const std::string id2 = extension->id();
2608 EXPECT_TRUE(extension->HasAPIPermission(
2609 APIPermission::kUnlimitedStorage));
2610 EXPECT_TRUE(extension->web_extent().MatchesURL(
2611 extensions::AppLaunchInfo::GetFullLaunchURL(extension)));
2612 const GURL origin2(
2613 extensions::AppLaunchInfo::GetFullLaunchURL(extension).GetOrigin());
2614 EXPECT_EQ(origin1, origin2);
2615 EXPECT_TRUE(profile_->GetExtensionSpecialStoragePolicy()->
2616 IsStorageUnlimited(origin2));
2619 // Uninstall one of them, unlimited storage should still be granted
2620 // to the origin.
2621 UninstallExtension(id1, false);
2622 EXPECT_EQ(1u, registry_->enabled_extensions().size());
2623 EXPECT_TRUE(profile_->GetExtensionSpecialStoragePolicy()->
2624 IsStorageUnlimited(origin1));
2626 // Uninstall the other, unlimited storage should be revoked.
2627 UninstallExtension(id2, false);
2628 EXPECT_EQ(0u, registry_->enabled_extensions().size());
2629 EXPECT_FALSE(profile_->GetExtensionSpecialStoragePolicy()->
2630 IsStorageUnlimited(origin2));
2633 TEST_F(ExtensionServiceTest, InstallAppsAndCheckStorageProtection) {
2634 InitializeEmptyExtensionService();
2635 EXPECT_TRUE(registry_->enabled_extensions().is_empty());
2637 int pref_count = 0;
2639 const Extension* extension =
2640 PackAndInstallCRX(data_dir_.AppendASCII("app1"), INSTALL_NEW);
2641 ValidatePrefKeyCount(++pref_count);
2642 ASSERT_EQ(1u, registry_->enabled_extensions().size());
2643 EXPECT_TRUE(extension->is_app());
2644 const std::string id1 = extension->id();
2645 const GURL origin1(
2646 extensions::AppLaunchInfo::GetFullLaunchURL(extension).GetOrigin());
2647 EXPECT_TRUE(profile_->GetExtensionSpecialStoragePolicy()->
2648 IsStorageProtected(origin1));
2650 // App 4 has a different origin (maps.google.com).
2651 extension = PackAndInstallCRX(data_dir_.AppendASCII("app4"), INSTALL_NEW);
2652 ValidatePrefKeyCount(++pref_count);
2653 ASSERT_EQ(2u, registry_->enabled_extensions().size());
2654 const std::string id2 = extension->id();
2655 const GURL origin2(
2656 extensions::AppLaunchInfo::GetFullLaunchURL(extension).GetOrigin());
2657 ASSERT_NE(origin1, origin2);
2658 EXPECT_TRUE(profile_->GetExtensionSpecialStoragePolicy()->
2659 IsStorageProtected(origin2));
2661 UninstallExtension(id1, false);
2662 EXPECT_EQ(1u, registry_->enabled_extensions().size());
2664 UninstallExtension(id2, false);
2666 EXPECT_TRUE(registry_->enabled_extensions().is_empty());
2667 EXPECT_FALSE(profile_->GetExtensionSpecialStoragePolicy()->
2668 IsStorageProtected(origin1));
2669 EXPECT_FALSE(profile_->GetExtensionSpecialStoragePolicy()->
2670 IsStorageProtected(origin2));
2673 // Test that when an extension version is reinstalled, nothing happens.
2674 TEST_F(ExtensionServiceTest, Reinstall) {
2675 InitializeEmptyExtensionService();
2677 // A simple extension that should install without error.
2678 base::FilePath path = data_dir_.AppendASCII("good.crx");
2679 InstallCRX(path, INSTALL_NEW);
2681 ValidatePrefKeyCount(1);
2682 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
2683 ValidateIntegerPref(good_crx, "location", Manifest::INTERNAL);
2685 // Reinstall the same version, it should overwrite the previous one.
2686 InstallCRX(path, INSTALL_UPDATED);
2688 ValidatePrefKeyCount(1);
2689 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
2690 ValidateIntegerPref(good_crx, "location", Manifest::INTERNAL);
2693 // Test that we can determine if extensions came from the
2694 // Chrome web store.
2695 TEST_F(ExtensionServiceTest, FromWebStore) {
2696 InitializeEmptyExtensionService();
2698 // A simple extension that should install without error.
2699 base::FilePath path = data_dir_.AppendASCII("good.crx");
2700 // Not from web store.
2701 const Extension* extension = InstallCRX(path, INSTALL_NEW);
2702 std::string id = extension->id();
2704 ValidatePrefKeyCount(1);
2705 ASSERT_TRUE(ValidateBooleanPref(good_crx, "from_webstore", false));
2706 ASSERT_FALSE(extension->from_webstore());
2708 // Test install from web store.
2709 InstallCRXFromWebStore(path, INSTALL_UPDATED); // From web store.
2711 ValidatePrefKeyCount(1);
2712 ASSERT_TRUE(ValidateBooleanPref(good_crx, "from_webstore", true));
2714 // Reload so extension gets reinitialized with new value.
2715 service_->ReloadExtensionsForTest();
2716 extension = service_->GetExtensionById(id, false);
2717 ASSERT_TRUE(extension->from_webstore());
2719 // Upgrade to version 2.0
2720 path = data_dir_.AppendASCII("good2.crx");
2721 UpdateExtension(good_crx, path, ENABLED);
2722 ValidatePrefKeyCount(1);
2723 ASSERT_TRUE(ValidateBooleanPref(good_crx, "from_webstore", true));
2726 // Test upgrading a signed extension.
2727 TEST_F(ExtensionServiceTest, UpgradeSignedGood) {
2728 InitializeEmptyExtensionService();
2730 base::FilePath path = data_dir_.AppendASCII("good.crx");
2731 const Extension* extension = InstallCRX(path, INSTALL_NEW);
2732 std::string id = extension->id();
2734 ASSERT_EQ("1.0.0.0", extension->version()->GetString());
2735 ASSERT_EQ(0u, GetErrors().size());
2737 // Upgrade to version 1.0.0.1.
2738 // Also test that the extension's old and new title are correctly retrieved.
2739 path = data_dir_.AppendASCII("good2.crx");
2740 InstallCRX(path, INSTALL_UPDATED, Extension::NO_FLAGS, "My extension 1");
2741 extension = service_->GetExtensionById(id, false);
2743 ASSERT_EQ("1.0.0.1", extension->version()->GetString());
2744 ASSERT_EQ("My updated extension 1", extension->name());
2745 ASSERT_EQ(0u, GetErrors().size());
2748 // Test upgrading a signed extension with a bad signature.
2749 TEST_F(ExtensionServiceTest, UpgradeSignedBad) {
2750 InitializeEmptyExtensionService();
2752 base::FilePath path = data_dir_.AppendASCII("good.crx");
2753 InstallCRX(path, INSTALL_NEW);
2755 // Try upgrading with a bad signature. This should fail during the unpack,
2756 // because the key will not match the signature.
2757 path = data_dir_.AppendASCII("bad_signature.crx");
2758 InstallCRX(path, INSTALL_FAILED);
2761 // Test a normal update via the UpdateExtension API
2762 TEST_F(ExtensionServiceTest, UpdateExtension) {
2763 InitializeEmptyExtensionService();
2765 base::FilePath path = data_dir_.AppendASCII("good.crx");
2767 const Extension* good = InstallCRX(path, INSTALL_NEW);
2768 ASSERT_EQ("1.0.0.0", good->VersionString());
2769 ASSERT_EQ(good_crx, good->id());
2771 path = data_dir_.AppendASCII("good2.crx");
2772 UpdateExtension(good_crx, path, ENABLED);
2773 ASSERT_EQ("1.0.0.1",
2774 service_->GetExtensionById(good_crx, false)->
2775 version()->GetString());
2778 // Extensions should not be updated during browser shutdown.
2779 TEST_F(ExtensionServiceTest, UpdateExtensionDuringShutdown) {
2780 InitializeEmptyExtensionService();
2782 // Install an extension.
2783 base::FilePath path = data_dir_.AppendASCII("good.crx");
2784 const Extension* good = InstallCRX(path, INSTALL_NEW);
2785 ASSERT_EQ(good_crx, good->id());
2787 // Simulate shutdown.
2788 service_->set_browser_terminating_for_test(true);
2790 // Update should fail and extension should not be updated.
2791 path = data_dir_.AppendASCII("good2.crx");
2792 bool updated = service_->UpdateExtension(good_crx, path, true, NULL);
2793 ASSERT_FALSE(updated);
2794 ASSERT_EQ("1.0.0.0",
2795 service_->GetExtensionById(good_crx, false)->
2796 version()->GetString());
2799 // Test updating a not-already-installed extension - this should fail
2800 TEST_F(ExtensionServiceTest, UpdateNotInstalledExtension) {
2801 InitializeEmptyExtensionService();
2803 base::FilePath path = data_dir_.AppendASCII("good.crx");
2804 UpdateExtension(good_crx, path, UPDATED);
2805 base::RunLoop().RunUntilIdle();
2807 ASSERT_EQ(0u, registry_->enabled_extensions().size());
2808 ASSERT_FALSE(installed_);
2809 ASSERT_EQ(0u, loaded_.size());
2812 // Makes sure you can't downgrade an extension via UpdateExtension
2813 TEST_F(ExtensionServiceTest, UpdateWillNotDowngrade) {
2814 InitializeEmptyExtensionService();
2816 base::FilePath path = data_dir_.AppendASCII("good2.crx");
2818 const Extension* good = InstallCRX(path, INSTALL_NEW);
2819 ASSERT_EQ("1.0.0.1", good->VersionString());
2820 ASSERT_EQ(good_crx, good->id());
2822 // Change path from good2.crx -> good.crx
2823 path = data_dir_.AppendASCII("good.crx");
2824 UpdateExtension(good_crx, path, FAILED);
2825 ASSERT_EQ("1.0.0.1",
2826 service_->GetExtensionById(good_crx, false)->
2827 version()->GetString());
2830 // Make sure calling update with an identical version does nothing
2831 TEST_F(ExtensionServiceTest, UpdateToSameVersionIsNoop) {
2832 InitializeEmptyExtensionService();
2834 base::FilePath path = data_dir_.AppendASCII("good.crx");
2836 const Extension* good = InstallCRX(path, INSTALL_NEW);
2837 ASSERT_EQ(good_crx, good->id());
2838 UpdateExtension(good_crx, path, FAILED_SILENTLY);
2841 // Tests that updating an extension does not clobber old state.
2842 TEST_F(ExtensionServiceTest, UpdateExtensionPreservesState) {
2843 InitializeEmptyExtensionService();
2845 base::FilePath path = data_dir_.AppendASCII("good.crx");
2847 const Extension* good = InstallCRX(path, INSTALL_NEW);
2848 ASSERT_EQ("1.0.0.0", good->VersionString());
2849 ASSERT_EQ(good_crx, good->id());
2851 // Disable it and allow it to run in incognito. These settings should carry
2852 // over to the updated version.
2853 service_->DisableExtension(good->id(), Extension::DISABLE_USER_ACTION);
2854 extensions::util::SetIsIncognitoEnabled(good->id(), profile_.get(), true);
2855 ExtensionPrefs::Get(profile_.get())
2856 ->SetDidExtensionEscalatePermissions(good, true);
2858 path = data_dir_.AppendASCII("good2.crx");
2859 UpdateExtension(good_crx, path, INSTALLED);
2860 ASSERT_EQ(1u, registry_->disabled_extensions().size());
2861 const Extension* good2 = service_->GetExtensionById(good_crx, true);
2862 ASSERT_EQ("1.0.0.1", good2->version()->GetString());
2863 EXPECT_TRUE(extensions::util::IsIncognitoEnabled(
2864 good2->id(), profile_.get()));
2865 EXPECT_TRUE(ExtensionPrefs::Get(profile_.get())
2866 ->DidExtensionEscalatePermissions(good2->id()));
2869 // Tests that updating preserves extension location.
2870 TEST_F(ExtensionServiceTest, UpdateExtensionPreservesLocation) {
2871 InitializeEmptyExtensionService();
2873 base::FilePath path = data_dir_.AppendASCII("good.crx");
2875 const Extension* good =
2876 InstallCRXWithLocation(path, Manifest::EXTERNAL_PREF, INSTALL_NEW);
2878 ASSERT_EQ("1.0.0.0", good->VersionString());
2879 ASSERT_EQ(good_crx, good->id());
2881 path = data_dir_.AppendASCII("good2.crx");
2882 UpdateExtension(good_crx, path, ENABLED);
2883 const Extension* good2 = service_->GetExtensionById(good_crx, false);
2884 ASSERT_EQ("1.0.0.1", good2->version()->GetString());
2885 EXPECT_EQ(good2->location(), Manifest::EXTERNAL_PREF);
2888 // Makes sure that LOAD extension types can downgrade.
2889 TEST_F(ExtensionServiceTest, LoadExtensionsCanDowngrade) {
2890 InitializeEmptyExtensionService();
2892 base::ScopedTempDir temp;
2893 ASSERT_TRUE(temp.CreateUniqueTempDir());
2895 // We'll write the extension manifest dynamically to a temporary path
2896 // to make it easier to change the version number.
2897 base::FilePath extension_path = temp.path();
2898 base::FilePath manifest_path =
2899 extension_path.Append(extensions::kManifestFilename);
2900 ASSERT_FALSE(base::PathExists(manifest_path));
2902 // Start with version 2.0.
2903 base::DictionaryValue manifest;
2904 manifest.SetString("version", "2.0");
2905 manifest.SetString("name", "LOAD Downgrade Test");
2906 manifest.SetInteger("manifest_version", 2);
2908 JSONFileValueSerializer serializer(manifest_path);
2909 ASSERT_TRUE(serializer.Serialize(manifest));
2911 extensions::UnpackedInstaller::Create(service_)->Load(extension_path);
2912 base::RunLoop().RunUntilIdle();
2914 EXPECT_EQ(0u, GetErrors().size());
2915 ASSERT_EQ(1u, loaded_.size());
2916 EXPECT_EQ(Manifest::UNPACKED, loaded_[0]->location());
2917 EXPECT_EQ(1u, registry_->enabled_extensions().size());
2918 EXPECT_EQ("2.0", loaded_[0]->VersionString());
2920 // Now set the version number to 1.0, reload the extensions and verify that
2921 // the downgrade was accepted.
2922 manifest.SetString("version", "1.0");
2923 ASSERT_TRUE(serializer.Serialize(manifest));
2925 extensions::UnpackedInstaller::Create(service_)->Load(extension_path);
2926 base::RunLoop().RunUntilIdle();
2928 EXPECT_EQ(0u, GetErrors().size());
2929 ASSERT_EQ(1u, loaded_.size());
2930 EXPECT_EQ(Manifest::UNPACKED, loaded_[0]->location());
2931 EXPECT_EQ(1u, registry_->enabled_extensions().size());
2932 EXPECT_EQ("1.0", loaded_[0]->VersionString());
2935 #if !defined(OS_CHROMEOS)
2936 // LOAD extensions with plugins require approval.
2937 TEST_F(ExtensionServiceTest, LoadExtensionsWithPlugins) {
2938 base::FilePath extension_with_plugin_path = good1_path();
2939 base::FilePath extension_no_plugin_path = good2_path();
2941 InitPluginService();
2942 InitializeEmptyExtensionService();
2943 InitializeProcessManager();
2944 service_->set_show_extensions_prompts(true);
2946 // Start by canceling any install prompts.
2947 CommandLine::ForCurrentProcess()->AppendSwitchASCII(
2948 switches::kAppsGalleryInstallAutoConfirmForTests,
2949 "cancel");
2951 // The extension that has a plugin should not install.
2952 extensions::UnpackedInstaller::Create(service_)->Load(
2953 extension_with_plugin_path);
2954 base::RunLoop().RunUntilIdle();
2955 EXPECT_EQ(0u, GetErrors().size());
2956 EXPECT_EQ(0u, loaded_.size());
2957 EXPECT_EQ(0u, registry_->enabled_extensions().size());
2958 EXPECT_EQ(0u, registry_->disabled_extensions().size());
2960 // But the extension with no plugin should since there's no prompt.
2961 ExtensionErrorReporter::GetInstance()->ClearErrors();
2962 extensions::UnpackedInstaller::Create(service_)->Load(
2963 extension_no_plugin_path);
2964 base::RunLoop().RunUntilIdle();
2965 EXPECT_EQ(0u, GetErrors().size());
2966 EXPECT_EQ(1u, loaded_.size());
2967 EXPECT_EQ(1u, registry_->enabled_extensions().size());
2968 EXPECT_EQ(0u, registry_->disabled_extensions().size());
2969 EXPECT_TRUE(registry_->enabled_extensions().Contains(good2));
2971 // The plugin extension should install if we accept the dialog.
2972 CommandLine::ForCurrentProcess()->AppendSwitchASCII(
2973 switches::kAppsGalleryInstallAutoConfirmForTests,
2974 "accept");
2976 ExtensionErrorReporter::GetInstance()->ClearErrors();
2977 extensions::UnpackedInstaller::Create(service_)->Load(
2978 extension_with_plugin_path);
2979 base::RunLoop().RunUntilIdle();
2980 EXPECT_EQ(0u, GetErrors().size());
2981 EXPECT_EQ(2u, loaded_.size());
2982 EXPECT_EQ(2u, registry_->enabled_extensions().size());
2983 EXPECT_EQ(0u, registry_->disabled_extensions().size());
2984 EXPECT_TRUE(registry_->enabled_extensions().Contains(good1));
2985 EXPECT_TRUE(registry_->enabled_extensions().Contains(good2));
2987 // Make sure the granted permissions have been setup.
2988 scoped_refptr<PermissionSet> permissions(
2989 ExtensionPrefs::Get(profile_.get())->GetGrantedPermissions(good1));
2990 EXPECT_FALSE(permissions->IsEmpty());
2991 EXPECT_TRUE(permissions->HasEffectiveFullAccess());
2992 EXPECT_FALSE(permissions->apis().empty());
2993 EXPECT_TRUE(permissions->HasAPIPermission(APIPermission::kPlugin));
2995 // We should be able to reload the extension without getting another prompt.
2996 loaded_.clear();
2997 CommandLine::ForCurrentProcess()->AppendSwitchASCII(
2998 switches::kAppsGalleryInstallAutoConfirmForTests,
2999 "cancel");
3001 service_->ReloadExtension(good1);
3002 base::RunLoop().RunUntilIdle();
3003 EXPECT_EQ(1u, loaded_.size());
3004 EXPECT_EQ(2u, registry_->enabled_extensions().size());
3005 EXPECT_EQ(0u, registry_->disabled_extensions().size());
3007 #endif // !defined(OS_CHROMEOS)
3009 namespace {
3011 bool IsExtension(const Extension* extension) {
3012 return extension->GetType() == Manifest::TYPE_EXTENSION;
3015 } // namespace
3017 // Test adding a pending extension.
3018 TEST_F(ExtensionServiceTest, AddPendingExtensionFromSync) {
3019 InitializeEmptyExtensionService();
3021 const std::string kFakeId(all_zero);
3022 const GURL kFakeUpdateURL("http:://fake.update/url");
3023 const bool kFakeInstallSilently(true);
3025 EXPECT_TRUE(service_->pending_extension_manager()->AddFromSync(
3026 kFakeId, kFakeUpdateURL, &IsExtension,
3027 kFakeInstallSilently));
3029 const extensions::PendingExtensionInfo* pending_extension_info;
3030 ASSERT_TRUE((pending_extension_info = service_->pending_extension_manager()->
3031 GetById(kFakeId)));
3032 EXPECT_EQ(kFakeUpdateURL, pending_extension_info->update_url());
3033 EXPECT_EQ(&IsExtension, pending_extension_info->should_allow_install_);
3034 EXPECT_EQ(kFakeInstallSilently, pending_extension_info->install_silently());
3037 namespace {
3038 const char kGoodId[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
3039 const char kGoodUpdateURL[] = "http://good.update/url";
3040 const bool kGoodIsFromSync = true;
3041 const bool kGoodInstallSilently = true;
3042 } // namespace
3044 // Test updating a pending extension.
3045 TEST_F(ExtensionServiceTest, UpdatePendingExtension) {
3046 InitializeEmptyExtensionService();
3047 EXPECT_TRUE(service_->pending_extension_manager()->AddFromSync(
3048 kGoodId, GURL(kGoodUpdateURL), &IsExtension,
3049 kGoodInstallSilently));
3050 EXPECT_TRUE(service_->pending_extension_manager()->IsIdPending(kGoodId));
3052 base::FilePath path = data_dir_.AppendASCII("good.crx");
3053 UpdateExtension(kGoodId, path, ENABLED);
3055 EXPECT_FALSE(service_->pending_extension_manager()->IsIdPending(kGoodId));
3057 const Extension* extension = service_->GetExtensionById(kGoodId, true);
3058 ASSERT_TRUE(extension);
3061 namespace {
3063 bool IsTheme(const Extension* extension) {
3064 return extension->is_theme();
3067 } // namespace
3069 // Test updating a pending theme.
3070 // Disabled due to ASAN failure. http://crbug.com/108320
3071 TEST_F(ExtensionServiceTest, DISABLED_UpdatePendingTheme) {
3072 InitializeEmptyExtensionService();
3073 EXPECT_TRUE(service_->pending_extension_manager()->AddFromSync(
3074 theme_crx, GURL(), &IsTheme, false));
3075 EXPECT_TRUE(service_->pending_extension_manager()->IsIdPending(theme_crx));
3077 base::FilePath path = data_dir_.AppendASCII("theme.crx");
3078 UpdateExtension(theme_crx, path, ENABLED);
3080 EXPECT_FALSE(service_->pending_extension_manager()->IsIdPending(theme_crx));
3082 const Extension* extension = service_->GetExtensionById(theme_crx, true);
3083 ASSERT_TRUE(extension);
3085 EXPECT_FALSE(ExtensionPrefs::Get(profile_.get())
3086 ->IsExtensionDisabled(extension->id()));
3087 EXPECT_TRUE(service_->IsExtensionEnabled(theme_crx));
3090 #if defined(OS_CHROMEOS)
3091 // Always fails on ChromeOS: http://crbug.com/79737
3092 #define MAYBE_UpdatePendingExternalCrx DISABLED_UpdatePendingExternalCrx
3093 #else
3094 #define MAYBE_UpdatePendingExternalCrx UpdatePendingExternalCrx
3095 #endif
3096 // Test updating a pending CRX as if the source is an external extension
3097 // with an update URL. In this case we don't know if the CRX is a theme
3098 // or not.
3099 TEST_F(ExtensionServiceTest, MAYBE_UpdatePendingExternalCrx) {
3100 InitializeEmptyExtensionService();
3101 EXPECT_TRUE(service_->pending_extension_manager()->AddFromExternalUpdateUrl(
3102 theme_crx,
3103 std::string(),
3104 GURL(),
3105 Manifest::EXTERNAL_PREF_DOWNLOAD,
3106 Extension::NO_FLAGS,
3107 false));
3109 EXPECT_TRUE(service_->pending_extension_manager()->IsIdPending(theme_crx));
3111 base::FilePath path = data_dir_.AppendASCII("theme.crx");
3112 UpdateExtension(theme_crx, path, ENABLED);
3114 EXPECT_FALSE(service_->pending_extension_manager()->IsIdPending(theme_crx));
3116 const Extension* extension = service_->GetExtensionById(theme_crx, true);
3117 ASSERT_TRUE(extension);
3119 EXPECT_FALSE(ExtensionPrefs::Get(profile_.get())
3120 ->IsExtensionDisabled(extension->id()));
3121 EXPECT_TRUE(service_->IsExtensionEnabled(extension->id()));
3122 EXPECT_FALSE(extensions::util::IsIncognitoEnabled(extension->id(),
3123 profile_.get()));
3126 // Test updating a pending CRX as if the source is an external extension
3127 // with an update URL. The external update should overwrite a sync update,
3128 // but a sync update should not overwrite a non-sync update.
3129 TEST_F(ExtensionServiceTest, UpdatePendingExternalCrxWinsOverSync) {
3130 InitializeEmptyExtensionService();
3132 // Add a crx to be installed from the update mechanism.
3133 EXPECT_TRUE(service_->pending_extension_manager()->AddFromSync(
3134 kGoodId, GURL(kGoodUpdateURL), &IsExtension,
3135 kGoodInstallSilently));
3137 // Check that there is a pending crx, with is_from_sync set to true.
3138 const extensions::PendingExtensionInfo* pending_extension_info;
3139 ASSERT_TRUE((pending_extension_info = service_->pending_extension_manager()->
3140 GetById(kGoodId)));
3141 EXPECT_TRUE(pending_extension_info->is_from_sync());
3143 // Add a crx to be updated, with the same ID, from a non-sync source.
3144 EXPECT_TRUE(service_->pending_extension_manager()->AddFromExternalUpdateUrl(
3145 kGoodId,
3146 std::string(),
3147 GURL(kGoodUpdateURL),
3148 Manifest::EXTERNAL_PREF_DOWNLOAD,
3149 Extension::NO_FLAGS,
3150 false));
3152 // Check that there is a pending crx, with is_from_sync set to false.
3153 ASSERT_TRUE((pending_extension_info = service_->pending_extension_manager()->
3154 GetById(kGoodId)));
3155 EXPECT_FALSE(pending_extension_info->is_from_sync());
3156 EXPECT_EQ(Manifest::EXTERNAL_PREF_DOWNLOAD,
3157 pending_extension_info->install_source());
3159 // Add a crx to be installed from the update mechanism.
3160 EXPECT_FALSE(service_->pending_extension_manager()->AddFromSync(
3161 kGoodId, GURL(kGoodUpdateURL), &IsExtension,
3162 kGoodInstallSilently));
3164 // Check that the external, non-sync update was not overridden.
3165 ASSERT_TRUE((pending_extension_info = service_->pending_extension_manager()->
3166 GetById(kGoodId)));
3167 EXPECT_FALSE(pending_extension_info->is_from_sync());
3168 EXPECT_EQ(Manifest::EXTERNAL_PREF_DOWNLOAD,
3169 pending_extension_info->install_source());
3172 // Updating a theme should fail if the updater is explicitly told that
3173 // the CRX is not a theme.
3174 TEST_F(ExtensionServiceTest, UpdatePendingCrxThemeMismatch) {
3175 InitializeEmptyExtensionService();
3176 EXPECT_TRUE(service_->pending_extension_manager()->AddFromSync(
3177 theme_crx, GURL(), &IsExtension, true));
3179 EXPECT_TRUE(service_->pending_extension_manager()->IsIdPending(theme_crx));
3181 base::FilePath path = data_dir_.AppendASCII("theme.crx");
3182 UpdateExtension(theme_crx, path, FAILED_SILENTLY);
3184 EXPECT_FALSE(service_->pending_extension_manager()->IsIdPending(theme_crx));
3186 const Extension* extension = service_->GetExtensionById(theme_crx, true);
3187 ASSERT_FALSE(extension);
3190 // TODO(akalin): Test updating a pending extension non-silently once
3191 // we can mock out ExtensionInstallUI and inject our version into
3192 // UpdateExtension().
3194 // Test updating a pending extension which fails the should-install test.
3195 TEST_F(ExtensionServiceTest, UpdatePendingExtensionFailedShouldInstallTest) {
3196 InitializeEmptyExtensionService();
3197 // Add pending extension with a flipped is_theme.
3198 EXPECT_TRUE(service_->pending_extension_manager()->AddFromSync(
3199 kGoodId, GURL(kGoodUpdateURL), &IsTheme, kGoodInstallSilently));
3200 EXPECT_TRUE(service_->pending_extension_manager()->IsIdPending(kGoodId));
3202 base::FilePath path = data_dir_.AppendASCII("good.crx");
3203 UpdateExtension(kGoodId, path, UPDATED);
3205 // TODO(akalin): Figure out how to check that the extensions
3206 // directory is cleaned up properly in OnExtensionInstalled().
3208 EXPECT_FALSE(service_->pending_extension_manager()->IsIdPending(kGoodId));
3211 // TODO(akalin): Figure out how to test that installs of pending
3212 // unsyncable extensions are blocked.
3214 // Test updating a pending extension for one that is not pending.
3215 TEST_F(ExtensionServiceTest, UpdatePendingExtensionNotPending) {
3216 InitializeEmptyExtensionService();
3218 base::FilePath path = data_dir_.AppendASCII("good.crx");
3219 UpdateExtension(kGoodId, path, UPDATED);
3221 EXPECT_FALSE(service_->pending_extension_manager()->IsIdPending(kGoodId));
3224 // Test updating a pending extension for one that is already
3225 // installed.
3226 TEST_F(ExtensionServiceTest, UpdatePendingExtensionAlreadyInstalled) {
3227 InitializeEmptyExtensionService();
3229 base::FilePath path = data_dir_.AppendASCII("good.crx");
3230 const Extension* good = InstallCRX(path, INSTALL_NEW);
3231 ASSERT_EQ(1u, registry_->enabled_extensions().size());
3233 EXPECT_FALSE(good->is_theme());
3235 // Use AddExtensionImpl() as AddFrom*() would balk.
3236 service_->pending_extension_manager()->AddExtensionImpl(
3237 good->id(),
3238 std::string(),
3239 extensions::ManifestURL::GetUpdateURL(good),
3240 Version(),
3241 &IsExtension,
3242 kGoodIsFromSync,
3243 kGoodInstallSilently,
3244 Manifest::INTERNAL,
3245 Extension::NO_FLAGS,
3246 false);
3247 UpdateExtension(good->id(), path, ENABLED);
3249 EXPECT_FALSE(service_->pending_extension_manager()->IsIdPending(kGoodId));
3252 #if defined(ENABLE_BLACKLIST_TESTS)
3253 // Tests blacklisting then unblacklisting extensions after the service has been
3254 // initialized.
3255 TEST_F(ExtensionServiceTest, SetUnsetBlacklistInPrefs) {
3256 extensions::TestBlacklist test_blacklist;
3257 // A profile with 3 extensions installed: good0, good1, and good2.
3258 InitializeGoodInstalledExtensionService();
3259 test_blacklist.Attach(service_->blacklist_);
3260 service_->Init();
3262 const extensions::ExtensionSet& enabled_extensions =
3263 registry_->enabled_extensions();
3264 const extensions::ExtensionSet& blacklisted_extensions =
3265 registry_->blacklisted_extensions();
3267 EXPECT_TRUE(enabled_extensions.Contains(good0) &&
3268 !blacklisted_extensions.Contains(good0));
3269 EXPECT_TRUE(enabled_extensions.Contains(good1) &&
3270 !blacklisted_extensions.Contains(good1));
3271 EXPECT_TRUE(enabled_extensions.Contains(good2) &&
3272 !blacklisted_extensions.Contains(good2));
3274 EXPECT_FALSE(IsPrefExist(good0, "blacklist"));
3275 EXPECT_FALSE(IsPrefExist(good1, "blacklist"));
3276 EXPECT_FALSE(IsPrefExist(good2, "blacklist"));
3277 EXPECT_FALSE(IsPrefExist("invalid_id", "blacklist"));
3279 // Blacklist good0 and good1 (and an invalid extension ID).
3280 test_blacklist.SetBlacklistState(
3281 good0, extensions::BLACKLISTED_MALWARE, true);
3282 test_blacklist.SetBlacklistState(
3283 good1, extensions::BLACKLISTED_MALWARE, true);
3284 test_blacklist.SetBlacklistState(
3285 "invalid_id", extensions::BLACKLISTED_MALWARE, true);
3286 base::RunLoop().RunUntilIdle();
3288 EXPECT_TRUE(!enabled_extensions.Contains(good0) &&
3289 blacklisted_extensions.Contains(good0));
3290 EXPECT_TRUE(!enabled_extensions.Contains(good1) &&
3291 blacklisted_extensions.Contains(good1));
3292 EXPECT_TRUE(enabled_extensions.Contains(good2) &&
3293 !blacklisted_extensions.Contains(good2));
3295 EXPECT_TRUE(ValidateBooleanPref(good0, "blacklist", true));
3296 EXPECT_TRUE(ValidateBooleanPref(good1, "blacklist", true));
3297 EXPECT_FALSE(IsPrefExist(good2, "blacklist"));
3298 EXPECT_FALSE(IsPrefExist("invalid_id", "blacklist"));
3300 // Un-blacklist good1 and blacklist good2.
3301 test_blacklist.Clear(false);
3302 test_blacklist.SetBlacklistState(
3303 good0, extensions::BLACKLISTED_MALWARE, true);
3304 test_blacklist.SetBlacklistState(
3305 good2, extensions::BLACKLISTED_MALWARE, true);
3306 test_blacklist.SetBlacklistState(
3307 "invalid_id", extensions::BLACKLISTED_MALWARE, true);
3308 base::RunLoop().RunUntilIdle();
3310 EXPECT_TRUE(!enabled_extensions.Contains(good0) &&
3311 blacklisted_extensions.Contains(good0));
3312 EXPECT_TRUE(enabled_extensions.Contains(good1) &&
3313 !blacklisted_extensions.Contains(good1));
3314 EXPECT_TRUE(!enabled_extensions.Contains(good2) &&
3315 blacklisted_extensions.Contains(good2));
3317 EXPECT_TRUE(ValidateBooleanPref(good0, "blacklist", true));
3318 EXPECT_FALSE(IsPrefExist(good1, "blacklist"));
3319 EXPECT_TRUE(ValidateBooleanPref(good2, "blacklist", true));
3320 EXPECT_FALSE(IsPrefExist("invalid_id", "blacklist"));
3322 #endif // defined(ENABLE_BLACKLIST_TESTS)
3324 #if defined(ENABLE_BLACKLIST_TESTS)
3325 // Tests trying to install a blacklisted extension.
3326 TEST_F(ExtensionServiceTest, BlacklistedExtensionWillNotInstall) {
3327 scoped_refptr<FakeSafeBrowsingDatabaseManager> blacklist_db(
3328 new FakeSafeBrowsingDatabaseManager(true));
3329 Blacklist::ScopedDatabaseManagerForTest scoped_blacklist_db(blacklist_db);
3331 InitializeEmptyExtensionService();
3332 service_->Init();
3334 // After blacklisting good_crx, we cannot install it.
3335 blacklist_db->SetUnsafe(good_crx).NotifyUpdate();
3336 base::RunLoop().RunUntilIdle();
3338 base::FilePath path = data_dir_.AppendASCII("good.crx");
3339 // HACK: specify WAS_INSTALLED_BY_DEFAULT so that test machinery doesn't
3340 // decide to install this silently. Somebody should fix these tests, all
3341 // 6,000 lines of them. Hah!
3342 InstallCRX(path, INSTALL_FAILED, Extension::WAS_INSTALLED_BY_DEFAULT);
3343 EXPECT_EQ(0u, registry_->enabled_extensions().size());
3345 #endif // defined(ENABLE_BLACKLIST_TESTS)
3347 #if defined(ENABLE_BLACKLIST_TESTS)
3348 // Unload blacklisted extension on policy change.
3349 TEST_F(ExtensionServiceTest, UnloadBlacklistedExtensionPolicy) {
3350 extensions::TestBlacklist test_blacklist;
3352 // A profile with no extensions installed.
3353 InitializeEmptyExtensionService();
3354 test_blacklist.Attach(service_->blacklist_);
3356 base::FilePath path = data_dir_.AppendASCII("good.crx");
3358 const Extension* good = InstallCRX(path, INSTALL_NEW);
3359 EXPECT_EQ(good_crx, good->id());
3360 UpdateExtension(good_crx, path, FAILED_SILENTLY);
3361 EXPECT_EQ(1u, registry_->enabled_extensions().size());
3363 base::ListValue whitelist;
3364 PrefService* prefs = ExtensionPrefs::Get(profile_.get())->pref_service();
3365 whitelist.Append(new base::StringValue(good_crx));
3366 prefs->Set(extensions::pref_names::kInstallAllowList, whitelist);
3368 test_blacklist.SetBlacklistState(
3369 good_crx, extensions::BLACKLISTED_MALWARE, true);
3370 base::RunLoop().RunUntilIdle();
3372 // The good_crx is blacklisted and the whitelist doesn't negate it.
3373 ASSERT_TRUE(ValidateBooleanPref(good_crx, "blacklist", true));
3374 EXPECT_EQ(0u, registry_->enabled_extensions().size());
3376 #endif // defined(ENABLE_BLACKLIST_TESTS)
3378 #if defined(ENABLE_BLACKLIST_TESTS)
3379 // Tests that a blacklisted extension is eventually unloaded on startup, if it
3380 // wasn't already.
3381 TEST_F(ExtensionServiceTest, WillNotLoadBlacklistedExtensionsFromDirectory) {
3382 extensions::TestBlacklist test_blacklist;
3384 // A profile with 3 extensions installed: good0, good1, and good2.
3385 InitializeGoodInstalledExtensionService();
3386 test_blacklist.Attach(service_->blacklist_);
3388 // Blacklist good1 before the service initializes.
3389 test_blacklist.SetBlacklistState(
3390 good1, extensions::BLACKLISTED_MALWARE, false);
3392 // Load extensions.
3393 service_->Init();
3394 ASSERT_EQ(3u, loaded_.size()); // hasn't had time to blacklist yet
3396 base::RunLoop().RunUntilIdle();
3398 ASSERT_EQ(1u, registry_->blacklisted_extensions().size());
3399 ASSERT_EQ(2u, registry_->enabled_extensions().size());
3401 ASSERT_TRUE(registry_->enabled_extensions().Contains(good0));
3402 ASSERT_TRUE(registry_->blacklisted_extensions().Contains(good1));
3403 ASSERT_TRUE(registry_->enabled_extensions().Contains(good2));
3405 #endif // defined(ENABLE_BLACKLIST_TESTS)
3407 #if defined(ENABLE_BLACKLIST_TESTS)
3408 // Tests extensions blacklisted in prefs on startup; one still blacklisted by
3409 // safe browsing, the other not. The not-blacklisted one should recover.
3410 TEST_F(ExtensionServiceTest, BlacklistedInPrefsFromStartup) {
3411 extensions::TestBlacklist test_blacklist;
3413 InitializeGoodInstalledExtensionService();
3414 test_blacklist.Attach(service_->blacklist_);
3415 ExtensionPrefs::Get(profile_.get())->SetExtensionBlacklisted(good0, true);
3416 ExtensionPrefs::Get(profile_.get())->SetExtensionBlacklisted(good1, true);
3418 test_blacklist.SetBlacklistState(
3419 good1, extensions::BLACKLISTED_MALWARE, false);
3421 service_->Init();
3423 ASSERT_EQ(2u, registry_->blacklisted_extensions().size());
3424 ASSERT_EQ(1u, registry_->enabled_extensions().size());
3426 ASSERT_TRUE(registry_->blacklisted_extensions().Contains(good0));
3427 ASSERT_TRUE(registry_->blacklisted_extensions().Contains(good1));
3428 ASSERT_TRUE(registry_->enabled_extensions().Contains(good2));
3430 // Give time for the blacklist to update.
3431 base::RunLoop().RunUntilIdle();
3433 ASSERT_EQ(1u, registry_->blacklisted_extensions().size());
3434 ASSERT_EQ(2u, registry_->enabled_extensions().size());
3436 ASSERT_TRUE(registry_->enabled_extensions().Contains(good0));
3437 ASSERT_TRUE(registry_->blacklisted_extensions().Contains(good1));
3438 ASSERT_TRUE(registry_->enabled_extensions().Contains(good2));
3440 #endif // defined(ENABLE_BLACKLIST_TESTS)
3442 #if defined(ENABLE_BLACKLIST_TESTS)
3443 // Extension is added to blacklist with BLACKLISTED_POTENTIALLY_UNWANTED state
3444 // after it is installed. It is then successfully re-enabled by the user.
3445 TEST_F(ExtensionServiceTest, GreylistedExtensionDisabled) {
3446 extensions::TestBlacklist test_blacklist;
3447 // A profile with 3 extensions installed: good0, good1, and good2.
3448 InitializeGoodInstalledExtensionService();
3449 test_blacklist.Attach(service_->blacklist_);
3450 service_->Init();
3452 const extensions::ExtensionSet& enabled_extensions =
3453 registry_->enabled_extensions();
3454 const extensions::ExtensionSet& disabled_extensions =
3455 registry_->disabled_extensions();
3457 EXPECT_TRUE(enabled_extensions.Contains(good0));
3458 EXPECT_TRUE(enabled_extensions.Contains(good1));
3459 EXPECT_TRUE(enabled_extensions.Contains(good2));
3461 // Blacklist good0 and good1 (and an invalid extension ID).
3462 test_blacklist.SetBlacklistState(
3463 good0, extensions::BLACKLISTED_CWS_POLICY_VIOLATION, true);
3464 test_blacklist.SetBlacklistState(
3465 good1, extensions::BLACKLISTED_POTENTIALLY_UNWANTED, true);
3466 test_blacklist.SetBlacklistState(
3467 "invalid_id", extensions::BLACKLISTED_MALWARE, true);
3468 base::RunLoop().RunUntilIdle();
3470 EXPECT_FALSE(enabled_extensions.Contains(good0));
3471 EXPECT_TRUE(disabled_extensions.Contains(good0));
3472 EXPECT_FALSE(enabled_extensions.Contains(good1));
3473 EXPECT_TRUE(disabled_extensions.Contains(good1));
3474 EXPECT_TRUE(enabled_extensions.Contains(good2));
3475 EXPECT_FALSE(disabled_extensions.Contains(good2));
3477 ValidateIntegerPref(
3478 good0, "blacklist_state", extensions::BLACKLISTED_CWS_POLICY_VIOLATION);
3479 ValidateIntegerPref(
3480 good1, "blacklist_state", extensions::BLACKLISTED_POTENTIALLY_UNWANTED);
3482 // Now user enables good0.
3483 service_->EnableExtension(good0);
3485 EXPECT_TRUE(enabled_extensions.Contains(good0));
3486 EXPECT_FALSE(disabled_extensions.Contains(good0));
3487 EXPECT_FALSE(enabled_extensions.Contains(good1));
3488 EXPECT_TRUE(disabled_extensions.Contains(good1));
3490 // Remove extensions from blacklist.
3491 test_blacklist.SetBlacklistState(
3492 good0, extensions::NOT_BLACKLISTED, true);
3493 test_blacklist.SetBlacklistState(
3494 good1, extensions::NOT_BLACKLISTED, true);
3495 base::RunLoop().RunUntilIdle();
3497 // All extensions are enabled.
3498 EXPECT_TRUE(enabled_extensions.Contains(good0));
3499 EXPECT_FALSE(disabled_extensions.Contains(good0));
3500 EXPECT_TRUE(enabled_extensions.Contains(good1));
3501 EXPECT_FALSE(disabled_extensions.Contains(good1));
3502 EXPECT_TRUE(enabled_extensions.Contains(good2));
3503 EXPECT_FALSE(disabled_extensions.Contains(good2));
3505 #endif // defined(ENABLE_BLACKLIST_TESTS)
3507 #if defined(ENABLE_BLACKLIST_TESTS)
3508 // When extension is removed from greylist, do not re-enable it if it is
3509 // disabled by user.
3510 TEST_F(ExtensionServiceTest, GreylistDontEnableManuallyDisabled) {
3511 extensions::TestBlacklist test_blacklist;
3512 // A profile with 3 extensions installed: good0, good1, and good2.
3513 InitializeGoodInstalledExtensionService();
3514 test_blacklist.Attach(service_->blacklist_);
3515 service_->Init();
3517 const extensions::ExtensionSet& enabled_extensions =
3518 registry_->enabled_extensions();
3519 const extensions::ExtensionSet& disabled_extensions =
3520 registry_->disabled_extensions();
3522 // Manually disable.
3523 service_->DisableExtension(good0, extensions::Extension::DISABLE_USER_ACTION);
3525 test_blacklist.SetBlacklistState(
3526 good0, extensions::BLACKLISTED_CWS_POLICY_VIOLATION, true);
3527 test_blacklist.SetBlacklistState(
3528 good1, extensions::BLACKLISTED_POTENTIALLY_UNWANTED, true);
3529 test_blacklist.SetBlacklistState(
3530 good2, extensions::BLACKLISTED_SECURITY_VULNERABILITY, true);
3531 base::RunLoop().RunUntilIdle();
3533 // All extensions disabled.
3534 EXPECT_FALSE(enabled_extensions.Contains(good0));
3535 EXPECT_TRUE(disabled_extensions.Contains(good0));
3536 EXPECT_FALSE(enabled_extensions.Contains(good1));
3537 EXPECT_TRUE(disabled_extensions.Contains(good1));
3538 EXPECT_FALSE(enabled_extensions.Contains(good2));
3539 EXPECT_TRUE(disabled_extensions.Contains(good2));
3541 // Greylisted extension can be enabled.
3542 service_->EnableExtension(good1);
3543 EXPECT_TRUE(enabled_extensions.Contains(good1));
3544 EXPECT_FALSE(disabled_extensions.Contains(good1));
3546 // good1 is now manually disabled.
3547 service_->DisableExtension(good1, extensions::Extension::DISABLE_USER_ACTION);
3548 EXPECT_FALSE(enabled_extensions.Contains(good1));
3549 EXPECT_TRUE(disabled_extensions.Contains(good1));
3551 // Remove extensions from blacklist.
3552 test_blacklist.SetBlacklistState(
3553 good0, extensions::NOT_BLACKLISTED, true);
3554 test_blacklist.SetBlacklistState(
3555 good1, extensions::NOT_BLACKLISTED, true);
3556 test_blacklist.SetBlacklistState(
3557 good2, extensions::NOT_BLACKLISTED, true);
3558 base::RunLoop().RunUntilIdle();
3560 // good0 and good1 remain disabled.
3561 EXPECT_FALSE(enabled_extensions.Contains(good0));
3562 EXPECT_TRUE(disabled_extensions.Contains(good0));
3563 EXPECT_FALSE(enabled_extensions.Contains(good1));
3564 EXPECT_TRUE(disabled_extensions.Contains(good1));
3565 EXPECT_TRUE(enabled_extensions.Contains(good2));
3566 EXPECT_FALSE(disabled_extensions.Contains(good2));
3568 #endif // defined(ENABLE_BLACKLIST_TESTS)
3570 #if defined(ENABLE_BLACKLIST_TESTS)
3571 // Blacklisted extension with unknown state are not enabled/disabled.
3572 TEST_F(ExtensionServiceTest, GreylistUnknownDontChange) {
3573 extensions::TestBlacklist test_blacklist;
3574 // A profile with 3 extensions installed: good0, good1, and good2.
3575 InitializeGoodInstalledExtensionService();
3576 test_blacklist.Attach(service_->blacklist_);
3577 service_->Init();
3579 const extensions::ExtensionSet& enabled_extensions =
3580 registry_->enabled_extensions();
3581 const extensions::ExtensionSet& disabled_extensions =
3582 registry_->disabled_extensions();
3584 test_blacklist.SetBlacklistState(
3585 good0, extensions::BLACKLISTED_CWS_POLICY_VIOLATION, true);
3586 test_blacklist.SetBlacklistState(
3587 good1, extensions::BLACKLISTED_POTENTIALLY_UNWANTED, true);
3588 base::RunLoop().RunUntilIdle();
3590 EXPECT_FALSE(enabled_extensions.Contains(good0));
3591 EXPECT_TRUE(disabled_extensions.Contains(good0));
3592 EXPECT_FALSE(enabled_extensions.Contains(good1));
3593 EXPECT_TRUE(disabled_extensions.Contains(good1));
3594 EXPECT_TRUE(enabled_extensions.Contains(good2));
3595 EXPECT_FALSE(disabled_extensions.Contains(good2));
3597 test_blacklist.SetBlacklistState(
3598 good0, extensions::NOT_BLACKLISTED, true);
3599 test_blacklist.SetBlacklistState(
3600 good1, extensions::BLACKLISTED_UNKNOWN, true);
3601 test_blacklist.SetBlacklistState(
3602 good2, extensions::BLACKLISTED_UNKNOWN, true);
3603 base::RunLoop().RunUntilIdle();
3605 // good0 re-enabled, other remain as they were.
3606 EXPECT_TRUE(enabled_extensions.Contains(good0));
3607 EXPECT_FALSE(disabled_extensions.Contains(good0));
3608 EXPECT_FALSE(enabled_extensions.Contains(good1));
3609 EXPECT_TRUE(disabled_extensions.Contains(good1));
3610 EXPECT_TRUE(enabled_extensions.Contains(good2));
3611 EXPECT_FALSE(disabled_extensions.Contains(good2));
3613 #endif // defined(ENABLE_BLACKLIST_TESTS)
3615 // Will not install extension blacklisted by policy.
3616 TEST_F(ExtensionServiceTest, BlacklistedByPolicyWillNotInstall) {
3617 InitializeEmptyExtensionService();
3619 // Blacklist everything.
3621 ListPrefUpdate update(profile_->GetPrefs(),
3622 extensions::pref_names::kInstallDenyList);
3623 base::ListValue* blacklist = update.Get();
3624 blacklist->Append(new base::StringValue("*"));
3627 // Blacklist prevents us from installing good_crx.
3628 base::FilePath path = data_dir_.AppendASCII("good.crx");
3629 InstallCRX(path, INSTALL_FAILED);
3630 EXPECT_EQ(0u, registry_->enabled_extensions().size());
3632 // Now whitelist this particular extension.
3634 ListPrefUpdate update(profile_->GetPrefs(),
3635 extensions::pref_names::kInstallAllowList);
3636 base::ListValue* whitelist = update.Get();
3637 whitelist->Append(new base::StringValue(good_crx));
3640 // Ensure we can now install good_crx.
3641 InstallCRX(path, INSTALL_NEW);
3642 EXPECT_EQ(1u, registry_->enabled_extensions().size());
3645 // Extension blacklisted by policy get unloaded after installing.
3646 TEST_F(ExtensionServiceTest, BlacklistedByPolicyRemovedIfRunning) {
3647 InitializeEmptyExtensionService();
3649 // Install good_crx.
3650 base::FilePath path = data_dir_.AppendASCII("good.crx");
3651 InstallCRX(path, INSTALL_NEW);
3652 EXPECT_EQ(1u, registry_->enabled_extensions().size());
3654 { // Scope for pref update notification.
3655 PrefService* prefs = profile_->GetPrefs();
3656 ListPrefUpdate update(prefs, extensions::pref_names::kInstallDenyList);
3657 base::ListValue* blacklist = update.Get();
3658 ASSERT_TRUE(blacklist != NULL);
3660 // Blacklist this extension.
3661 blacklist->Append(new base::StringValue(good_crx));
3664 // Extension should not be running now.
3665 base::RunLoop().RunUntilIdle();
3666 EXPECT_EQ(0u, registry_->enabled_extensions().size());
3669 // Tests that component extensions are not blacklisted by policy.
3670 TEST_F(ExtensionServiceTest, ComponentExtensionWhitelisted) {
3671 InitializeEmptyExtensionService();
3673 // Blacklist everything.
3675 ListPrefUpdate update(profile_->GetPrefs(),
3676 extensions::pref_names::kInstallDenyList);
3677 base::ListValue* blacklist = update.Get();
3678 blacklist->Append(new base::StringValue("*"));
3681 // Install a component extension.
3682 base::FilePath path = data_dir_
3683 .AppendASCII("good")
3684 .AppendASCII("Extensions")
3685 .AppendASCII(good0)
3686 .AppendASCII("1.0.0.0");
3687 std::string manifest;
3688 ASSERT_TRUE(base::ReadFileToString(
3689 path.Append(extensions::kManifestFilename), &manifest));
3690 service_->component_loader()->Add(manifest, path);
3691 service_->Init();
3693 // Extension should be installed despite blacklist.
3694 ASSERT_EQ(1u, registry_->enabled_extensions().size());
3695 EXPECT_TRUE(service_->GetExtensionById(good0, false));
3697 // Poke external providers and make sure the extension is still present.
3698 service_->CheckForExternalUpdates();
3699 ASSERT_EQ(1u, registry_->enabled_extensions().size());
3700 EXPECT_TRUE(service_->GetExtensionById(good0, false));
3702 // Extension should not be uninstalled on blacklist changes.
3704 ListPrefUpdate update(profile_->GetPrefs(),
3705 extensions::pref_names::kInstallDenyList);
3706 base::ListValue* blacklist = update.Get();
3707 blacklist->Append(new base::StringValue(good0));
3709 base::RunLoop().RunUntilIdle();
3710 ASSERT_EQ(1u, registry_->enabled_extensions().size());
3711 EXPECT_TRUE(service_->GetExtensionById(good0, false));
3714 // Tests that policy-installed extensions are not blacklisted by policy.
3715 TEST_F(ExtensionServiceTest, PolicyInstalledExtensionsWhitelisted) {
3716 InitializeEmptyExtensionService();
3719 // Blacklist everything.
3720 ListPrefUpdate blacklist_update(
3721 profile_->GetPrefs(), extensions::pref_names::kInstallDenyList);
3722 base::ListValue* blacklist = blacklist_update.Get();
3723 blacklist->AppendString("*");
3725 // Mark good.crx for force-installation.
3726 DictionaryPrefUpdate forcelist_update(
3727 profile_->GetPrefs(),
3728 extensions::pref_names::kInstallForceList);
3729 extensions::ExternalPolicyLoader::AddExtension(
3730 forcelist_update.Get(), good_crx, "http://example.com/update_url");
3733 // Have policy force-install an extension.
3734 MockExtensionProvider* provider =
3735 new MockExtensionProvider(service_,
3736 Manifest::EXTERNAL_POLICY_DOWNLOAD);
3737 AddMockExternalProvider(provider);
3738 provider->UpdateOrAddExtension(good_crx, "1.0.0.0",
3739 data_dir_.AppendASCII("good.crx"));
3741 // Reloading extensions should find our externally registered extension
3742 // and install it.
3743 content::WindowedNotificationObserver observer(
3744 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
3745 content::NotificationService::AllSources());
3746 service_->CheckForExternalUpdates();
3747 observer.Wait();
3749 // Extension should be installed despite blacklist.
3750 ASSERT_EQ(1u, registry_->enabled_extensions().size());
3751 EXPECT_TRUE(service_->GetExtensionById(good_crx, false));
3753 // Blacklist update should not uninstall the extension.
3755 ListPrefUpdate update(profile_->GetPrefs(),
3756 extensions::pref_names::kInstallDenyList);
3757 base::ListValue* blacklist = update.Get();
3758 blacklist->Append(new base::StringValue(good0));
3760 base::RunLoop().RunUntilIdle();
3761 ASSERT_EQ(1u, registry_->enabled_extensions().size());
3762 EXPECT_TRUE(service_->GetExtensionById(good_crx, false));
3765 // Tests that extensions cannot be installed if the policy provider prohibits
3766 // it. This functionality is implemented in CrxInstaller::ConfirmInstall().
3767 TEST_F(ExtensionServiceTest, ManagementPolicyProhibitsInstall) {
3768 InitializeEmptyExtensionService();
3770 management_policy_->UnregisterAllProviders();
3771 extensions::TestManagementPolicyProvider provider_(
3772 extensions::TestManagementPolicyProvider::PROHIBIT_LOAD);
3773 management_policy_->RegisterProvider(&provider_);
3775 InstallCRX(data_dir_.AppendASCII("good.crx"), INSTALL_FAILED);
3776 EXPECT_EQ(0u, registry_->enabled_extensions().size());
3779 // Tests that extensions cannot be loaded from prefs if the policy provider
3780 // prohibits it. This functionality is implemented in InstalledLoader::Load().
3781 TEST_F(ExtensionServiceTest, ManagementPolicyProhibitsLoadFromPrefs) {
3782 InitializeEmptyExtensionService();
3784 // Create a fake extension to be loaded as though it were read from prefs.
3785 base::FilePath path = data_dir_.AppendASCII("management")
3786 .AppendASCII("simple_extension");
3787 base::DictionaryValue manifest;
3788 manifest.SetString(keys::kName, "simple_extension");
3789 manifest.SetString(keys::kVersion, "1");
3790 // UNPACKED is for extensions loaded from a directory. We use it here, even
3791 // though we're testing loading from prefs, so that we don't need to provide
3792 // an extension key.
3793 extensions::ExtensionInfo extension_info(
3794 &manifest, std::string(), path, Manifest::UNPACKED);
3796 // Ensure we can load it with no management policy in place.
3797 management_policy_->UnregisterAllProviders();
3798 EXPECT_EQ(0u, registry_->enabled_extensions().size());
3799 extensions::InstalledLoader(service_).Load(extension_info, false);
3800 EXPECT_EQ(1u, registry_->enabled_extensions().size());
3802 const Extension* extension = (registry_->enabled_extensions().begin())->get();
3803 EXPECT_TRUE(service_->UninstallExtension(extension->id(), false, NULL));
3804 EXPECT_EQ(0u, registry_->enabled_extensions().size());
3806 // Ensure we cannot load it if management policy prohibits installation.
3807 extensions::TestManagementPolicyProvider provider_(
3808 extensions::TestManagementPolicyProvider::PROHIBIT_LOAD);
3809 management_policy_->RegisterProvider(&provider_);
3811 extensions::InstalledLoader(service_).Load(extension_info, false);
3812 EXPECT_EQ(0u, registry_->enabled_extensions().size());
3815 // Tests disabling an extension when prohibited by the ManagementPolicy.
3816 TEST_F(ExtensionServiceTest, ManagementPolicyProhibitsDisable) {
3817 InitializeEmptyExtensionService();
3819 InstallCRX(data_dir_.AppendASCII("good.crx"), INSTALL_NEW);
3820 EXPECT_EQ(1u, registry_->enabled_extensions().size());
3821 EXPECT_EQ(0u, registry_->disabled_extensions().size());
3823 management_policy_->UnregisterAllProviders();
3824 extensions::TestManagementPolicyProvider provider(
3825 extensions::TestManagementPolicyProvider::PROHIBIT_MODIFY_STATUS);
3826 management_policy_->RegisterProvider(&provider);
3828 // Attempt to disable it.
3829 service_->DisableExtension(good_crx, Extension::DISABLE_USER_ACTION);
3831 EXPECT_EQ(1u, registry_->enabled_extensions().size());
3832 EXPECT_TRUE(service_->GetExtensionById(good_crx, false));
3833 EXPECT_EQ(0u, registry_->disabled_extensions().size());
3836 // Tests uninstalling an extension when prohibited by the ManagementPolicy.
3837 TEST_F(ExtensionServiceTest, ManagementPolicyProhibitsUninstall) {
3838 InitializeEmptyExtensionService();
3840 InstallCRX(data_dir_.AppendASCII("good.crx"), INSTALL_NEW);
3841 EXPECT_EQ(1u, registry_->enabled_extensions().size());
3842 EXPECT_EQ(0u, registry_->disabled_extensions().size());
3844 management_policy_->UnregisterAllProviders();
3845 extensions::TestManagementPolicyProvider provider(
3846 extensions::TestManagementPolicyProvider::PROHIBIT_MODIFY_STATUS);
3847 management_policy_->RegisterProvider(&provider);
3849 // Attempt to uninstall it.
3850 EXPECT_FALSE(service_->UninstallExtension(good_crx, false, NULL));
3852 EXPECT_EQ(1u, registry_->enabled_extensions().size());
3853 EXPECT_TRUE(service_->GetExtensionById(good_crx, false));
3856 // Tests that previously installed extensions that are now prohibited from
3857 // being installed are removed.
3858 TEST_F(ExtensionServiceTest, ManagementPolicyUnloadsAllProhibited) {
3859 InitializeEmptyExtensionService();
3861 InstallCRX(data_dir_.AppendASCII("good.crx"), INSTALL_NEW);
3862 InstallCRX(data_dir_.AppendASCII("page_action.crx"), INSTALL_NEW);
3863 EXPECT_EQ(2u, registry_->enabled_extensions().size());
3864 EXPECT_EQ(0u, registry_->disabled_extensions().size());
3866 management_policy_->UnregisterAllProviders();
3867 extensions::TestManagementPolicyProvider provider(
3868 extensions::TestManagementPolicyProvider::PROHIBIT_LOAD);
3869 management_policy_->RegisterProvider(&provider);
3871 // Run the policy check.
3872 service_->CheckManagementPolicy();
3873 EXPECT_EQ(0u, registry_->enabled_extensions().size());
3874 EXPECT_EQ(0u, registry_->disabled_extensions().size());
3877 // Tests that previously disabled extensions that are now required to be
3878 // enabled are re-enabled on reinstall.
3879 TEST_F(ExtensionServiceTest, ManagementPolicyRequiresEnable) {
3880 InitializeEmptyExtensionService();
3882 // Install, then disable, an extension.
3883 InstallCRX(data_dir_.AppendASCII("good.crx"), INSTALL_NEW);
3884 EXPECT_EQ(1u, registry_->enabled_extensions().size());
3885 service_->DisableExtension(good_crx, Extension::DISABLE_USER_ACTION);
3886 EXPECT_EQ(1u, registry_->disabled_extensions().size());
3888 // Register an ExtensionMnagementPolicy that requires the extension to remain
3889 // enabled.
3890 management_policy_->UnregisterAllProviders();
3891 extensions::TestManagementPolicyProvider provider(
3892 extensions::TestManagementPolicyProvider::MUST_REMAIN_ENABLED);
3893 management_policy_->RegisterProvider(&provider);
3895 // Reinstall the extension.
3896 InstallCRX(data_dir_.AppendASCII("good.crx"), INSTALL_UPDATED);
3897 EXPECT_EQ(1u, registry_->enabled_extensions().size());
3898 EXPECT_EQ(0u, registry_->disabled_extensions().size());
3901 // Flaky on windows; http://crbug.com/309833
3902 #if defined(OS_WIN)
3903 #define MAYBE_ExternalExtensionAutoAcknowledgement DISABLED_ExternalExtensionAutoAcknowledgement
3904 #else
3905 #define MAYBE_ExternalExtensionAutoAcknowledgement ExternalExtensionAutoAcknowledgement
3906 #endif
3907 TEST_F(ExtensionServiceTest, MAYBE_ExternalExtensionAutoAcknowledgement) {
3908 InitializeEmptyExtensionService();
3909 set_extensions_enabled(true);
3912 // Register and install an external extension.
3913 MockExtensionProvider* provider =
3914 new MockExtensionProvider(service_, Manifest::EXTERNAL_PREF);
3915 AddMockExternalProvider(provider);
3916 provider->UpdateOrAddExtension(good_crx, "1.0.0.0",
3917 data_dir_.AppendASCII("good.crx"));
3920 // Have policy force-install an extension.
3921 MockExtensionProvider* provider =
3922 new MockExtensionProvider(service_,
3923 Manifest::EXTERNAL_POLICY_DOWNLOAD);
3924 AddMockExternalProvider(provider);
3925 provider->UpdateOrAddExtension(page_action, "1.0.0.0",
3926 data_dir_.AppendASCII("page_action.crx"));
3929 // Providers are set up. Let them run.
3930 int count = 2;
3931 content::WindowedNotificationObserver observer(
3932 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
3933 base::Bind(&WaitForCountNotificationsCallback, &count));
3934 service_->CheckForExternalUpdates();
3936 observer.Wait();
3938 ASSERT_EQ(2u, registry_->enabled_extensions().size());
3939 EXPECT_TRUE(service_->GetExtensionById(good_crx, false));
3940 EXPECT_TRUE(service_->GetExtensionById(page_action, false));
3941 ExtensionPrefs* prefs = ExtensionPrefs::Get(profile_.get());
3942 ASSERT_TRUE(!prefs->IsExternalExtensionAcknowledged(good_crx));
3943 ASSERT_TRUE(prefs->IsExternalExtensionAcknowledged(page_action));
3946 #if !defined(OS_CHROMEOS)
3947 // This tests if default apps are installed correctly.
3948 TEST_F(ExtensionServiceTest, DefaultAppsInstall) {
3949 InitializeEmptyExtensionService();
3950 set_extensions_enabled(true);
3953 std::string json_data =
3955 " \"ldnnhddmnhbkjipkidpdiheffobcpfmf\" : {"
3956 " \"external_crx\": \"good.crx\","
3957 " \"external_version\": \"1.0.0.0\","
3958 " \"is_bookmark_app\": false"
3959 " }"
3960 "}";
3961 default_apps::Provider* provider =
3962 new default_apps::Provider(
3963 profile_.get(),
3964 service_,
3965 new extensions::ExternalTestingLoader(json_data, data_dir_),
3966 Manifest::INTERNAL,
3967 Manifest::INVALID_LOCATION,
3968 Extension::FROM_WEBSTORE | Extension::WAS_INSTALLED_BY_DEFAULT);
3970 AddMockExternalProvider(provider);
3973 ASSERT_EQ(0u, registry_->enabled_extensions().size());
3974 content::WindowedNotificationObserver observer(
3975 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
3976 content::NotificationService::AllSources());
3977 service_->CheckForExternalUpdates();
3978 observer.Wait();
3980 ASSERT_EQ(1u, registry_->enabled_extensions().size());
3981 EXPECT_TRUE(service_->GetExtensionById(good_crx, false));
3982 const Extension* extension = service_->GetExtensionById(good_crx, false);
3983 EXPECT_TRUE(extension->from_webstore());
3984 EXPECT_TRUE(extension->was_installed_by_default());
3986 #endif
3988 // Tests disabling extensions
3989 TEST_F(ExtensionServiceTest, DisableExtension) {
3990 InitializeEmptyExtensionService();
3992 InstallCRX(data_dir_.AppendASCII("good.crx"), INSTALL_NEW);
3993 EXPECT_TRUE(service_->GetExtensionById(good_crx, true));
3994 EXPECT_TRUE(service_->GetExtensionById(good_crx, false));
3996 EXPECT_EQ(1u, registry_->enabled_extensions().size());
3997 EXPECT_EQ(0u, registry_->disabled_extensions().size());
3998 EXPECT_EQ(0u, registry_->terminated_extensions().size());
3999 EXPECT_EQ(0u, registry_->blacklisted_extensions().size());
4001 // Disable it.
4002 service_->DisableExtension(good_crx, Extension::DISABLE_USER_ACTION);
4004 EXPECT_TRUE(service_->GetExtensionById(good_crx, true));
4005 EXPECT_FALSE(service_->GetExtensionById(good_crx, false));
4006 EXPECT_EQ(0u, registry_->enabled_extensions().size());
4007 EXPECT_EQ(1u, registry_->disabled_extensions().size());
4008 EXPECT_EQ(0u, registry_->terminated_extensions().size());
4009 EXPECT_EQ(0u, registry_->blacklisted_extensions().size());
4012 TEST_F(ExtensionServiceTest, TerminateExtension) {
4013 InitializeEmptyExtensionService();
4015 InstallCRX(data_dir_.AppendASCII("good.crx"), INSTALL_NEW);
4016 EXPECT_EQ(1u, registry_->enabled_extensions().size());
4017 EXPECT_EQ(0u, registry_->disabled_extensions().size());
4018 EXPECT_EQ(0u, registry_->terminated_extensions().size());
4019 EXPECT_EQ(0u, registry_->blacklisted_extensions().size());
4021 TerminateExtension(good_crx);
4023 EXPECT_EQ(0u, registry_->enabled_extensions().size());
4024 EXPECT_EQ(0u, registry_->disabled_extensions().size());
4025 EXPECT_EQ(1u, registry_->terminated_extensions().size());
4026 EXPECT_EQ(0u, registry_->blacklisted_extensions().size());
4029 TEST_F(ExtensionServiceTest, DisableTerminatedExtension) {
4030 InitializeEmptyExtensionService();
4032 InstallCRX(data_dir_.AppendASCII("good.crx"), INSTALL_NEW);
4033 TerminateExtension(good_crx);
4034 EXPECT_TRUE(registry_->GetExtensionById(
4035 good_crx, extensions::ExtensionRegistry::TERMINATED));
4037 // Disable it.
4038 service_->DisableExtension(good_crx, Extension::DISABLE_USER_ACTION);
4040 EXPECT_FALSE(registry_->GetExtensionById(
4041 good_crx, extensions::ExtensionRegistry::TERMINATED));
4042 EXPECT_TRUE(service_->GetExtensionById(good_crx, true));
4044 EXPECT_EQ(0u, registry_->enabled_extensions().size());
4045 EXPECT_EQ(1u, registry_->disabled_extensions().size());
4046 EXPECT_EQ(0u, registry_->terminated_extensions().size());
4047 EXPECT_EQ(0u, registry_->blacklisted_extensions().size());
4050 // Tests disabling all extensions (simulating --disable-extensions flag).
4051 TEST_F(ExtensionServiceTest, DisableAllExtensions) {
4052 InitializeEmptyExtensionService();
4054 base::FilePath path = data_dir_.AppendASCII("good.crx");
4055 InstallCRX(path, INSTALL_NEW);
4057 EXPECT_EQ(1u, registry_->enabled_extensions().size());
4058 EXPECT_EQ(0u, registry_->disabled_extensions().size());
4060 // Disable extensions.
4061 service_->set_extensions_enabled(false);
4062 service_->ReloadExtensionsForTest();
4064 // There shouldn't be extensions in either list.
4065 EXPECT_EQ(0u, registry_->enabled_extensions().size());
4066 EXPECT_EQ(0u, registry_->disabled_extensions().size());
4068 // This shouldn't do anything when all extensions are disabled.
4069 service_->EnableExtension(good_crx);
4070 service_->ReloadExtensionsForTest();
4072 // There still shouldn't be extensions in either list.
4073 EXPECT_EQ(0u, registry_->enabled_extensions().size());
4074 EXPECT_EQ(0u, registry_->disabled_extensions().size());
4076 // And then re-enable the extensions.
4077 service_->set_extensions_enabled(true);
4078 service_->ReloadExtensionsForTest();
4080 EXPECT_EQ(1u, registry_->enabled_extensions().size());
4081 EXPECT_EQ(0u, registry_->disabled_extensions().size());
4084 // Tests reloading extensions.
4085 TEST_F(ExtensionServiceTest, ReloadExtensions) {
4086 InitializeEmptyExtensionService();
4088 // Simple extension that should install without error.
4089 base::FilePath path = data_dir_.AppendASCII("good.crx");
4090 InstallCRX(path, INSTALL_NEW,
4091 Extension::FROM_WEBSTORE | Extension::WAS_INSTALLED_BY_DEFAULT);
4092 const char* extension_id = good_crx;
4093 service_->DisableExtension(extension_id, Extension::DISABLE_USER_ACTION);
4095 EXPECT_EQ(0u, registry_->enabled_extensions().size());
4096 EXPECT_EQ(1u, registry_->disabled_extensions().size());
4098 service_->ReloadExtensionsForTest();
4100 // The creation flags should not change when reloading the extension.
4101 const Extension* extension = service_->GetExtensionById(good_crx, true);
4102 EXPECT_TRUE(extension->from_webstore());
4103 EXPECT_TRUE(extension->was_installed_by_default());
4104 EXPECT_FALSE(extension->from_bookmark());
4106 // Extension counts shouldn't change.
4107 EXPECT_EQ(0u, registry_->enabled_extensions().size());
4108 EXPECT_EQ(1u, registry_->disabled_extensions().size());
4110 service_->EnableExtension(extension_id);
4112 EXPECT_EQ(1u, registry_->enabled_extensions().size());
4113 EXPECT_EQ(0u, registry_->disabled_extensions().size());
4115 // Need to clear |loaded_| manually before reloading as the
4116 // EnableExtension() call above inserted into it and
4117 // UnloadAllExtensions() doesn't send out notifications.
4118 loaded_.clear();
4119 service_->ReloadExtensionsForTest();
4121 // Extension counts shouldn't change.
4122 EXPECT_EQ(1u, registry_->enabled_extensions().size());
4123 EXPECT_EQ(0u, registry_->disabled_extensions().size());
4126 // Tests reloading an extension.
4127 TEST_F(ExtensionServiceTest, ReloadExtension) {
4128 InitializeEmptyExtensionService();
4129 InitializeProcessManager();
4131 // Simple extension that should install without error.
4132 const char* extension_id = "behllobkkfkfnphdnhnkndlbkcpglgmj";
4133 base::FilePath ext = data_dir_
4134 .AppendASCII("good")
4135 .AppendASCII("Extensions")
4136 .AppendASCII(extension_id)
4137 .AppendASCII("1.0.0.0");
4138 extensions::UnpackedInstaller::Create(service_)->Load(ext);
4139 base::RunLoop().RunUntilIdle();
4141 EXPECT_EQ(1u, registry_->enabled_extensions().size());
4142 EXPECT_EQ(0u, registry_->disabled_extensions().size());
4144 service_->ReloadExtension(extension_id);
4146 // Extension should be disabled now, waiting to be reloaded.
4147 EXPECT_EQ(0u, registry_->enabled_extensions().size());
4148 EXPECT_EQ(1u, registry_->disabled_extensions().size());
4149 EXPECT_EQ(
4150 Extension::DISABLE_RELOAD,
4151 ExtensionPrefs::Get(profile_.get())->GetDisableReasons(extension_id));
4153 // Reloading again should not crash.
4154 service_->ReloadExtension(extension_id);
4156 // Finish reloading
4157 base::RunLoop().RunUntilIdle();
4159 // Extension should be enabled again.
4160 EXPECT_EQ(1u, registry_->enabled_extensions().size());
4161 EXPECT_EQ(0u, registry_->disabled_extensions().size());
4164 TEST_F(ExtensionServiceTest, UninstallExtension) {
4165 InitializeEmptyExtensionService();
4166 InstallCRX(data_dir_.AppendASCII("good.crx"), INSTALL_NEW);
4167 EXPECT_EQ(1u, registry_->enabled_extensions().size());
4168 UninstallExtension(good_crx, false);
4169 EXPECT_EQ(0u, registry_->enabled_extensions().size());
4172 TEST_F(ExtensionServiceTest, UninstallTerminatedExtension) {
4173 InitializeEmptyExtensionService();
4174 InstallCRX(data_dir_.AppendASCII("good.crx"), INSTALL_NEW);
4175 TerminateExtension(good_crx);
4176 UninstallExtension(good_crx, false);
4179 // Tests the uninstaller helper.
4180 TEST_F(ExtensionServiceTest, UninstallExtensionHelper) {
4181 InitializeEmptyExtensionService();
4182 InstallCRX(data_dir_.AppendASCII("good.crx"), INSTALL_NEW);
4183 UninstallExtension(good_crx, true);
4186 TEST_F(ExtensionServiceTest, UninstallExtensionHelperTerminated) {
4187 InitializeEmptyExtensionService();
4188 InstallCRX(data_dir_.AppendASCII("good.crx"), INSTALL_NEW);
4189 TerminateExtension(good_crx);
4190 UninstallExtension(good_crx, true);
4193 // An extension disabled because of unsupported requirements should re-enabled
4194 // if updated to a version with supported requirements as long as there are no
4195 // other disable reasons.
4196 TEST_F(ExtensionServiceTest, UpgradingRequirementsEnabled) {
4197 InitializeEmptyExtensionService();
4198 BlackListWebGL();
4200 base::FilePath path = data_dir_.AppendASCII("requirements");
4201 base::FilePath pem_path = data_dir_.AppendASCII("requirements")
4202 .AppendASCII("v1_good.pem");
4203 const Extension* extension_v1 = PackAndInstallCRX(path.AppendASCII("v1_good"),
4204 pem_path,
4205 INSTALL_NEW);
4206 std::string id = extension_v1->id();
4207 EXPECT_TRUE(service_->IsExtensionEnabled(id));
4209 base::FilePath v2_bad_requirements_crx = GetTemporaryFile();
4211 PackCRX(path.AppendASCII("v2_bad_requirements"),
4212 pem_path,
4213 v2_bad_requirements_crx);
4214 UpdateExtension(id, v2_bad_requirements_crx, INSTALLED);
4215 EXPECT_FALSE(service_->IsExtensionEnabled(id));
4217 base::FilePath v3_good_crx = GetTemporaryFile();
4219 PackCRX(path.AppendASCII("v3_good"), pem_path, v3_good_crx);
4220 UpdateExtension(id, v3_good_crx, ENABLED);
4221 EXPECT_TRUE(service_->IsExtensionEnabled(id));
4224 // Extensions disabled through user action should stay disabled.
4225 TEST_F(ExtensionServiceTest, UpgradingRequirementsDisabled) {
4226 InitializeEmptyExtensionService();
4227 BlackListWebGL();
4229 base::FilePath path = data_dir_.AppendASCII("requirements");
4230 base::FilePath pem_path = data_dir_.AppendASCII("requirements")
4231 .AppendASCII("v1_good.pem");
4232 const Extension* extension_v1 = PackAndInstallCRX(path.AppendASCII("v1_good"),
4233 pem_path,
4234 INSTALL_NEW);
4235 std::string id = extension_v1->id();
4236 service_->DisableExtension(id, Extension::DISABLE_USER_ACTION);
4237 EXPECT_FALSE(service_->IsExtensionEnabled(id));
4239 base::FilePath v2_bad_requirements_crx = GetTemporaryFile();
4241 PackCRX(path.AppendASCII("v2_bad_requirements"),
4242 pem_path,
4243 v2_bad_requirements_crx);
4244 UpdateExtension(id, v2_bad_requirements_crx, INSTALLED);
4245 EXPECT_FALSE(service_->IsExtensionEnabled(id));
4247 base::FilePath v3_good_crx = GetTemporaryFile();
4249 PackCRX(path.AppendASCII("v3_good"), pem_path, v3_good_crx);
4250 UpdateExtension(id, v3_good_crx, INSTALLED);
4251 EXPECT_FALSE(service_->IsExtensionEnabled(id));
4254 // The extension should not re-enabled because it was disabled from a
4255 // permission increase.
4256 TEST_F(ExtensionServiceTest, UpgradingRequirementsPermissions) {
4257 InitializeEmptyExtensionService();
4258 BlackListWebGL();
4260 base::FilePath path = data_dir_.AppendASCII("requirements");
4261 base::FilePath pem_path = data_dir_.AppendASCII("requirements")
4262 .AppendASCII("v1_good.pem");
4263 const Extension* extension_v1 = PackAndInstallCRX(path.AppendASCII("v1_good"),
4264 pem_path,
4265 INSTALL_NEW);
4266 std::string id = extension_v1->id();
4267 EXPECT_TRUE(service_->IsExtensionEnabled(id));
4269 base::FilePath v2_bad_requirements_and_permissions_crx = GetTemporaryFile();
4271 PackCRX(path.AppendASCII("v2_bad_requirements_and_permissions"),
4272 pem_path,
4273 v2_bad_requirements_and_permissions_crx);
4274 UpdateExtension(id, v2_bad_requirements_and_permissions_crx, INSTALLED);
4275 EXPECT_FALSE(service_->IsExtensionEnabled(id));
4277 base::FilePath v3_bad_permissions_crx = GetTemporaryFile();
4279 PackCRX(path.AppendASCII("v3_bad_permissions"),
4280 pem_path,
4281 v3_bad_permissions_crx);
4282 UpdateExtension(id, v3_bad_permissions_crx, INSTALLED);
4283 EXPECT_FALSE(service_->IsExtensionEnabled(id));
4286 // Unpacked extensions are not allowed to be installed if they have unsupported
4287 // requirements.
4288 TEST_F(ExtensionServiceTest, UnpackedRequirements) {
4289 InitializeEmptyExtensionService();
4290 BlackListWebGL();
4292 base::FilePath path = data_dir_.AppendASCII("requirements")
4293 .AppendASCII("v2_bad_requirements");
4294 extensions::UnpackedInstaller::Create(service_)->Load(path);
4295 base::RunLoop().RunUntilIdle();
4296 EXPECT_EQ(1u, GetErrors().size());
4297 EXPECT_EQ(0u, registry_->enabled_extensions().size());
4300 class ExtensionCookieCallback {
4301 public:
4302 ExtensionCookieCallback()
4303 : result_(false),
4304 weak_factory_(base::MessageLoop::current()) {}
4306 void SetCookieCallback(bool result) {
4307 base::MessageLoop::current()->PostTask(FROM_HERE,
4308 base::Bind(&base::MessageLoop::Quit, weak_factory_.GetWeakPtr()));
4309 result_ = result;
4312 void GetAllCookiesCallback(const net::CookieList& list) {
4313 base::MessageLoop::current()->PostTask(FROM_HERE,
4314 base::Bind(&base::MessageLoop::Quit, weak_factory_.GetWeakPtr()));
4315 list_ = list;
4317 net::CookieList list_;
4318 bool result_;
4319 base::WeakPtrFactory<base::MessageLoop> weak_factory_;
4322 // Verifies extension state is removed upon uninstall.
4323 TEST_F(ExtensionServiceTest, ClearExtensionData) {
4324 InitializeEmptyExtensionService();
4325 ExtensionCookieCallback callback;
4327 // Load a test extension.
4328 base::FilePath path = data_dir_;
4329 path = path.AppendASCII("good.crx");
4330 const Extension* extension = InstallCRX(path, INSTALL_NEW);
4331 ASSERT_TRUE(extension);
4332 GURL ext_url(extension->url());
4333 std::string origin_id = webkit_database::GetIdentifierFromOrigin(ext_url);
4335 // Set a cookie for the extension.
4336 net::CookieMonster* cookie_monster =
4337 profile_->GetRequestContextForExtensions()->GetURLRequestContext()->
4338 cookie_store()->GetCookieMonster();
4339 ASSERT_TRUE(cookie_monster);
4340 net::CookieOptions options;
4341 cookie_monster->SetCookieWithOptionsAsync(
4342 ext_url, "dummy=value", options,
4343 base::Bind(&ExtensionCookieCallback::SetCookieCallback,
4344 base::Unretained(&callback)));
4345 base::RunLoop().RunUntilIdle();
4346 EXPECT_TRUE(callback.result_);
4348 cookie_monster->GetAllCookiesForURLAsync(
4349 ext_url,
4350 base::Bind(&ExtensionCookieCallback::GetAllCookiesCallback,
4351 base::Unretained(&callback)));
4352 base::RunLoop().RunUntilIdle();
4353 EXPECT_EQ(1U, callback.list_.size());
4355 // Open a database.
4356 webkit_database::DatabaseTracker* db_tracker =
4357 BrowserContext::GetDefaultStoragePartition(profile_.get())->
4358 GetDatabaseTracker();
4359 base::string16 db_name = base::UTF8ToUTF16("db");
4360 base::string16 description = base::UTF8ToUTF16("db_description");
4361 int64 size;
4362 db_tracker->DatabaseOpened(origin_id, db_name, description, 1, &size);
4363 db_tracker->DatabaseClosed(origin_id, db_name);
4364 std::vector<webkit_database::OriginInfo> origins;
4365 db_tracker->GetAllOriginsInfo(&origins);
4366 EXPECT_EQ(1U, origins.size());
4367 EXPECT_EQ(origin_id, origins[0].GetOriginIdentifier());
4369 // Create local storage. We only simulate this by creating the backing files.
4370 // Note: This test depends on details of how the dom_storage library
4371 // stores data in the host file system.
4372 base::FilePath lso_dir_path =
4373 profile_->GetPath().AppendASCII("Local Storage");
4374 base::FilePath lso_file_path = lso_dir_path.AppendASCII(origin_id)
4375 .AddExtension(FILE_PATH_LITERAL(".localstorage"));
4376 EXPECT_TRUE(base::CreateDirectory(lso_dir_path));
4377 EXPECT_EQ(0, base::WriteFile(lso_file_path, NULL, 0));
4378 EXPECT_TRUE(base::PathExists(lso_file_path));
4380 // Create indexed db. Similarly, it is enough to only simulate this by
4381 // creating the directory on the disk.
4382 IndexedDBContext* idb_context =
4383 BrowserContext::GetDefaultStoragePartition(profile_.get())->
4384 GetIndexedDBContext();
4385 idb_context->SetTaskRunnerForTesting(
4386 base::MessageLoop::current()->message_loop_proxy().get());
4387 base::FilePath idb_path = idb_context->GetFilePathForTesting(origin_id);
4388 EXPECT_TRUE(base::CreateDirectory(idb_path));
4389 EXPECT_TRUE(base::DirectoryExists(idb_path));
4391 // Uninstall the extension.
4392 service_->UninstallExtension(good_crx, false, NULL);
4393 base::RunLoop().RunUntilIdle();
4395 // Check that the cookie is gone.
4396 cookie_monster->GetAllCookiesForURLAsync(
4397 ext_url,
4398 base::Bind(&ExtensionCookieCallback::GetAllCookiesCallback,
4399 base::Unretained(&callback)));
4400 base::RunLoop().RunUntilIdle();
4401 EXPECT_EQ(0U, callback.list_.size());
4403 // The database should have vanished as well.
4404 origins.clear();
4405 db_tracker->GetAllOriginsInfo(&origins);
4406 EXPECT_EQ(0U, origins.size());
4408 // Check that the LSO file has been removed.
4409 EXPECT_FALSE(base::PathExists(lso_file_path));
4411 // Check if the indexed db has disappeared too.
4412 EXPECT_FALSE(base::DirectoryExists(idb_path));
4415 // Verifies app state is removed upon uninstall.
4416 TEST_F(ExtensionServiceTest, ClearAppData) {
4417 InitializeEmptyExtensionService();
4418 ExtensionCookieCallback callback;
4420 int pref_count = 0;
4422 // Install app1 with unlimited storage.
4423 const Extension* extension =
4424 PackAndInstallCRX(data_dir_.AppendASCII("app1"), INSTALL_NEW);
4425 ValidatePrefKeyCount(++pref_count);
4426 ASSERT_EQ(1u, registry_->enabled_extensions().size());
4427 const std::string id1 = extension->id();
4428 EXPECT_TRUE(extension->HasAPIPermission(
4429 APIPermission::kUnlimitedStorage));
4430 const GURL origin1(
4431 extensions::AppLaunchInfo::GetFullLaunchURL(extension).GetOrigin());
4432 EXPECT_TRUE(profile_->GetExtensionSpecialStoragePolicy()->
4433 IsStorageUnlimited(origin1));
4434 std::string origin_id = webkit_database::GetIdentifierFromOrigin(origin1);
4436 // Install app2 from the same origin with unlimited storage.
4437 extension = PackAndInstallCRX(data_dir_.AppendASCII("app2"), INSTALL_NEW);
4438 ValidatePrefKeyCount(++pref_count);
4439 ASSERT_EQ(2u, registry_->enabled_extensions().size());
4440 const std::string id2 = extension->id();
4441 EXPECT_TRUE(extension->HasAPIPermission(
4442 APIPermission::kUnlimitedStorage));
4443 EXPECT_TRUE(extension->web_extent().MatchesURL(
4444 extensions::AppLaunchInfo::GetFullLaunchURL(extension)));
4445 const GURL origin2(
4446 extensions::AppLaunchInfo::GetFullLaunchURL(extension).GetOrigin());
4447 EXPECT_EQ(origin1, origin2);
4448 EXPECT_TRUE(profile_->GetExtensionSpecialStoragePolicy()->
4449 IsStorageUnlimited(origin2));
4451 // Set a cookie for the extension.
4452 net::CookieMonster* cookie_monster =
4453 profile_->GetRequestContext()->GetURLRequestContext()->
4454 cookie_store()->GetCookieMonster();
4455 ASSERT_TRUE(cookie_monster);
4456 net::CookieOptions options;
4457 cookie_monster->SetCookieWithOptionsAsync(
4458 origin1, "dummy=value", options,
4459 base::Bind(&ExtensionCookieCallback::SetCookieCallback,
4460 base::Unretained(&callback)));
4461 base::RunLoop().RunUntilIdle();
4462 EXPECT_TRUE(callback.result_);
4464 cookie_monster->GetAllCookiesForURLAsync(
4465 origin1,
4466 base::Bind(&ExtensionCookieCallback::GetAllCookiesCallback,
4467 base::Unretained(&callback)));
4468 base::RunLoop().RunUntilIdle();
4469 EXPECT_EQ(1U, callback.list_.size());
4471 // Open a database.
4472 webkit_database::DatabaseTracker* db_tracker =
4473 BrowserContext::GetDefaultStoragePartition(profile_.get())->
4474 GetDatabaseTracker();
4475 base::string16 db_name = base::UTF8ToUTF16("db");
4476 base::string16 description = base::UTF8ToUTF16("db_description");
4477 int64 size;
4478 db_tracker->DatabaseOpened(origin_id, db_name, description, 1, &size);
4479 db_tracker->DatabaseClosed(origin_id, db_name);
4480 std::vector<webkit_database::OriginInfo> origins;
4481 db_tracker->GetAllOriginsInfo(&origins);
4482 EXPECT_EQ(1U, origins.size());
4483 EXPECT_EQ(origin_id, origins[0].GetOriginIdentifier());
4485 // Create local storage. We only simulate this by creating the backing files.
4486 // Note: This test depends on details of how the dom_storage library
4487 // stores data in the host file system.
4488 base::FilePath lso_dir_path =
4489 profile_->GetPath().AppendASCII("Local Storage");
4490 base::FilePath lso_file_path = lso_dir_path.AppendASCII(origin_id)
4491 .AddExtension(FILE_PATH_LITERAL(".localstorage"));
4492 EXPECT_TRUE(base::CreateDirectory(lso_dir_path));
4493 EXPECT_EQ(0, base::WriteFile(lso_file_path, NULL, 0));
4494 EXPECT_TRUE(base::PathExists(lso_file_path));
4496 // Create indexed db. Similarly, it is enough to only simulate this by
4497 // creating the directory on the disk.
4498 IndexedDBContext* idb_context =
4499 BrowserContext::GetDefaultStoragePartition(profile_.get())->
4500 GetIndexedDBContext();
4501 idb_context->SetTaskRunnerForTesting(
4502 base::MessageLoop::current()->message_loop_proxy().get());
4503 base::FilePath idb_path = idb_context->GetFilePathForTesting(origin_id);
4504 EXPECT_TRUE(base::CreateDirectory(idb_path));
4505 EXPECT_TRUE(base::DirectoryExists(idb_path));
4507 // Uninstall one of them, unlimited storage should still be granted
4508 // to the origin.
4509 UninstallExtension(id1, false);
4510 EXPECT_EQ(1u, registry_->enabled_extensions().size());
4511 EXPECT_TRUE(profile_->GetExtensionSpecialStoragePolicy()->
4512 IsStorageUnlimited(origin1));
4514 // Check that the cookie is still there.
4515 cookie_monster->GetAllCookiesForURLAsync(
4516 origin1,
4517 base::Bind(&ExtensionCookieCallback::GetAllCookiesCallback,
4518 base::Unretained(&callback)));
4519 base::RunLoop().RunUntilIdle();
4520 EXPECT_EQ(1U, callback.list_.size());
4522 // Now uninstall the other. Storage should be cleared for the apps.
4523 UninstallExtension(id2, false);
4524 EXPECT_EQ(0u, registry_->enabled_extensions().size());
4525 EXPECT_FALSE(profile_->GetExtensionSpecialStoragePolicy()->
4526 IsStorageUnlimited(origin1));
4528 // Check that the cookie is gone.
4529 cookie_monster->GetAllCookiesForURLAsync(
4530 origin1,
4531 base::Bind(&ExtensionCookieCallback::GetAllCookiesCallback,
4532 base::Unretained(&callback)));
4533 base::RunLoop().RunUntilIdle();
4534 EXPECT_EQ(0U, callback.list_.size());
4536 // The database should have vanished as well.
4537 origins.clear();
4538 db_tracker->GetAllOriginsInfo(&origins);
4539 EXPECT_EQ(0U, origins.size());
4541 // Check that the LSO file has been removed.
4542 EXPECT_FALSE(base::PathExists(lso_file_path));
4544 // Check if the indexed db has disappeared too.
4545 EXPECT_FALSE(base::DirectoryExists(idb_path));
4548 // Tests loading single extensions (like --load-extension)
4549 // Flaky crashes. http://crbug.com/231806
4550 TEST_F(ExtensionServiceTest, DISABLED_LoadExtension) {
4551 InitializeEmptyExtensionService();
4553 base::FilePath ext1 = data_dir_
4554 .AppendASCII("good")
4555 .AppendASCII("Extensions")
4556 .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
4557 .AppendASCII("1.0.0.0");
4558 extensions::UnpackedInstaller::Create(service_)->Load(ext1);
4559 base::RunLoop().RunUntilIdle();
4560 EXPECT_EQ(0u, GetErrors().size());
4561 ASSERT_EQ(1u, loaded_.size());
4562 EXPECT_EQ(Manifest::UNPACKED, loaded_[0]->location());
4563 EXPECT_EQ(1u, registry_->enabled_extensions().size());
4565 ValidatePrefKeyCount(1);
4567 base::FilePath no_manifest = data_dir_
4568 .AppendASCII("bad")
4569 // .AppendASCII("Extensions")
4570 .AppendASCII("cccccccccccccccccccccccccccccccc")
4571 .AppendASCII("1");
4572 extensions::UnpackedInstaller::Create(service_)->Load(no_manifest);
4573 base::RunLoop().RunUntilIdle();
4574 EXPECT_EQ(1u, GetErrors().size());
4575 ASSERT_EQ(1u, loaded_.size());
4576 EXPECT_EQ(1u, registry_->enabled_extensions().size());
4578 // Test uninstall.
4579 std::string id = loaded_[0]->id();
4580 EXPECT_FALSE(unloaded_id_.length());
4581 service_->UninstallExtension(id, false, NULL);
4582 base::RunLoop().RunUntilIdle();
4583 EXPECT_EQ(id, unloaded_id_);
4584 ASSERT_EQ(0u, loaded_.size());
4585 EXPECT_EQ(0u, registry_->enabled_extensions().size());
4588 // Tests that we generate IDs when they are not specified in the manifest for
4589 // --load-extension.
4590 TEST_F(ExtensionServiceTest, GenerateID) {
4591 InitializeEmptyExtensionService();
4593 base::FilePath no_id_ext = data_dir_.AppendASCII("no_id");
4594 extensions::UnpackedInstaller::Create(service_)->Load(no_id_ext);
4595 base::RunLoop().RunUntilIdle();
4596 EXPECT_EQ(0u, GetErrors().size());
4597 ASSERT_EQ(1u, loaded_.size());
4598 ASSERT_TRUE(Extension::IdIsValid(loaded_[0]->id()));
4599 EXPECT_EQ(loaded_[0]->location(), Manifest::UNPACKED);
4601 ValidatePrefKeyCount(1);
4603 std::string previous_id = loaded_[0]->id();
4605 // If we reload the same path, we should get the same extension ID.
4606 extensions::UnpackedInstaller::Create(service_)->Load(no_id_ext);
4607 base::RunLoop().RunUntilIdle();
4608 ASSERT_EQ(1u, loaded_.size());
4609 ASSERT_EQ(previous_id, loaded_[0]->id());
4612 TEST_F(ExtensionServiceTest, UnpackedValidatesLocales) {
4613 InitializeEmptyExtensionService();
4615 base::FilePath bad_locale = data_dir_.AppendASCII("unpacked").
4616 AppendASCII("bad_messages_file");
4617 extensions::UnpackedInstaller::Create(service_)->Load(bad_locale);
4618 base::RunLoop().RunUntilIdle();
4619 EXPECT_EQ(1u, GetErrors().size());
4620 base::FilePath ms_messages_file = bad_locale.AppendASCII("_locales")
4621 .AppendASCII("ms")
4622 .AppendASCII("messages.json");
4623 EXPECT_THAT(base::UTF16ToUTF8(GetErrors()[0]), testing::AllOf(
4624 testing::HasSubstr(
4625 base::UTF16ToUTF8(ms_messages_file.LossyDisplayName())),
4626 testing::HasSubstr("Dictionary keys must be quoted.")));
4627 ASSERT_EQ(0u, loaded_.size());
4630 void ExtensionServiceTest::TestExternalProvider(
4631 MockExtensionProvider* provider, Manifest::Location location) {
4632 // Verify that starting with no providers loads no extensions.
4633 service_->Init();
4634 ASSERT_EQ(0u, loaded_.size());
4636 provider->set_visit_count(0);
4638 // Register a test extension externally using the mock registry provider.
4639 base::FilePath source_path = data_dir_.AppendASCII("good.crx");
4641 // Add the extension.
4642 provider->UpdateOrAddExtension(good_crx, "1.0.0.0", source_path);
4644 // Reloading extensions should find our externally registered extension
4645 // and install it.
4646 content::WindowedNotificationObserver observer(
4647 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
4648 content::NotificationService::AllSources());
4649 service_->CheckForExternalUpdates();
4650 observer.Wait();
4652 ASSERT_EQ(0u, GetErrors().size());
4653 ASSERT_EQ(1u, loaded_.size());
4654 ASSERT_EQ(location, loaded_[0]->location());
4655 ASSERT_EQ("1.0.0.0", loaded_[0]->version()->GetString());
4656 ValidatePrefKeyCount(1);
4657 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
4658 ValidateIntegerPref(good_crx, "location", location);
4660 // Reload extensions without changing anything. The extension should be
4661 // loaded again.
4662 loaded_.clear();
4663 service_->ReloadExtensionsForTest();
4664 base::RunLoop().RunUntilIdle();
4665 ASSERT_EQ(0u, GetErrors().size());
4666 ASSERT_EQ(1u, loaded_.size());
4667 ValidatePrefKeyCount(1);
4668 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
4669 ValidateIntegerPref(good_crx, "location", location);
4671 // Now update the extension with a new version. We should get upgraded.
4672 source_path = source_path.DirName().AppendASCII("good2.crx");
4673 provider->UpdateOrAddExtension(good_crx, "1.0.0.1", source_path);
4675 loaded_.clear();
4676 content::WindowedNotificationObserver observer_2(
4677 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
4678 content::NotificationService::AllSources());
4679 service_->CheckForExternalUpdates();
4680 observer_2.Wait();
4681 ASSERT_EQ(0u, GetErrors().size());
4682 ASSERT_EQ(1u, loaded_.size());
4683 ASSERT_EQ("1.0.0.1", loaded_[0]->version()->GetString());
4684 ValidatePrefKeyCount(1);
4685 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
4686 ValidateIntegerPref(good_crx, "location", location);
4688 // Uninstall the extension and reload. Nothing should happen because the
4689 // preference should prevent us from reinstalling.
4690 std::string id = loaded_[0]->id();
4691 bool no_uninstall =
4692 management_policy_->MustRemainEnabled(loaded_[0].get(), NULL);
4693 service_->UninstallExtension(id, false, NULL);
4694 base::RunLoop().RunUntilIdle();
4696 base::FilePath install_path = extensions_install_dir_.AppendASCII(id);
4697 if (no_uninstall) {
4698 // Policy controlled extensions should not have been touched by uninstall.
4699 ASSERT_TRUE(base::PathExists(install_path));
4700 } else {
4701 // The extension should also be gone from the install directory.
4702 ASSERT_FALSE(base::PathExists(install_path));
4703 loaded_.clear();
4704 service_->CheckForExternalUpdates();
4705 base::RunLoop().RunUntilIdle();
4706 ASSERT_EQ(0u, loaded_.size());
4707 ValidatePrefKeyCount(1);
4708 ValidateIntegerPref(good_crx, "state",
4709 Extension::EXTERNAL_EXTENSION_UNINSTALLED);
4710 ValidateIntegerPref(good_crx, "location", location);
4712 // Now clear the preference and reinstall.
4713 SetPrefInteg(good_crx, "state", Extension::ENABLED);
4715 loaded_.clear();
4716 content::WindowedNotificationObserver observer(
4717 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
4718 content::NotificationService::AllSources());
4719 service_->CheckForExternalUpdates();
4720 observer.Wait();
4721 ASSERT_EQ(1u, loaded_.size());
4723 ValidatePrefKeyCount(1);
4724 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
4725 ValidateIntegerPref(good_crx, "location", location);
4727 if (management_policy_->MustRemainEnabled(loaded_[0].get(), NULL)) {
4728 EXPECT_EQ(2, provider->visit_count());
4729 } else {
4730 // Now test an externally triggered uninstall (deleting the registry key or
4731 // the pref entry).
4732 provider->RemoveExtension(good_crx);
4734 loaded_.clear();
4735 service_->OnExternalProviderReady(provider);
4736 base::RunLoop().RunUntilIdle();
4737 ASSERT_EQ(0u, loaded_.size());
4738 ValidatePrefKeyCount(0);
4740 // The extension should also be gone from the install directory.
4741 ASSERT_FALSE(base::PathExists(install_path));
4743 // Now test the case where user uninstalls and then the extension is removed
4744 // from the external provider.
4745 content::WindowedNotificationObserver observer(
4746 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
4747 content::NotificationService::AllSources());
4748 provider->UpdateOrAddExtension(good_crx, "1.0.0.1", source_path);
4749 service_->CheckForExternalUpdates();
4750 observer.Wait();
4752 ASSERT_EQ(1u, loaded_.size());
4753 ASSERT_EQ(0u, GetErrors().size());
4755 // User uninstalls.
4756 loaded_.clear();
4757 service_->UninstallExtension(id, false, NULL);
4758 base::RunLoop().RunUntilIdle();
4759 ASSERT_EQ(0u, loaded_.size());
4761 // Then remove the extension from the extension provider.
4762 provider->RemoveExtension(good_crx);
4764 // Should still be at 0.
4765 loaded_.clear();
4766 extensions::InstalledLoader(service_).LoadAllExtensions();
4767 base::RunLoop().RunUntilIdle();
4768 ASSERT_EQ(0u, loaded_.size());
4769 ValidatePrefKeyCount(1);
4771 EXPECT_EQ(5, provider->visit_count());
4775 // Tests the external installation feature
4776 #if defined(OS_WIN)
4777 TEST_F(ExtensionServiceTest, ExternalInstallRegistry) {
4778 // This should all work, even when normal extension installation is disabled.
4779 InitializeEmptyExtensionService();
4780 set_extensions_enabled(false);
4782 // Now add providers. Extension system takes ownership of the objects.
4783 MockExtensionProvider* reg_provider =
4784 new MockExtensionProvider(service_, Manifest::EXTERNAL_REGISTRY);
4785 AddMockExternalProvider(reg_provider);
4786 TestExternalProvider(reg_provider, Manifest::EXTERNAL_REGISTRY);
4788 #endif
4790 TEST_F(ExtensionServiceTest, ExternalInstallPref) {
4791 InitializeEmptyExtensionService();
4793 // Now add providers. Extension system takes ownership of the objects.
4794 MockExtensionProvider* pref_provider =
4795 new MockExtensionProvider(service_, Manifest::EXTERNAL_PREF);
4797 AddMockExternalProvider(pref_provider);
4798 TestExternalProvider(pref_provider, Manifest::EXTERNAL_PREF);
4801 TEST_F(ExtensionServiceTest, ExternalInstallPrefUpdateUrl) {
4802 // This should all work, even when normal extension installation is disabled.
4803 InitializeEmptyExtensionService();
4804 set_extensions_enabled(false);
4806 // TODO(skerner): The mock provider is not a good model of a provider
4807 // that works with update URLs, because it adds file and version info.
4808 // Extend the mock to work with update URLs. This test checks the
4809 // behavior that is common to all external extension visitors. The
4810 // browser test ExtensionManagementTest.ExternalUrlUpdate tests that
4811 // what the visitor does results in an extension being downloaded and
4812 // installed.
4813 MockExtensionProvider* pref_provider =
4814 new MockExtensionProvider(service_,
4815 Manifest::EXTERNAL_PREF_DOWNLOAD);
4816 AddMockExternalProvider(pref_provider);
4817 TestExternalProvider(pref_provider, Manifest::EXTERNAL_PREF_DOWNLOAD);
4820 TEST_F(ExtensionServiceTest, ExternalInstallPolicyUpdateUrl) {
4821 // This should all work, even when normal extension installation is disabled.
4822 InitializeEmptyExtensionService();
4823 set_extensions_enabled(false);
4825 // TODO(skerner): The mock provider is not a good model of a provider
4826 // that works with update URLs, because it adds file and version info.
4827 // Extend the mock to work with update URLs. This test checks the
4828 // behavior that is common to all external extension visitors. The
4829 // browser test ExtensionManagementTest.ExternalUrlUpdate tests that
4830 // what the visitor does results in an extension being downloaded and
4831 // installed.
4832 MockExtensionProvider* pref_provider =
4833 new MockExtensionProvider(service_,
4834 Manifest::EXTERNAL_POLICY_DOWNLOAD);
4835 AddMockExternalProvider(pref_provider);
4836 TestExternalProvider(pref_provider, Manifest::EXTERNAL_POLICY_DOWNLOAD);
4839 // Tests that external extensions get uninstalled when the external extension
4840 // providers can't account for them.
4841 TEST_F(ExtensionServiceTest, ExternalUninstall) {
4842 // Start the extensions service with one external extension already installed.
4843 base::FilePath source_install_dir = data_dir_
4844 .AppendASCII("good")
4845 .AppendASCII("Extensions");
4846 base::FilePath pref_path = source_install_dir
4847 .DirName()
4848 .AppendASCII("PreferencesExternal");
4850 // This initializes the extensions service with no ExternalProviders.
4851 InitializeInstalledExtensionService(pref_path, source_install_dir);
4852 set_extensions_enabled(false);
4854 service_->Init();
4856 ASSERT_EQ(0u, GetErrors().size());
4857 ASSERT_EQ(0u, loaded_.size());
4859 // Verify that it's not the disabled extensions flag causing it not to load.
4860 set_extensions_enabled(true);
4861 service_->ReloadExtensionsForTest();
4862 base::RunLoop().RunUntilIdle();
4864 ASSERT_EQ(0u, GetErrors().size());
4865 ASSERT_EQ(0u, loaded_.size());
4868 // Test that running multiple update checks simultaneously does not
4869 // keep the update from succeeding.
4870 TEST_F(ExtensionServiceTest, MultipleExternalUpdateCheck) {
4871 InitializeEmptyExtensionService();
4873 MockExtensionProvider* provider =
4874 new MockExtensionProvider(service_, Manifest::EXTERNAL_PREF);
4875 AddMockExternalProvider(provider);
4877 // Verify that starting with no providers loads no extensions.
4878 service_->Init();
4879 ASSERT_EQ(0u, loaded_.size());
4881 // Start two checks for updates.
4882 provider->set_visit_count(0);
4883 service_->CheckForExternalUpdates();
4884 service_->CheckForExternalUpdates();
4885 base::RunLoop().RunUntilIdle();
4887 // Two calls should cause two checks for external extensions.
4888 EXPECT_EQ(2, provider->visit_count());
4889 EXPECT_EQ(0u, GetErrors().size());
4890 EXPECT_EQ(0u, loaded_.size());
4892 // Register a test extension externally using the mock registry provider.
4893 base::FilePath source_path = data_dir_.AppendASCII("good.crx");
4894 provider->UpdateOrAddExtension(good_crx, "1.0.0.0", source_path);
4896 // Two checks for external updates should find the extension, and install it
4897 // once.
4898 content::WindowedNotificationObserver observer(
4899 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
4900 content::NotificationService::AllSources());
4901 provider->set_visit_count(0);
4902 service_->CheckForExternalUpdates();
4903 service_->CheckForExternalUpdates();
4904 observer.Wait();
4905 EXPECT_EQ(2, provider->visit_count());
4906 ASSERT_EQ(0u, GetErrors().size());
4907 ASSERT_EQ(1u, loaded_.size());
4908 ASSERT_EQ(Manifest::EXTERNAL_PREF, loaded_[0]->location());
4909 ASSERT_EQ("1.0.0.0", loaded_[0]->version()->GetString());
4910 ValidatePrefKeyCount(1);
4911 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
4912 ValidateIntegerPref(good_crx, "location", Manifest::EXTERNAL_PREF);
4914 provider->RemoveExtension(good_crx);
4915 provider->set_visit_count(0);
4916 service_->CheckForExternalUpdates();
4917 service_->CheckForExternalUpdates();
4918 base::RunLoop().RunUntilIdle();
4920 // Two calls should cause two checks for external extensions.
4921 // Because the external source no longer includes good_crx,
4922 // good_crx will be uninstalled. So, expect that no extensions
4923 // are loaded.
4924 EXPECT_EQ(2, provider->visit_count());
4925 EXPECT_EQ(0u, GetErrors().size());
4926 EXPECT_EQ(0u, loaded_.size());
4929 TEST_F(ExtensionServiceTest, ExternalPrefProvider) {
4930 InitializeEmptyExtensionService();
4932 // Test some valid extension records.
4933 // Set a base path to avoid erroring out on relative paths.
4934 // Paths starting with // are absolute on every platform we support.
4935 base::FilePath base_path(FILE_PATH_LITERAL("//base/path"));
4936 ASSERT_TRUE(base_path.IsAbsolute());
4937 MockProviderVisitor visitor(base_path);
4938 std::string json_data =
4940 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
4941 " \"external_crx\": \"RandomExtension.crx\","
4942 " \"external_version\": \"1.0\""
4943 " },"
4944 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\": {"
4945 " \"external_crx\": \"RandomExtension2.crx\","
4946 " \"external_version\": \"2.0\""
4947 " },"
4948 " \"cccccccccccccccccccccccccccccccc\": {"
4949 " \"external_update_url\": \"http:\\\\foo.com/update\","
4950 " \"install_parameter\": \"id\""
4951 " }"
4952 "}";
4953 EXPECT_EQ(3, visitor.Visit(json_data));
4955 // Simulate an external_extensions.json file that contains seven invalid
4956 // records:
4957 // - One that is missing the 'external_crx' key.
4958 // - One that is missing the 'external_version' key.
4959 // - One that is specifying .. in the path.
4960 // - One that specifies both a file and update URL.
4961 // - One that specifies no file or update URL.
4962 // - One that has an update URL that is not well formed.
4963 // - One that contains a malformed version.
4964 // - One that has an invalid id.
4965 // - One that has a non-dictionary value.
4966 // - One that has an integer 'external_version' instead of a string.
4967 // The final extension is valid, and we check that it is read to make sure
4968 // failures don't stop valid records from being read.
4969 json_data =
4971 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
4972 " \"external_version\": \"1.0\""
4973 " },"
4974 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\": {"
4975 " \"external_crx\": \"RandomExtension.crx\""
4976 " },"
4977 " \"cccccccccccccccccccccccccccccccc\": {"
4978 " \"external_crx\": \"..\\\\foo\\\\RandomExtension2.crx\","
4979 " \"external_version\": \"2.0\""
4980 " },"
4981 " \"dddddddddddddddddddddddddddddddd\": {"
4982 " \"external_crx\": \"RandomExtension2.crx\","
4983 " \"external_version\": \"2.0\","
4984 " \"external_update_url\": \"http:\\\\foo.com/update\""
4985 " },"
4986 " \"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\": {"
4987 " },"
4988 " \"ffffffffffffffffffffffffffffffff\": {"
4989 " \"external_update_url\": \"This string is not a valid URL\""
4990 " },"
4991 " \"gggggggggggggggggggggggggggggggg\": {"
4992 " \"external_crx\": \"RandomExtension3.crx\","
4993 " \"external_version\": \"This is not a valid version!\""
4994 " },"
4995 " \"This is not a valid id!\": {},"
4996 " \"hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh\": true,"
4997 " \"iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii\": {"
4998 " \"external_crx\": \"RandomExtension4.crx\","
4999 " \"external_version\": 1.0"
5000 " },"
5001 " \"pppppppppppppppppppppppppppppppp\": {"
5002 " \"external_crx\": \"RandomValidExtension.crx\","
5003 " \"external_version\": \"1.0\""
5004 " }"
5005 "}";
5006 EXPECT_EQ(1, visitor.Visit(json_data));
5008 // Check that if a base path is not provided, use of a relative
5009 // path fails.
5010 base::FilePath empty;
5011 MockProviderVisitor visitor_no_relative_paths(empty);
5013 // Use absolute paths. Expect success.
5014 json_data =
5016 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5017 " \"external_crx\": \"//RandomExtension1.crx\","
5018 " \"external_version\": \"3.0\""
5019 " },"
5020 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\": {"
5021 " \"external_crx\": \"//path/to/RandomExtension2.crx\","
5022 " \"external_version\": \"3.0\""
5023 " }"
5024 "}";
5025 EXPECT_EQ(2, visitor_no_relative_paths.Visit(json_data));
5027 // Use a relative path. Expect that it will error out.
5028 json_data =
5030 " \"cccccccccccccccccccccccccccccccc\": {"
5031 " \"external_crx\": \"RandomExtension2.crx\","
5032 " \"external_version\": \"3.0\""
5033 " }"
5034 "}";
5035 EXPECT_EQ(0, visitor_no_relative_paths.Visit(json_data));
5037 // Test supported_locales.
5038 json_data =
5040 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5041 " \"external_crx\": \"RandomExtension.crx\","
5042 " \"external_version\": \"1.0\","
5043 " \"supported_locales\": [ \"en\" ]"
5044 " },"
5045 " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\": {"
5046 " \"external_crx\": \"RandomExtension2.crx\","
5047 " \"external_version\": \"2.0\","
5048 " \"supported_locales\": [ \"en-GB\" ]"
5049 " },"
5050 " \"cccccccccccccccccccccccccccccccc\": {"
5051 " \"external_crx\": \"RandomExtension2.crx\","
5052 " \"external_version\": \"3.0\","
5053 " \"supported_locales\": [ \"en_US\", \"fr\" ]"
5054 " }"
5055 "}";
5057 ScopedBrowserLocale guard("en-US");
5058 EXPECT_EQ(2, visitor.Visit(json_data));
5061 // Test keep_if_present.
5062 json_data =
5064 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5065 " \"external_crx\": \"RandomExtension.crx\","
5066 " \"external_version\": \"1.0\","
5067 " \"keep_if_present\": true"
5068 " }"
5069 "}";
5071 EXPECT_EQ(0, visitor.Visit(json_data));
5074 // Test is_bookmark_app.
5075 MockProviderVisitor from_bookmark_visitor(
5076 base_path, Extension::FROM_BOOKMARK);
5077 json_data =
5079 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5080 " \"external_crx\": \"RandomExtension.crx\","
5081 " \"external_version\": \"1.0\","
5082 " \"is_bookmark_app\": true"
5083 " }"
5084 "}";
5085 EXPECT_EQ(1, from_bookmark_visitor.Visit(json_data));
5087 // Test is_from_webstore.
5088 MockProviderVisitor from_webstore_visitor(
5089 base_path, Extension::FROM_WEBSTORE);
5090 json_data =
5092 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5093 " \"external_crx\": \"RandomExtension.crx\","
5094 " \"external_version\": \"1.0\","
5095 " \"is_from_webstore\": true"
5096 " }"
5097 "}";
5098 EXPECT_EQ(1, from_webstore_visitor.Visit(json_data));
5100 // Test was_installed_by_eom.
5101 MockProviderVisitor was_installed_by_eom_visitor(
5102 base_path, Extension::WAS_INSTALLED_BY_OEM);
5103 json_data =
5105 " \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\": {"
5106 " \"external_crx\": \"RandomExtension.crx\","
5107 " \"external_version\": \"1.0\","
5108 " \"was_installed_by_oem\": true"
5109 " }"
5110 "}";
5111 EXPECT_EQ(1, was_installed_by_eom_visitor.Visit(json_data));
5114 // Test loading good extensions from the profile directory.
5115 TEST_F(ExtensionServiceTest, LoadAndRelocalizeExtensions) {
5116 // Ensure we're testing in "en" and leave global state untouched.
5117 extension_l10n_util::ScopedLocaleForTest testLocale("en");
5119 // Initialize the test dir with a good Preferences/extensions.
5120 base::FilePath source_install_dir = data_dir_
5121 .AppendASCII("l10n");
5122 base::FilePath pref_path =
5123 source_install_dir.Append(chrome::kPreferencesFilename);
5124 InitializeInstalledExtensionService(pref_path, source_install_dir);
5126 service_->Init();
5128 ASSERT_EQ(3u, loaded_.size());
5130 // This was equal to "sr" on load.
5131 ValidateStringPref(loaded_[0]->id(), keys::kCurrentLocale, "en");
5133 // These are untouched by re-localization.
5134 ValidateStringPref(loaded_[1]->id(), keys::kCurrentLocale, "en");
5135 EXPECT_FALSE(IsPrefExist(loaded_[1]->id(), keys::kCurrentLocale));
5137 // This one starts with Serbian name, and gets re-localized into English.
5138 EXPECT_EQ("My name is simple.", loaded_[0]->name());
5140 // These are untouched by re-localization.
5141 EXPECT_EQ("My name is simple.", loaded_[1]->name());
5142 EXPECT_EQ("no l10n", loaded_[2]->name());
5145 class ExtensionsReadyRecorder : public content::NotificationObserver {
5146 public:
5147 ExtensionsReadyRecorder() : ready_(false) {
5148 registrar_.Add(this, chrome::NOTIFICATION_EXTENSIONS_READY,
5149 content::NotificationService::AllSources());
5152 void set_ready(bool value) { ready_ = value; }
5153 bool ready() { return ready_; }
5155 private:
5156 virtual void Observe(int type,
5157 const content::NotificationSource& source,
5158 const content::NotificationDetails& details) OVERRIDE {
5159 switch (type) {
5160 case chrome::NOTIFICATION_EXTENSIONS_READY:
5161 ready_ = true;
5162 break;
5163 default:
5164 NOTREACHED();
5168 content::NotificationRegistrar registrar_;
5169 bool ready_;
5172 // Test that we get enabled/disabled correctly for all the pref/command-line
5173 // combinations. We don't want to derive from the ExtensionServiceTest class
5174 // for this test, so we use ExtensionServiceTestSimple.
5176 // Also tests that we always fire EXTENSIONS_READY, no matter whether we are
5177 // enabled or not.
5178 TEST(ExtensionServiceTestSimple, Enabledness) {
5179 // Make sure the PluginService singleton is destroyed at the end of the test.
5180 base::ShadowingAtExitManager at_exit_manager;
5181 #if defined(ENABLE_PLUGINS)
5182 content::PluginService::GetInstance()->Init();
5183 content::PluginService::GetInstance()->DisablePluginsDiscoveryForTesting();
5184 #endif
5186 ExtensionErrorReporter::Init(false); // no noisy errors
5187 ExtensionsReadyRecorder recorder;
5188 scoped_ptr<TestingProfile> profile(new TestingProfile());
5189 content::TestBrowserThreadBundle thread_bundle_;
5190 #if defined OS_CHROMEOS
5191 chromeos::ScopedTestDeviceSettingsService device_settings_service;
5192 chromeos::ScopedTestCrosSettings cros_settings;
5193 scoped_ptr<chromeos::ScopedTestUserManager> user_manager(
5194 new chromeos::ScopedTestUserManager);
5195 #endif
5196 scoped_ptr<CommandLine> command_line;
5197 base::FilePath install_dir = profile->GetPath()
5198 .AppendASCII(extensions::kInstallDirectoryName);
5200 // By default, we are enabled.
5201 command_line.reset(new CommandLine(CommandLine::NO_PROGRAM));
5202 ExtensionService* service = static_cast<extensions::TestExtensionSystem*>(
5203 ExtensionSystem::Get(profile.get()))->
5204 CreateExtensionService(
5205 command_line.get(),
5206 install_dir,
5207 false);
5208 EXPECT_TRUE(service->extensions_enabled());
5209 service->Init();
5210 base::RunLoop().RunUntilIdle();
5211 EXPECT_TRUE(recorder.ready());
5212 #if defined OS_CHROMEOS
5213 user_manager.reset();
5214 #endif
5216 // If either the command line or pref is set, we are disabled.
5217 recorder.set_ready(false);
5218 profile.reset(new TestingProfile());
5219 command_line->AppendSwitch(switches::kDisableExtensions);
5220 service = static_cast<extensions::TestExtensionSystem*>(
5221 ExtensionSystem::Get(profile.get()))->
5222 CreateExtensionService(
5223 command_line.get(),
5224 install_dir,
5225 false);
5226 EXPECT_FALSE(service->extensions_enabled());
5227 service->Init();
5228 base::RunLoop().RunUntilIdle();
5229 EXPECT_TRUE(recorder.ready());
5231 recorder.set_ready(false);
5232 profile.reset(new TestingProfile());
5233 profile->GetPrefs()->SetBoolean(prefs::kDisableExtensions, true);
5234 service = static_cast<extensions::TestExtensionSystem*>(
5235 ExtensionSystem::Get(profile.get()))->
5236 CreateExtensionService(
5237 command_line.get(),
5238 install_dir,
5239 false);
5240 EXPECT_FALSE(service->extensions_enabled());
5241 service->Init();
5242 base::RunLoop().RunUntilIdle();
5243 EXPECT_TRUE(recorder.ready());
5245 recorder.set_ready(false);
5246 profile.reset(new TestingProfile());
5247 profile->GetPrefs()->SetBoolean(prefs::kDisableExtensions, true);
5248 command_line.reset(new CommandLine(CommandLine::NO_PROGRAM));
5249 service = static_cast<extensions::TestExtensionSystem*>(
5250 ExtensionSystem::Get(profile.get()))->
5251 CreateExtensionService(
5252 command_line.get(),
5253 install_dir,
5254 false);
5255 EXPECT_FALSE(service->extensions_enabled());
5256 service->Init();
5257 base::RunLoop().RunUntilIdle();
5258 EXPECT_TRUE(recorder.ready());
5260 // Explicitly delete all the resources used in this test.
5261 profile.reset();
5262 service = NULL;
5263 // Execute any pending deletion tasks.
5264 base::RunLoop().RunUntilIdle();
5267 // Test loading extensions that require limited and unlimited storage quotas.
5268 TEST_F(ExtensionServiceTest, StorageQuota) {
5269 InitializeEmptyExtensionService();
5271 base::FilePath extensions_path = data_dir_
5272 .AppendASCII("storage_quota");
5274 base::FilePath limited_quota_ext =
5275 extensions_path.AppendASCII("limited_quota")
5276 .AppendASCII("1.0");
5278 // The old permission name for unlimited quota was "unlimited_storage", but
5279 // we changed it to "unlimitedStorage". This tests both versions.
5280 base::FilePath unlimited_quota_ext =
5281 extensions_path.AppendASCII("unlimited_quota")
5282 .AppendASCII("1.0");
5283 base::FilePath unlimited_quota_ext2 =
5284 extensions_path.AppendASCII("unlimited_quota")
5285 .AppendASCII("2.0");
5286 extensions::UnpackedInstaller::Create(service_)->Load(limited_quota_ext);
5287 extensions::UnpackedInstaller::Create(service_)->Load(unlimited_quota_ext);
5288 extensions::UnpackedInstaller::Create(service_)->Load(unlimited_quota_ext2);
5289 base::RunLoop().RunUntilIdle();
5291 ASSERT_EQ(3u, loaded_.size());
5292 EXPECT_TRUE(profile_.get());
5293 EXPECT_FALSE(profile_->IsOffTheRecord());
5294 EXPECT_FALSE(profile_->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
5295 loaded_[0]->url()));
5296 EXPECT_TRUE(profile_->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
5297 loaded_[1]->url()));
5298 EXPECT_TRUE(profile_->GetExtensionSpecialStoragePolicy()->IsStorageUnlimited(
5299 loaded_[2]->url()));
5302 // Tests ComponentLoader::Add().
5303 TEST_F(ExtensionServiceTest, ComponentExtensions) {
5304 InitializeEmptyExtensionService();
5306 // Component extensions should work even when extensions are disabled.
5307 set_extensions_enabled(false);
5309 base::FilePath path = data_dir_
5310 .AppendASCII("good")
5311 .AppendASCII("Extensions")
5312 .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
5313 .AppendASCII("1.0.0.0");
5315 std::string manifest;
5316 ASSERT_TRUE(base::ReadFileToString(
5317 path.Append(extensions::kManifestFilename), &manifest));
5319 service_->component_loader()->Add(manifest, path);
5320 service_->Init();
5322 // Note that we do not pump messages -- the extension should be loaded
5323 // immediately.
5325 EXPECT_EQ(0u, GetErrors().size());
5326 ASSERT_EQ(1u, loaded_.size());
5327 EXPECT_EQ(Manifest::COMPONENT, loaded_[0]->location());
5328 EXPECT_EQ(1u, registry_->enabled_extensions().size());
5330 // Component extensions get a prefs entry on first install.
5331 ValidatePrefKeyCount(1);
5333 // Reload all extensions, and make sure it comes back.
5334 std::string extension_id = (*registry_->enabled_extensions().begin())->id();
5335 loaded_.clear();
5336 service_->ReloadExtensionsForTest();
5337 ASSERT_EQ(1u, registry_->enabled_extensions().size());
5338 EXPECT_EQ(extension_id, (*registry_->enabled_extensions().begin())->id());
5341 TEST_F(ExtensionServiceTest, DeferredSyncStartupPreInstalledComponent) {
5342 InitializeEmptyExtensionService();
5343 InitializeExtensionSyncService();
5345 bool flare_was_called = false;
5346 syncer::ModelType triggered_type(syncer::UNSPECIFIED);
5347 base::WeakPtrFactory<ExtensionServiceTest> factory(this);
5348 extension_sync_service_->SetSyncStartFlare(
5349 base::Bind(&ExtensionServiceTest::MockSyncStartFlare,
5350 factory.GetWeakPtr(),
5351 &flare_was_called, // Safe due to WeakPtrFactory scope.
5352 &triggered_type)); // Safe due to WeakPtrFactory scope.
5354 // Install a component extension.
5355 std::string manifest;
5356 ASSERT_TRUE(base::ReadFileToString(
5357 good0_path().Append(extensions::kManifestFilename), &manifest));
5358 service_->component_loader()->Add(manifest, good0_path());
5359 ASSERT_FALSE(service_->is_ready());
5360 service_->Init();
5361 ASSERT_TRUE(service_->is_ready());
5363 // Extensions added before service is_ready() don't trigger sync startup.
5364 EXPECT_FALSE(flare_was_called);
5365 ASSERT_EQ(syncer::UNSPECIFIED, triggered_type);
5368 TEST_F(ExtensionServiceTest, DeferredSyncStartupPreInstalledNormal) {
5369 InitializeGoodInstalledExtensionService();
5370 InitializeExtensionSyncService();
5372 bool flare_was_called = false;
5373 syncer::ModelType triggered_type(syncer::UNSPECIFIED);
5374 base::WeakPtrFactory<ExtensionServiceTest> factory(this);
5375 extension_sync_service_->SetSyncStartFlare(
5376 base::Bind(&ExtensionServiceTest::MockSyncStartFlare,
5377 factory.GetWeakPtr(),
5378 &flare_was_called, // Safe due to WeakPtrFactory scope.
5379 &triggered_type)); // Safe due to WeakPtrFactory scope.
5381 ASSERT_FALSE(service_->is_ready());
5382 service_->Init();
5383 ASSERT_EQ(3u, loaded_.size());
5384 ASSERT_TRUE(service_->is_ready());
5386 // Extensions added before service is_ready() don't trigger sync startup.
5387 EXPECT_FALSE(flare_was_called);
5388 ASSERT_EQ(syncer::UNSPECIFIED, triggered_type);
5391 TEST_F(ExtensionServiceTest, DeferredSyncStartupOnInstall) {
5392 InitializeEmptyExtensionService();
5393 InitializeExtensionSyncService();
5394 service_->Init();
5395 ASSERT_TRUE(service_->is_ready());
5397 bool flare_was_called = false;
5398 syncer::ModelType triggered_type(syncer::UNSPECIFIED);
5399 base::WeakPtrFactory<ExtensionServiceTest> factory(this);
5400 extension_sync_service_->SetSyncStartFlare(
5401 base::Bind(&ExtensionServiceTest::MockSyncStartFlare,
5402 factory.GetWeakPtr(),
5403 &flare_was_called, // Safe due to WeakPtrFactory scope.
5404 &triggered_type)); // Safe due to WeakPtrFactory scope.
5406 base::FilePath path = data_dir_.AppendASCII("good.crx");
5407 InstallCRX(path, INSTALL_NEW);
5409 EXPECT_TRUE(flare_was_called);
5410 EXPECT_EQ(syncer::EXTENSIONS, triggered_type);
5412 // Reset.
5413 flare_was_called = false;
5414 triggered_type = syncer::UNSPECIFIED;
5416 // Once sync starts, flare should no longer be invoked.
5417 extension_sync_service_->MergeDataAndStartSyncing(
5418 syncer::EXTENSIONS,
5419 syncer::SyncDataList(),
5420 scoped_ptr<syncer::SyncChangeProcessor>(
5421 new syncer::FakeSyncChangeProcessor),
5422 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5423 path = data_dir_.AppendASCII("page_action.crx");
5424 InstallCRX(path, INSTALL_NEW);
5425 EXPECT_FALSE(flare_was_called);
5426 ASSERT_EQ(syncer::UNSPECIFIED, triggered_type);
5429 TEST_F(ExtensionServiceTest, DisableExtensionFromSync) {
5430 // Start the extensions service with one external extension already installed.
5431 base::FilePath source_install_dir = data_dir_
5432 .AppendASCII("good")
5433 .AppendASCII("Extensions");
5434 base::FilePath pref_path =
5435 source_install_dir.DirName().Append(chrome::kPreferencesFilename);
5437 InitializeInstalledExtensionService(pref_path, source_install_dir);
5438 InitializeExtensionSyncService();
5440 // The user has enabled sync.
5441 ProfileSyncService* sync_service =
5442 ProfileSyncServiceFactory::GetForProfile(profile_.get());
5443 sync_service->SetSyncSetupCompleted();
5445 service_->Init();
5446 ASSERT_TRUE(service_->is_ready());
5448 ASSERT_EQ(3u, loaded_.size());
5450 // We start enabled.
5451 const Extension* extension = service_->GetExtensionById(good0, true);
5452 ASSERT_TRUE(extension);
5453 ASSERT_TRUE(service_->IsExtensionEnabled(good0));
5454 extensions::ExtensionSyncData disable_good_crx(*extension, false, false);
5456 // Then sync data arrives telling us to disable |good0|.
5457 syncer::SyncDataList sync_data;
5458 sync_data.push_back(disable_good_crx.GetSyncData());
5459 extension_sync_service_->MergeDataAndStartSyncing(
5460 syncer::EXTENSIONS,
5461 sync_data,
5462 scoped_ptr<syncer::SyncChangeProcessor>(
5463 new syncer::FakeSyncChangeProcessor),
5464 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5465 ASSERT_FALSE(service_->IsExtensionEnabled(good0));
5468 TEST_F(ExtensionServiceTest, DontDisableExtensionWithPendingEnableFromSync) {
5469 // Start the extensions service with one external extension already installed.
5470 base::FilePath source_install_dir = data_dir_
5471 .AppendASCII("good")
5472 .AppendASCII("Extensions");
5473 base::FilePath pref_path =
5474 source_install_dir.DirName().Append(chrome::kPreferencesFilename);
5476 InitializeInstalledExtensionService(pref_path, source_install_dir);
5477 InitializeExtensionSyncService();
5479 // The user has enabled sync.
5480 ProfileSyncService* sync_service =
5481 ProfileSyncServiceFactory::GetForProfile(profile_.get());
5482 sync_service->SetSyncSetupCompleted();
5484 service_->Init();
5485 ASSERT_TRUE(service_->is_ready());
5486 ASSERT_EQ(3u, loaded_.size());
5488 const Extension* extension = service_->GetExtensionById(good0, true);
5489 ASSERT_TRUE(service_->IsExtensionEnabled(good0));
5491 // Disable extension before first sync data arrives.
5492 service_->DisableExtension(good0, Extension::DISABLE_USER_ACTION);
5493 ASSERT_FALSE(service_->IsExtensionEnabled(good0));
5495 // Enable extension - this is now the most recent state.
5496 service_->EnableExtension(good0);
5497 ASSERT_TRUE(service_->IsExtensionEnabled(good0));
5499 // Now sync data comes in that says to disable good0. This should be
5500 // ignored.
5501 extensions::ExtensionSyncData disable_good_crx(*extension, false, false);
5502 syncer::SyncDataList sync_data;
5503 sync_data.push_back(disable_good_crx.GetSyncData());
5504 extension_sync_service_->MergeDataAndStartSyncing(
5505 syncer::EXTENSIONS,
5506 sync_data,
5507 scoped_ptr<syncer::SyncChangeProcessor>(
5508 new syncer::FakeSyncChangeProcessor),
5509 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5511 // The extension was enabled locally before the sync data arrived, so it
5512 // should still be enabled now.
5513 ASSERT_TRUE(service_->IsExtensionEnabled(good0));
5516 TEST_F(ExtensionServiceTest, GetSyncData) {
5517 InitializeEmptyExtensionService();
5518 InitializeExtensionSyncService();
5519 InstallCRX(data_dir_.AppendASCII("good.crx"), INSTALL_NEW);
5520 const Extension* extension = service_->GetInstalledExtension(good_crx);
5521 ASSERT_TRUE(extension);
5523 extension_sync_service_->MergeDataAndStartSyncing(
5524 syncer::EXTENSIONS,
5525 syncer::SyncDataList(),
5526 scoped_ptr<syncer::SyncChangeProcessor>(
5527 new syncer::FakeSyncChangeProcessor),
5528 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5530 syncer::SyncDataList list = extension_sync_service_->GetAllSyncData(
5531 syncer::EXTENSIONS);
5532 ASSERT_EQ(list.size(), 1U);
5533 extensions::ExtensionSyncData data(list[0]);
5534 EXPECT_EQ(extension->id(), data.id());
5535 EXPECT_FALSE(data.uninstalled());
5536 EXPECT_EQ(service_->IsExtensionEnabled(good_crx), data.enabled());
5537 EXPECT_EQ(extensions::util::IsIncognitoEnabled(good_crx, profile_.get()),
5538 data.incognito_enabled());
5539 EXPECT_TRUE(data.version().Equals(*extension->version()));
5540 EXPECT_EQ(extensions::ManifestURL::GetUpdateURL(extension),
5541 data.update_url());
5542 EXPECT_EQ(extension->name(), data.name());
5545 TEST_F(ExtensionServiceTest, GetSyncDataTerminated) {
5546 InitializeEmptyExtensionService();
5547 InitializeExtensionSyncService();
5548 InstallCRX(data_dir_.AppendASCII("good.crx"), INSTALL_NEW);
5549 TerminateExtension(good_crx);
5550 const Extension* extension = service_->GetInstalledExtension(good_crx);
5551 ASSERT_TRUE(extension);
5553 syncer::FakeSyncChangeProcessor processor;
5554 extension_sync_service_->MergeDataAndStartSyncing(
5555 syncer::EXTENSIONS,
5556 syncer::SyncDataList(),
5557 scoped_ptr<syncer::SyncChangeProcessor>(
5558 new syncer::FakeSyncChangeProcessor),
5559 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5561 syncer::SyncDataList list = extension_sync_service_->GetAllSyncData(
5562 syncer::EXTENSIONS);
5563 ASSERT_EQ(list.size(), 1U);
5564 extensions::ExtensionSyncData data(list[0]);
5565 EXPECT_EQ(extension->id(), data.id());
5566 EXPECT_FALSE(data.uninstalled());
5567 EXPECT_EQ(service_->IsExtensionEnabled(good_crx), data.enabled());
5568 EXPECT_EQ(extensions::util::IsIncognitoEnabled(good_crx, profile_.get()),
5569 data.incognito_enabled());
5570 EXPECT_TRUE(data.version().Equals(*extension->version()));
5571 EXPECT_EQ(extensions::ManifestURL::GetUpdateURL(extension),
5572 data.update_url());
5573 EXPECT_EQ(extension->name(), data.name());
5576 TEST_F(ExtensionServiceTest, GetSyncDataFilter) {
5577 InitializeEmptyExtensionService();
5578 InitializeExtensionSyncService();
5579 InstallCRX(data_dir_.AppendASCII("good.crx"), INSTALL_NEW);
5580 const Extension* extension = service_->GetInstalledExtension(good_crx);
5581 ASSERT_TRUE(extension);
5583 syncer::FakeSyncChangeProcessor processor;
5584 extension_sync_service_->MergeDataAndStartSyncing(
5585 syncer::APPS,
5586 syncer::SyncDataList(),
5587 scoped_ptr<syncer::SyncChangeProcessor>(
5588 new syncer::FakeSyncChangeProcessor),
5589 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5591 syncer::SyncDataList list = extension_sync_service_->GetAllSyncData(
5592 syncer::EXTENSIONS);
5593 ASSERT_EQ(list.size(), 0U);
5596 TEST_F(ExtensionServiceTest, GetSyncExtensionDataUserSettings) {
5597 InitializeEmptyExtensionService();
5598 InitializeProcessManager();
5599 InitializeExtensionSyncService();
5600 InstallCRX(data_dir_.AppendASCII("good.crx"), INSTALL_NEW);
5601 const Extension* extension = service_->GetInstalledExtension(good_crx);
5602 ASSERT_TRUE(extension);
5604 syncer::FakeSyncChangeProcessor processor;
5605 extension_sync_service_->MergeDataAndStartSyncing(
5606 syncer::EXTENSIONS,
5607 syncer::SyncDataList(),
5608 scoped_ptr<syncer::SyncChangeProcessor>(
5609 new syncer::FakeSyncChangeProcessor),
5610 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5613 syncer::SyncDataList list = extension_sync_service_->GetAllSyncData(
5614 syncer::EXTENSIONS);
5615 ASSERT_EQ(list.size(), 1U);
5616 extensions::ExtensionSyncData data(list[0]);
5617 EXPECT_TRUE(data.enabled());
5618 EXPECT_FALSE(data.incognito_enabled());
5621 service_->DisableExtension(good_crx, Extension::DISABLE_USER_ACTION);
5623 syncer::SyncDataList list = extension_sync_service_->GetAllSyncData(
5624 syncer::EXTENSIONS);
5625 ASSERT_EQ(list.size(), 1U);
5626 extensions::ExtensionSyncData data(list[0]);
5627 EXPECT_FALSE(data.enabled());
5628 EXPECT_FALSE(data.incognito_enabled());
5631 extensions::util::SetIsIncognitoEnabled(good_crx, profile_.get(), true);
5633 syncer::SyncDataList list = extension_sync_service_->GetAllSyncData(
5634 syncer::EXTENSIONS);
5635 ASSERT_EQ(list.size(), 1U);
5636 extensions::ExtensionSyncData data(list[0]);
5637 EXPECT_FALSE(data.enabled());
5638 EXPECT_TRUE(data.incognito_enabled());
5641 service_->EnableExtension(good_crx);
5643 syncer::SyncDataList list = extension_sync_service_->GetAllSyncData(
5644 syncer::EXTENSIONS);
5645 ASSERT_EQ(list.size(), 1U);
5646 extensions::ExtensionSyncData data(list[0]);
5647 EXPECT_TRUE(data.enabled());
5648 EXPECT_TRUE(data.incognito_enabled());
5652 TEST_F(ExtensionServiceTest, SyncForUninstalledExternalExtension) {
5653 InitializeEmptyExtensionService();
5654 InitializeExtensionSyncService();
5655 InstallCRXWithLocation(data_dir_.AppendASCII("good.crx"),
5656 Manifest::EXTERNAL_PREF, INSTALL_NEW);
5657 const Extension* extension = service_->GetInstalledExtension(good_crx);
5658 ASSERT_TRUE(extension);
5660 syncer::FakeSyncChangeProcessor processor;
5661 extension_sync_service_->MergeDataAndStartSyncing(
5662 syncer::EXTENSIONS,
5663 syncer::SyncDataList(),
5664 scoped_ptr<syncer::SyncChangeProcessor>(
5665 new syncer::FakeSyncChangeProcessor),
5666 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5668 UninstallExtension(good_crx, false);
5669 EXPECT_TRUE(ExtensionPrefs::Get(profile_.get())
5670 ->IsExternalExtensionUninstalled(good_crx));
5672 sync_pb::EntitySpecifics specifics;
5673 sync_pb::AppSpecifics* app_specifics = specifics.mutable_app();
5674 sync_pb::ExtensionSpecifics* extension_specifics =
5675 app_specifics->mutable_extension();
5676 extension_specifics->set_id(good_crx);
5677 extension_specifics->set_version("1.0");
5678 extension_specifics->set_enabled(true);
5680 syncer::SyncData sync_data =
5681 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
5682 syncer::SyncChange sync_change(FROM_HERE,
5683 syncer::SyncChange::ACTION_UPDATE,
5684 sync_data);
5685 syncer::SyncChangeList list(1);
5686 list[0] = sync_change;
5688 extension_sync_service_->ProcessSyncChanges(FROM_HERE, list);
5689 EXPECT_TRUE(ExtensionPrefs::Get(profile_.get())
5690 ->IsExternalExtensionUninstalled(good_crx));
5693 TEST_F(ExtensionServiceTest, GetSyncAppDataUserSettings) {
5694 InitializeEmptyExtensionService();
5695 InitializeExtensionSyncService();
5696 const Extension* app =
5697 PackAndInstallCRX(data_dir_.AppendASCII("app"), INSTALL_NEW);
5698 ASSERT_TRUE(app);
5699 ASSERT_TRUE(app->is_app());
5701 syncer::FakeSyncChangeProcessor processor;
5702 extension_sync_service_->MergeDataAndStartSyncing(
5703 syncer::APPS,
5704 syncer::SyncDataList(),
5705 scoped_ptr<syncer::SyncChangeProcessor>(
5706 new syncer::FakeSyncChangeProcessor),
5707 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5709 syncer::StringOrdinal initial_ordinal =
5710 syncer::StringOrdinal::CreateInitialOrdinal();
5712 syncer::SyncDataList list = extension_sync_service_->GetAllSyncData(
5713 syncer::APPS);
5714 ASSERT_EQ(list.size(), 1U);
5716 extensions::AppSyncData app_sync_data(list[0]);
5717 EXPECT_TRUE(initial_ordinal.Equals(app_sync_data.app_launch_ordinal()));
5718 EXPECT_TRUE(initial_ordinal.Equals(app_sync_data.page_ordinal()));
5721 AppSorting* sorting = ExtensionPrefs::Get(profile_.get())->app_sorting();
5722 sorting->SetAppLaunchOrdinal(app->id(), initial_ordinal.CreateAfter());
5724 syncer::SyncDataList list = extension_sync_service_->GetAllSyncData(
5725 syncer::APPS);
5726 ASSERT_EQ(list.size(), 1U);
5728 extensions::AppSyncData app_sync_data(list[0]);
5729 EXPECT_TRUE(initial_ordinal.LessThan(app_sync_data.app_launch_ordinal()));
5730 EXPECT_TRUE(initial_ordinal.Equals(app_sync_data.page_ordinal()));
5733 sorting->SetPageOrdinal(app->id(), initial_ordinal.CreateAfter());
5735 syncer::SyncDataList list = extension_sync_service_->GetAllSyncData(
5736 syncer::APPS);
5737 ASSERT_EQ(list.size(), 1U);
5739 extensions::AppSyncData app_sync_data(list[0]);
5740 EXPECT_TRUE(initial_ordinal.LessThan(app_sync_data.app_launch_ordinal()));
5741 EXPECT_TRUE(initial_ordinal.LessThan(app_sync_data.page_ordinal()));
5745 // TODO (rdevlin.cronin): The OnExtensionMoved() method has been removed from
5746 // ExtensionService, so this test probably needs a new home. Unfortunately, it
5747 // relies pretty heavily on things like InitializeExtension[Sync]Service() and
5748 // PackAndInstallCRX(). When we clean up a bit more, this should move out.
5749 TEST_F(ExtensionServiceTest, GetSyncAppDataUserSettingsOnExtensionMoved) {
5750 InitializeEmptyExtensionService();
5751 InitializeExtensionSyncService();
5752 const size_t kAppCount = 3;
5753 const Extension* apps[kAppCount];
5754 apps[0] = PackAndInstallCRX(data_dir_.AppendASCII("app1"), INSTALL_NEW);
5755 apps[1] = PackAndInstallCRX(data_dir_.AppendASCII("app2"), INSTALL_NEW);
5756 apps[2] = PackAndInstallCRX(data_dir_.AppendASCII("app4"), INSTALL_NEW);
5757 for (size_t i = 0; i < kAppCount; ++i) {
5758 ASSERT_TRUE(apps[i]);
5759 ASSERT_TRUE(apps[i]->is_app());
5762 syncer::FakeSyncChangeProcessor processor;
5763 extension_sync_service_->MergeDataAndStartSyncing(
5764 syncer::APPS,
5765 syncer::SyncDataList(),
5766 scoped_ptr<syncer::SyncChangeProcessor>(
5767 new syncer::FakeSyncChangeProcessor),
5768 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5770 ExtensionPrefs::Get(service_->GetBrowserContext())
5771 ->app_sorting()
5772 ->OnExtensionMoved(apps[0]->id(), apps[1]->id(), apps[2]->id());
5774 syncer::SyncDataList list = extension_sync_service_->GetAllSyncData(
5775 syncer::APPS);
5776 ASSERT_EQ(list.size(), 3U);
5778 extensions::AppSyncData data[kAppCount];
5779 for (size_t i = 0; i < kAppCount; ++i) {
5780 data[i] = extensions::AppSyncData(list[i]);
5783 // The sync data is not always in the same order our apps were installed in,
5784 // so we do that sorting here so we can make sure the values are changed as
5785 // expected.
5786 syncer::StringOrdinal app_launch_ordinals[kAppCount];
5787 for (size_t i = 0; i < kAppCount; ++i) {
5788 for (size_t j = 0; j < kAppCount; ++j) {
5789 if (apps[i]->id() == data[j].id())
5790 app_launch_ordinals[i] = data[j].app_launch_ordinal();
5794 EXPECT_TRUE(app_launch_ordinals[1].LessThan(app_launch_ordinals[0]));
5795 EXPECT_TRUE(app_launch_ordinals[0].LessThan(app_launch_ordinals[2]));
5799 TEST_F(ExtensionServiceTest, GetSyncDataList) {
5800 InitializeEmptyExtensionService();
5801 InitializeExtensionSyncService();
5802 InstallCRX(data_dir_.AppendASCII("good.crx"), INSTALL_NEW);
5803 InstallCRX(data_dir_.AppendASCII("page_action.crx"), INSTALL_NEW);
5804 InstallCRX(data_dir_.AppendASCII("theme.crx"), INSTALL_NEW);
5805 InstallCRX(data_dir_.AppendASCII("theme2.crx"), INSTALL_NEW);
5807 syncer::FakeSyncChangeProcessor processor;
5808 extension_sync_service_->MergeDataAndStartSyncing(
5809 syncer::APPS,
5810 syncer::SyncDataList(),
5811 scoped_ptr<syncer::SyncChangeProcessor>(
5812 new syncer::FakeSyncChangeProcessor),
5813 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5814 extension_sync_service_->MergeDataAndStartSyncing(
5815 syncer::EXTENSIONS,
5816 syncer::SyncDataList(),
5817 scoped_ptr<syncer::SyncChangeProcessor>(
5818 new syncer::FakeSyncChangeProcessor),
5819 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5821 service_->DisableExtension(page_action, Extension::DISABLE_USER_ACTION);
5822 TerminateExtension(theme2_crx);
5824 EXPECT_EQ(0u, extension_sync_service_->GetAllSyncData(syncer::APPS).size());
5825 EXPECT_EQ(2u, extension_sync_service_->
5826 GetAllSyncData(syncer::EXTENSIONS).size());
5829 TEST_F(ExtensionServiceTest, ProcessSyncDataUninstall) {
5830 InitializeEmptyExtensionService();
5831 InitializeExtensionSyncService();
5832 syncer::FakeSyncChangeProcessor processor;
5833 extension_sync_service_->MergeDataAndStartSyncing(
5834 syncer::EXTENSIONS,
5835 syncer::SyncDataList(),
5836 scoped_ptr<syncer::SyncChangeProcessor>(
5837 new syncer::FakeSyncChangeProcessor),
5838 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5840 sync_pb::EntitySpecifics specifics;
5841 sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension();
5842 ext_specifics->set_id(good_crx);
5843 ext_specifics->set_version("1.0");
5844 syncer::SyncData sync_data =
5845 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
5846 syncer::SyncChange sync_change(FROM_HERE,
5847 syncer::SyncChange::ACTION_DELETE,
5848 sync_data);
5849 syncer::SyncChangeList list(1);
5850 list[0] = sync_change;
5852 // Should do nothing.
5853 extension_sync_service_->ProcessSyncChanges(FROM_HERE, list);
5854 EXPECT_FALSE(service_->GetExtensionById(good_crx, true));
5856 // Install the extension.
5857 base::FilePath extension_path = data_dir_.AppendASCII("good.crx");
5858 InstallCRX(extension_path, INSTALL_NEW);
5859 EXPECT_TRUE(service_->GetExtensionById(good_crx, true));
5861 // Should uninstall the extension.
5862 extension_sync_service_->ProcessSyncChanges(FROM_HERE, list);
5863 EXPECT_FALSE(service_->GetExtensionById(good_crx, true));
5865 // Should again do nothing.
5866 extension_sync_service_->ProcessSyncChanges(FROM_HERE, list);
5867 EXPECT_FALSE(service_->GetExtensionById(good_crx, true));
5870 TEST_F(ExtensionServiceTest, ProcessSyncDataWrongType) {
5871 InitializeEmptyExtensionService();
5872 InitializeExtensionSyncService();
5874 // Install the extension.
5875 base::FilePath extension_path = data_dir_.AppendASCII("good.crx");
5876 InstallCRX(extension_path, INSTALL_NEW);
5877 EXPECT_TRUE(service_->GetExtensionById(good_crx, true));
5879 sync_pb::EntitySpecifics specifics;
5880 sync_pb::AppSpecifics* app_specifics = specifics.mutable_app();
5881 sync_pb::ExtensionSpecifics* extension_specifics =
5882 app_specifics->mutable_extension();
5883 extension_specifics->set_id(good_crx);
5884 extension_specifics->set_version(
5885 service_->GetInstalledExtension(good_crx)->version()->GetString());
5888 extension_specifics->set_enabled(true);
5889 syncer::SyncData sync_data =
5890 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
5891 syncer::SyncChange sync_change(FROM_HERE,
5892 syncer::SyncChange::ACTION_DELETE,
5893 sync_data);
5894 syncer::SyncChangeList list(1);
5895 list[0] = sync_change;
5897 // Should do nothing
5898 extension_sync_service_->ProcessSyncChanges(FROM_HERE, list);
5899 EXPECT_TRUE(service_->GetExtensionById(good_crx, true));
5903 extension_specifics->set_enabled(false);
5904 syncer::SyncData sync_data =
5905 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
5906 syncer::SyncChange sync_change(FROM_HERE,
5907 syncer::SyncChange::ACTION_UPDATE,
5908 sync_data);
5909 syncer::SyncChangeList list(1);
5910 list[0] = sync_change;
5912 // Should again do nothing.
5913 extension_sync_service_->ProcessSyncChanges(FROM_HERE, list);
5914 EXPECT_TRUE(service_->GetExtensionById(good_crx, false));
5918 TEST_F(ExtensionServiceTest, ProcessSyncDataSettings) {
5919 InitializeEmptyExtensionService();
5920 InitializeProcessManager();
5921 InitializeExtensionSyncService();
5922 syncer::FakeSyncChangeProcessor processor;
5923 extension_sync_service_->MergeDataAndStartSyncing(
5924 syncer::EXTENSIONS,
5925 syncer::SyncDataList(),
5926 scoped_ptr<syncer::SyncChangeProcessor>(
5927 new syncer::FakeSyncChangeProcessor),
5928 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5930 InstallCRX(data_dir_.AppendASCII("good.crx"), INSTALL_NEW);
5931 EXPECT_TRUE(service_->IsExtensionEnabled(good_crx));
5932 EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile_.get()));
5934 sync_pb::EntitySpecifics specifics;
5935 sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension();
5936 ext_specifics->set_id(good_crx);
5937 ext_specifics->set_version(
5938 service_->GetInstalledExtension(good_crx)->version()->GetString());
5939 ext_specifics->set_enabled(false);
5942 syncer::SyncData sync_data =
5943 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
5944 syncer::SyncChange sync_change(FROM_HERE,
5945 syncer::SyncChange::ACTION_UPDATE,
5946 sync_data);
5947 syncer::SyncChangeList list(1);
5948 list[0] = sync_change;
5949 extension_sync_service_->ProcessSyncChanges(FROM_HERE, list);
5950 EXPECT_FALSE(service_->IsExtensionEnabled(good_crx));
5951 EXPECT_FALSE(
5952 extensions::util::IsIncognitoEnabled(good_crx, profile_.get()));
5956 ext_specifics->set_enabled(true);
5957 ext_specifics->set_incognito_enabled(true);
5958 syncer::SyncData sync_data =
5959 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
5960 syncer::SyncChange sync_change(FROM_HERE,
5961 syncer::SyncChange::ACTION_UPDATE,
5962 sync_data);
5963 syncer::SyncChangeList list(1);
5964 list[0] = sync_change;
5965 extension_sync_service_->ProcessSyncChanges(FROM_HERE, list);
5966 EXPECT_TRUE(service_->IsExtensionEnabled(good_crx));
5967 EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good_crx, profile_.get()));
5971 ext_specifics->set_enabled(false);
5972 ext_specifics->set_incognito_enabled(true);
5973 syncer::SyncData sync_data =
5974 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
5975 syncer::SyncChange sync_change(FROM_HERE,
5976 syncer::SyncChange::ACTION_UPDATE,
5977 sync_data);
5978 syncer::SyncChangeList list(1);
5979 list[0] = sync_change;
5980 extension_sync_service_->ProcessSyncChanges(FROM_HERE, list);
5981 EXPECT_FALSE(service_->IsExtensionEnabled(good_crx));
5982 EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good_crx, profile_.get()));
5985 EXPECT_FALSE(service_->pending_extension_manager()->IsIdPending(good_crx));
5988 TEST_F(ExtensionServiceTest, ProcessSyncDataTerminatedExtension) {
5989 InitializeExtensionServiceWithUpdater();
5990 InitializeExtensionSyncService();
5991 syncer::FakeSyncChangeProcessor processor;
5992 extension_sync_service_->MergeDataAndStartSyncing(
5993 syncer::EXTENSIONS,
5994 syncer::SyncDataList(),
5995 scoped_ptr<syncer::SyncChangeProcessor>(
5996 new syncer::FakeSyncChangeProcessor),
5997 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
5999 InstallCRX(data_dir_.AppendASCII("good.crx"), INSTALL_NEW);
6000 TerminateExtension(good_crx);
6001 EXPECT_TRUE(service_->IsExtensionEnabled(good_crx));
6002 EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile_.get()));
6004 sync_pb::EntitySpecifics specifics;
6005 sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension();
6006 ext_specifics->set_id(good_crx);
6007 ext_specifics->set_version(
6008 service_->GetInstalledExtension(good_crx)->version()->GetString());
6009 ext_specifics->set_enabled(false);
6010 ext_specifics->set_incognito_enabled(true);
6011 syncer::SyncData sync_data =
6012 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6013 syncer::SyncChange sync_change(FROM_HERE,
6014 syncer::SyncChange::ACTION_UPDATE,
6015 sync_data);
6016 syncer::SyncChangeList list(1);
6017 list[0] = sync_change;
6019 extension_sync_service_->ProcessSyncChanges(FROM_HERE, list);
6020 EXPECT_FALSE(service_->IsExtensionEnabled(good_crx));
6021 EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good_crx, profile_.get()));
6023 EXPECT_FALSE(service_->pending_extension_manager()->IsIdPending(good_crx));
6026 TEST_F(ExtensionServiceTest, ProcessSyncDataVersionCheck) {
6027 InitializeExtensionServiceWithUpdater();
6028 InitializeExtensionSyncService();
6029 syncer::FakeSyncChangeProcessor processor;
6030 extension_sync_service_->MergeDataAndStartSyncing(
6031 syncer::EXTENSIONS,
6032 syncer::SyncDataList(),
6033 scoped_ptr<syncer::SyncChangeProcessor>(
6034 new syncer::FakeSyncChangeProcessor),
6035 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6037 InstallCRX(data_dir_.AppendASCII("good.crx"), INSTALL_NEW);
6038 EXPECT_TRUE(service_->IsExtensionEnabled(good_crx));
6039 EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile_.get()));
6041 sync_pb::EntitySpecifics specifics;
6042 sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension();
6043 ext_specifics->set_id(good_crx);
6044 ext_specifics->set_enabled(true);
6047 ext_specifics->set_version(
6048 service_->GetInstalledExtension(good_crx)->version()->GetString());
6049 syncer::SyncData sync_data =
6050 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6051 syncer::SyncChange sync_change(FROM_HERE,
6052 syncer::SyncChange::ACTION_UPDATE,
6053 sync_data);
6054 syncer::SyncChangeList list(1);
6055 list[0] = sync_change;
6057 // Should do nothing if extension version == sync version.
6058 extension_sync_service_->ProcessSyncChanges(FROM_HERE, list);
6059 EXPECT_FALSE(service_->updater()->WillCheckSoon());
6062 // Should do nothing if extension version > sync version (but see
6063 // the TODO in ProcessExtensionSyncData).
6065 ext_specifics->set_version("0.0.0.0");
6066 syncer::SyncData sync_data =
6067 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6068 syncer::SyncChange sync_change(FROM_HERE,
6069 syncer::SyncChange::ACTION_UPDATE,
6070 sync_data);
6071 syncer::SyncChangeList list(1);
6072 list[0] = sync_change;
6074 extension_sync_service_->ProcessSyncChanges(FROM_HERE, list);
6075 EXPECT_FALSE(service_->updater()->WillCheckSoon());
6078 // Should kick off an update if extension version < sync version.
6080 ext_specifics->set_version("9.9.9.9");
6081 syncer::SyncData sync_data =
6082 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6083 syncer::SyncChange sync_change(FROM_HERE,
6084 syncer::SyncChange::ACTION_UPDATE,
6085 sync_data);
6086 syncer::SyncChangeList list(1);
6087 list[0] = sync_change;
6089 extension_sync_service_->ProcessSyncChanges(FROM_HERE, list);
6090 EXPECT_TRUE(service_->updater()->WillCheckSoon());
6093 EXPECT_FALSE(service_->pending_extension_manager()->IsIdPending(good_crx));
6096 TEST_F(ExtensionServiceTest, ProcessSyncDataNotInstalled) {
6097 InitializeExtensionServiceWithUpdater();
6098 InitializeExtensionSyncService();
6099 syncer::FakeSyncChangeProcessor processor;
6100 extension_sync_service_->MergeDataAndStartSyncing(
6101 syncer::EXTENSIONS,
6102 syncer::SyncDataList(),
6103 scoped_ptr<syncer::SyncChangeProcessor>(
6104 new syncer::FakeSyncChangeProcessor),
6105 scoped_ptr<syncer::SyncErrorFactory>(new syncer::SyncErrorFactoryMock()));
6107 sync_pb::EntitySpecifics specifics;
6108 sync_pb::ExtensionSpecifics* ext_specifics = specifics.mutable_extension();
6109 ext_specifics->set_id(good_crx);
6110 ext_specifics->set_enabled(false);
6111 ext_specifics->set_incognito_enabled(true);
6112 ext_specifics->set_update_url("http://www.google.com/");
6113 ext_specifics->set_version("1.2.3.4");
6114 syncer::SyncData sync_data =
6115 syncer::SyncData::CreateLocalData(good_crx, "Name", specifics);
6116 syncer::SyncChange sync_change(FROM_HERE,
6117 syncer::SyncChange::ACTION_UPDATE,
6118 sync_data);
6119 syncer::SyncChangeList list(1);
6120 list[0] = sync_change;
6123 EXPECT_TRUE(service_->IsExtensionEnabled(good_crx));
6124 EXPECT_FALSE(extensions::util::IsIncognitoEnabled(good_crx, profile_.get()));
6125 extension_sync_service_->ProcessSyncChanges(FROM_HERE, list);
6126 EXPECT_TRUE(service_->updater()->WillCheckSoon());
6127 EXPECT_FALSE(service_->IsExtensionEnabled(good_crx));
6128 EXPECT_TRUE(extensions::util::IsIncognitoEnabled(good_crx, profile_.get()));
6130 const extensions::PendingExtensionInfo* info;
6131 EXPECT_TRUE((info = service_->pending_extension_manager()->
6132 GetById(good_crx)));
6133 EXPECT_EQ(ext_specifics->update_url(), info->update_url().spec());
6134 EXPECT_TRUE(info->is_from_sync());
6135 EXPECT_TRUE(info->install_silently());
6136 EXPECT_EQ(Manifest::INTERNAL, info->install_source());
6137 // TODO(akalin): Figure out a way to test |info.ShouldAllowInstall()|.
6140 TEST_F(ExtensionServiceTest, InstallPriorityExternalUpdateUrl) {
6141 InitializeEmptyExtensionService();
6143 base::FilePath path = data_dir_.AppendASCII("good.crx");
6144 InstallCRX(path, INSTALL_NEW);
6145 ValidatePrefKeyCount(1u);
6146 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
6147 ValidateIntegerPref(good_crx, "location", Manifest::INTERNAL);
6149 extensions::PendingExtensionManager* pending =
6150 service_->pending_extension_manager();
6151 EXPECT_FALSE(pending->IsIdPending(kGoodId));
6153 // Skip install when the location is the same.
6154 EXPECT_FALSE(service_->OnExternalExtensionUpdateUrlFound(kGoodId,
6155 std::string(),
6156 GURL(kGoodUpdateURL),
6157 Manifest::INTERNAL,
6158 Extension::NO_FLAGS,
6159 false));
6160 EXPECT_FALSE(pending->IsIdPending(kGoodId));
6162 // Install when the location has higher priority.
6163 EXPECT_TRUE(service_->OnExternalExtensionUpdateUrlFound(
6164 kGoodId,
6165 std::string(),
6166 GURL(kGoodUpdateURL),
6167 Manifest::EXTERNAL_POLICY_DOWNLOAD,
6168 Extension::NO_FLAGS,
6169 false));
6170 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6172 // Try the low priority again. Should be rejected.
6173 EXPECT_FALSE(service_->OnExternalExtensionUpdateUrlFound(
6174 kGoodId,
6175 std::string(),
6176 GURL(kGoodUpdateURL),
6177 Manifest::EXTERNAL_PREF_DOWNLOAD,
6178 Extension::NO_FLAGS,
6179 false));
6180 // The existing record should still be present in the pending extension
6181 // manager.
6182 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6184 pending->Remove(kGoodId);
6186 // Skip install when the location has the same priority as the installed
6187 // location.
6188 EXPECT_FALSE(service_->OnExternalExtensionUpdateUrlFound(kGoodId,
6189 std::string(),
6190 GURL(kGoodUpdateURL),
6191 Manifest::INTERNAL,
6192 Extension::NO_FLAGS,
6193 false));
6195 EXPECT_FALSE(pending->IsIdPending(kGoodId));
6198 TEST_F(ExtensionServiceTest, InstallPriorityExternalLocalFile) {
6199 Version older_version("0.1.0.0");
6200 Version newer_version("2.0.0.0");
6202 // We don't want the extension to be installed. A path that doesn't
6203 // point to a valid CRX ensures this.
6204 const base::FilePath kInvalidPathToCrx = base::FilePath();
6206 const int kCreationFlags = 0;
6207 const bool kDontMarkAcknowledged = false;
6209 InitializeEmptyExtensionService();
6211 // The test below uses install source constants to test that
6212 // priority is enforced. It assumes a specific ranking of install
6213 // sources: Registry (EXTERNAL_REGISTRY) overrides external pref
6214 // (EXTERNAL_PREF), and external pref overrides user install (INTERNAL).
6215 // The following assertions verify these assumptions:
6216 ASSERT_EQ(Manifest::EXTERNAL_REGISTRY,
6217 Manifest::GetHigherPriorityLocation(Manifest::EXTERNAL_REGISTRY,
6218 Manifest::EXTERNAL_PREF));
6219 ASSERT_EQ(Manifest::EXTERNAL_REGISTRY,
6220 Manifest::GetHigherPriorityLocation(Manifest::EXTERNAL_REGISTRY,
6221 Manifest::INTERNAL));
6222 ASSERT_EQ(Manifest::EXTERNAL_PREF,
6223 Manifest::GetHigherPriorityLocation(Manifest::EXTERNAL_PREF,
6224 Manifest::INTERNAL));
6226 extensions::PendingExtensionManager* pending =
6227 service_->pending_extension_manager();
6228 EXPECT_FALSE(pending->IsIdPending(kGoodId));
6231 // Simulate an external source adding the extension as INTERNAL.
6232 content::WindowedNotificationObserver observer(
6233 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
6234 content::NotificationService::AllSources());
6235 EXPECT_TRUE(
6236 service_->OnExternalExtensionFileFound(
6237 kGoodId, &older_version, kInvalidPathToCrx,
6238 Manifest::INTERNAL, kCreationFlags, kDontMarkAcknowledged));
6239 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6240 observer.Wait();
6241 VerifyCrxInstall(kInvalidPathToCrx, INSTALL_FAILED);
6245 // Simulate an external source adding the extension as EXTERNAL_PREF.
6246 content::WindowedNotificationObserver observer(
6247 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
6248 content::NotificationService::AllSources());
6249 EXPECT_TRUE(
6250 service_->OnExternalExtensionFileFound(
6251 kGoodId, &older_version, kInvalidPathToCrx,
6252 Manifest::EXTERNAL_PREF, kCreationFlags, kDontMarkAcknowledged));
6253 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6254 observer.Wait();
6255 VerifyCrxInstall(kInvalidPathToCrx, INSTALL_FAILED);
6258 // Simulate an external source adding as EXTERNAL_PREF again.
6259 // This is rejected because the version and the location are the same as
6260 // the previous installation, which is still pending.
6261 EXPECT_FALSE(
6262 service_->OnExternalExtensionFileFound(
6263 kGoodId, &older_version, kInvalidPathToCrx,
6264 Manifest::EXTERNAL_PREF, kCreationFlags, kDontMarkAcknowledged));
6265 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6267 // Try INTERNAL again. Should fail.
6268 EXPECT_FALSE(
6269 service_->OnExternalExtensionFileFound(
6270 kGoodId, &older_version, kInvalidPathToCrx,
6271 Manifest::INTERNAL, kCreationFlags, kDontMarkAcknowledged));
6272 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6275 // Now the registry adds the extension.
6276 content::WindowedNotificationObserver observer(
6277 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
6278 content::NotificationService::AllSources());
6279 EXPECT_TRUE(
6280 service_->OnExternalExtensionFileFound(kGoodId,
6281 &older_version,
6282 kInvalidPathToCrx,
6283 Manifest::EXTERNAL_REGISTRY,
6284 kCreationFlags,
6285 kDontMarkAcknowledged));
6286 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6287 observer.Wait();
6288 VerifyCrxInstall(kInvalidPathToCrx, INSTALL_FAILED);
6291 // Registry outranks both external pref and internal, so both fail.
6292 EXPECT_FALSE(
6293 service_->OnExternalExtensionFileFound(
6294 kGoodId, &older_version, kInvalidPathToCrx,
6295 Manifest::EXTERNAL_PREF, kCreationFlags, kDontMarkAcknowledged));
6296 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6298 EXPECT_FALSE(
6299 service_->OnExternalExtensionFileFound(
6300 kGoodId, &older_version, kInvalidPathToCrx,
6301 Manifest::INTERNAL, kCreationFlags, kDontMarkAcknowledged));
6302 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6304 pending->Remove(kGoodId);
6306 // Install the extension.
6307 base::FilePath path = data_dir_.AppendASCII("good.crx");
6308 const Extension* ext = InstallCRX(path, INSTALL_NEW);
6309 ValidatePrefKeyCount(1u);
6310 ValidateIntegerPref(good_crx, "state", Extension::ENABLED);
6311 ValidateIntegerPref(good_crx, "location", Manifest::INTERNAL);
6313 // Now test the logic of OnExternalExtensionFileFound() when the extension
6314 // being added is already installed.
6316 // Tests assume |older_version| is less than the installed version, and
6317 // |newer_version| is greater. Verify this:
6318 ASSERT_TRUE(older_version.IsOlderThan(ext->VersionString()));
6319 ASSERT_TRUE(ext->version()->IsOlderThan(newer_version.GetString()));
6321 // An external install for the same location should fail if the version is
6322 // older, or the same, and succeed if the version is newer.
6324 // Older than the installed version...
6325 EXPECT_FALSE(
6326 service_->OnExternalExtensionFileFound(
6327 kGoodId, &older_version, kInvalidPathToCrx,
6328 Manifest::INTERNAL, kCreationFlags, kDontMarkAcknowledged));
6329 EXPECT_FALSE(pending->IsIdPending(kGoodId));
6331 // Same version as the installed version...
6332 EXPECT_FALSE(
6333 service_->OnExternalExtensionFileFound(
6334 kGoodId, ext->version(), kInvalidPathToCrx,
6335 Manifest::INTERNAL, kCreationFlags, kDontMarkAcknowledged));
6336 EXPECT_FALSE(pending->IsIdPending(kGoodId));
6338 // Newer than the installed version...
6339 EXPECT_TRUE(
6340 service_->OnExternalExtensionFileFound(
6341 kGoodId, &newer_version, kInvalidPathToCrx,
6342 Manifest::INTERNAL, kCreationFlags, kDontMarkAcknowledged));
6343 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6345 // An external install for a higher priority install source should succeed
6346 // if the version is greater. |older_version| is not...
6347 EXPECT_FALSE(
6348 service_->OnExternalExtensionFileFound(
6349 kGoodId, &older_version, kInvalidPathToCrx,
6350 Manifest::EXTERNAL_PREF, kCreationFlags, kDontMarkAcknowledged));
6351 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6353 // |newer_version| is newer.
6354 EXPECT_TRUE(
6355 service_->OnExternalExtensionFileFound(
6356 kGoodId, &newer_version, kInvalidPathToCrx,
6357 Manifest::EXTERNAL_PREF, kCreationFlags, kDontMarkAcknowledged));
6358 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6360 // An external install for an even higher priority install source should
6361 // succeed if the version is greater.
6362 EXPECT_TRUE(
6363 service_->OnExternalExtensionFileFound(
6364 kGoodId, &newer_version, kInvalidPathToCrx,
6365 Manifest::EXTERNAL_REGISTRY, kCreationFlags, kDontMarkAcknowledged));
6366 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6368 // Because EXTERNAL_PREF is a lower priority source than EXTERNAL_REGISTRY,
6369 // adding from external pref will now fail.
6370 EXPECT_FALSE(
6371 service_->OnExternalExtensionFileFound(
6372 kGoodId, &newer_version, kInvalidPathToCrx,
6373 Manifest::EXTERNAL_PREF, kCreationFlags, kDontMarkAcknowledged));
6374 EXPECT_TRUE(pending->IsIdPending(kGoodId));
6377 TEST_F(ExtensionServiceTest, ConcurrentExternalLocalFile) {
6378 Version kVersion123("1.2.3");
6379 Version kVersion124("1.2.4");
6380 Version kVersion125("1.2.5");
6381 const base::FilePath kInvalidPathToCrx = base::FilePath();
6382 const int kCreationFlags = 0;
6383 const bool kDontMarkAcknowledged = false;
6385 InitializeEmptyExtensionService();
6387 extensions::PendingExtensionManager* pending =
6388 service_->pending_extension_manager();
6389 EXPECT_FALSE(pending->IsIdPending(kGoodId));
6391 // An external provider starts installing from a local crx.
6392 EXPECT_TRUE(
6393 service_->OnExternalExtensionFileFound(
6394 kGoodId, &kVersion123, kInvalidPathToCrx,
6395 Manifest::EXTERNAL_PREF, kCreationFlags, kDontMarkAcknowledged));
6396 const extensions::PendingExtensionInfo* info;
6397 EXPECT_TRUE((info = pending->GetById(kGoodId)));
6398 EXPECT_TRUE(info->version().IsValid());
6399 EXPECT_TRUE(info->version().Equals(kVersion123));
6401 // Adding a newer version overrides the currently pending version.
6402 EXPECT_TRUE(
6403 service_->OnExternalExtensionFileFound(
6404 kGoodId, &kVersion124, kInvalidPathToCrx,
6405 Manifest::EXTERNAL_PREF, kCreationFlags, kDontMarkAcknowledged));
6406 EXPECT_TRUE((info = pending->GetById(kGoodId)));
6407 EXPECT_TRUE(info->version().IsValid());
6408 EXPECT_TRUE(info->version().Equals(kVersion124));
6410 // Adding an older version fails.
6411 EXPECT_FALSE(
6412 service_->OnExternalExtensionFileFound(
6413 kGoodId, &kVersion123, kInvalidPathToCrx,
6414 Manifest::EXTERNAL_PREF, kCreationFlags, kDontMarkAcknowledged));
6415 EXPECT_TRUE((info = pending->GetById(kGoodId)));
6416 EXPECT_TRUE(info->version().IsValid());
6417 EXPECT_TRUE(info->version().Equals(kVersion124));
6419 // Adding an older version fails even when coming from a higher-priority
6420 // location.
6421 EXPECT_FALSE(
6422 service_->OnExternalExtensionFileFound(
6423 kGoodId, &kVersion123, kInvalidPathToCrx,
6424 Manifest::EXTERNAL_REGISTRY, kCreationFlags, kDontMarkAcknowledged));
6425 EXPECT_TRUE((info = pending->GetById(kGoodId)));
6426 EXPECT_TRUE(info->version().IsValid());
6427 EXPECT_TRUE(info->version().Equals(kVersion124));
6429 // Adding the latest version from the webstore overrides a specific version.
6430 GURL kUpdateUrl("http://example.com/update");
6431 EXPECT_TRUE(service_->OnExternalExtensionUpdateUrlFound(
6432 kGoodId,
6433 std::string(),
6434 kUpdateUrl,
6435 Manifest::EXTERNAL_POLICY_DOWNLOAD,
6436 Extension::NO_FLAGS,
6437 false));
6438 EXPECT_TRUE((info = pending->GetById(kGoodId)));
6439 EXPECT_FALSE(info->version().IsValid());
6442 // This makes sure we can package and install CRX files that use whitelisted
6443 // permissions.
6444 TEST_F(ExtensionServiceTest, InstallWhitelistedExtension) {
6445 std::string test_id = "hdkklepkcpckhnpgjnmbdfhehckloojk";
6446 CommandLine::ForCurrentProcess()->AppendSwitchASCII(
6447 extensions::switches::kWhitelistedExtensionID, test_id);
6449 InitializeEmptyExtensionService();
6450 base::FilePath path = data_dir_
6451 .AppendASCII("permissions");
6452 base::FilePath pem_path = path
6453 .AppendASCII("whitelist.pem");
6454 path = path
6455 .AppendASCII("whitelist");
6457 const Extension* extension = PackAndInstallCRX(path, pem_path, INSTALL_NEW);
6458 EXPECT_EQ(0u, GetErrors().size());
6459 ASSERT_EQ(1u, registry_->enabled_extensions().size());
6460 EXPECT_EQ(test_id, extension->id());
6463 // Test that when multiple sources try to install an extension,
6464 // we consistently choose the right one. To make tests easy to read,
6465 // methods that fake requests to install crx files in several ways
6466 // are provided.
6467 class ExtensionSourcePriorityTest : public ExtensionServiceTest {
6468 public:
6469 virtual void SetUp() {
6470 ExtensionServiceTest::SetUp();
6472 // All tests use a single extension. Put the id and path in member vars
6473 // that all methods can read.
6474 crx_id_ = kGoodId;
6475 crx_path_ = data_dir_.AppendASCII("good.crx");
6478 // Fake an external source adding a URL to fetch an extension from.
6479 bool AddPendingExternalPrefUrl() {
6480 return service_->pending_extension_manager()->AddFromExternalUpdateUrl(
6481 crx_id_,
6482 std::string(),
6483 GURL(),
6484 Manifest::EXTERNAL_PREF_DOWNLOAD,
6485 Extension::NO_FLAGS,
6486 false);
6489 // Fake an external file from external_extensions.json.
6490 bool AddPendingExternalPrefFileInstall() {
6491 Version version("1.0.0.0");
6493 return service_->OnExternalExtensionFileFound(
6494 crx_id_, &version, crx_path_, Manifest::EXTERNAL_PREF,
6495 Extension::NO_FLAGS, false);
6498 // Fake a request from sync to install an extension.
6499 bool AddPendingSyncInstall() {
6500 return service_->pending_extension_manager()->AddFromSync(
6501 crx_id_, GURL(kGoodUpdateURL), &IsExtension, kGoodInstallSilently);
6504 // Fake a policy install.
6505 bool AddPendingPolicyInstall() {
6506 // Get path to the CRX with id |kGoodId|.
6507 return service_->OnExternalExtensionUpdateUrlFound(
6508 crx_id_,
6509 std::string(),
6510 GURL(),
6511 Manifest::EXTERNAL_POLICY_DOWNLOAD,
6512 Extension::NO_FLAGS,
6513 false);
6516 // Get the install source of a pending extension.
6517 Manifest::Location GetPendingLocation() {
6518 const extensions::PendingExtensionInfo* info;
6519 EXPECT_TRUE((info = service_->pending_extension_manager()->
6520 GetById(crx_id_)));
6521 return info->install_source();
6524 // Is an extension pending from a sync request?
6525 bool GetPendingIsFromSync() {
6526 const extensions::PendingExtensionInfo* info;
6527 EXPECT_TRUE((info = service_->pending_extension_manager()->
6528 GetById(crx_id_)));
6529 return info->is_from_sync();
6532 // Is the CRX id these tests use pending?
6533 bool IsCrxPending() {
6534 return service_->pending_extension_manager()->IsIdPending(crx_id_);
6537 // Is an extension installed?
6538 bool IsCrxInstalled() {
6539 return (service_->GetExtensionById(crx_id_, true) != NULL);
6542 protected:
6543 // All tests use a single extension. Making the id and path member
6544 // vars avoids pasing the same argument to every method.
6545 std::string crx_id_;
6546 base::FilePath crx_path_;
6549 // Test that a pending request for installation of an external CRX from
6550 // an update URL overrides a pending request to install the same extension
6551 // from sync.
6552 TEST_F(ExtensionSourcePriorityTest, PendingExternalFileOverSync) {
6553 InitializeEmptyExtensionService();
6555 ASSERT_FALSE(IsCrxInstalled());
6557 // Install pending extension from sync.
6558 content::WindowedNotificationObserver observer(
6559 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
6560 content::NotificationService::AllSources());
6561 EXPECT_TRUE(AddPendingSyncInstall());
6562 ASSERT_EQ(Manifest::INTERNAL, GetPendingLocation());
6563 EXPECT_TRUE(GetPendingIsFromSync());
6564 ASSERT_FALSE(IsCrxInstalled());
6566 // Install pending as external prefs json would.
6567 AddPendingExternalPrefFileInstall();
6568 ASSERT_EQ(Manifest::EXTERNAL_PREF, GetPendingLocation());
6569 ASSERT_FALSE(IsCrxInstalled());
6571 // Another request from sync should be ignored.
6572 EXPECT_FALSE(AddPendingSyncInstall());
6573 ASSERT_EQ(Manifest::EXTERNAL_PREF, GetPendingLocation());
6574 ASSERT_FALSE(IsCrxInstalled());
6576 observer.Wait();
6577 VerifyCrxInstall(crx_path_, INSTALL_NEW);
6578 ASSERT_TRUE(IsCrxInstalled());
6581 // Test that an install of an external CRX from an update overrides
6582 // an install of the same extension from sync.
6583 TEST_F(ExtensionSourcePriorityTest, PendingExternalUrlOverSync) {
6584 InitializeEmptyExtensionService();
6585 ASSERT_FALSE(IsCrxInstalled());
6587 EXPECT_TRUE(AddPendingSyncInstall());
6588 ASSERT_EQ(Manifest::INTERNAL, GetPendingLocation());
6589 EXPECT_TRUE(GetPendingIsFromSync());
6590 ASSERT_FALSE(IsCrxInstalled());
6592 ASSERT_TRUE(AddPendingExternalPrefUrl());
6593 ASSERT_EQ(Manifest::EXTERNAL_PREF_DOWNLOAD, GetPendingLocation());
6594 EXPECT_FALSE(GetPendingIsFromSync());
6595 ASSERT_FALSE(IsCrxInstalled());
6597 EXPECT_FALSE(AddPendingSyncInstall());
6598 ASSERT_EQ(Manifest::EXTERNAL_PREF_DOWNLOAD, GetPendingLocation());
6599 EXPECT_FALSE(GetPendingIsFromSync());
6600 ASSERT_FALSE(IsCrxInstalled());
6603 // Test that an external install request stops sync from installing
6604 // the same extension.
6605 TEST_F(ExtensionSourcePriorityTest, InstallExternalBlocksSyncRequest) {
6606 InitializeEmptyExtensionService();
6607 ASSERT_FALSE(IsCrxInstalled());
6609 // External prefs starts an install.
6610 AddPendingExternalPrefFileInstall();
6612 // Crx installer was made, but has not yet run.
6613 ASSERT_FALSE(IsCrxInstalled());
6615 // Before the CRX installer runs, Sync requests that the same extension
6616 // be installed. Should fail, because an external source is pending.
6617 content::WindowedNotificationObserver observer(
6618 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
6619 content::NotificationService::AllSources());
6620 ASSERT_FALSE(AddPendingSyncInstall());
6622 // Wait for the external source to install.
6623 observer.Wait();
6624 VerifyCrxInstall(crx_path_, INSTALL_NEW);
6625 ASSERT_TRUE(IsCrxInstalled());
6627 // Now that the extension is installed, sync request should fail
6628 // because the extension is already installed.
6629 ASSERT_FALSE(AddPendingSyncInstall());
6632 // Test that installing an external extension displays a GlobalError.
6633 TEST_F(ExtensionServiceTest, ExternalInstallGlobalError) {
6634 FeatureSwitch::ScopedOverride prompt(
6635 FeatureSwitch::prompt_for_external_extensions(), true);
6637 InitializeEmptyExtensionService();
6638 MockExtensionProvider* provider =
6639 new MockExtensionProvider(service_, Manifest::EXTERNAL_PREF);
6640 AddMockExternalProvider(provider);
6642 service_->UpdateExternalExtensionAlert();
6643 // Should return false, meaning there aren't any extensions that the user
6644 // needs to know about.
6645 EXPECT_FALSE(extensions::HasExternalInstallError(service_));
6647 // This is a normal extension, installed normally.
6648 // This should NOT trigger an alert.
6649 set_extensions_enabled(true);
6650 base::FilePath path = data_dir_.AppendASCII("good.crx");
6651 InstallCRX(path, INSTALL_NEW);
6653 service_->CheckForExternalUpdates();
6654 base::RunLoop().RunUntilIdle();
6655 EXPECT_FALSE(extensions::HasExternalInstallError(service_));
6657 // A hosted app, installed externally.
6658 // This should NOT trigger an alert.
6659 provider->UpdateOrAddExtension(hosted_app, "1.0.0.0",
6660 data_dir_.AppendASCII("hosted_app.crx"));
6662 content::WindowedNotificationObserver observer(
6663 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
6664 content::NotificationService::AllSources());
6665 service_->CheckForExternalUpdates();
6666 observer.Wait();
6667 EXPECT_FALSE(extensions::HasExternalInstallError(service_));
6669 // Another normal extension, but installed externally.
6670 // This SHOULD trigger an alert.
6671 provider->UpdateOrAddExtension(page_action, "1.0.0.0",
6672 data_dir_.AppendASCII("page_action.crx"));
6674 content::WindowedNotificationObserver observer2(
6675 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
6676 content::NotificationService::AllSources());
6677 service_->CheckForExternalUpdates();
6678 observer2.Wait();
6679 EXPECT_TRUE(extensions::HasExternalInstallError(service_));
6682 // Test that external extensions are initially disabled, and that enabling
6683 // them clears the prompt.
6684 TEST_F(ExtensionServiceTest, ExternalInstallInitiallyDisabled) {
6685 FeatureSwitch::ScopedOverride prompt(
6686 FeatureSwitch::prompt_for_external_extensions(), true);
6688 InitializeEmptyExtensionService();
6689 MockExtensionProvider* provider =
6690 new MockExtensionProvider(service_, Manifest::EXTERNAL_PREF);
6691 AddMockExternalProvider(provider);
6693 provider->UpdateOrAddExtension(page_action, "1.0.0.0",
6694 data_dir_.AppendASCII("page_action.crx"));
6696 content::WindowedNotificationObserver observer(
6697 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
6698 content::NotificationService::AllSources());
6699 service_->CheckForExternalUpdates();
6700 observer.Wait();
6701 EXPECT_TRUE(extensions::HasExternalInstallError(service_));
6702 EXPECT_FALSE(service_->IsExtensionEnabled(page_action));
6704 const Extension* extension =
6705 registry_->disabled_extensions().GetByID(page_action);
6706 EXPECT_TRUE(extension);
6707 EXPECT_EQ(page_action, extension->id());
6709 service_->EnableExtension(page_action);
6710 EXPECT_FALSE(extensions::HasExternalInstallError(service_));
6711 EXPECT_TRUE(service_->IsExtensionEnabled(page_action));
6714 // Test that installing multiple external extensions works.
6715 // Flaky on windows; http://crbug.com/295757 .
6716 #if defined(OS_WIN)
6717 #define MAYBE_ExternalInstallMultiple DISABLED_ExternalInstallMultiple
6718 #else
6719 #define MAYBE_ExternalInstallMultiple ExternalInstallMultiple
6720 #endif
6721 TEST_F(ExtensionServiceTest, MAYBE_ExternalInstallMultiple) {
6722 FeatureSwitch::ScopedOverride prompt(
6723 FeatureSwitch::prompt_for_external_extensions(), true);
6725 InitializeEmptyExtensionService();
6726 MockExtensionProvider* provider =
6727 new MockExtensionProvider(service_, Manifest::EXTERNAL_PREF);
6728 AddMockExternalProvider(provider);
6730 provider->UpdateOrAddExtension(page_action, "1.0.0.0",
6731 data_dir_.AppendASCII("page_action.crx"));
6732 provider->UpdateOrAddExtension(good_crx, "1.0.0.0",
6733 data_dir_.AppendASCII("good.crx"));
6734 provider->UpdateOrAddExtension(theme_crx, "2.0",
6735 data_dir_.AppendASCII("theme.crx"));
6737 int count = 3;
6738 content::WindowedNotificationObserver observer(
6739 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
6740 base::Bind(&WaitForCountNotificationsCallback, &count));
6741 service_->CheckForExternalUpdates();
6742 observer.Wait();
6743 EXPECT_TRUE(extensions::HasExternalInstallError(service_));
6744 EXPECT_FALSE(service_->IsExtensionEnabled(page_action));
6745 EXPECT_FALSE(service_->IsExtensionEnabled(good_crx));
6746 EXPECT_FALSE(service_->IsExtensionEnabled(theme_crx));
6748 service_->EnableExtension(page_action);
6749 EXPECT_TRUE(extensions::HasExternalInstallError(service_));
6750 EXPECT_FALSE(extensions::HasExternalInstallBubble(service_));
6751 service_->EnableExtension(theme_crx);
6752 EXPECT_TRUE(extensions::HasExternalInstallError(service_));
6753 EXPECT_FALSE(extensions::HasExternalInstallBubble(service_));
6754 service_->EnableExtension(good_crx);
6755 EXPECT_FALSE(extensions::HasExternalInstallError(service_));
6756 EXPECT_FALSE(extensions::HasExternalInstallBubble(service_));
6759 // Test that there is a bubble for external extensions that update
6760 // from the webstore if the profile is not new.
6761 TEST_F(ExtensionServiceTest, ExternalInstallUpdatesFromWebstoreOldProfile) {
6762 FeatureSwitch::ScopedOverride prompt(
6763 FeatureSwitch::prompt_for_external_extensions(), true);
6765 // This sets up the ExtensionPrefs used by our ExtensionService to be
6766 // post-first run.
6767 ExtensionServiceInitParams params = CreateDefaultInitParams();
6768 params.is_first_run = false;
6769 InitializeExtensionService(params);
6771 base::FilePath crx_path = temp_dir_.path().AppendASCII("webstore.crx");
6772 PackCRX(data_dir_.AppendASCII("update_from_webstore"),
6773 data_dir_.AppendASCII("update_from_webstore.pem"),
6774 crx_path);
6776 MockExtensionProvider* provider =
6777 new MockExtensionProvider(service_, Manifest::EXTERNAL_PREF);
6778 AddMockExternalProvider(provider);
6779 provider->UpdateOrAddExtension(updates_from_webstore, "1", crx_path);
6781 content::WindowedNotificationObserver observer(
6782 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
6783 content::NotificationService::AllSources());
6784 service_->CheckForExternalUpdates();
6785 observer.Wait();
6786 EXPECT_TRUE(extensions::HasExternalInstallError(service_));
6787 EXPECT_TRUE(extensions::HasExternalInstallBubble(service_));
6788 EXPECT_FALSE(service_->IsExtensionEnabled(updates_from_webstore));
6791 // Test that there is no bubble for external extensions if the profile is new.
6792 TEST_F(ExtensionServiceTest, ExternalInstallUpdatesFromWebstoreNewProfile) {
6793 FeatureSwitch::ScopedOverride prompt(
6794 FeatureSwitch::prompt_for_external_extensions(), true);
6796 InitializeEmptyExtensionService();
6798 base::FilePath crx_path = temp_dir_.path().AppendASCII("webstore.crx");
6799 PackCRX(data_dir_.AppendASCII("update_from_webstore"),
6800 data_dir_.AppendASCII("update_from_webstore.pem"),
6801 crx_path);
6803 MockExtensionProvider* provider =
6804 new MockExtensionProvider(service_, Manifest::EXTERNAL_PREF);
6805 AddMockExternalProvider(provider);
6806 provider->UpdateOrAddExtension(updates_from_webstore, "1", crx_path);
6808 content::WindowedNotificationObserver observer(
6809 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
6810 content::NotificationService::AllSources());
6811 service_->CheckForExternalUpdates();
6812 observer.Wait();
6813 EXPECT_TRUE(extensions::HasExternalInstallError(service_));
6814 EXPECT_FALSE(extensions::HasExternalInstallBubble(service_));
6815 EXPECT_FALSE(service_->IsExtensionEnabled(updates_from_webstore));
6818 TEST_F(ExtensionServiceTest, InstallBlacklistedExtension) {
6819 InitializeEmptyExtensionService();
6821 scoped_refptr<Extension> extension = extensions::ExtensionBuilder()
6822 .SetManifest(extensions::DictionaryBuilder()
6823 .Set("name", "extension")
6824 .Set("version", "1.0")
6825 .Set("manifest_version", 2).Build())
6826 .Build();
6827 ASSERT_TRUE(extension.get());
6828 const std::string& id = extension->id();
6830 std::set<std::string> id_set;
6831 id_set.insert(id);
6832 extensions::ExtensionNotificationObserver notifications(
6833 content::NotificationService::AllSources(), id_set);
6835 // Installation should be allowed but the extension should never have been
6836 // loaded and it should be blacklisted in prefs.
6837 service_->OnExtensionInstalled(
6838 extension.get(),
6839 syncer::StringOrdinal(),
6840 false /* has requirement errors */,
6841 extensions::BLACKLISTED_MALWARE,
6842 false /* wait for idle */);
6843 base::RunLoop().RunUntilIdle();
6845 // Extension was installed but not loaded.
6846 EXPECT_TRUE(notifications.CheckNotifications(
6847 chrome::NOTIFICATION_EXTENSION_INSTALLED));
6848 EXPECT_TRUE(service_->GetInstalledExtension(id));
6850 EXPECT_FALSE(registry_->enabled_extensions().Contains(id));
6851 EXPECT_TRUE(registry_->blacklisted_extensions().Contains(id));
6853 EXPECT_TRUE(ExtensionPrefs::Get(profile_.get())->IsExtensionBlacklisted(id));
6854 EXPECT_TRUE(ExtensionPrefs::Get(profile_.get())
6855 ->IsBlacklistedExtensionAcknowledged(id));
6858 TEST_F(ExtensionServiceTest, ReconcileKnownDisabledNoneDisabled) {
6859 // A profile with 3 extensions installed: good0, good1, and good2.
6860 InitializeGoodInstalledExtensionService();
6862 // Initializing shouldn't disable any extensions if none are known to be
6863 // disabled.
6864 service_->Init();
6866 extensions::ExtensionIdSet expected_extensions;
6867 expected_extensions.insert(good0);
6868 expected_extensions.insert(good1);
6869 expected_extensions.insert(good2);
6871 extensions::ExtensionIdSet expected_disabled_extensions;
6873 EXPECT_EQ(expected_extensions, registry_->enabled_extensions().GetIDs());
6874 EXPECT_EQ(expected_disabled_extensions,
6875 registry_->disabled_extensions().GetIDs());
6878 TEST_F(ExtensionServiceTest, ReconcileKnownDisabledWithSideEnable) {
6879 // A profile with 3 extensions installed: good0, good1, and good2.
6880 InitializeGoodInstalledExtensionService();
6882 ExtensionPrefs* extension_prefs = ExtensionPrefs::Get(profile_.get());
6884 // Disable good1.
6885 extension_prefs->SetExtensionState(good1, Extension::DISABLED);
6887 // Mark both good1 and good2 as "known_disabled" (effectively making good2
6888 // look as if it had been side-enabled).
6889 extensions::ExtensionIdSet known_disabled;
6890 known_disabled.insert(good1);
6891 known_disabled.insert(good2);
6892 extension_prefs->SetKnownDisabled(known_disabled);
6894 // Initialize the service (which should disable good2 since it's known to be
6895 // disabled).
6896 service_->Init();
6898 extensions::ExtensionIdSet expected_extensions;
6899 expected_extensions.insert(good0);
6901 extensions::ExtensionIdSet expected_disabled_extensions;
6902 expected_disabled_extensions.insert(good1);
6903 expected_disabled_extensions.insert(good2);
6905 EXPECT_EQ(expected_extensions, registry_->enabled_extensions().GetIDs());
6906 EXPECT_EQ(expected_disabled_extensions,
6907 registry_->disabled_extensions().GetIDs());
6909 // Make sure that re-enabling an extension sticks across calls to
6910 // ReconcileKnownDisabled().
6911 service_->EnableExtension(good2);
6912 service_->ReconcileKnownDisabled();
6913 expected_extensions.insert(good2);
6914 expected_disabled_extensions.erase(good2);
6916 EXPECT_EQ(expected_extensions, registry_->enabled_extensions().GetIDs());
6917 EXPECT_EQ(expected_disabled_extensions,
6918 registry_->disabled_extensions().GetIDs());