Upstream version 11.40.277.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / supervised_user / supervised_user_service.h
1 // Copyright 2014 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 #ifndef CHROME_BROWSER_SUPERVISED_USER_SUPERVISED_USER_SERVICE_H_
6 #define CHROME_BROWSER_SUPERVISED_USER_SUPERVISED_USER_SERVICE_H_
7
8 #include <map>
9 #include <set>
10 #include <string>
11 #include <vector>
12
13 #include "base/callback.h"
14 #include "base/gtest_prod_util.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "base/observer_list.h"
17 #include "base/prefs/pref_change_registrar.h"
18 #include "base/scoped_observer.h"
19 #include "base/strings/string16.h"
20 #include "chrome/browser/supervised_user/experimental/supervised_user_blacklist.h"
21 #include "chrome/browser/supervised_user/supervised_user_url_filter.h"
22 #include "chrome/browser/supervised_user/supervised_users.h"
23 #include "chrome/browser/sync/profile_sync_service_observer.h"
24 #include "chrome/browser/sync/sync_type_preference_provider.h"
25 #include "chrome/browser/ui/browser_list_observer.h"
26 #include "components/keyed_service/core/keyed_service.h"
27 #include "content/public/browser/web_contents.h"
28
29 #if defined(ENABLE_EXTENSIONS)
30 #include "extensions/browser/extension_registry_observer.h"
31 #include "extensions/browser/management_policy.h"
32 #endif
33
34 class Browser;
35 class GoogleServiceAuthError;
36 class PermissionRequestCreator;
37 class Profile;
38 class SupervisedUserBlacklistDownloader;
39 class SupervisedUserRegistrationUtility;
40 class SupervisedUserServiceObserver;
41 class SupervisedUserSettingsService;
42 class SupervisedUserSiteList;
43 class SupervisedUserURLFilter;
44
45 namespace base {
46 class FilePath;
47 }
48
49 namespace extensions {
50 class ExtensionRegistry;
51 }
52
53 namespace net {
54 class URLRequestContextGetter;
55 }
56
57 namespace user_prefs {
58 class PrefRegistrySyncable;
59 }
60
61 // This class handles all the information related to a given supervised profile
62 // (e.g. the installed content packs, the default URL filtering behavior, or
63 // manual whitelist/blacklist overrides).
64 class SupervisedUserService : public KeyedService,
65 #if defined(ENABLE_EXTENSIONS)
66                               public extensions::ManagementPolicy::Provider,
67                               public extensions::ExtensionRegistryObserver,
68 #endif
69                               public SyncTypePreferenceProvider,
70                               public ProfileSyncServiceObserver,
71                               public chrome::BrowserListObserver {
72  public:
73   typedef std::vector<base::string16> CategoryList;
74   typedef base::Callback<void(content::WebContents*)> NavigationBlockedCallback;
75   typedef base::Callback<void(const GoogleServiceAuthError&)> AuthErrorCallback;
76   typedef base::Callback<void(bool)> SuccessCallback;
77
78   class Delegate {
79    public:
80     virtual ~Delegate() {}
81     // Returns true to indicate that the delegate handled the (de)activation, or
82     // false to indicate that the SupervisedUserService itself should handle it.
83     virtual bool SetActive(bool active) = 0;
84     // Returns the path to a blacklist file to load, or an empty path to
85     // indicate "none".
86     virtual base::FilePath GetBlacklistPath() const;
87     // Returns the URL from which to download a blacklist if no local one exists
88     // yet. The blacklist file will be stored at |GetBlacklistPath()|.
89     virtual GURL GetBlacklistURL() const;
90     // Returns the identifier ("cx") of the Custom Search Engine to use for the
91     // experimental "SafeSites" feature, or the empty string to disable the
92     // feature.
93     virtual std::string GetSafeSitesCx() const;
94     // Returns a custom Google API key to use for SafeSites, or the empty string
95     // to use the default one.
96     virtual std::string GetSafeSitesApiKey() const;
97   };
98
99   ~SupervisedUserService() override;
100
101   // ProfileKeyedService override:
102   void Shutdown() override;
103
104   static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry);
105
106   void SetDelegate(Delegate* delegate);
107
108   // Returns the URL filter for the IO thread, for filtering network requests
109   // (in SupervisedUserResourceThrottle).
110   scoped_refptr<const SupervisedUserURLFilter> GetURLFilterForIOThread();
111
112   // Returns the URL filter for the UI thread, for filtering navigations and
113   // classifying sites in the history view.
114   SupervisedUserURLFilter* GetURLFilterForUIThread();
115
116   // Returns the URL's category, obtained from the installed content packs.
117   int GetCategory(const GURL& url);
118
119   // Returns the list of all known human-readable category names, sorted by ID
120   // number. Called in the critical path of drawing the history UI, so needs to
121   // be fast.
122   void GetCategoryNames(CategoryList* list);
123
124   // Whether the user can request access to blocked URLs.
125   bool AccessRequestsEnabled();
126
127   // Adds an access request for the given URL. The requests are stored using
128   // a prefix followed by a URIEncoded version of the URL. Each entry contains
129   // a dictionary which currently has the timestamp of the request in it.
130   void AddAccessRequest(const GURL& url, const SuccessCallback& callback);
131
132   // Returns the email address of the custodian.
133   std::string GetCustodianEmailAddress() const;
134
135   // Returns the name of the custodian, or the email address if the name is
136   // empty.
137   std::string GetCustodianName() const;
138
139   // Returns the email address of the second custodian, or the empty string
140   // if there is no second custodian.
141   std::string GetSecondCustodianEmailAddress() const;
142
143   // Returns the name of the second custodian, or the email address if the name
144   // is empty, or the empty string is there is no second custodian.
145   std::string GetSecondCustodianName() const;
146
147   // Initializes this object. This method does nothing if the profile is not
148   // supervised.
149   void Init();
150
151   // Initializes this profile for syncing, using the provided |refresh_token| to
152   // mint access tokens for Sync.
153   void InitSync(const std::string& refresh_token);
154
155   // Convenience method that registers this supervised user using
156   // |registration_utility| and initializes sync with the returned token.
157   // The |callback| will be called when registration is complete,
158   // whether it succeeded or not -- unless registration was cancelled manually,
159   // in which case the callback will be ignored.
160   void RegisterAndInitSync(
161       SupervisedUserRegistrationUtility* registration_utility,
162       Profile* custodian_profile,
163       const std::string& supervised_user_id,
164       const AuthErrorCallback& callback);
165
166   void set_elevated_for_testing(bool skip) {
167     elevated_for_testing_ = skip;
168   }
169
170   void AddNavigationBlockedCallback(const NavigationBlockedCallback& callback);
171   void DidBlockNavigation(content::WebContents* web_contents);
172
173   void AddObserver(SupervisedUserServiceObserver* observer);
174   void RemoveObserver(SupervisedUserServiceObserver* observer);
175
176   // Will take ownership of |creator|.
177   void AddPermissionRequestCreatorForTesting(PermissionRequestCreator* creator);
178
179 #if defined(ENABLE_EXTENSIONS)
180   // extensions::ManagementPolicy::Provider implementation:
181   std::string GetDebugPolicyProviderName() const override;
182   bool UserMayLoad(const extensions::Extension* extension,
183                    base::string16* error) const override;
184   bool UserMayModifySettings(const extensions::Extension* extension,
185                              base::string16* error) const override;
186
187   // extensions::ExtensionRegistryObserver implementation.
188   void OnExtensionLoaded(content::BrowserContext* browser_context,
189                          const extensions::Extension* extension) override;
190   void OnExtensionUnloaded(
191       content::BrowserContext* browser_context,
192       const extensions::Extension* extension,
193       extensions::UnloadedExtensionInfo::Reason reason) override;
194 #endif
195
196   // SyncTypePreferenceProvider implementation:
197   syncer::ModelTypeSet GetPreferredDataTypes() const override;
198
199   // ProfileSyncServiceObserver implementation:
200   void OnStateChanged() override;
201
202   // chrome::BrowserListObserver implementation:
203   void OnBrowserSetLastActive(Browser* browser) override;
204
205  private:
206   friend class SupervisedUserServiceExtensionTestBase;
207   friend class SupervisedUserServiceFactory;
208   FRIEND_TEST_ALL_PREFIXES(SingleClientSupervisedUserSettingsSyncTest, Sanity);
209   FRIEND_TEST_ALL_PREFIXES(SupervisedUserServiceTest, ClearOmitOnRegistration);
210   FRIEND_TEST_ALL_PREFIXES(SupervisedUserServiceTest,
211                            ChangesIncludedSessionOnChangedSettings);
212   FRIEND_TEST_ALL_PREFIXES(SupervisedUserServiceTest,
213                            ChangesSyncSessionStateOnChangedSettings);
214   // A bridge from the UI thread to the SupervisedUserURLFilters, one of which
215   // lives on the IO thread. This class mediates access to them and makes sure
216   // they are kept in sync.
217   class URLFilterContext {
218    public:
219     URLFilterContext();
220     ~URLFilterContext();
221
222     SupervisedUserURLFilter* ui_url_filter() const;
223     SupervisedUserURLFilter* io_url_filter() const;
224
225     void SetDefaultFilteringBehavior(
226         SupervisedUserURLFilter::FilteringBehavior behavior);
227     void LoadWhitelists(ScopedVector<SupervisedUserSiteList> site_lists);
228     void LoadBlacklist(const base::FilePath& path);
229     void SetManualHosts(scoped_ptr<std::map<std::string, bool> > host_map);
230     void SetManualURLs(scoped_ptr<std::map<GURL, bool> > url_map);
231
232     void InitAsyncURLChecker(net::URLRequestContextGetter* context,
233                              const std::string& cx,
234                              const std::string& api_key);
235
236    private:
237     void OnBlacklistLoaded();
238
239     // SupervisedUserURLFilter is refcounted because the IO thread filter is
240     // used both by ProfileImplIOData and OffTheRecordProfileIOData (to filter
241     // network requests), so they both keep a reference to it.
242     // Clients should not keep references to the UI thread filter, however
243     // (the filter will live as long as the profile lives, and afterwards it
244     // should not be used anymore either).
245     scoped_refptr<SupervisedUserURLFilter> ui_url_filter_;
246     scoped_refptr<SupervisedUserURLFilter> io_url_filter_;
247
248     SupervisedUserBlacklist blacklist_;
249
250     DISALLOW_COPY_AND_ASSIGN(URLFilterContext);
251   };
252
253   // Use |SupervisedUserServiceFactory::GetForProfile(..)| to get
254   // an instance of this service.
255   explicit SupervisedUserService(Profile* profile);
256
257   void SetActive(bool active);
258
259   void OnCustodianProfileDownloaded(const base::string16& full_name);
260
261   void OnSupervisedUserRegistered(const AuthErrorCallback& callback,
262                                   Profile* custodian_profile,
263                                   const GoogleServiceAuthError& auth_error,
264                                   const std::string& token);
265
266   void SetupSync();
267   void StartSetupSync();
268   void FinishSetupSyncWhenReady();
269   void FinishSetupSync();
270
271   bool ProfileIsSupervised() const;
272
273   void OnCustodianInfoChanged();
274
275 #if defined(ENABLE_EXTENSIONS)
276   // Internal implementation for ExtensionManagementPolicy::Delegate methods.
277   // If |error| is not NULL, it will be filled with an error message if the
278   // requested extension action (install, modify status, etc.) is not permitted.
279   bool ExtensionManagementPolicyImpl(const extensions::Extension* extension,
280                                      base::string16* error) const;
281
282   // Returns a list of all installed and enabled site lists in the current
283   // supervised profile.
284   ScopedVector<SupervisedUserSiteList> GetActiveSiteLists();
285
286   // Extensions helper to SetActive().
287   void SetExtensionsActive();
288 #endif
289
290   SupervisedUserSettingsService* GetSettingsService();
291
292   size_t FindEnabledPermissionRequestCreator(size_t start);
293   void AddAccessRequestInternal(const GURL& url,
294                                 const SuccessCallback& callback,
295                                 size_t index);
296   void OnPermissionRequestIssued(const GURL& url,
297                                  const SuccessCallback& callback,
298                                  size_t index,
299                                  bool success);
300
301   void OnSupervisedUserIdChanged();
302
303   void OnDefaultFilteringBehaviorChanged();
304
305   void UpdateSiteLists();
306
307   // Asynchronously downloads a static blacklist file from |url|, stores it at
308   // |path|, loads it, and applies it to the URL filters. If |url| is not valid
309   // (e.g. empty), directly tries to load from |path|.
310   void LoadBlacklist(const base::FilePath& path, const GURL& url);
311
312   // Asynchronously loads a static blacklist from a binary file at |path| and
313   // applies it to the URL filters.
314   void LoadBlacklistFromFile(const base::FilePath& path);
315
316   void OnBlacklistDownloadDone(const base::FilePath& path, bool success);
317
318   // Updates the manual overrides for hosts in the URL filters when the
319   // corresponding preference is changed.
320   void UpdateManualHosts();
321
322   // Updates the manual overrides for URLs in the URL filters when the
323   // corresponding preference is changed.
324   void UpdateManualURLs();
325
326   // Returns the human readable name of the supervised user.
327   std::string GetSupervisedUserName() const;
328
329   // Subscribes to the SupervisedUserPrefStore, refreshes
330   // |includes_sync_sessions_type_| and triggers reconfiguring the
331   // ProfileSyncService.
332   void OnHistoryRecordingStateChanged();
333
334   // Returns true if the syncer::SESSIONS type should be included in Sync.
335   bool IncludesSyncSessionsType() const;
336
337   // The option a custodian sets to either record or prevent recording the
338   // supervised user's history. Set by |FetchNewSessionSyncState()| and
339   // defaults to true.
340   bool includes_sync_sessions_type_;
341
342   // Owns us via the KeyedService mechanism.
343   Profile* profile_;
344
345   bool active_;
346
347   Delegate* delegate_;
348
349 #if defined(ENABLE_EXTENSIONS)
350   ScopedObserver<extensions::ExtensionRegistry,
351                  extensions::ExtensionRegistryObserver>
352       extension_registry_observer_;
353 #endif
354
355   PrefChangeRegistrar pref_change_registrar_;
356
357   // True iff we're waiting for the Sync service to be initialized.
358   bool waiting_for_sync_initialization_;
359   bool is_profile_active_;
360
361   std::vector<NavigationBlockedCallback> navigation_blocked_callbacks_;
362
363   // Sets a profile in elevated state for testing if set to true.
364   bool elevated_for_testing_;
365
366   // True only when |Init()| method has been called.
367   bool did_init_;
368
369   // True only when |Shutdown()| method has been called.
370   bool did_shutdown_;
371
372   URLFilterContext url_filter_context_;
373   scoped_ptr<SupervisedUserBlacklistDownloader> blacklist_downloader_;
374
375   // Used to create permission requests.
376   ScopedVector<PermissionRequestCreator> permissions_creators_;
377
378   ObserverList<SupervisedUserServiceObserver> observer_list_;
379
380   base::WeakPtrFactory<SupervisedUserService> weak_ptr_factory_;
381 };
382
383 #endif  // CHROME_BROWSER_SUPERVISED_USER_SUPERVISED_USER_SERVICE_H_