Home | History | Annotate | Download | only in managed_mode
      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 #ifndef CHROME_BROWSER_MANAGED_MODE_MANAGED_USER_SERVICE_H_
      6 #define CHROME_BROWSER_MANAGED_MODE_MANAGED_USER_SERVICE_H_
      7 
      8 #include <set>
      9 #include <vector>
     10 
     11 #include "base/callback.h"
     12 #include "base/memory/scoped_ptr.h"
     13 #include "base/prefs/pref_change_registrar.h"
     14 #include "base/strings/string16.h"
     15 #include "chrome/browser/extensions/management_policy.h"
     16 #include "chrome/browser/managed_mode/managed_mode_url_filter.h"
     17 #include "chrome/browser/managed_mode/managed_users.h"
     18 #include "chrome/browser/profiles/profile_manager.h"
     19 #include "chrome/browser/sync/profile_sync_service_observer.h"
     20 #include "components/browser_context_keyed_service/browser_context_keyed_service.h"
     21 #include "content/public/browser/notification_observer.h"
     22 #include "content/public/browser/notification_registrar.h"
     23 #include "content/public/browser/web_contents.h"
     24 
     25 class Browser;
     26 class GoogleServiceAuthError;
     27 class ManagedModeURLFilter;
     28 class ManagedModeSiteList;
     29 class ManagedUserRegistrationUtility;
     30 class Profile;
     31 
     32 namespace policy {
     33 class ManagedModePolicyProvider;
     34 }
     35 
     36 namespace user_prefs {
     37 class PrefRegistrySyncable;
     38 }
     39 
     40 // This class handles all the information related to a given managed profile
     41 // (e.g. the installed content packs, the default URL filtering behavior, or
     42 // manual whitelist/blacklist overrides).
     43 class ManagedUserService : public BrowserContextKeyedService,
     44                            public extensions::ManagementPolicy::Provider,
     45                            public ProfileSyncServiceObserver,
     46                            public content::NotificationObserver,
     47                            public chrome::BrowserListObserver {
     48  public:
     49   typedef std::vector<string16> CategoryList;
     50   typedef base::Callback<void(content::WebContents*)> NavigationBlockedCallback;
     51 
     52   enum ManualBehavior {
     53     MANUAL_NONE = 0,
     54     MANUAL_ALLOW,
     55     MANUAL_BLOCK
     56   };
     57 
     58   virtual ~ManagedUserService();
     59 
     60   // ProfileKeyedService override:
     61   virtual void Shutdown() OVERRIDE;
     62 
     63   static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry);
     64 
     65   // Returns true if managed users are enabled by either Finch or the command
     66   // line flag.
     67   // TODO(pamg, sergiu): Remove this once the feature is fully launched.
     68   static bool AreManagedUsersEnabled();
     69 
     70   // Returns the URL filter for the IO thread, for filtering network requests
     71   // (in ManagedModeResourceThrottle).
     72   scoped_refptr<const ManagedModeURLFilter> GetURLFilterForIOThread();
     73 
     74   // Returns the URL filter for the UI thread, for filtering navigations and
     75   // classifying sites in the history view.
     76   ManagedModeURLFilter* GetURLFilterForUIThread();
     77 
     78   // Returns the URL's category, obtained from the installed content packs.
     79   int GetCategory(const GURL& url);
     80 
     81   // Returns the list of all known human-readable category names, sorted by ID
     82   // number. Called in the critical path of drawing the history UI, so needs to
     83   // be fast.
     84   void GetCategoryNames(CategoryList* list);
     85 
     86   // Whether the user can request access to blocked URLs.
     87   bool AccessRequestsEnabled();
     88 
     89   // Adds an access request for the given URL. The requests are stored using
     90   // a prefix followed by a URIEncoded version of the URL. Each entry contains
     91   // a dictionary which currently has the timestamp of the request in it.
     92   void AddAccessRequest(const GURL& url);
     93 
     94   // Returns the email address of the custodian.
     95   std::string GetCustodianEmailAddress() const;
     96 
     97   // Returns the name of the custodian, or the email address if the name is
     98   // empty.
     99   std::string GetCustodianName() const;
    100 
    101   // These methods allow querying and modifying the manual filtering behavior.
    102   // The manual behavior is set by the user and overrides all other settings
    103   // (whitelists or the default behavior).
    104 
    105   // Returns the manual behavior for the given host.
    106   ManualBehavior GetManualBehaviorForHost(const std::string& hostname);
    107 
    108   // Returns the manual behavior for the given URL.
    109   ManualBehavior GetManualBehaviorForURL(const GURL& url);
    110 
    111   // Returns all URLS on the given host that have exceptions.
    112   void GetManualExceptionsForHost(const std::string& host,
    113                                   std::vector<GURL>* urls);
    114 
    115   // Initializes this object. This method does nothing if the profile is not
    116   // managed.
    117   void Init();
    118 
    119   // Marks the profile as managed and initializes it.
    120   void InitForTesting();
    121 
    122   // Initializes this profile for syncing, using the provided |refresh_token| to
    123   // mint access tokens for Sync.
    124   void InitSync(const std::string& refresh_token);
    125 
    126   // Convenience method that registers this managed user using
    127   // |registration_utility| and initializes sync with the returned token.
    128   // The |callback| will be called when registration is complete,
    129   // whether it suceeded or not -- unless registration was cancelled manually,
    130   // in which case the callback will be ignored.
    131   void RegisterAndInitSync(ManagedUserRegistrationUtility* registration_utility,
    132                            Profile* custodian_profile,
    133                            const std::string& managed_user_id,
    134                            const ProfileManager::CreateCallback& callback);
    135 
    136   // Returns a pseudo-email address for systems that expect well-formed email
    137   // addresses (like Sync), even though we're not signed in.
    138   static const char* GetManagedUserPseudoEmail();
    139 
    140   void set_elevated_for_testing(bool skip) {
    141     elevated_for_testing_ = skip;
    142   }
    143 
    144   void AddNavigationBlockedCallback(const NavigationBlockedCallback& callback);
    145   void DidBlockNavigation(content::WebContents* web_contents);
    146 
    147   void AddInitCallback(const base::Closure& callback);
    148 
    149   // extensions::ManagementPolicy::Provider implementation:
    150   virtual std::string GetDebugPolicyProviderName() const OVERRIDE;
    151   virtual bool UserMayLoad(const extensions::Extension* extension,
    152                            string16* error) const OVERRIDE;
    153   virtual bool UserMayModifySettings(const extensions::Extension* extension,
    154                                      string16* error) const OVERRIDE;
    155 
    156   // ProfileSyncServiceObserver implementation:
    157   virtual void OnStateChanged() OVERRIDE;
    158 
    159   // content::NotificationObserver implementation:
    160   virtual void Observe(int type,
    161                        const content::NotificationSource& source,
    162                        const content::NotificationDetails& details) OVERRIDE;
    163 
    164   // chrome::BrowserListObserver implementation:
    165   virtual void OnBrowserSetLastActive(Browser* browser) OVERRIDE;
    166 
    167  private:
    168   friend class ManagedUserServiceExtensionTest;
    169   friend class ManagedUserServiceFactory;
    170   FRIEND_TEST_ALL_PREFIXES(ManagedUserServiceTest,
    171                            ExtensionManagementPolicyProviderUnmanaged);
    172   FRIEND_TEST_ALL_PREFIXES(ManagedUserServiceTest,
    173                            ExtensionManagementPolicyProviderManaged);
    174 
    175   // A bridge from ManagedMode (which lives on the UI thread) to the
    176   // ManagedModeURLFilters, one of which lives on the IO thread. This class
    177   // mediates access to them and makes sure they are kept in sync.
    178   class URLFilterContext {
    179    public:
    180     URLFilterContext();
    181     ~URLFilterContext();
    182 
    183     ManagedModeURLFilter* ui_url_filter() const;
    184     ManagedModeURLFilter* io_url_filter() const;
    185 
    186     void SetDefaultFilteringBehavior(
    187         ManagedModeURLFilter::FilteringBehavior behavior);
    188     void LoadWhitelists(ScopedVector<ManagedModeSiteList> site_lists);
    189     void SetManualHosts(scoped_ptr<std::map<std::string, bool> > host_map);
    190     void SetManualURLs(scoped_ptr<std::map<GURL, bool> > url_map);
    191 
    192    private:
    193     // ManagedModeURLFilter is refcounted because the IO thread filter is used
    194     // both by ProfileImplIOData and OffTheRecordProfileIOData (to filter
    195     // network requests), so they both keep a reference to it.
    196     // Clients should not keep references to the UI thread filter, however
    197     // (the filter will live as long as the profile lives, and afterwards it
    198     // should not be used anymore either).
    199     scoped_refptr<ManagedModeURLFilter> ui_url_filter_;
    200     scoped_refptr<ManagedModeURLFilter> io_url_filter_;
    201 
    202     DISALLOW_COPY_AND_ASSIGN(URLFilterContext);
    203   };
    204 
    205   // Use |ManagedUserServiceFactory::GetForProfile(..)| to get
    206   // an instance of this service.
    207   explicit ManagedUserService(Profile* profile);
    208 
    209   void OnCustodianProfileDownloaded(const string16& full_name);
    210 
    211   void OnManagedUserRegistered(const ProfileManager::CreateCallback& callback,
    212                                Profile* custodian_profile,
    213                                const GoogleServiceAuthError& auth_error,
    214                                const std::string& token);
    215 
    216   void SetupSync();
    217 
    218   bool ProfileIsManaged() const;
    219 
    220   // Internal implementation for ExtensionManagementPolicy::Delegate methods.
    221   // If |error| is not NULL, it will be filled with an error message if the
    222   // requested extension action (install, modify status, etc.) is not permitted.
    223   bool ExtensionManagementPolicyImpl(const extensions::Extension* extension,
    224                                      string16* error) const;
    225 
    226   // Returns a list of all installed and enabled site lists in the current
    227   // managed profile.
    228   ScopedVector<ManagedModeSiteList> GetActiveSiteLists();
    229 
    230   policy::ManagedModePolicyProvider* GetPolicyProvider();
    231 
    232   void OnDefaultFilteringBehaviorChanged();
    233 
    234   void UpdateSiteLists();
    235 
    236   // Updates the manual overrides for hosts in the URL filters when the
    237   // corresponding preference is changed.
    238   void UpdateManualHosts();
    239 
    240   // Updates the manual overrides for URLs in the URL filters when the
    241   // corresponding preference is changed.
    242   void UpdateManualURLs();
    243 
    244   // Records some events (opening the managed user profile, switching from the
    245   // managed user profile, and quitting the browser); each is stored
    246   // using a key with a prefix (|key_prefix|) indicating the type of the event.
    247   // Each entry is a dictionary which has the timestamp of the event.
    248   void RecordProfileAndBrowserEventsHelper(const char* key_prefix);
    249 
    250   base::WeakPtrFactory<ManagedUserService> weak_ptr_factory_;
    251 
    252   // Owns us via the BrowserContextKeyedService mechanism.
    253   Profile* profile_;
    254 
    255   content::NotificationRegistrar registrar_;
    256   PrefChangeRegistrar pref_change_registrar_;
    257 
    258   // True iff we're waiting for the Sync service to be initialized.
    259   bool waiting_for_sync_initialization_;
    260   bool is_profile_active_;
    261 
    262   std::vector<base::Closure> init_callbacks_;
    263 
    264   std::vector<NavigationBlockedCallback> navigation_blocked_callbacks_;
    265 
    266   // Sets a profile in elevated state for testing if set to true.
    267   bool elevated_for_testing_;
    268 
    269   // True only when |Shutdown()| method has been called.
    270   bool did_shutdown_;
    271 
    272   URLFilterContext url_filter_context_;
    273 };
    274 
    275 #endif  // CHROME_BROWSER_MANAGED_MODE_MANAGED_USER_SERVICE_H_
    276