File: privacy_sandbox_prompt_helper.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 (290 lines) | stat: -rw-r--r-- 12,309 bytes parent folder | download | duplicates (2)
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
// 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/privacy_sandbox/privacy_sandbox_prompt_helper.h"

#include "base/hash/hash.h"
#include "base/metrics/histogram_functions.h"
#include "chrome/browser/privacy_sandbox/notice/desktop_entrypoint_handlers_helper.h"
#include "chrome/browser/privacy_sandbox/privacy_sandbox_queue_manager.h"
#include "chrome/browser/privacy_sandbox/privacy_sandbox_service.h"
#include "chrome/browser/privacy_sandbox/privacy_sandbox_service_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search/search.h"
#include "chrome/browser/search_engine_choice/search_engine_choice_dialog_service.h"
#include "chrome/browser/search_engine_choice/search_engine_choice_dialog_service_factory.h"
#include "chrome/browser/sync/sync_service_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/privacy_sandbox/privacy_sandbox_prompt.h"
#include "chrome/browser/ui/profiles/profile_customization_bubble_sync_controller.h"
#include "chrome/common/extensions/chrome_manifest_url_handlers.h"
#include "chrome/common/webui_url_constants.h"
#include "components/privacy_sandbox/privacy_sandbox_features.h"
#include "components/sync/service/sync_service.h"
#include "components/web_modal/web_contents_modal_dialog_host.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/url_constants.h"
#include "extensions/browser/extension_registry.h"

namespace {
constexpr char kPrivacySandboxPromptHelperEventHistogram[] =
    "Settings.PrivacySandbox.PromptHelperEvent2";
constexpr int kMinRequiredDialogHeight = 100;

// Gets the type of prompt that should be displayed for |profile|, this includes
// the possibility of no prompt being required.
PrivacySandboxService::PromptType GetRequiredPromptType(Profile* profile) {
  if (!profile || !profile->IsRegularProfile()) {
    return PrivacySandboxService::PromptType::kNone;
  }

  auto* privacy_sandbox_service =
      PrivacySandboxServiceFactory::GetForProfile(profile);
  if (!privacy_sandbox_service) {
    return PrivacySandboxService::PromptType::kNone;
  }

  return privacy_sandbox_service->GetRequiredPromptType(
      PrivacySandboxService::SurfaceType::kDesktop);
}

#if BUILDFLAG(IS_CHROMEOS)
bool HasExtensionNtpOverride(
    extensions::ExtensionRegistry* extension_registry) {
  for (const auto& extension : extension_registry->enabled_extensions()) {
    const auto& overrides =
        extensions::URLOverrides::GetChromeURLOverrides(extension.get());
    if (overrides.find(chrome::kChromeUINewTabHost) != overrides.end()) {
      return true;
    }
  }
  return false;
}

// Returns whether |url| is an NTP controlled entirely by Chrome.
bool IsChromeControlledNtpUrl(const GURL& url) {
  // Convert to origins for comparison, as any appended paths are irrelevant.
  const auto ntp_origin = url::Origin::Create(url);

  return ntp_origin ==
             url::Origin::Create(GURL(chrome::kChromeUINewTabPageURL)) ||
         ntp_origin == url::Origin::Create(
                           GURL(chrome::kChromeUINewTabPageThirdPartyURL));
}
#endif  // BUILDFLAG(IS_CHROMEOS)

}  // namespace

PrivacySandboxPromptHelper::~PrivacySandboxPromptHelper() = default;

PrivacySandboxPromptHelper::PrivacySandboxPromptHelper(
    content::WebContents* web_contents)
    : WebContentsObserver(web_contents),
      content::WebContentsUserData<PrivacySandboxPromptHelper>(*web_contents) {
  base::UmaHistogramEnumeration(
      kPrivacySandboxPromptHelperEventHistogram,
      SettingsPrivacySandboxPromptHelperEvent::kCreated);
}

