1 // Copyright (c) 2012 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 // Maps hostnames to custom content settings.  Written on the UI thread and read
6 // on any thread.  One instance per profile.
7 
8 #ifndef COMPONENTS_CONTENT_SETTINGS_CORE_BROWSER_HOST_CONTENT_SETTINGS_MAP_H_
9 #define COMPONENTS_CONTENT_SETTINGS_CORE_BROWSER_HOST_CONTENT_SETTINGS_MAP_H_
10 
11 #include <map>
12 #include <memory>
13 #include <string>
14 #include <vector>
15 
16 #include "base/macros.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/observer_list.h"
19 #include "base/threading/platform_thread.h"
20 #include "base/threading/thread_checker.h"
21 #include "build/build_config.h"
22 #include "components/content_settings/core/browser/content_settings_observer.h"
23 #include "components/content_settings/core/browser/content_settings_utils.h"
24 #include "components/content_settings/core/browser/user_modifiable_provider.h"
25 #include "components/content_settings/core/common/content_settings.h"
26 #include "components/content_settings/core/common/content_settings_pattern.h"
27 #include "components/content_settings/core/common/content_settings_types.h"
28 #include "components/keyed_service/core/refcounted_keyed_service.h"
29 #include "components/prefs/pref_change_registrar.h"
30 
31 class GURL;
32 class PrefService;
33 
34 namespace base {
35 class Value;
36 class Clock;
37 }
38 
39 namespace content_settings {
40 class ObservableProvider;
41 class ProviderInterface;
42 class PrefProvider;
43 class RuleIterator;
44 class TestUtils;
45 }
46 
47 namespace user_prefs {
48 class PrefRegistrySyncable;
49 }
50 
51 class HostContentSettingsMap : public content_settings::Observer,
52                                public RefcountedKeyedService {
53  public:
54   enum ProviderType {
55     // EXTENSION names is a layering violation when this class will move to
56     // components.
57     // TODO(mukai): find the solution.
58     POLICY_PROVIDER = 0,
59     SUPERVISED_PROVIDER,
60     CUSTOM_EXTENSION_PROVIDER,
61     INSTALLED_WEBAPP_PROVIDER,
62     NOTIFICATION_ANDROID_PROVIDER,
63     EPHEMERAL_PROVIDER,
64     PREF_PROVIDER,
65     DEFAULT_PROVIDER,
66 
67     // The following providers are for tests only.
68     PROVIDER_FOR_TESTS,
69     OTHER_PROVIDER_FOR_TESTS,
70 
71     NUM_PROVIDER_TYPES
72   };
73 
74   // This should be called on the UI thread, otherwise |thread_checker_| handles
75   // CalledOnValidThread() wrongly. |is_off_the_record| indicates incognito
76   // profile or a guest session.
77   HostContentSettingsMap(PrefService* prefs,
78                          bool is_off_the_record,
79                          bool store_last_modified,
80                          bool migrate_requesting_and_top_level_origin_settings);
81 
82   static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry);
83 
84   // Adds a new provider for |type|. This should be used instead of
85   // |RegisterProvider|, not in addition.
86   //
87   // Providers added via this method will be queried when
88   // |GetSettingLastModifiedDate| is called and their settings may be cleared by
89   // |ClearSettingsForOneTypeWithPredicate| if they were recently modified.
90   void RegisterUserModifiableProvider(
91       ProviderType type,
92       std::unique_ptr<content_settings::UserModifiableProvider> provider);
93 
94   // Adds a new provider for |type|.
95   void RegisterProvider(
96       ProviderType type,
97       std::unique_ptr<content_settings::ObservableProvider> provider);
98 
99   // Returns the default setting for a particular content type. If |provider_id|
100   // is not NULL, the id of the provider which provided the default setting is
101   // assigned to it.
102   //
103   // This may be called on any thread.
104   ContentSetting GetDefaultContentSetting(ContentSettingsType content_type,
105                                           std::string* provider_id) const;
106 
107   // Returns a single |ContentSetting| which applies to the given URLs.  Note
108   // that certain internal schemes are whitelisted. For |CONTENT_TYPE_COOKIES|,
109   // |CookieSettings| should be used instead. For content types that can't be
110   // converted to a |ContentSetting|, |GetContentSettingValue| should be called.
111   // If there is no content setting, returns CONTENT_SETTING_DEFAULT.
112   //
113   // May be called on any thread.
114   ContentSetting GetContentSetting(
115       const GURL& primary_url,
116       const GURL& secondary_url,
117       ContentSettingsType content_type,
118       const std::string& resource_identifier) const;
119 
120   // This is the same as GetContentSetting() but ignores providers which are not
121   // user-controllable (e.g. policy and extensions).
122   ContentSetting GetUserModifiableContentSetting(
123       const GURL& primary_url,
124       const GURL& secondary_url,
125       ContentSettingsType content_type,
126       const std::string& resource_identifier) const;
127 
128   // Returns a single content setting |Value| which applies to the given URLs.
129   // If |info| is not NULL, then the |source| field of |info| is set to the
130   // source of the returned |Value| (POLICY, EXTENSION, USER, ...) and the
131   // |primary_pattern| and the |secondary_pattern| fields of |info| are set to
132   // the patterns of the applying rule.  Note that certain internal schemes are
133   // whitelisted. For whitelisted schemes the |source| field of |info| is set
134   // the |SETTING_SOURCE_WHITELIST| and the |primary_pattern| and
135   // |secondary_pattern| are set to a wildcard pattern.  If there is no content
136   // setting, NULL is returned and the |source| field of |info| is set to
137   // |SETTING_SOURCE_NONE|. The pattern fields of |info| are set to empty
138   // patterns.
139   // May be called on any thread.
140   std::unique_ptr<base::Value> GetWebsiteSetting(
141       const GURL& primary_url,
142       const GURL& secondary_url,
143       ContentSettingsType content_type,
144       const std::string& resource_identifier,
145       content_settings::SettingInfo* info) const;
146 
147   // For a given content type, returns all patterns with a non-default setting,
148   // mapped to their actual settings, in the precedence order of the rules.
149   // |settings| must be a non-NULL outparam.
150   //
151   // This may be called on any thread.
152   void GetSettingsForOneType(ContentSettingsType content_type,
153                              const std::string& resource_identifier,
154                              ContentSettingsForOneType* settings) const;
155 
156   // Sets the default setting for a particular content type. This method must
157   // not be invoked on an incognito map.
158   //
159   // This should only be called on the UI thread.
160   void SetDefaultContentSetting(ContentSettingsType content_type,
161                                 ContentSetting setting);
162 
163   // Sets the content |setting| for the given patterns, |content_type| and
164   // |resource_identifier|. Setting the value to CONTENT_SETTING_DEFAULT causes
165   // the default setting for that type to be used when loading pages matching
166   // this pattern. Unless adding a custom-scoped setting, most developers will
167   // want to use SetContentSettingDefaultScope() instead.
168   //
169   // NOTICE: This is just a convenience method for content types that use
170   // |CONTENT_SETTING| as their data type. For content types that use other
171   // data types please use the method SetWebsiteSettingDefaultScope().
172   //
173   // This should only be called on the UI thread.
174   void SetContentSettingCustomScope(
175       const ContentSettingsPattern& primary_pattern,
176       const ContentSettingsPattern& secondary_pattern,
177       ContentSettingsType content_type,
178       const std::string& resource_identifier,
179       ContentSetting setting);
180 
181   // Sets the content |setting| for the default scope of the url that is
182   // appropriate for the given |content_type| and |resource_identifier|.
183   // Setting the value to CONTENT_SETTING_DEFAULT causes the default setting
184   // for that type to be used.
185   //
186   // NOTICE: This is just a convenience method for content types that use
187   // |CONTENT_SETTING| as their data type. For content types that use other
188   // data types please use the method SetWebsiteSettingDefaultScope().
189   //
190   // This should only be called on the UI thread.
191   //
192   // Internally this will call SetContentSettingCustomScope() with the default
193   // scope patterns for the given |content_type|. Developers will generally want
194   // to use this function instead of SetContentSettingCustomScope() unless they
195   // need to specify custom scoping.
196   void SetContentSettingDefaultScope(const GURL& primary_url,
197                                      const GURL& secondary_url,
198                                      ContentSettingsType content_type,
199                                      const std::string& resource_identifier,
200                                      ContentSetting setting);
201 
202   // Sets the |value| for the default scope of the url that is appropriate for
203   // the given |content_type| and |resource_identifier|. Setting the value to
204   // null removes the default pattern pair for this content type.
205   //
206   // Internally this will call SetWebsiteSettingCustomScope() with the default
207   // scope patterns for the given |content_type|. Developers will generally want
208   // to use this function instead of SetWebsiteSettingCustomScope() unless they
209   // need to specify custom scoping.
210   void SetWebsiteSettingDefaultScope(const GURL& requesting_url,
211                                      const GURL& top_level_url,
212                                      ContentSettingsType content_type,
213                                      const std::string& resource_identifier,
214                                      std::unique_ptr<base::Value> value);
215 
216   // Sets a rule to apply the |value| for all sites matching |pattern|,
217   // |content_type| and |resource_identifier|. Setting the value to null removes
218   // the given pattern pair. Unless adding a custom-scoped setting, most
219   // developers will want to use SetWebsiteSettingDefaultScope() instead.
220   void SetWebsiteSettingCustomScope(
221       const ContentSettingsPattern& primary_pattern,
222       const ContentSettingsPattern& secondary_pattern,
223       ContentSettingsType content_type,
224       const std::string& resource_identifier,
225       std::unique_ptr<base::Value> value);
226 
227   // Check if a call to SetNarrowestContentSetting would succeed or if it would
228   // fail because of an invalid pattern.
229   bool CanSetNarrowestContentSetting(
230       const GURL& primary_url,
231       const GURL& secondary_url,
232       ContentSettingsType type) const;
233 
234   // Checks whether the specified |type| controls a feature that is restricted
235   // to secure origins.
236   bool IsRestrictedToSecureOrigins(ContentSettingsType type) const;
237 
238   // Sets the most specific rule that currently defines the setting for the
239   // given content type. TODO(raymes): Remove this once all content settings
240   // are scoped to origin scope. There is no scope more narrow than origin
241   // scope, so we can just blindly set the value of the origin scope when that
242   // happens.
243   void SetNarrowestContentSetting(const GURL& primary_url,
244                                   const GURL& secondary_url,
245                                   ContentSettingsType type,
246                                   ContentSetting setting);
247 
248   // Clears all host-specific settings for one content type.
249   //
250   // This should only be called on the UI thread.
251   void ClearSettingsForOneType(ContentSettingsType content_type);
252 
253   // Return the |last_modified| date of a content setting. This will only return
254   // valid values for settings from the PreferenceProvider. Settings from other
255   // providers will return base::Time().
256   //
257   // This may be called on any thread.
258   base::Time GetSettingLastModifiedDate(
259       const ContentSettingsPattern& primary_pattern,
260       const ContentSettingsPattern& secondary_pattern,
261       ContentSettingsType content_type) const;
262 
263   using PatternSourcePredicate = base::RepeatingCallback<bool(
264       const ContentSettingsPattern& primary_pattern,
265       const ContentSettingsPattern& secondary_pattern)>;
266 
267   // If |pattern_predicate| is null, this method is equivalent to the above.
268   // Otherwise, it only deletes exceptions matched by |pattern_predicate| that
269   // were modified at or after |begin_time| and before |end_time|.
270   void ClearSettingsForOneTypeWithPredicate(
271       ContentSettingsType content_type,
272       base::Time begin_time,
273       base::Time end_time,
274       PatternSourcePredicate pattern_predicate);
275 
276   // RefcountedKeyedService implementation.
277   void ShutdownOnUIThread() override;
278 
279   // content_settings::Observer implementation.
280   void OnContentSettingChanged(const ContentSettingsPattern& primary_pattern,
281                                const ContentSettingsPattern& secondary_pattern,
282                                ContentSettingsType content_type,
283                                const std::string& resource_identifier) override;
284 
285   // Returns the ProviderType associated with the given source string.
286   // TODO(estade): I regret adding this. At the moment there are no legitimate
287   // uses. We should stick to ProviderType rather than string so we don't have
288   // to convert backwards.
289   static ProviderType GetProviderTypeFromSource(const std::string& source);
290 
291   // Returns the SettingSource associated with the given |provider_name| string.
292   static content_settings::SettingSource GetSettingSourceFromProviderName(
293       const std::string& provider_name);
294 
295   // Whether this settings map is for an incognito or guest session.
IsOffTheRecord()296   bool IsOffTheRecord() const { return is_off_the_record_; }
297 
298   // Adds/removes an observer for content settings changes.
299   void AddObserver(content_settings::Observer* observer);
300   void RemoveObserver(content_settings::Observer* observer);
301 
302   // Schedules any pending lossy website settings to be written to disk.
303   void FlushLossyWebsiteSettings();
304 
305   base::WeakPtr<HostContentSettingsMap> GetWeakPtr();
306 
307   // Injects a clock into the PrefProvider to allow control over the
308   // |last_modified| timestamp.
309   void SetClockForTesting(base::Clock* clock);
310 
311   // Returns the provider that contains content settings from user preferences.
GetPrefProvider()312   content_settings::PrefProvider* GetPrefProvider() const {
313     return pref_provider_;
314   }
315 
316  private:
317   friend class base::RefCountedThreadSafe<HostContentSettingsMap>;
318   friend class content_settings::TestUtils;
319   FRIEND_TEST_ALL_PREFIXES(HostContentSettingsMapTest,
320                            MigrateRequestingAndTopLevelOriginSettings);
321   FRIEND_TEST_ALL_PREFIXES(
322       HostContentSettingsMapTest,
323       MigrateRequestingAndTopLevelOriginSettingsResetsEmbeddedSetting);
324 
325   ~HostContentSettingsMap() override;
326 
327   ContentSetting GetDefaultContentSettingFromProvider(
328       ContentSettingsType content_type,
329       content_settings::ProviderInterface* provider) const;
330 
331   // Retrieves default content setting for |content_type|, and writes the
332   // provider's type to |provider_type| (must not be null).
333   ContentSetting GetDefaultContentSettingInternal(
334       ContentSettingsType content_type,
335       ProviderType* provider_type) const;
336 
337   // Collect UMA data of exceptions.
338   void RecordExceptionMetrics();
339 
340   // Adds content settings for |content_type| and |resource_identifier|,
341   // provided by |provider|, into |settings|. If |incognito| is true, adds only
342   // the content settings which are applicable to the incognito mode and differ
343   // from the normal mode. Otherwise, adds the content settings for the normal
344   // mode (applying inheritance rules if |is_off_the_record_|).
345   void AddSettingsForOneType(
346       const content_settings::ProviderInterface* provider,
347       ProviderType provider_type,
348       ContentSettingsType content_type,
349       const std::string& resource_identifier,
350       ContentSettingsForOneType* settings,
351       bool incognito) const;
352 
353   // Call UsedContentSettingsProviders() whenever you access
354   // content_settings_providers_ (apart from initialization and
355   // teardown), so that we can DCHECK in RegisterExtensionService that
356   // it is not being called too late.
357   void UsedContentSettingsProviders() const;
358 
359   // Returns the single content setting |value| with a toggle for if it
360   // takes the global on/off switch into account.
361   std::unique_ptr<base::Value> GetWebsiteSettingInternal(
362       const GURL& primary_url,
363       const GURL& secondary_url,
364       ContentSettingsType content_type,
365       const std::string& resource_identifier,
366       ProviderType first_provider_to_search,
367       content_settings::SettingInfo* info) const;
368 
369   content_settings::PatternPair GetNarrowestPatterns(
370       const GURL& primary_url,
371       const GURL& secondary_url,
372       ContentSettingsType type) const;
373 
374   static std::unique_ptr<base::Value> GetContentSettingValueAndPatterns(
375       const content_settings::ProviderInterface* provider,
376       const GURL& primary_url,
377       const GURL& secondary_url,
378       ContentSettingsType content_type,
379       const std::string& resource_identifier,
380       bool include_incognito,
381       ContentSettingsPattern* primary_pattern,
382       ContentSettingsPattern* secondary_pattern);
383 
384   static std::unique_ptr<base::Value> GetContentSettingValueAndPatterns(
385       content_settings::RuleIterator* rule_iterator,
386       const GURL& primary_url,
387       const GURL& secondary_url,
388       ContentSettingsPattern* primary_pattern,
389       ContentSettingsPattern* secondary_pattern);
390 
391   // Make sure existing non-default Flash settings set by the user are marked to
392   // always show the Flash setting for this site in Page Info.
393   // TODO(patricialor): Remove after m66 (migration code).
394   void InitializePluginsDataSettings();
395 
396   // Migrate requesting and top level origin content settings to remove all
397   // settings that have a top level pattern. If there is a pattern set for
398   // (http://x.com, http://y.com) this will remove that pattern and also remove
399   // (http://y.com, *). The reason the second pattern is removed is to ensure
400   // that permission won't automatically be granted to x.com when it's embedded
401   // in y.com when permission delegation is enabled.
402   // TODO(raymes): Remove 2 milestones after permission delegation ships.
403   // https://crbug.com/818004.
404   void MigrateRequestingAndTopLevelOriginSettings();
405 
406 #ifndef NDEBUG
407   // This starts as the thread ID of the thread that constructs this
408   // object, and remains until used by a different thread, at which
409   // point it is set to base::kInvalidThreadId. This allows us to
410   // DCHECK on unsafe usage of content_settings_providers_ (they
411   // should be set up on a single thread, after which they are
412   // immutable).
413   mutable base::PlatformThreadId used_from_thread_id_;
414 #endif
415 
416   // Weak; owned by the Profile.
417   PrefService* prefs_;
418 
419   // Whether this settings map is for an incognito or guest session.
420   bool is_off_the_record_;
421 
422   // Whether ContentSettings in the PrefProvider will store a last_modified
423   // timestamp.
424   bool store_last_modified_;
425 
426   // Content setting providers. This is only modified at construction
427   // time and by RegisterExtensionService, both of which should happen
428   // before any other uses of it.
429   std::map<ProviderType, std::unique_ptr<content_settings::ProviderInterface>>
430       content_settings_providers_;
431 
432   // List of content settings providers containing settings which can be
433   // modified by the user. Members are owned by the
434   // |content_settings_providers_| map above.
435   std::vector<content_settings::UserModifiableProvider*>
436       user_modifiable_providers_;
437 
438   // content_settings_providers_[PREF_PROVIDER] but specialized.
439   content_settings::PrefProvider* pref_provider_ = nullptr;
440 
441   base::ThreadChecker thread_checker_;
442 
443   base::ObserverList<content_settings::Observer>::Unchecked observers_;
444 
445   base::WeakPtrFactory<HostContentSettingsMap> weak_ptr_factory_{this};
446 
447   DISALLOW_COPY_AND_ASSIGN(HostContentSettingsMap);
448 };
449 
450 #endif  // COMPONENTS_CONTENT_SETTINGS_CORE_BROWSER_HOST_CONTENT_SETTINGS_MAP_H_
451