File: search_permissions_service.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (322 lines) | stat: -rw-r--r-- 12,693 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/android/search_permissions/search_permissions_service.h"

#include <memory>

#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/permissions/permission_decision_auto_blocker_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
#include "chrome/browser/search_engines/ui_thread_search_terms_data.h"
#include "chrome/common/pref_names.h"
#include "components/content_settings/core/browser/content_settings_utils.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/common/content_settings_types.h"
#include "components/permissions/features.h"
#include "components/permissions/permission_decision_auto_blocker.h"
#include "components/permissions/permission_uma_util.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/pref_service.h"
#include "components/search_engines/template_url.h"
#include "components/search_engines/template_url_service.h"
#include "url/gurl.h"
#include "url/url_constants.h"

namespace {

const char kDSENameKey[] = "dse_name";
const char kDSEOriginKey[] = "dse_origin";
const char kDSEGeolocationSettingKey[] = "geolocation_setting_to_restore";
const char kDSENotificationsSettingKey[] = "notifications_setting_to_restore";

// Default implementation of SearchEngineDelegate that is used for production
// code.
class SearchEngineDelegateImpl
    : public SearchPermissionsService::SearchEngineDelegate {
 public:
  explicit SearchEngineDelegateImpl(Profile* profile)
      : profile_(profile),
        template_url_service_(
            TemplateURLServiceFactory::GetForProfile(profile_)) {}

  std::u16string GetDSEName() override {
    if (template_url_service_) {
      const TemplateURL* template_url =
          template_url_service_->GetDefaultSearchProvider();
      if (template_url)
        return template_url->short_name();
    }

    return std::u16string();
  }

  url::Origin GetDSEOrigin() override {
    if (template_url_service_) {
      return template_url_service_->GetDefaultSearchProviderOrigin();
    }

    return url::Origin();
  }

 private:
  raw_ptr<Profile> profile_;

  // Will be null in unittests.
  raw_ptr<TemplateURLService> template_url_service_;
};

}  // namespace

struct SearchPermissionsService::PrefValue {
  std::u16string dse_name;
  std::string dse_origin;
  ContentSetting geolocation_setting_to_restore;
  ContentSetting notifications_setting_to_restore;
};

// static
SearchPermissionsService*
SearchPermissionsService::Factory::GetForBrowserContext(
    content::BrowserContext* context) {
  return static_cast<SearchPermissionsService*>(
      GetInstance()->GetServiceForBrowserContext(context, true));
}

// static
SearchPermissionsService::Factory*
SearchPermissionsService::Factory::GetInstance() {
  return base::Singleton<SearchPermissionsService::Factory>::get();
}

SearchPermissionsService::Factory::Factory()
    : ProfileKeyedServiceFactory(
          "SearchPermissionsService",
          ProfileSelections::Builder()
              .WithRegular(ProfileSelection::kOriginalOnly)
              // TODO(crbug.com/40257657): Check if this service is needed in
              // Guest mode.
              .WithGuest(ProfileSelection::kOriginalOnly)
              .Build()) {
  DependsOn(HostContentSettingsMapFactory::GetInstance());
  DependsOn(TemplateURLServiceFactory::GetInstance());
}

SearchPermissionsService::Factory::~Factory() = default;

bool SearchPermissionsService::Factory::ServiceIsCreatedWithBrowserContext()
    const {
  return true;
}

std::unique_ptr<KeyedService>
SearchPermissionsService::Factory::BuildServiceInstanceForBrowserContext(
    content::BrowserContext* context) const {
  return std::make_unique<SearchPermissionsService>(
      Profile::FromBrowserContext(context));
}

void SearchPermissionsService::Factory::RegisterProfilePrefs(
    user_prefs::PrefRegistrySyncable* registry) {
  registry->RegisterDictionaryPref(prefs::kDSEGeolocationSettingDeprecated);
  registry->RegisterDictionaryPref(prefs::kDSEPermissionsSettings);
  registry->RegisterBooleanPref(prefs::kDSEWasDisabledByPolicy, false);
}

