Add more checks to investigate SupervisedUserPrefStore crash at startup.
[chromium-blink-merge.git] / chrome / browser / supervised_user / supervised_user_service.h
blob8b16b444a0875752654da385048645ae6778b8d7
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 <string>
10 #include <vector>
12 #include "base/callback.h"
13 #include "base/gtest_prod_util.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/observer_list.h"
16 #include "base/prefs/pref_change_registrar.h"
17 #include "base/scoped_observer.h"
18 #include "base/strings/string16.h"
19 #include "chrome/browser/supervised_user/experimental/supervised_user_blacklist.h"
20 #include "chrome/browser/supervised_user/supervised_user_url_filter.h"
21 #include "chrome/browser/supervised_user/supervised_users.h"
22 #include "chrome/browser/sync/profile_sync_service_observer.h"
23 #include "chrome/browser/sync/sync_type_preference_provider.h"
24 #include "chrome/browser/ui/browser_list_observer.h"
25 #include "components/keyed_service/core/keyed_service.h"
26 #include "net/url_request/url_request_context_getter.h"
28 #if defined(ENABLE_EXTENSIONS)
29 #include "extensions/browser/management_policy.h"
30 #endif
32 class Browser;
33 class GoogleServiceAuthError;
34 class PermissionRequestCreator;
35 class Profile;
36 class SupervisedUserBlacklistDownloader;
37 class SupervisedUserRegistrationUtility;
38 class SupervisedUserServiceObserver;
39 class SupervisedUserSettingsService;
40 class SupervisedUserSiteList;
41 class SupervisedUserURLFilter;
42 class SupervisedUserWhitelistService;
44 namespace base {
45 class FilePath;
48 namespace content {
49 class WebContents;
52 namespace extensions {
53 class ExtensionRegistry;
56 namespace user_prefs {
57 class PrefRegistrySyncable;
60 // This class handles all the information related to a given supervised profile
61 // (e.g. the installed content packs, the default URL filtering behavior, or
62 // manual whitelist/blacklist overrides).
63 class SupervisedUserService : public KeyedService,
64 #if defined(ENABLE_EXTENSIONS)
65 public extensions::ManagementPolicy::Provider,
66 #endif
67 public SyncTypePreferenceProvider,
68 public ProfileSyncServiceObserver,
69 public chrome::BrowserListObserver,
70 public SupervisedUserURLFilter::Observer {
71 public:
72 typedef base::Callback<void(content::WebContents*)> NavigationBlockedCallback;
73 typedef base::Callback<void(const GoogleServiceAuthError&)> AuthErrorCallback;
74 typedef base::Callback<void(bool)> SuccessCallback;
76 class Delegate {
77 public:
78 virtual ~Delegate() {}
79 // Returns true to indicate that the delegate handled the (de)activation, or
80 // false to indicate that the SupervisedUserService itself should handle it.
81 virtual bool SetActive(bool active) = 0;
82 // Returns the path to a blacklist file to load, or an empty path to
83 // indicate "none".
84 virtual base::FilePath GetBlacklistPath() const;
85 // Returns the URL from which to download a blacklist if no local one exists
86 // yet. The blacklist file will be stored at |GetBlacklistPath()|.
87 virtual GURL GetBlacklistURL() const;
88 // Returns the identifier ("cx") of the Custom Search Engine to use for the
89 // experimental "SafeSites" feature, or the empty string to disable the
90 // feature.
91 virtual std::string GetSafeSitesCx() const;
94 ~SupervisedUserService() override;
96 // ProfileKeyedService override:
97 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 whitelist service.
112 SupervisedUserWhitelistService* GetWhitelistService();
114 // Whether the user can request access to blocked URLs.
115 bool AccessRequestsEnabled();
117 // Adds an access request for the given URL. The requests are stored using
118 // a prefix followed by a URIEncoded version of the URL. Each entry contains
119 // a dictionary which currently has the timestamp of the request in it.
120 void AddAccessRequest(const GURL& url, const SuccessCallback& callback);
122 // Returns the email address of the custodian.
123 std::string GetCustodianEmailAddress() const;
125 // Returns the name of the custodian, or the email address if the name is
126 // empty.
127 std::string GetCustodianName() const;
129 // Returns the email address of the second custodian, or the empty string
130 // if there is no second custodian.
131 std::string GetSecondCustodianEmailAddress() const;
133 // Returns the name of the second custodian, or the email address if the name
134 // is empty, or the empty string is there is no second custodian.
135 std::string GetSecondCustodianName() const;
137 // Initializes this object. This method does nothing if the profile is not
138 // supervised.
139 void Init();
141 // Initializes this profile for syncing, using the provided |refresh_token| to
142 // mint access tokens for Sync.
143 void InitSync(const std::string& refresh_token);
145 // Convenience method that registers this supervised user using
146 // |registration_utility| and initializes sync with the returned token.
147 // The |callback| will be called when registration is complete,
148 // whether it succeeded or not -- unless registration was cancelled manually,
149 // in which case the callback will be ignored.
150 void RegisterAndInitSync(
151 SupervisedUserRegistrationUtility* registration_utility,
152 Profile* custodian_profile,
153 const std::string& supervised_user_id,
154 const AuthErrorCallback& callback);
156 void AddNavigationBlockedCallback(const NavigationBlockedCallback& callback);
157 void DidBlockNavigation(content::WebContents* web_contents);
159 void AddObserver(SupervisedUserServiceObserver* observer);
160 void RemoveObserver(SupervisedUserServiceObserver* observer);
162 void AddPermissionRequestCreator(
163 scoped_ptr<PermissionRequestCreator> creator);
165 #if defined(ENABLE_EXTENSIONS)
166 // extensions::ManagementPolicy::Provider implementation:
167 std::string GetDebugPolicyProviderName() const override;
168 bool UserMayLoad(const extensions::Extension* extension,
169 base::string16* error) const override;
170 bool UserMayModifySettings(const extensions::Extension* extension,
171 base::string16* error) const override;
172 #endif
174 // SyncTypePreferenceProvider implementation:
175 syncer::ModelTypeSet GetPreferredDataTypes() const override;
177 // ProfileSyncServiceObserver implementation:
178 void OnStateChanged() override;
180 // chrome::BrowserListObserver implementation:
181 void OnBrowserSetLastActive(Browser* browser) override;
183 // SupervisedUserURLFilter::Observer implementation:
184 void OnSiteListUpdated() override;
186 private:
187 friend class SupervisedUserServiceExtensionTestBase;
188 friend class SupervisedUserServiceFactory;
189 FRIEND_TEST_ALL_PREFIXES(SingleClientSupervisedUserSettingsSyncTest, Sanity);
190 FRIEND_TEST_ALL_PREFIXES(SupervisedUserServiceTest, ClearOmitOnRegistration);
191 FRIEND_TEST_ALL_PREFIXES(SupervisedUserServiceTest,
192 ChangesIncludedSessionOnChangedSettings);
193 FRIEND_TEST_ALL_PREFIXES(SupervisedUserServiceTest,
194 ChangesSyncSessionStateOnChangedSettings);
196 // A bridge from the UI thread to the SupervisedUserURLFilters, one of which
197 // lives on the IO thread. This class mediates access to them and makes sure
198 // they are kept in sync.
199 class URLFilterContext {
200 public:
201 URLFilterContext();
202 ~URLFilterContext();
204 SupervisedUserURLFilter* ui_url_filter() const;
205 SupervisedUserURLFilter* io_url_filter() const;
207 void SetDefaultFilteringBehavior(
208 SupervisedUserURLFilter::FilteringBehavior behavior);
209 void LoadWhitelists(
210 const std::vector<scoped_refptr<SupervisedUserSiteList>>& site_lists);
211 void LoadBlacklist(const base::FilePath& path,
212 const base::Closure& callback);
213 void SetManualHosts(scoped_ptr<std::map<std::string, bool>> host_map);
214 void SetManualURLs(scoped_ptr<std::map<GURL, bool>> url_map);
216 void InitAsyncURLChecker(
217 const scoped_refptr<net::URLRequestContextGetter>& context,
218 const std::string& cx);
220 void Clear();
222 private:
223 void OnBlacklistLoaded(const base::Closure& callback);
225 // SupervisedUserURLFilter is refcounted because the IO thread filter is
226 // used both by ProfileImplIOData and OffTheRecordProfileIOData (to filter
227 // network requests), so they both keep a reference to it.
228 // Clients should not keep references to the UI thread filter, however
229 // (the filter will live as long as the profile lives, and afterwards it
230 // should not be used anymore either).
231 scoped_refptr<SupervisedUserURLFilter> ui_url_filter_;
232 scoped_refptr<SupervisedUserURLFilter> io_url_filter_;
234 SupervisedUserBlacklist blacklist_;
236 DISALLOW_COPY_AND_ASSIGN(URLFilterContext);
239 // Use |SupervisedUserServiceFactory::GetForProfile(..)| to get
240 // an instance of this service.
241 explicit SupervisedUserService(Profile* profile);
243 void SetActive(bool active);
245 void OnCustodianProfileDownloaded(const base::string16& full_name);
247 void OnSupervisedUserRegistered(const AuthErrorCallback& callback,
248 Profile* custodian_profile,
249 const GoogleServiceAuthError& auth_error,
250 const std::string& token);
252 void SetupSync();
253 void StartSetupSync();
254 void FinishSetupSyncWhenReady();
255 void FinishSetupSync();
257 bool ProfileIsSupervised() const;
259 void OnCustodianInfoChanged();
261 #if defined(ENABLE_EXTENSIONS)
262 // Internal implementation for ExtensionManagementPolicy::Delegate methods.
263 // If |error| is not NULL, it will be filled with an error message if the
264 // requested extension action (install, modify status, etc.) is not permitted.
265 bool ExtensionManagementPolicyImpl(const extensions::Extension* extension,
266 base::string16* error) const;
268 // Extensions helper to SetActive().
269 void SetExtensionsActive();
270 #endif
272 SupervisedUserSettingsService* GetSettingsService();
274 size_t FindEnabledPermissionRequestCreator(size_t start);
275 void AddAccessRequestInternal(const GURL& url,
276 const SuccessCallback& callback,
277 size_t index);
278 void OnPermissionRequestIssued(const GURL& url,
279 const SuccessCallback& callback,
280 size_t index,
281 bool success);
283 void OnSupervisedUserIdChanged();
285 void OnDefaultFilteringBehaviorChanged();
287 void OnSiteListsChanged(
288 const std::vector<scoped_refptr<SupervisedUserSiteList>>& site_lists);
290 // Asynchronously downloads a static blacklist file from |url|, stores it at
291 // |path|, loads it, and applies it to the URL filters. If |url| is not valid
292 // (e.g. empty), directly tries to load from |path|.
293 void LoadBlacklist(const base::FilePath& path, const GURL& url);
295 // Asynchronously loads a static blacklist from a binary file at |path| and
296 // applies it to the URL filters.
297 void LoadBlacklistFromFile(const base::FilePath& path);
299 void OnBlacklistDownloadDone(const base::FilePath& path, bool success);
301 void OnBlacklistLoaded();
303 // Updates the manual overrides for hosts in the URL filters when the
304 // corresponding preference is changed.
305 void UpdateManualHosts();
307 // Updates the manual overrides for URLs in the URL filters when the
308 // corresponding preference is changed.
309 void UpdateManualURLs();
311 // Returns the human readable name of the supervised user.
312 std::string GetSupervisedUserName() const;
314 // Subscribes to the SupervisedUserPrefStore, refreshes
315 // |includes_sync_sessions_type_| and triggers reconfiguring the
316 // ProfileSyncService.
317 void OnHistoryRecordingStateChanged();
319 // Returns true if the syncer::SESSIONS type should be included in Sync.
320 bool IncludesSyncSessionsType() const;
322 // The option a custodian sets to either record or prevent recording the
323 // supervised user's history. Set by |FetchNewSessionSyncState()| and
324 // defaults to true.
325 bool includes_sync_sessions_type_;
327 // Owns us via the KeyedService mechanism.
328 Profile* profile_;
330 bool active_;
332 Delegate* delegate_;
334 PrefChangeRegistrar pref_change_registrar_;
336 // True iff we're waiting for the Sync service to be initialized.
337 bool waiting_for_sync_initialization_;
338 bool is_profile_active_;
340 std::vector<NavigationBlockedCallback> navigation_blocked_callbacks_;
342 // True only when |Init()| method has been called.
343 bool did_init_;
345 // True only when |Shutdown()| method has been called.
346 bool did_shutdown_;
348 URLFilterContext url_filter_context_;
349 scoped_ptr<SupervisedUserBlacklistDownloader> blacklist_downloader_;
351 scoped_ptr<SupervisedUserWhitelistService> whitelist_service_;
353 // Used to create permission requests.
354 ScopedVector<PermissionRequestCreator> permissions_creators_;
356 ObserverList<SupervisedUserServiceObserver> observer_list_;
358 base::WeakPtrFactory<SupervisedUserService> weak_ptr_factory_;
361 #endif // CHROME_BROWSER_SUPERVISED_USER_SUPERVISED_USER_SERVICE_H_