void PrivacySandboxPromptHelper::DidFinishNavigation(
    content::NavigationHandle* navigation_handle) {
  if (!ProfileRequiresPrompt(profile())) {
    base::UmaHistogramEnumeration(
        kPrivacySandboxPromptHelperEventHistogram,
        SettingsPrivacySandboxPromptHelperEvent::kPromptNotRequired);
    return;
  }

  // Only valid top frame navigations are considered.
  if (!navigation_handle || !navigation_handle->HasCommitted() ||
      !navigation_handle->IsInPrimaryMainFrame() ||
      navigation_handle->IsSameDocument()) {
    base::UmaHistogramEnumeration(
        kPrivacySandboxPromptHelperEventHistogram,
        SettingsPrivacySandboxPromptHelperEvent::kNonTopFrameNavigation);
    return;
  }

#if BUILDFLAG(IS_CHROMEOS)
  // TODO(crbug.com/1315580, crbug.com/1315579): When navigating to a NTP that
  // isn't Chrome-controlled on ChromeOS, open an about blank tab to display the
  // prompt. On other platforms, it's being handled during the startup.
  if (web_contents()->GetLastCommittedURL() == chrome::kChromeUINewTabURL) {
    const bool has_extention_override =
        HasExtensionNtpOverride(extensions::ExtensionRegistry::Get(profile()));

    const GURL new_tab_page = search::GetNewTabPageURL(profile());
    const bool is_non_chrome_controlled_ntp =
        navigation_handle->GetURL() == new_tab_page &&
        !IsChromeControlledNtpUrl(new_tab_page);

    if (has_extention_override || is_non_chrome_controlled_ntp) {
      web_contents()->OpenURL(
          content::OpenURLParams(GURL(url::kAboutBlankURL), content::Referrer(),
                                 WindowOpenDisposition::NEW_FOREGROUND_TAB,
                                 ui::PAGE_TRANSITION_AUTO_TOPLEVEL,
                                 /*is_renderer_initiated=*/false),
          /*navigation_handle_callback=*/{});
      base::UmaHistogramEnumeration(
          kPrivacySandboxPromptHelperEventHistogram,
          SettingsPrivacySandboxPromptHelperEvent::kAboutBlankOpened);
      return;
    }
  }
#endif  // BUILDFLAG(IS_CHROMEOS)

  // Check whether the navigation target is a suitable prompt location. The
  // navigation URL, rather than the visible or committed URL, is required to
  // distinguish between different types of NTPs.
  if (!privacy_sandbox::IsUrlSuitableForPrompt(navigation_handle->GetURL())) {
    base::UmaHistogramEnumeration(
        kPrivacySandboxPromptHelperEventHistogram,
        SettingsPrivacySandboxPromptHelperEvent::kUrlNotSuitable);
    return;
  }

  // If a Sync setup is in progress, the prompt should not be shown.
  if (auto* sync_service = SyncServiceFactory::GetForProfile(profile())) {
    if (sync_service->IsSetupInProgress()) {
      base::UmaHistogramEnumeration(
          kPrivacySandboxPromptHelperEventHistogram,
          SettingsPrivacySandboxPromptHelperEvent::kSyncSetupInProgress);
      return;
    }
  }

  auto* browser =
      chrome::FindBrowserWithTab(navigation_handle->GetWebContents());

  // If a sign-in dialog is being currently displayed or is about to be
  // displayed, the prompt should not be shown to avoid conflict.
  // TODO(crbug.com/370806609): When we add sign in notice to queue, put this
  // behind flag / remove.
  bool signin_dialog_showing =
      browser->signin_view_controller()->ShowsModalDialog();
#if !BUILDFLAG(IS_CHROMEOS)
  signin_dialog_showing =
      signin_dialog_showing ||
      IsProfileCustomizationBubbleSyncControllerRunning(browser);
#endif  // !BUILDFLAG(IS_CHROMEOS)
  if (signin_dialog_showing) {
    base::UmaHistogramEnumeration(
        kPrivacySandboxPromptHelperEventHistogram,
        SettingsPrivacySandboxPromptHelperEvent::kSigninDialogShown);
    return;
  }

  // If a Privacy Sandbox prompt already exists for this browser, do not attempt
  // to open another one.
  if (auto* privacy_sandbox_service =
          PrivacySandboxServiceFactory::GetForProfile(profile())) {
    if (privacy_sandbox_service->IsPromptOpenForBrowser(browser)) {
      base::UmaHistogramEnumeration(kPrivacySandboxPromptHelperEventHistogram,
                                    SettingsPrivacySandboxPromptHelperEvent::
                                        kPromptAlreadyExistsForBrowser);
      return;
    }
  }

  // The PrivacySandbox prompt can always fit inside a normal tabbed window due
  // to its minimum width, so checking the height is enough here. Other non
  // normal tabbed browsers will be exlcuded in a later check.
  const bool is_window_height_too_small =
      browser->window()
          ->GetWebContentsModalDialogHost()
          ->GetMaximumDialogSize()
          .height() < kMinRequiredDialogHeight;
  // If the windows height is too small, it is difficult to read or interact
  // with the dialog. The dialog is blocking modal, that is why we want to
  // prevent it from showing if there isn't enough space.
  if (is_window_height_too_small) {
    base::UmaHistogramEnumeration(
        kPrivacySandboxPromptHelperEventHistogram,
        SettingsPrivacySandboxPromptHelperEvent::kWindowTooSmall);
    return;
  }

  // Avoid showing the prompt on popups, pip, anything that isn't a normal
  // browser.
  if (browser->type() != Browser::TYPE_NORMAL) {
    base::UmaHistogramEnumeration(
        kPrivacySandboxPromptHelperEventHistogram,
        SettingsPrivacySandboxPromptHelperEvent::kNonNormalBrowser);
    return;
  }

  // If the handle is not being held, do not attempt to show the prompt.
  // We want to check this constraint at the very end for histogram emitting
  // reasons.
  if (auto* privacy_sandbox_service =
          PrivacySandboxServiceFactory::GetForProfile(profile())) {
    privacy_sandbox::PrivacySandboxQueueManager& queue_manager =
        privacy_sandbox_service->GetPrivacySandboxNoticeQueueManager();
    if (base::FeatureList::IsEnabled(
            privacy_sandbox::kPrivacySandboxNoticeQueue) &&
        !queue_manager.IsHoldingHandle()) {
      queue_manager.MaybeEmitQueueStateMetrics();
      return;
    }
  }

  // Record the URL that the prompt was displayed over.
  uint32_t host_hash = base::Hash(navigation_handle->GetURL().IsAboutBlank()
                                      ? "about:blank"
                                      : navigation_handle->GetURL().host());
  base::UmaHistogramSparse(
      "Settings.PrivacySandbox.DialogDisplayHost",
      static_cast<base::HistogramBase::Sample32>(host_hash));

  browser->tab_strip_model()->ActivateTabAt(
      browser->tab_strip_model()->GetIndexOfWebContents(
          navigation_handle->GetWebContents()));

  PrivacySandboxDialog::Show(browser, GetRequiredPromptType(profile()));
  base::UmaHistogramEnumeration(
      kPrivacySandboxPromptHelperEventHistogram,
      SettingsPrivacySandboxPromptHelperEvent::kPromptShown);
}