SearchPermissionsService::SearchPermissionsService(Profile* profile)
    : profile_(profile),
      pref_service_(profile_->GetPrefs()),
      host_content_settings_map_(
          HostContentSettingsMapFactory::GetForProfile(profile_)) {
  // This class should never be constructed in incognito.
  DCHECK(!profile_->IsOffTheRecord());

  delegate_ = std::make_unique<SearchEngineDelegateImpl>(profile_);

  InitializeSettingsIfNeeded();
}

bool SearchPermissionsService::IsDseOrigin(const url::Origin& origin) {
  return origin.scheme() == url::kHttpsScheme &&
         origin.IsSameOriginWith(delegate_->GetDSEOrigin());
}

void SearchPermissionsService::Shutdown() {
  delegate_.reset();
}

SearchPermissionsService::~SearchPermissionsService() = default;

ContentSetting SearchPermissionsService::RestoreOldSettingAndReturnPrevious(
    const GURL& dse_origin,
    ContentSettingsType type,
    ContentSetting setting_to_restore,
    bool preserve_block_setting) {
  // Read the current value of the old DSE. This is the DSE setting that we want
  // to try to apply to the new DSE origin.
  ContentSetting dse_setting = GetContentSetting(dse_origin, type);

  // The user's setting should never be ASK while an origin is the DSE. There
  // should be no way for the user to reset the DSE content setting to ASK.
  if (dse_setting == CONTENT_SETTING_ASK) {
    // The style guide suggests not to handle cases which are invalid code paths
    // however in this case there are security risks to state being invalid so
    // we ensure the dse_setting is reverted to BLOCK.
    dse_setting = CONTENT_SETTING_BLOCK;
  }

  // If `preserve_block_setting` is set we don't restore a "BLOCK" setting.
  if (dse_setting == CONTENT_SETTING_BLOCK && preserve_block_setting)
    setting_to_restore = CONTENT_SETTING_BLOCK;

  // Restore the setting for the old origin. If the user has changed the setting
  // since the origin became the DSE, we reset the setting so the user will be
  // prompted.
  if (setting_to_restore != dse_setting)
    setting_to_restore = CONTENT_SETTING_ASK;
  SetContentSetting(dse_origin, type, setting_to_restore);

  return dse_setting;
}

void SearchPermissionsService::InitializeSettingsIfNeeded() {
  GURL dse_origin = delegate_->GetDSEOrigin().GetURL();

  // `dse_origin` can be invalid in tests or if the DSE is disabled by policy.
  // If that's the case or if `RevertDSEAutomaticPermissions` is enabled, we
  // restore the old settings and erase the pref.
  const bool disabled_by_policy = !dse_origin.is_valid();
  if (pref_service_->HasPrefPath(prefs::kDSEPermissionsSettings)) {
    if (disabled_by_policy)
      pref_service_->SetBoolean(prefs::kDSEWasDisabledByPolicy, true);

    PrefValue pref = GetDSEPref();
    GURL old_dse_origin(pref.dse_origin);

    ContentSetting effective_setting = RestoreOldSettingAndReturnPrevious(
        old_dse_origin, ContentSettingsType::GEOLOCATION,
        pref.geolocation_setting_to_restore, !disabled_by_policy);
    if (!disabled_by_policy) {
      RecordAutoDSEPermissionReverted(ContentSettingsType::GEOLOCATION,
                                      pref.geolocation_setting_to_restore,
                                      effective_setting, dse_origin);
    }

    if (pref.notifications_setting_to_restore != CONTENT_SETTING_DEFAULT) {
      effective_setting = RestoreOldSettingAndReturnPrevious(
          old_dse_origin, ContentSettingsType::NOTIFICATIONS,
          pref.notifications_setting_to_restore, !disabled_by_policy);
      if (!disabled_by_policy) {
        RecordAutoDSEPermissionReverted(ContentSettingsType::NOTIFICATIONS,
                                        pref.notifications_setting_to_restore,
                                        effective_setting, dse_origin);
      }
    }
    pref_service_->ClearPref(prefs::kDSEPermissionsSettings);
  }

  RecordEffectiveDSEOriginPermissions();
}

