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_
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"
35 class GoogleServiceAuthError;
36 class PermissionRequestCreator;
38 class SupervisedUserBlacklistDownloader;
39 class SupervisedUserRegistrationUtility;
40 class SupervisedUserServiceObserver;
41 class SupervisedUserSettingsService;
42 class SupervisedUserSiteList;
43 class SupervisedUserURLFilter;
49 namespace extensions {
50 class ExtensionRegistry;
54 class URLRequestContextGetter;
57 namespace user_prefs {
58 class PrefRegistrySyncable;
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,
69 public SyncTypePreferenceProvider,
70 public ProfileSyncServiceObserver,
71 public chrome::BrowserListObserver {
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;
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
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
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;
99 ~SupervisedUserService() override;
101 // ProfileKeyedService override:
102 void Shutdown() override;
104 static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry);
106 void SetDelegate(Delegate* delegate);
108 // Returns the URL filter for the IO thread, for filtering network requests
109 // (in SupervisedUserResourceThrottle).
110 scoped_refptr<const SupervisedUserURLFilter> GetURLFilterForIOThread();
112 // Returns the URL filter for the UI thread, for filtering navigations and
113 // classifying sites in the history view.
114 SupervisedUserURLFilter* GetURLFilterForUIThread();
116 // Returns the URL's category, obtained from the installed content packs.
117 int GetCategory(const GURL& url);
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
122 void GetCategoryNames(CategoryList* list);
124 // Whether the user can request access to blocked URLs.
125 bool AccessRequestsEnabled();
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);
132 // Returns the email address of the custodian.
133 std::string GetCustodianEmailAddress() const;
135 // Returns the name of the custodian, or the email address if the name is
137 std::string GetCustodianName() const;
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;
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;
147 // Initializes this object. This method does nothing if the profile is not
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);
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);
166 void set_elevated_for_testing(bool skip) {
167 elevated_for_testing_ = skip;
170 void AddNavigationBlockedCallback(const NavigationBlockedCallback& callback);
171 void DidBlockNavigation(content::WebContents* web_contents);
173 void AddObserver(SupervisedUserServiceObserver* observer);
174 void RemoveObserver(SupervisedUserServiceObserver* observer);
176 // Will take ownership of |creator|.
177 void AddPermissionRequestCreatorForTesting(PermissionRequestCreator* creator);
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;
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;
196 // SyncTypePreferenceProvider implementation:
197 syncer::ModelTypeSet GetPreferredDataTypes() const override;
199 // ProfileSyncServiceObserver implementation:
200 void OnStateChanged() override;
202 // chrome::BrowserListObserver implementation:
203 void OnBrowserSetLastActive(Browser* browser) override;
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 {
222 SupervisedUserURLFilter* ui_url_filter() const;
223 SupervisedUserURLFilter* io_url_filter() const;
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);
232 void InitAsyncURLChecker(net::URLRequestContextGetter* context,
233 const std::string& cx,
234 const std::string& api_key);
237 void OnBlacklistLoaded();
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_;
248 SupervisedUserBlacklist blacklist_;
250 DISALLOW_COPY_AND_ASSIGN(URLFilterContext);
253 // Use |SupervisedUserServiceFactory::GetForProfile(..)| to get
254 // an instance of this service.
255 explicit SupervisedUserService(Profile* profile);
257 void SetActive(bool active);
259 void OnCustodianProfileDownloaded(const base::string16& full_name);
261 void OnSupervisedUserRegistered(const AuthErrorCallback& callback,
262 Profile* custodian_profile,
263 const GoogleServiceAuthError& auth_error,
264 const std::string& token);
267 void StartSetupSync();
268 void FinishSetupSyncWhenReady();
269 void FinishSetupSync();
271 bool ProfileIsSupervised() const;
273 void OnCustodianInfoChanged();
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;
282 // Returns a list of all installed and enabled site lists in the current
283 // supervised profile.
284 ScopedVector<SupervisedUserSiteList> GetActiveSiteLists();
286 // Extensions helper to SetActive().
287 void SetExtensionsActive();
290 SupervisedUserSettingsService* GetSettingsService();
292 size_t FindEnabledPermissionRequestCreator(size_t start);
293 void AddAccessRequestInternal(const GURL& url,
294 const SuccessCallback& callback,
296 void OnPermissionRequestIssued(const GURL& url,
297 const SuccessCallback& callback,
301 void OnSupervisedUserIdChanged();
303 void OnDefaultFilteringBehaviorChanged();
305 void UpdateSiteLists();
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);
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);
316 void OnBlacklistDownloadDone(const base::FilePath& path, bool success);
318 // Updates the manual overrides for hosts in the URL filters when the
319 // corresponding preference is changed.
320 void UpdateManualHosts();
322 // Updates the manual overrides for URLs in the URL filters when the
323 // corresponding preference is changed.
324 void UpdateManualURLs();
326 // Returns the human readable name of the supervised user.
327 std::string GetSupervisedUserName() const;
329 // Subscribes to the SupervisedUserPrefStore, refreshes
330 // |includes_sync_sessions_type_| and triggers reconfiguring the
331 // ProfileSyncService.
332 void OnHistoryRecordingStateChanged();
334 // Returns true if the syncer::SESSIONS type should be included in Sync.
335 bool IncludesSyncSessionsType() const;
337 // The option a custodian sets to either record or prevent recording the
338 // supervised user's history. Set by |FetchNewSessionSyncState()| and
340 bool includes_sync_sessions_type_;
342 // Owns us via the KeyedService mechanism.
349 #if defined(ENABLE_EXTENSIONS)
350 ScopedObserver<extensions::ExtensionRegistry,
351 extensions::ExtensionRegistryObserver>
352 extension_registry_observer_;
355 PrefChangeRegistrar pref_change_registrar_;
357 // True iff we're waiting for the Sync service to be initialized.
358 bool waiting_for_sync_initialization_;
359 bool is_profile_active_;
361 std::vector<NavigationBlockedCallback> navigation_blocked_callbacks_;
363 // Sets a profile in elevated state for testing if set to true.
364 bool elevated_for_testing_;
366 // True only when |Init()| method has been called.
369 // True only when |Shutdown()| method has been called.
372 URLFilterContext url_filter_context_;
373 scoped_ptr<SupervisedUserBlacklistDownloader> blacklist_downloader_;
375 // Used to create permission requests.
376 ScopedVector<PermissionRequestCreator> permissions_creators_;
378 ObserverList<SupervisedUserServiceObserver> observer_list_;
380 base::WeakPtrFactory<SupervisedUserService> weak_ptr_factory_;
383 #endif // CHROME_BROWSER_SUPERVISED_USER_SUPERVISED_USER_SERVICE_H_