File: notification_telemetry_service.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (282 lines) | stat: -rw-r--r-- 11,830 bytes parent folder | download | duplicates (4)
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
// Copyright 2025 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/safe_browsing/notification_telemetry/notification_telemetry_service.h"

#include "base/check.h"
#include "base/logging.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/escape.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/push_messaging/push_messaging_service_factory.h"
#include "chrome/browser/push_messaging/push_messaging_service_impl.h"
#include "chrome/browser/safe_browsing/notification_telemetry/notification_telemetry_service_factory.h"
#include "components/safe_browsing/core/browser/db/database_manager.h"
#include "components/safe_browsing/core/common/proto/csd.pb.h"
#include "components/safe_browsing/core/common/utils.h"
#include "content/public/browser/service_worker_context.h"
#include "content/public/browser/service_worker_registration_information.h"
#include "content/public/browser/storage_partition.h"
#include "google_apis/google_api_keys.h"
#include "net/base/load_flags.h"
#include "net/http/http_status_code.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
#include "url/gurl.h"
#include "url/origin.h"

namespace safe_browsing {

ServiceWorkerTelemetryInfo::ServiceWorkerTelemetryInfo() noexcept = default;
ServiceWorkerTelemetryInfo::ServiceWorkerTelemetryInfo(
    const ServiceWorkerTelemetryInfo& other) noexcept = default;
ServiceWorkerTelemetryInfo::~ServiceWorkerTelemetryInfo() = default;

namespace {

// Size of the stored service worker info cache.
const int kNotificationTelemetryServiceWorkerInfoMaxCount = 20;

const char kSbIncidentReportUrl[] =
    "https://sb-ssl.google.com/safebrowsing/clientreport/incident";

constexpr net::NetworkTrafficAnnotationTag
    kSafeBrowsingIncidentTrafficAnnotation =
        net::DefineNetworkTrafficAnnotation("notification_telemetry", R"(
          semantics {
            sender: "Notification Telemetry Service"
            description:
              "Chrome will upload registration data for service workers that "
              "subscribe to push messages. The data uploaded consists of the "
              "service worker scope URL and the URLs of the scripts imported "
              "by the service worker during installation. This data is only "
              "collected if the service worker's scope URL is not on the "
              "Safe Browsing allowlist. It will be used to detect websites "
              "that install service workers to display abusive notifications."
            trigger:
              "User navigates to a website that installs a service worker "
              "to display push notifications."
            data:
              "The service worker scope URL and the URLs of the imported "
              "scripts that don't match the scope origin. See "
              "ServiceWorkerRegistrationIncident in 'https://cs.chromium.org/ "
              "chromium/src/components/safe_browsing/csd.proto' for details."
            destination: GOOGLE_OWNED_SERVICE
            internal {
              contacts {
                owners: "chrome-counter-abuse-alerts@google.com"
              }
            }
            user_data {
              type: SENSITIVE_URL
            }
            last_reviewed: "2025-04-28"
          }
          policy {
            cookies_allowed: YES
            cookies_store: "Safe Browsing cookie store"
            setting:
              "Users can enable this feature by selecting the "
              "'Enhanced protection' option in "
              "'Settings->Privacy and security->Security->Safe Browsing`. "
              "The feature is disabled by default because the default "
              "Safe Browsing setting is 'Standard protection'."
            chrome_policy {
               SafeBrowsingEnabled {
                 policy_options {mode: MANDATORY}
                 SafeBrowsingEnabled: false
              }
            }
          })");

}  // namespace

// static
NotificationTelemetryService* NotificationTelemetryService::Get(
    Profile* profile) {
  return NotificationTelemetryServiceFactory::GetInstance()->GetForProfile(
      profile);
}

NotificationTelemetryService::NotificationTelemetryService(
    Profile* profile,
    scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
    scoped_refptr<SafeBrowsingDatabaseManager> database_manager)
    : url_loader_factory_(url_loader_factory),
      database_manager_(database_manager),
      profile_(profile) {
  service_worker_context_ =
      profile_->GetDefaultStoragePartition()->GetServiceWorkerContext();
  service_worker_context_->AddObserver(this);
  PushMessagingServiceImpl* push_messaging_service =
      PushMessagingServiceFactory::GetForProfile(profile_);
  // Notification Telemetry Service is a keyed service and will outlive
  // any invocations of the callback being registered with the push messaging
  // service (also a keyed service).
  push_messaging_service->SetSubscribeFromWorkerCallback(base::BindRepeating(
      &NotificationTelemetryService::OnNewNotificationServiceWorkerSubscription,
      base::Unretained(this)));
}

NotificationTelemetryService::~NotificationTelemetryService() {
  service_worker_context_->RemoveObserver(this);
}

void NotificationTelemetryService::OnRegistrationStored(
    int64_t registration_id,
    const GURL& scope,
    const content::ServiceWorkerRegistrationInformation&
        service_worker_registration_info) {
  // Only collect information for ESB users
  if (!IsEnhancedProtectionEnabled(*profile_->GetPrefs())) {
    return;
  }
  // Check feature flag after ESB check so that the Finch experiment
  // groups only include clients that can send telemetry reports.
  if (!base::FeatureList::IsEnabled(safe_browsing::kNotificationTelemetry)) {
    return;
  }
  // Check that at least one of the resources belongs to an external domain
  bool external_resource = false;
  url::Origin scope_origin = url::Origin::Create(scope);
  for (auto& resource : service_worker_registration_info.resources) {
    url::Origin resource_url = url::Origin::Create(resource);
    if (resource_url != scope_origin) {
      external_resource = true;
      break;
    }
  }
  // Check with safe browsing to see if the origin is allowlisted.
  if (external_resource) {
    ServiceWorkerTelemetryInfo service_worker_info;
    service_worker_info.scope = scope;
    service_worker_info.registration_id = registration_id;
    service_worker_info.resources = service_worker_registration_info.resources;
    database_manager_->CheckUrlForHighConfidenceAllowlist(
        scope, base::BindOnce(&NotificationTelemetryService::DatabaseCheckDone,
                              weak_factory_.GetWeakPtr(), service_worker_info));
  }
}

// static
int NotificationTelemetryService::ServiceWorkerInfoCacheSizeForTest() {
  return kNotificationTelemetryServiceWorkerInfoMaxCount;
}

void NotificationTelemetryService::DatabaseCheckDone(
    ServiceWorkerTelemetryInfo service_worker_info,
    bool allow_listed,
    std::optional<
        SafeBrowsingDatabaseManager::HighConfidenceAllowlistCheckLoggingDetails>
        logging_details) {
  base::UmaHistogramBoolean(
      "SafeBrowsing.NotificationTelemetry.ServiceWorkerScopeURL.IsAllowlisted",
      allow_listed);

  // No handling required for service workers with allowlisted scope URLs.
  if (allow_listed) {
    return;
  }
  // Only store up to `kNotificationTelemetryServiceWorkerInfoMaxCount` entries.
  // Remove the oldest entry in the store if necessary to accommodate a new one.
  if (service_worker_infos_.size() >=
      kNotificationTelemetryServiceWorkerInfoMaxCount) {
    service_worker_infos_.erase(service_worker_infos_.begin());
  }
  service_worker_infos_.push_back(service_worker_info);
}

void NotificationTelemetryService::OnNewNotificationServiceWorkerSubscription(
    int64_t registration_id) {
  // Only collect information for ESB users
  if (!IsEnhancedProtectionEnabled(*profile_->GetPrefs())) {
    return;
  }
  // Check feature flag after ESB check so that the Finch experiment
  // groups only include clients that can send telemetry reports.
  if (!base::FeatureList::IsEnabled(safe_browsing::kNotificationTelemetry)) {
    return;
  }
  // Check the stored service worker list to see if there is an
  // entry that has the same registration id for which we received
  // the notification.
  auto it =
      std::find_if(service_worker_infos_.begin(), service_worker_infos_.end(),
                   [registration_id](const ServiceWorkerTelemetryInfo& info) {
                     return registration_id == info.registration_id;
                   });
  // No match found, so return without doing anything.
  if (it == service_worker_infos_.end()) {
    return;
  }
  // Match found, save the matched registration data
  // and delete the matched entry in the stored list.
  ServiceWorkerTelemetryInfo report_data = std::move(*it);
  service_worker_infos_.erase(it);

  // Generate a telemetry report with the matched data.
  std::unique_ptr<ClientIncidentReport_IncidentData> incident_data =
      std::make_unique<ClientIncidentReport_IncidentData>();
  ClientIncidentReport_IncidentData_ServiceWorkerRegistrationIncident*
      notification_resource_report =
          incident_data->mutable_notification_import_script();

  notification_resource_report->set_scope_url(report_data.scope.spec());
  for (const auto& resource : report_data.resources) {
    std::string* import_script_url =
        notification_resource_report->add_import_script_url();
    *import_script_url = resource.spec();
  }

  std::unique_ptr<ClientIncidentReport> report =
      std::make_unique<ClientIncidentReport>();
  report->mutable_incident()->AddAllocated(incident_data.release());
  std::string post_data;
  if (!report->SerializeToString(&post_data)) {
    return;
  }

  // Send report for upload
  auto resource_request = std::make_unique<network::ResourceRequest>();
  resource_request->url = GetTelemetryReportUrl();
  resource_request->method = "POST";
  resource_request->load_flags = net::LOAD_DISABLE_CACHE;
  resource_request->credentials_mode = network::mojom::CredentialsMode::kOmit;

  url_loader_ = network::SimpleURLLoader::Create(
      std::move(resource_request), kSafeBrowsingIncidentTrafficAnnotation);
  url_loader_->AttachStringForUpload(post_data, "application/octet-stream");
  // Using base::Unretained is safe here as Network Telemetry Service owns
  // `url_loader_`.
  url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
      url_loader_factory_.get(),
      base::BindOnce(&NotificationTelemetryService::UploadComplete,
                     base::Unretained(this)));
}

void NotificationTelemetryService::UploadComplete(
    std::unique_ptr<std::string> response_body) {
  // Take ownership of the loader in this scope.
  std::unique_ptr<network::SimpleURLLoader> url_loader(std::move(url_loader_));
  int response_code = 0;
  if (url_loader->ResponseInfo() && url_loader->ResponseInfo()->headers) {
    response_code = url_loader->ResponseInfo()->headers->response_code();
  }
  RecordHttpResponseOrErrorCode(
      "SafeBrowsing.NotificationTelemetry.NetworkResult",
      url_loader->NetError(), response_code);
}

// static
GURL NotificationTelemetryService::GetTelemetryReportUrl() {
  GURL url(kSbIncidentReportUrl);
  std::string api_key(google_apis::GetAPIKey());
  if (api_key.empty()) {
    return url;
  }
  return url.Resolve("?key=" + base::EscapeQueryParamValue(api_key, true));
}
}  // namespace safe_browsing