File: download_warning_desktop_hats_utils.cc

package info (click to toggle)
chromium 139.0.7258.127-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,122,156 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 (540 lines) | stat: -rw-r--r-- 19,869 bytes parent folder | download | duplicates (5)
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
// Copyright 2024 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/download/download_warning_desktop_hats_utils.h"

#include <algorithm>
#include <cstdint>
#include <iterator>
#include <string>
#include <vector>

#include "base/containers/contains.h"
#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/sequenced_task_runner.h"
#include "base/time/time.h"
#include "base/version_info/channel.h"
#include "build/build_config.h"
#include "chrome/browser/download/download_item_model.h"
#include "chrome/browser/download/download_item_warning_data.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/hats/hats_service.h"
#include "chrome/browser/ui/hats/hats_service_factory.h"
#include "chrome/browser/ui/hats/survey_config.h"
#include "chrome/common/channel_info.h"
#include "chrome/common/pref_names.h"
#include "components/download/public/common/download_item.h"
#include "components/prefs/pref_service.h"
#include "components/safe_browsing/buildflags.h"
#include "components/safe_browsing/core/common/features.h"
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"
#include "content/public/browser/download_item_utils.h"

namespace {

// Placeholder strings for fields that are not logged.
constexpr char kNotAvailable[] = "Not available";
constexpr char kNotLoggedNoSafeBrowsing[] =
    "Not logged because Safe Browsing is off";
constexpr char kNotLoggedNoEnhancedProtection[] =
    "Not logged because Enhanced Protection is off";

bool IsDownloadBubbleTrigger(DownloadWarningHatsType type) {
  return type == DownloadWarningHatsType::kDownloadBubbleBypass ||
         type == DownloadWarningHatsType::kDownloadBubbleHeed ||
         type == DownloadWarningHatsType::kDownloadBubbleIgnore;
}

bool IsDownloadsPageTrigger(DownloadWarningHatsType type) {
  return !IsDownloadBubbleTrigger(type);
}

std::string GetOutcomeStringData(DownloadWarningHatsType type) {
  switch (type) {
    case DownloadWarningHatsType::kDownloadBubbleBypass:
    case DownloadWarningHatsType::kDownloadsPageBypass:
      return "Bypassed warning";
    case DownloadWarningHatsType::kDownloadBubbleHeed:
    case DownloadWarningHatsType::kDownloadsPageHeed:
      return "Heeded warning";
    case DownloadWarningHatsType::kDownloadBubbleIgnore:
    case DownloadWarningHatsType::kDownloadsPageIgnore:
      return "Ignored warning";
  }
}

std::string GetSurfaceStringData(DownloadWarningHatsType type) {
  return IsDownloadBubbleTrigger(type) ? "Download bubble" : "Downloads page";
}

std::string GetDangerTypeStringData(const DownloadItemModel& model) {
  std::string danger_type_string =
      GetDownloadDangerTypeString(model.GetDangerType());

  switch (model.GetTailoredWarningType()) {
    case DownloadUIModel::TailoredWarningType::kNoTailoredWarning:
      break;
    case DownloadUIModel::TailoredWarningType::kCookieTheft:
      base::StrAppend(&danger_type_string, {", Cookie theft"});
      break;
    case DownloadUIModel::TailoredWarningType::kSuspiciousArchive:
      base::StrAppend(&danger_type_string, {", Suspicious archive"});
      break;
  }

  return danger_type_string;
}

std::string GetWarningTypeStringData(const DownloadUIModel& model) {
  switch (model.GetDangerUiPattern()) {
    case DownloadUIModel::DangerUiPattern::kNormal:
    case DownloadUIModel::DangerUiPattern::kOther:
      return "None";
    case DownloadUIModel::DangerUiPattern::kDangerous:
      return "Dangerous";
    case DownloadUIModel::DangerUiPattern::kSuspicious:
      return "Suspicious";
  }
}

std::string ElapsedTimeToSecondsString(base::TimeDelta elapsed_time) {
  return base::NumberToString(elapsed_time.InSeconds());
}

std::string SafeBrowsingStateToString(
    safe_browsing::SafeBrowsingState sb_state) {
  switch (sb_state) {
    case safe_browsing::SafeBrowsingState::NO_SAFE_BROWSING:
      return "No Safe Browsing";
    case safe_browsing::SafeBrowsingState::STANDARD_PROTECTION:
      return "Standard Protection";
    case safe_browsing::SafeBrowsingState::ENHANCED_PROTECTION:
      return "Enhanced Protection";
  }
}

// Produces a string consisting of comma-separated action events, each of which
// consists of the surface, action, and relative timestamp (ms) separated by
// colons. The first SHOWN event is included, and is the basis of all
// timestamps, however subsequent SHOWN events are not included.
std::string SerializeWarningActionEvents(
    DownloadItemWarningData::WarningSurface warning_first_shown_surface,
    const std::vector<DownloadItemWarningData::WarningActionEvent>& events) {
  // The first SHOWN event is not stored by DownloadItemWarningData, so we
  // construct it here.
  std::string first_event_string =
      DownloadItemWarningData::WarningActionEvent{
          warning_first_shown_surface,
          DownloadItemWarningData::WarningAction::SHOWN, 0,
          /*is_terminal_action=*/false}
          .ToString();

  std::vector<std::string> event_strings;
  event_strings.reserve(events.size() + 1);
  event_strings.push_back(std::move(first_event_string));
  std::ranges::transform(
      events.begin(), events.end(), std::back_inserter(event_strings),
      [](const DownloadItemWarningData::WarningActionEvent& event) {
        return event.ToString();
      });

  return base::JoinString(std::move(event_strings), ",");
}

}  // namespace