SearchPermissionsService::PrefValue SearchPermissionsService::GetDSEPref() {
  const base::Value::Dict& dict =
      pref_service_->GetDict(prefs::kDSEPermissionsSettings);

  PrefValue pref;
  const std::string* dse_name = dict.FindString(kDSENameKey);
  const std::string* dse_origin = dict.FindString(kDSEOriginKey);
  std::optional<int> geolocation_setting_to_restore =
      dict.FindInt(kDSEGeolocationSettingKey);
  std::optional<int> notifications_setting_to_restore =
      dict.FindInt(kDSENotificationsSettingKey);

  if (dse_name && dse_origin && geolocation_setting_to_restore &&
      notifications_setting_to_restore) {
    pref.dse_name = base::UTF8ToUTF16(*dse_name);
    pref.dse_origin = *dse_origin;
    pref.geolocation_setting_to_restore =
        IntToContentSetting(*geolocation_setting_to_restore);
    pref.notifications_setting_to_restore =
        IntToContentSetting(*notifications_setting_to_restore);
  }

  return pref;
}

ContentSetting SearchPermissionsService::GetContentSetting(
    const GURL& origin,
    ContentSettingsType type) {
  return host_content_settings_map_->GetUserModifiableContentSetting(
      origin, origin, type);
}

void SearchPermissionsService::SetContentSetting(const GURL& origin,
                                                 ContentSettingsType type,
                                                 ContentSetting setting) {
  // Clear a setting before setting it. This is needed because in general
  // notifications settings can't be changed from ALLOW<->BLOCK on Android O+.
  // We need to change the setting from ALLOW->BLOCK in one case, where the
  // previous DSE had permission blocked but the new DSE we're changing to has
  // permission allowed. Thus this works around that restriction.
  // WARNING: This is a special case and in general notification settings should
  // never be changed between ALLOW<->BLOCK on Android. Do not copy this code.
  // Check with the notifications team if you need to do something like this.
  host_content_settings_map_->SetContentSettingDefaultScope(
      origin, origin, type, CONTENT_SETTING_DEFAULT);

  // If we're restoring an ASK setting, it really implies that we should delete
  // the user-defined setting to fall back to the default.
  if (setting == CONTENT_SETTING_ASK)
    return;  // We deleted the setting above already.

  host_content_settings_map_->SetContentSettingDefaultScope(origin, origin,
                                                            type, setting);
}

void SearchPermissionsService::SetSearchEngineDelegateForTest(
    std::unique_ptr<SearchEngineDelegate> delegate) {
  delegate_ = std::move(delegate);
}

void SearchPermissionsService::RecordAutoDSEPermissionReverted(
    ContentSettingsType permission_type,
    ContentSetting backed_up_setting,
    ContentSetting effective_setting,
    const GURL& origin) {
  ContentSetting end_state_setting = GetContentSetting(origin, permission_type);
  permissions::PermissionUmaUtil::RecordAutoDSEPermissionReverted(
      permission_type, backed_up_setting, effective_setting, end_state_setting);
}

void SearchPermissionsService::RecordEffectiveDSEOriginPermissions() {
  GURL dse_origin = delegate_->GetDSEOrigin().GetURL();
  if (!dse_origin.is_valid())
    return;

  permissions::PermissionUmaUtil::RecordDSEEffectiveSetting(
      ContentSettingsType::NOTIFICATIONS,
      GetContentSetting(dse_origin, ContentSettingsType::NOTIFICATIONS));

  permissions::PermissionUmaUtil::RecordDSEEffectiveSetting(
      ContentSettingsType::GEOLOCATION,
      GetContentSetting(dse_origin, ContentSettingsType::GEOLOCATION));
}

void SearchPermissionsService::SetDSEPrefForTesting(
    ContentSetting geolocation_setting_to_restore,
    ContentSetting notifications_setting_to_restore) {
  base::Value::Dict dict;
  dict.Set(kDSENameKey, delegate_->GetDSEName());
  dict.Set(kDSEOriginKey, delegate_->GetDSEOrigin().GetURL().spec());
  dict.Set(kDSEGeolocationSettingKey, geolocation_setting_to_restore);
  dict.Set(kDSENotificationsSettingKey, notifications_setting_to_restore);
  pref_service_->SetDict(prefs::kDSEPermissionsSettings, std::move(dict));
}