Adding instrumentation to locate the source of jankiness
[chromium-blink-merge.git] / chrome / browser / supervised_user / supervised_user_service.h
blob79eb8bbbaa6c854bf2dbb3598718b2e453f1298a
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.
5 #ifndef CHROME_BROWSER_SUPERVISED_USER_SUPERVISED_USER_SERVICE_H_
6 #define CHROME_BROWSER_SUPERVISED_USER_SUPERVISED_USER_SERVICE_H_
8 #include <map>
9 #include <set>
10 #include <string>
11 #include <vector>
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"
29 #if defined(ENABLE_EXTENSIONS)
30 #include "extensions/browser/extension_registry_observer.h"
31 #include "extensions/browser/management_policy.h"
32 #endif
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;
45 namespace base {
46 class FilePath;
49 namespace extensions {
50 class ExtensionRegistry;
53 namespace user_prefs {
54 class PrefRegistrySyncable;
57 // This class handles all the information related to a given supervised profile
58 // (e.g. the installed content packs, the default URL filtering behavior, or
59 // manual whitelist/blacklist overrides).
60 class SupervisedUserService : public KeyedService,
61 #if defined(ENABLE_EXTENSIONS)
62 public extensions::ManagementPolicy::Provider,
63 public extensions::ExtensionRegistryObserver,
64 #endif
65 public SyncTypePreferenceProvider,
66 public ProfileSyncServiceObserver,
67 public chrome::BrowserListObserver {
68 public:
69 typedef std::vector<base::string16> CategoryList;
70 typedef base::Callback<void(content::WebContents*)> NavigationBlockedCallback;
71 typedef base::Callback<void(const GoogleServiceAuthError&)> AuthErrorCallback;
72 typedef base::Callback<void(bool)> SuccessCallback;
74 enum ManualBehavior {
75 MANUAL_NONE = 0,
76 MANUAL_ALLOW,
77 MANUAL_BLOCK
80 class Delegate {
81 public:
82 virtual ~Delegate() {}
83 // Returns true to indicate that the delegate handled the (de)activation, or
84 // false to indicate that the SupervisedUserService itself should handle it.
85 virtual bool SetActive(bool active) = 0;
86 // Returns the path to a blacklist file to load, or an empty path to
87 // indicate "none".
88 virtual base::FilePath GetBlacklistPath() const = 0;
89 // Returns the URL from which to download a blacklist if no local one exists
90 // yet. The blacklist file will be stored at |GetBlacklistPath()|.
91 virtual GURL GetBlacklistURL() const = 0;
94 virtual ~SupervisedUserService();
96 // ProfileKeyedService override:
97 virtual void Shutdown() override;
99 static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry);
101 void SetDelegate(Delegate* delegate);
103 // Returns the URL filter for the IO thread, for filtering network requests
104 // (in SupervisedUserResourceThrottle).
105 scoped_refptr<const SupervisedUserURLFilter> GetURLFilterForIOThread();
107 // Returns the URL filter for the UI thread, for filtering navigations and
108 // classifying sites in the history view.
109 SupervisedUserURLFilter* GetURLFilterForUIThread();
111 // Returns the URL's category, obtained from the installed content packs.
112 int GetCategory(const GURL& url);
114 // Returns the list of all known human-readable category names, sorted by ID
115 // number. Called in the critical path of drawing the history UI, so needs to
116 // be fast.
117 void GetCategoryNames(CategoryList* list);
119 // Whether the user can request access to blocked URLs.
120 bool AccessRequestsEnabled();
122 // Adds an access request for the given URL. The requests are stored using
123 // a prefix followed by a URIEncoded version of the URL. Each entry contains
124 // a dictionary which currently has the timestamp of the request in it.
125 void AddAccessRequest(const GURL& url, const SuccessCallback& callback);
127 // Returns the email address of the custodian.
128 std::string GetCustodianEmailAddress() const;
130 // Returns the name of the custodian, or the email address if the name is
131 // empty.
132 std::string GetCustodianName() const;
134 // These methods allow querying and modifying the manual filtering behavior.
135 // The manual behavior is set by the user and overrides all other settings
136 // (whitelists or the default behavior).
138 // Returns the manual behavior for the given host.
139 ManualBehavior GetManualBehaviorForHost(const std::string& hostname);
141 // Returns the manual behavior for the given URL.
142 ManualBehavior GetManualBehaviorForURL(const GURL& url);
144 // Returns all URLS on the given host that have exceptions.
145 void GetManualExceptionsForHost(const std::string& host,
146 std::vector<GURL>* urls);
148 // Initializes this object. This method does nothing if the profile is not
149 // supervised.
150 void Init();
152 // Initializes this profile for syncing, using the provided |refresh_token| to
153 // mint access tokens for Sync.
154 void InitSync(const std::string& refresh_token);
156 // Convenience method that registers this supervised user using
157 // |registration_utility| and initializes sync with the returned token.
158 // The |callback| will be called when registration is complete,
159 // whether it succeeded or not -- unless registration was cancelled manually,
160 // in which case the callback will be ignored.
161 void RegisterAndInitSync(
162 SupervisedUserRegistrationUtility* registration_utility,
163 Profile* custodian_profile,
164 const std::string& supervised_user_id,
165 const AuthErrorCallback& callback);
167 void set_elevated_for_testing(bool skip) {
168 elevated_for_testing_ = skip;
171 void AddNavigationBlockedCallback(const NavigationBlockedCallback& callback);
172 void DidBlockNavigation(content::WebContents* web_contents);
174 void AddObserver(SupervisedUserServiceObserver* observer);
175 void RemoveObserver(SupervisedUserServiceObserver* observer);
177 // Will take ownership of |creator|.
178 void AddPermissionRequestCreatorForTesting(PermissionRequestCreator* creator);
180 #if defined(ENABLE_EXTENSIONS)
181 // extensions::ManagementPolicy::Provider implementation:
182 virtual std::string GetDebugPolicyProviderName() const override;
183 virtual bool UserMayLoad(const extensions::Extension* extension,
184 base::string16* error) const override;
185 virtual bool UserMayModifySettings(const extensions::Extension* extension,
186 base::string16* error) const override;
188 // extensions::ExtensionRegistryObserver implementation.
189 virtual void OnExtensionLoaded(
190 content::BrowserContext* browser_context,
191 const extensions::Extension* extension) override;
192 virtual void OnExtensionUnloaded(
193 content::BrowserContext* browser_context,
194 const extensions::Extension* extension,
195 extensions::UnloadedExtensionInfo::Reason reason) override;
196 #endif
198 // SyncTypePreferenceProvider implementation:
199 virtual syncer::ModelTypeSet GetPreferredDataTypes() const override;
201 // ProfileSyncServiceObserver implementation:
202 virtual void OnStateChanged() override;
204 // chrome::BrowserListObserver implementation:
205 virtual void OnBrowserSetLastActive(Browser* browser) override;
207 private:
208 friend class SupervisedUserServiceExtensionTestBase;
209 friend class SupervisedUserServiceFactory;
210 FRIEND_TEST_ALL_PREFIXES(SingleClientSupervisedUserSettingsSyncTest, Sanity);
211 FRIEND_TEST_ALL_PREFIXES(SupervisedUserServiceTest, ClearOmitOnRegistration);
212 FRIEND_TEST_ALL_PREFIXES(SupervisedUserServiceTest,
213 ChangesIncludedSessionOnChangedSettings);
214 FRIEND_TEST_ALL_PREFIXES(SupervisedUserServiceTest,
215 ChangesSyncSessionStateOnChangedSettings);
216 // A bridge from the UI thread to the SupervisedUserURLFilters, one of which
217 // lives on the IO thread. This class mediates access to them and makes sure
218 // they are kept in sync.
219 class URLFilterContext {
220 public:
221 URLFilterContext();
222 ~URLFilterContext();
224 SupervisedUserURLFilter* ui_url_filter() const;
225 SupervisedUserURLFilter* io_url_filter() const;
227 void SetDefaultFilteringBehavior(
228 SupervisedUserURLFilter::FilteringBehavior behavior);
229 void LoadWhitelists(ScopedVector<SupervisedUserSiteList> site_lists);
230 void LoadBlacklist(const base::FilePath& path);
231 void SetManualHosts(scoped_ptr<std::map<std::string, bool> > host_map);
232 void SetManualURLs(scoped_ptr<std::map<GURL, bool> > url_map);
234 private:
235 void OnBlacklistLoaded();
237 // SupervisedUserURLFilter is refcounted because the IO thread filter is
238 // used both by ProfileImplIOData and OffTheRecordProfileIOData (to filter
239 // network requests), so they both keep a reference to it.
240 // Clients should not keep references to the UI thread filter, however
241 // (the filter will live as long as the profile lives, and afterwards it
242 // should not be used anymore either).
243 scoped_refptr<SupervisedUserURLFilter> ui_url_filter_;
244 scoped_refptr<SupervisedUserURLFilter> io_url_filter_;
246 SupervisedUserBlacklist blacklist_;
248 DISALLOW_COPY_AND_ASSIGN(URLFilterContext);
251 // Use |SupervisedUserServiceFactory::GetForProfile(..)| to get
252 // an instance of this service.
253 explicit SupervisedUserService(Profile* profile);
255 void SetActive(bool active);
257 void OnCustodianProfileDownloaded(const base::string16& full_name);
259 void OnSupervisedUserRegistered(const AuthErrorCallback& callback,
260 Profile* custodian_profile,
261 const GoogleServiceAuthError& auth_error,
262 const std::string& token);
264 void SetupSync();
265 void StartSetupSync();
266 void FinishSetupSyncWhenReady();
267 void FinishSetupSync();
269 bool ProfileIsSupervised() const;
271 void OnCustodianInfoChanged();
273 #if defined(ENABLE_EXTENSIONS)
274 // Internal implementation for ExtensionManagementPolicy::Delegate methods.
275 // If |error| is not NULL, it will be filled with an error message if the
276 // requested extension action (install, modify status, etc.) is not permitted.
277 bool ExtensionManagementPolicyImpl(const extensions::Extension* extension,
278 base::string16* error) const;
280 // Returns a list of all installed and enabled site lists in the current
281 // supervised profile.
282 ScopedVector<SupervisedUserSiteList> GetActiveSiteLists();
284 // Extensions helper to SetActive().
285 void SetExtensionsActive();
286 #endif
288 SupervisedUserSettingsService* GetSettingsService();
290 size_t FindEnabledPermissionRequestCreator(size_t start);
291 void AddAccessRequestInternal(const GURL& url,
292 const SuccessCallback& callback,
293 size_t index);
294 void OnPermissionRequestIssued(const GURL& url,
295 const SuccessCallback& callback,
296 size_t index,
297 bool success);
299 void OnSupervisedUserIdChanged();
301 void OnDefaultFilteringBehaviorChanged();
303 void UpdateSiteLists();
305 // Asynchronously downloads a static blacklist file from |url|, stores it at
306 // |path|, loads it, and applies it to the URL filters. If |url| is not valid
307 // (e.g. empty), directly tries to load from |path|.
308 void LoadBlacklist(const base::FilePath& path, const GURL& url);
310 // Asynchronously loads a static blacklist from a binary file at |path| and
311 // applies it to the URL filters.
312 void LoadBlacklistFromFile(const base::FilePath& path);
314 void OnBlacklistDownloadDone(const base::FilePath& path, bool success);
316 // Updates the manual overrides for hosts in the URL filters when the
317 // corresponding preference is changed.
318 void UpdateManualHosts();
320 // Updates the manual overrides for URLs in the URL filters when the
321 // corresponding preference is changed.
322 void UpdateManualURLs();
324 // Returns the human readable name of the supervised user.
325 std::string GetSupervisedUserName() const;
327 // Subscribes to the SupervisedUserPrefStore, refreshes
328 // |includes_sync_sessions_type_| and triggers reconfiguring the
329 // ProfileSyncService.
330 void OnHistoryRecordingStateChanged();
332 // Returns true if the syncer::SESSIONS type should be included in Sync.
333 bool IncludesSyncSessionsType() const;
335 // The option a custodian sets to either record or prevent recording the
336 // supervised user's history. Set by |FetchNewSessionSyncState()| and
337 // defaults to true.
338 bool includes_sync_sessions_type_;
340 // Owns us via the KeyedService mechanism.
341 Profile* profile_;
343 bool active_;
345 Delegate* delegate_;
347 #if defined(ENABLE_EXTENSIONS)
348 ScopedObserver<extensions::ExtensionRegistry,
349 extensions::ExtensionRegistryObserver>
350 extension_registry_observer_;
351 #endif
353 PrefChangeRegistrar pref_change_registrar_;
355 // True iff we're waiting for the Sync service to be initialized.
356 bool waiting_for_sync_initialization_;
357 bool is_profile_active_;
359 std::vector<NavigationBlockedCallback> navigation_blocked_callbacks_;
361 // Sets a profile in elevated state for testing if set to true.
362 bool elevated_for_testing_;
364 // True only when |Init()| method has been called.
365 bool did_init_;
367 // True only when |Shutdown()| method has been called.
368 bool did_shutdown_;
370 URLFilterContext url_filter_context_;
371 scoped_ptr<SupervisedUserBlacklistDownloader> blacklist_downloader_;
373 // Used to create permission requests.
374 ScopedVector<PermissionRequestCreator> permissions_creators_;
376 ObserverList<SupervisedUserServiceObserver> observer_list_;
378 base::WeakPtrFactory<SupervisedUserService> weak_ptr_factory_;
381 #endif // CHROME_BROWSER_SUPERVISED_USER_SUPERVISED_USER_SERVICE_H_