File: notification_permission_review_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 (284 lines) | stat: -rw-r--r-- 11,523 bytes parent folder | download | duplicates (3)
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
// Copyright 2022 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/ui/safety_hub/notification_permission_review_service.h"

#include <algorithm>
#include <map>
#include <set>
#include <string>

#include "base/containers/contains.h"
#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "chrome/browser/ui/safety_hub/safety_hub_service.h"
#include "chrome/common/chrome_features.h"
#include "chrome/grit/generated_resources.h"
#include "components/content_settings/core/common/content_settings.h"
#include "components/content_settings/core/common/content_settings_types.h"
#include "components/content_settings/core/common/content_settings_utils.h"
#include "components/permissions/notifications_engagement_service.h"
#include "components/safe_browsing/core/common/features.h"
#include "components/site_engagement/content/site_engagement_service.h"
#include "ui/base/l10n/l10n_util.h"

namespace {

constexpr char kExcludedKey[] = "exempted";

std::set<std::pair<ContentSettingsPattern, ContentSettingsPattern>>
GetIgnoredPatternPairs(scoped_refptr<HostContentSettingsMap> hcsm) {
  std::set<std::pair<ContentSettingsPattern, ContentSettingsPattern>> result;

  for (auto& item : hcsm->GetSettingsForOneType(
           ContentSettingsType::NOTIFICATION_PERMISSION_REVIEW)) {
    const base::Value& stored_value = item.setting_value;
    bool is_ignored =
        stored_value.is_dict() &&
        stored_value.GetDict().FindBool(kExcludedKey).value_or(false);
    if (is_ignored) {
      result.insert(
          {std::move(item.primary_pattern), std::move(item.secondary_pattern)});
    }
  }

  return result;
}

}  // namespace

NotificationPermissionsReviewService::NotificationPermissionsReviewService(
    HostContentSettingsMap* hcsm,
    site_engagement::SiteEngagementService* engagement_service)
    : engagement_service_(engagement_service), hcsm_(hcsm) {
  content_settings_observation_.Observe(hcsm);

#if BUILDFLAG(IS_ANDROID)
  if (!base::FeatureList::IsEnabled(features::kSafetyHub)) {
    return;
  }
#endif  // BUILDFLAG(IS_ANDROID)

  // Disruptive notification revocation overlaps with the notification review
  // module. Disable this module when the disruptive revocation is running.
  if (!IsDisruptiveNotificationRevocationEnabled()) {
    // TODO(crbug.com/40267370): Because there is only a UI thread for this
    // service, calling both |StartRepeatedUpdates()| and
    // |InitializeLatestResult()| will result in the result being calculated
    // twice when the service starts. When redesigning SafetyHubService, that
    // should be avoided.
    StartRepeatedUpdates();
    InitializeLatestResult();
  }
}

NotificationPermissionsReviewService::~NotificationPermissionsReviewService() =
    default;

void NotificationPermissionsReviewService::OnContentSettingChanged(
    const ContentSettingsPattern& primary_pattern,
    const ContentSettingsPattern& secondary_pattern,
    ContentSettingsTypeSet content_type_set) {
  if (content_type_set.Contains(
          ContentSettingsType::NOTIFICATION_PERMISSION_REVIEW)) {
    // In order to keep the latest result updated with the actual list that
    // should be reviewed, the latest result should be updated here. This is
    // triggered whenever an update is made to the ignore list. For other
    // updates on notification permissions,
    SetLatestResult(UpdateOnUIThread(
        std::make_unique<NotificationPermissionsReviewResult>()));
    return;
  }
  if (content_type_set.Contains(ContentSettingsType::NOTIFICATIONS)) {
    // Sites on the notification permission review blocklist are sites where the
    // notification permission is ALLOW and the user has indicated the site
    // should not be suggested again in the module for revocation. A change in
    // the notification permission for such a site (e.g. by the user or by
    // resetting permissions) is considered to be a signal that the site should
    // not longer be ignored, in case the permission is allowed again in the
    // future. Setting ContentSetting to ALLOW when it already is ALLOW will not
    // trigger this function.
    RemovePatternFromNotificationPermissionReviewBlocklist(primary_pattern,
                                                           secondary_pattern);
    // Update the result since the permission might have been revoked without
    // being on the ignore list and therefore wouldn't cause another
    // OnContentSettingChanged() event.
    SetLatestResult(UpdateOnUIThread(
        std::make_unique<NotificationPermissionsReviewResult>()));
    return;
  }
}

void NotificationPermissionsReviewService::Shutdown() {}

void NotificationPermissionsReviewService::
    AddPatternToNotificationPermissionReviewBlocklist(
        const ContentSettingsPattern& primary_pattern,
        const ContentSettingsPattern& secondary_pattern) {
  base::Value::Dict permission_dict;
  permission_dict.Set(kExcludedKey, base::Value(true));

  hcsm_->SetWebsiteSettingCustomScope(
      primary_pattern, secondary_pattern,
      ContentSettingsType::NOTIFICATION_PERMISSION_REVIEW,
      base::Value(std::move(permission_dict)));
}

void NotificationPermissionsReviewService::
    RemovePatternFromNotificationPermissionReviewBlocklist(
        const ContentSettingsPattern& primary_pattern,
        const ContentSettingsPattern& secondary_pattern) {
  hcsm_->SetWebsiteSettingCustomScope(
      primary_pattern, secondary_pattern,
      ContentSettingsType::NOTIFICATION_PERMISSION_REVIEW, {});
}

