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