DownloadWarningHatsProductSpecificData::DownloadWarningHatsProductSpecificData(
    DownloadWarningHatsType survey_type)
    : survey_type_(survey_type) {}

DownloadWarningHatsProductSpecificData::DownloadWarningHatsProductSpecificData(
    const DownloadWarningHatsProductSpecificData&) = default;

DownloadWarningHatsProductSpecificData&
DownloadWarningHatsProductSpecificData::operator=(
    const DownloadWarningHatsProductSpecificData&) = default;

DownloadWarningHatsProductSpecificData::DownloadWarningHatsProductSpecificData(
    DownloadWarningHatsProductSpecificData&&) = default;

DownloadWarningHatsProductSpecificData&
DownloadWarningHatsProductSpecificData::operator=(
    DownloadWarningHatsProductSpecificData&&) = default;

DownloadWarningHatsProductSpecificData::
    ~DownloadWarningHatsProductSpecificData() = default;

// static
DownloadWarningHatsProductSpecificData
DownloadWarningHatsProductSpecificData::Create(
    DownloadWarningHatsType survey_type,
    download::DownloadItem* download_item) {
  CHECK(download_item);
  CHECK(CanShowDownloadWarningHatsSurvey(download_item));

  DownloadWarningHatsProductSpecificData psd{survey_type};

  // Add placeholders for the fields that must be added later, to avoid CHECKing
  // even if they are forgotten.
  if (IsDownloadBubbleTrigger(survey_type)) {
    psd.bits_data_.insert({Fields::kPartialViewInteraction, false});
  }
  if (IsDownloadsPageTrigger(survey_type)) {
    psd.string_data_.insert({Fields::kNumPageWarnings, kNotAvailable});
  }

  psd.string_data_.insert(
      {Fields::kChannel,
       std::string(version_info::GetChannelString(chrome::GetChannel()))});

  psd.string_data_.insert(
      {Fields::kOutcome, GetOutcomeStringData(survey_type)});
  psd.string_data_.insert(
      {Fields::kSurface, GetSurfaceStringData(survey_type)});

  psd.string_data_.insert(
      {Fields::kSecondsSinceDownloadStarted,
       ElapsedTimeToSecondsString(base::Time::Now() -
                                  download_item->GetStartTime())});

  base::Time warning_shown_time =
      DownloadItemWarningData::WarningFirstShownTime(download_item);
  if (!warning_shown_time.is_null()) {
    psd.string_data_.insert(
        {Fields::kSecondsSinceWarningShown,
         ElapsedTimeToSecondsString(base::Time::Now() - warning_shown_time)});
  } else {
    psd.string_data_.insert({Fields::kSecondsSinceWarningShown, kNotAvailable});
  }

  psd.bits_data_.insert(
      {Fields::kUserGesture, download_item->HasUserGesture()});

  // This won't be used for generating any strings, so it's ok not to use the
  // correct StatusTextBuilder.
  DownloadItemModel download_model(download_item);

  psd.string_data_.insert(
      {Fields::kDangerType, GetDangerTypeStringData(download_model)});
  psd.string_data_.insert(
      {Fields::kWarningType, GetWarningTypeStringData(download_model)});

  if (survey_type == DownloadWarningHatsType::kDownloadBubbleIgnore) {
    psd.string_data_.insert(
        {Fields::kIgnoreTimeoutSeconds,
         ElapsedTimeToSecondsString(GetIgnoreDownloadBubbleWarningDelay())});
  }

  // Assemble the Profile-dependent PSD.
  Profile* profile = Profile::FromBrowserContext(
      content::DownloadItemUtils::GetBrowserContext(download_item));
  if (!profile) {
    psd.string_data_.insert({Fields::kSafeBrowsingState, kNotAvailable});
    psd.string_data_.insert({Fields::kPartialViewEnabled, kNotAvailable});
    psd.string_data_.insert({Fields::kUrlDownload, kNotAvailable});
    psd.string_data_.insert({Fields::kUrlReferrer, kNotAvailable});
    psd.string_data_.insert({Fields::kFilename, kNotAvailable});
    psd.string_data_.insert({Fields::kWarningInteractions, kNotAvailable});
    return psd;
  }

  psd.string_data_.insert(
      {Fields::kSafeBrowsingState,
       SafeBrowsingStateToString(
           safe_browsing::GetSafeBrowsingState(*profile->GetPrefs()))});

  psd.bits_data_.insert({Fields::kPartialViewEnabled,
                         profile->GetPrefs()->GetBoolean(
                             prefs::kDownloadBubblePartialViewEnabled)});

  // URL and filename logged only for Safe Browsing users.
  if (safe_browsing::IsSafeBrowsingEnabled(*profile->GetPrefs())) {
    psd.string_data_.insert({Fields::kUrlDownload,
                             download_item->GetURL().possibly_invalid_spec()});
    psd.string_data_.insert(
        {Fields::kUrlReferrer,
         download_item->GetReferrerUrl().possibly_invalid_spec()});
    psd.string_data_.insert(
        {Fields::kFilename,
         base::UTF16ToUTF8(
             download_item->GetFileNameToReportUser().LossyDisplayName())});
  } else {
    psd.string_data_.insert({Fields::kUrlDownload, kNotLoggedNoSafeBrowsing});
    psd.string_data_.insert({Fields::kUrlReferrer, kNotLoggedNoSafeBrowsing});
    psd.string_data_.insert({Fields::kFilename, kNotLoggedNoSafeBrowsing});
  }

  // Interaction details logged only for ESB users.
  std::optional<DownloadItemWarningData::WarningSurface>
      warning_first_shown_surface =
          DownloadItemWarningData::WarningFirstShownSurface(download_item);
  if (warning_first_shown_surface &&
      safe_browsing::IsEnhancedProtectionEnabled(*profile->GetPrefs())) {
    std::vector<DownloadItemWarningData::WarningActionEvent>
        warning_action_events =
            DownloadItemWarningData::GetWarningActionEvents(download_item);
    psd.string_data_.insert(
        {Fields::kWarningInteractions,
         SerializeWarningActionEvents(*warning_first_shown_surface,
                                      warning_action_events)});
  } else {
    psd.string_data_.insert(
        {Fields::kWarningInteractions, kNotLoggedNoEnhancedProtection});
  }

  return psd;
}