std::unique_ptr<SafetyHubService::Result>
NotificationPermissionsReviewService::UpdateOnUIThread(
    std::unique_ptr<SafetyHubService::Result> interim_result) {
  // Get blocklisted pattern pairs that should not be shown in the review list.
  std::set<std::pair<ContentSettingsPattern, ContentSettingsPattern>>
      ignored_patterns_set = GetIgnoredPatternPairs(hcsm_);

  // Get daily average notification count of pattern pairs.
  std::map<std::pair<ContentSettingsPattern, ContentSettingsPattern>, int>
      notification_count_map = permissions::NotificationsEngagementService::
          GetNotificationCountMapPerPatternPair(hcsm_.get());

  // Get the permissions with notification counts that needs to be reviewed.
  // This list is filtered based on notification count and site engagement
  // score.
  auto result = std::make_unique<NotificationPermissionsReviewResult>();
  for (auto& item :
       hcsm_->GetSettingsForOneType(ContentSettingsType::NOTIFICATIONS)) {
    std::pair pair(item.primary_pattern, item.secondary_pattern);

    // Invalid primary pattern should not be in the review list.
    if (!item.primary_pattern.IsValid()) {
      continue;
    }

    // Blocklisted permissions should not be in the review list.
    if (base::Contains(ignored_patterns_set, pair)) {
      continue;
    }

    // Only granted permissions should be in the review list.
    if (item.GetContentSetting() != CONTENT_SETTING_ALLOW) {
      continue;
    }

    // Only URLs that belong to a single origin should be in the review list.
    if (!content_settings::PatternAppliesToSingleOrigin(
            item.primary_pattern, item.secondary_pattern)) {
      continue;
    }

    // Converting primary pattern to GURL should always be valid, since
    // Notification Permission Review list only contains single origins.
    GURL url = GURL(item.primary_pattern.ToString());
    DCHECK(url.is_valid());

    int notification_count = notification_count_map[pair];
    if (!ShouldAddToNotificationPermissionReviewList(url, notification_count)) {
      continue;
    }

    NotificationPermissions notification_permission(
        item.primary_pattern, item.secondary_pattern, notification_count);

    result->AddNotificationPermission(notification_permission);
  }

  return result;
}

std::unique_ptr<NotificationPermissionsReviewResult>
NotificationPermissionsReviewService::GetNotificationPermissions() {
  if (IsDisruptiveNotificationRevocationEnabled()) {
    return std::make_unique<NotificationPermissionsReviewResult>();
  }
  // Return the cached result, which is kept in sync with the values on disk
  // (i.e. HCSM), when available. Otherwise, re-calculate the result.
  auto result = GetCachedResult().value_or(UpdateOnUIThread(
      std::make_unique<NotificationPermissionsReviewResult>()));
  return base::WrapUnique<NotificationPermissionsReviewResult>(
      static_cast<NotificationPermissionsReviewResult*>(result.release()));
}

base::Value::List NotificationPermissionsReviewService::
    PopulateNotificationPermissionReviewData() {
  return (GetNotificationPermissions().get())->GetSortedListValueForUI();
}

void NotificationPermissionsReviewService::SetNotificationPermissionsForOrigin(
    std::string origin,
    ContentSetting setting) {
  hcsm_->SetContentSettingCustomScope(
      ContentSettingsPattern::FromString(origin),
      ContentSettingsPattern::Wildcard(), ContentSettingsType::NOTIFICATIONS,
      setting);
}

base::TimeDelta
NotificationPermissionsReviewService::GetRepeatedUpdateInterval() {
  return base::Days(1);
}

base::OnceCallback<std::unique_ptr<SafetyHubService::Result>()>
NotificationPermissionsReviewService::GetBackgroundTask() {
  return base::BindOnce(&UpdateOnBackgroundThread);
}

// static
std::unique_ptr<SafetyHubService::Result>
NotificationPermissionsReviewService::UpdateOnBackgroundThread() {
  // Return an empty result.
  return std::make_unique<NotificationPermissionsReviewResult>();
}

std::unique_ptr<SafetyHubService::Result>
NotificationPermissionsReviewService::InitializeLatestResultImpl() {
  return UpdateOnUIThread(
      std::make_unique<NotificationPermissionsReviewResult>());
}

base::WeakPtr<SafetyHubService>
NotificationPermissionsReviewService::GetAsWeakRef() {
  return weak_factory_.GetWeakPtr();
}

bool NotificationPermissionsReviewService::
    ShouldAddToNotificationPermissionReviewList(GURL url,
                                                int notification_count) {
  // The notification permission should be added to the list if one of the
  // criteria below holds:
  // - Site engagement level is NONE OR MINIMAL and average daily notification
  // count is more than 0.
  // - Site engamment level is LOW and average daily notification count is
  // more than 3. Otherwise, the notification permission should not be added
  // to review list.
  double score = engagement_service_->GetScore(url);
  int low_engagement_notification_limit =
      features::kSafetyCheckNotificationPermissionsLowEnagementLimit.Get();
  bool is_low_engagement =
      !site_engagement::SiteEngagementService::IsEngagementAtLeast(
          score, blink::mojom::EngagementLevel::MEDIUM) &&
      notification_count > low_engagement_notification_limit;
  int min_engagement_notification_limit =
      features::kSafetyCheckNotificationPermissionsMinEnagementLimit.Get();
  bool is_minimal_engagement =
      !site_engagement::SiteEngagementService::IsEngagementAtLeast(
          score, blink::mojom::EngagementLevel::LOW) &&
      notification_count > min_engagement_notification_limit;

  return is_minimal_engagement || is_low_engagement;
}

bool NotificationPermissionsReviewService::
    IsDisruptiveNotificationRevocationEnabled() {
  return base::FeatureList::IsEnabled(
             features::kSafetyHubDisruptiveNotificationRevocation) &&
         !features::kSafetyHubDisruptiveNotificationRevocationShadowRun.Get();
}