// static
bool PrivacySandboxPromptHelper::ProfileRequiresPrompt(Profile* profile) {
  bool eligible = GetRequiredPromptType(profile) !=
                  PrivacySandboxService::PromptType::kNone;

  // TODO(crbug.com/370804492): When we add DMA notice to queue, put this behind
  // flag / remove.
  SearchEngineChoiceDialogService* search_engine_choice_dialog_service =
      SearchEngineChoiceDialogServiceFactory::GetForProfile(profile);
  if (search_engine_choice_dialog_service &&
      search_engine_choice_dialog_service->CanSuppressPrivacySandboxPromo()) {
    base::UmaHistogramEnumeration(kPrivacySandboxPromptHelperEventHistogram,
                                  SettingsPrivacySandboxPromptHelperEvent::
                                      kSearchEngineChoiceDialogShown);
    eligible = false;
  }

  if (auto* privacy_sandbox_service =
          PrivacySandboxServiceFactory::GetForProfile(profile)) {
    privacy_sandbox::PrivacySandboxQueueManager& queue_manager =
        privacy_sandbox_service->GetPrivacySandboxNoticeQueueManager();
    // When checking profile eligibility also update the queue.
    // Case 1: Profile is eligible, but not in the queue. Add to queue.
    // Case 2: Profile is ineligible, but we are queued, so we must unqueue. OR
    //         We are holding the handle, so we must release the handle and
    //         prevent showing.
    eligible ? queue_manager.MaybeQueueNotice()
             : queue_manager.MaybeUnqueueNotice();
  }

  return eligible;
}

Profile* PrivacySandboxPromptHelper::profile() {
  return Profile::FromBrowserContext(web_contents()->GetBrowserContext());
}

WEB_CONTENTS_USER_DATA_KEY_IMPL(PrivacySandboxPromptHelper);