void DownloadWarningHatsProductSpecificData::AddNumPageWarnings(int num) {
  if (IsDownloadsPageTrigger(survey_type_)) {
    string_data_.insert_or_assign(Fields::kNumPageWarnings,
                                  base::NumberToString(num));
  }
}

void DownloadWarningHatsProductSpecificData::AddPartialViewInteraction(
    bool partial_view_interaction) {
  if (IsDownloadBubbleTrigger(survey_type_)) {
    bits_data_.insert_or_assign(Fields::kPartialViewInteraction,
                                partial_view_interaction);
  }
}

// static
std::vector<std::string>
DownloadWarningHatsProductSpecificData::GetBitsDataFields(
    DownloadWarningHatsType survey_type) {
  std::vector<std::string> fields = {Fields::kPartialViewEnabled,
                                     Fields::kUserGesture};
  if (IsDownloadBubbleTrigger(survey_type)) {
    fields.push_back(Fields::kPartialViewInteraction);
  }
  return fields;
}

// static
std::vector<std::string>
DownloadWarningHatsProductSpecificData::GetStringDataFields(
    DownloadWarningHatsType survey_type) {
  std::vector<std::string> fields = {
      Fields::kOutcome,
      Fields::kSurface,
      Fields::kDangerType,
      Fields::kWarningType,
      Fields::kSafeBrowsingState,
      Fields::kChannel,
      Fields::kWarningInteractions,
      Fields::kSecondsSinceDownloadStarted,
      Fields::kSecondsSinceWarningShown,
      Fields::kUrlDownload,
      Fields::kUrlReferrer,
      Fields::kFilename,
      // TODO(chlily): Add kIgnoreTimeout.
  };
  if (IsDownloadsPageTrigger(survey_type)) {
    fields.push_back(Fields::kNumPageWarnings);
  }
  if (survey_type == DownloadWarningHatsType::kDownloadBubbleIgnore) {
    fields.push_back(Fields::kIgnoreTimeoutSeconds);
  }
  return fields;
}

DelayedDownloadWarningHatsLauncher::Task::Task(
    DelayedDownloadWarningHatsLauncher& hats_launcher,
    download::DownloadItem* download,
    base::OnceClosure task,
    base::TimeDelta delay)
    : observation_(&hats_launcher), task_(std::move(task)) {
  observation_.Observe(download);
  base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
      FROM_HERE, base::BindOnce(&Task::RunTask, weak_factory_.GetWeakPtr()),
      delay);
}

DelayedDownloadWarningHatsLauncher::Task::~Task() = default;

// It is expected that the caller will delete this after this executes.
void DelayedDownloadWarningHatsLauncher::Task::RunTask() {
  CHECK(task_);
  std::move(task_).Run();
}

DelayedDownloadWarningHatsLauncher::DelayedDownloadWarningHatsLauncher(
    Profile* profile,
    base::TimeDelta delay,
    PsdCompleter psd_completer)
    : profile_(profile),
      delay_(delay),
      psd_completer_(std::move(psd_completer)) {}

DelayedDownloadWarningHatsLauncher::~DelayedDownloadWarningHatsLauncher() =
    default;

void DelayedDownloadWarningHatsLauncher::OnDownloadUpdated(
    download::DownloadItem* download) {
  // If the formerly-eligible download is no longer eligible, cancel the survey.
  if (!CanShowDownloadWarningHatsSurvey(download)) {
    RemoveTaskIfAny(download);
  }
}

void DelayedDownloadWarningHatsLauncher::OnDownloadDestroyed(
    download::DownloadItem* download) {
  RemoveTaskIfAny(download);
}

void DelayedDownloadWarningHatsLauncher::RecordBrowserActivity() {
  last_activity_ = base::Time::Now();
}

bool DelayedDownloadWarningHatsLauncher::TryScheduleTask(
    DownloadWarningHatsType survey_type,
    download::DownloadItem* download) {
  CHECK(download);
  TaskKey key = GetTaskKey(download);
  if (base::Contains(tasks_, key)) {
    return false;
  }

  if (!CanShowDownloadWarningHatsSurvey(download)) {
    return false;
  }

  auto [_, inserted] = tasks_.try_emplace(
      key, *this, download,
      // Unretained is safe because `this` outlives the Task object.
      // `download` will be valid for as long as the Task lives, because the
      // Observer mechanism will delete the Task if `download` goes away.
      base::BindOnce(&DelayedDownloadWarningHatsLauncher::MaybeLaunchSurveyNow,
                     base::Unretained(this), survey_type, download),
      delay_);
  return inserted;
}

void DelayedDownloadWarningHatsLauncher::RemoveTaskIfAny(
    download::DownloadItem* download) {
  RemoveTaskByKeyIfAny(GetTaskKey(download));
}

DelayedDownloadWarningHatsLauncher::TaskKey
DelayedDownloadWarningHatsLauncher::GetTaskKey(
    download::DownloadItem* download) {
  return reinterpret_cast<TaskKey>(download);
}

void DelayedDownloadWarningHatsLauncher::RemoveTaskByKeyIfAny(TaskKey key) {
  tasks_.erase(key);
}

void DelayedDownloadWarningHatsLauncher::MaybeLaunchSurveyNow(
    DownloadWarningHatsType survey_type,
    download::DownloadItem* download) {
  if (!CanShowDownloadWarningHatsSurvey(download) || !WasUserActive()) {
    RemoveTaskIfAny(download);
    return;
  }

  auto psd =
      DownloadWarningHatsProductSpecificData::Create(survey_type, download);
  if (psd_completer_) {
    psd_completer_.Run(psd);
  }

  MaybeLaunchDownloadWarningHatsSurvey(profile_, psd,
                                       MakeSurveyDoneCallback(download),
                                       MakeSurveyDoneCallback(download));
}

base::OnceClosure DelayedDownloadWarningHatsLauncher::MakeSurveyDoneCallback(
    download::DownloadItem* download) {
  // This is needed to clean up the Task object after the survey runs. It must
  // be bound to a WeakPtr because nothing guarantees that this will be alive
  // when the survey task finishes (it generally takes a few seconds to actually
  // show the survey, and obviously takes much longer for the user to work
  // through the survey). If this callback runs, then `this` must still be
  // alive, which means the DownloadItem::Observer mechanism is maintaining the
  // invariant that any download with an entry in `tasks_` must be alive.
  // Therefore, the DownloadItem* will not be used after it is freed.
  return base::BindOnce(
      &DelayedDownloadWarningHatsLauncher::RemoveTaskByKeyIfAny,
      weak_factory_.GetWeakPtr(), GetTaskKey(download));
}

bool DelayedDownloadWarningHatsLauncher::WasUserActive() const {
  return base::Time::Now() - last_activity_ <= delay_;
}

bool CanShowDownloadWarningHatsSurvey(download::DownloadItem* download) {
  CHECK(download);
  return download->IsDangerous() && !download->IsDone();
}

std::optional<std::string> MaybeGetDownloadWarningHatsTrigger(
    DownloadWarningHatsType survey_type) {
  if (!base::FeatureList::IsEnabled(safe_browsing::kDownloadWarningSurvey)) {
    return std::nullopt;
  }

  const int eligible_survey_type =
      safe_browsing::kDownloadWarningSurveyType.Get();

  // Configuration error.
  if (eligible_survey_type < 0 ||
      eligible_survey_type >
          static_cast<int>(DownloadWarningHatsType::kMaxValue)) {
    return std::nullopt;
  }

  // User is not assigned to be eligible for this type.
  if (static_cast<DownloadWarningHatsType>(eligible_survey_type) !=
      survey_type) {
    return std::nullopt;
  }

  switch (survey_type) {
    case DownloadWarningHatsType::kDownloadBubbleBypass:
      return kHatsSurveyTriggerDownloadWarningBubbleBypass;
    case DownloadWarningHatsType::kDownloadBubbleHeed:
      return kHatsSurveyTriggerDownloadWarningBubbleHeed;
    case DownloadWarningHatsType::kDownloadBubbleIgnore:
      return kHatsSurveyTriggerDownloadWarningBubbleIgnore;
    case DownloadWarningHatsType::kDownloadsPageBypass:
      return kHatsSurveyTriggerDownloadWarningPageBypass;
    case DownloadWarningHatsType::kDownloadsPageHeed:
      return kHatsSurveyTriggerDownloadWarningPageHeed;
    case DownloadWarningHatsType::kDownloadsPageIgnore:
      return kHatsSurveyTriggerDownloadWarningPageIgnore;
  }
}

base::TimeDelta GetIgnoreDownloadBubbleWarningDelay() {
  return base::Seconds(
      safe_browsing::kDownloadWarningSurveyIgnoreDelaySeconds.Get());
}

void MaybeLaunchDownloadWarningHatsSurvey(
    Profile* profile,
    const DownloadWarningHatsProductSpecificData& psd,
    base::OnceClosure success_callback,
    base::OnceClosure failure_callback) {
  std::optional<std::string> trigger =
      MaybeGetDownloadWarningHatsTrigger(psd.survey_type());
  if (!trigger) {
    return;
  }

  HatsService* hats_service =
      HatsServiceFactory::GetForProfile(profile, /*create_if_necessary=*/true);
  if (hats_service) {
    hats_service->LaunchSurvey(*trigger, std::move(success_callback),
                               std::move(failure_callback), psd.bits_data(),
                               psd.string_data());
  }
}