File: notification_permission_browsertest.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 (377 lines) | stat: -rw-r--r-- 16,241 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
// 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/chrome_content_browser_client.h"
#include "chrome/browser/notifications/non_persistent_notification_handler.h"
#include "chrome/browser/notifications/notification_permission_context.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/permissions/permission_request_manager.h"
#include "components/permissions/permission_util.h"
#include "components/permissions/request_type.h"
#include "components/permissions/test/mock_permission_prompt_factory.h"
#include "components/permissions/test/mock_permission_request.h"
#include "components/ukm/test_ukm_recorder.h"
#include "content/public/common/content_client.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/content_mock_cert_verifier.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
#include "services/metrics/public/cpp/ukm_builders.h"

namespace {

using Permission = ukm::builders::Permission;

const char kTestFilePath[] =
    "/notifications/notification_permission_checker.html";
const char kTesterHost[] = "notification.com";
const char kIsolatedEmbedderHost[] = "isolated.com";
const char kEmbedderHost[] = "normal.com";

// A ChromeContentBrowserClient that returns a non-default
// StoragePartitionConfig for the given Origin.
class StoragePartitioningChromeContentBrowserClient
    : public ChromeContentBrowserClient {
 public:
  explicit StoragePartitioningChromeContentBrowserClient(
      const std::string& partitioned_host)
      : partitioned_host_(partitioned_host) {}

  ~StoragePartitioningChromeContentBrowserClient() override = default;

  content::StoragePartitionConfig GetStoragePartitionConfigForSite(
      content::BrowserContext* browser_context,
      const GURL& site) override {
    if (site.host() == partitioned_host_) {
      return content::StoragePartitionConfig::Create(
          browser_context, partitioned_host_, /*partition_name=*/"",
          /*in_memory=*/false);
    }
    return ChromeContentBrowserClient::GetStoragePartitionConfigForSite(
        browser_context, site);
  }

 private:
  std::string partitioned_host_;
};

}  // namespace

class NotificationPermissionBrowserTest : public InProcessBrowserTest {
 public:
  NotificationPermissionBrowserTest()
      : partitioning_client_(kIsolatedEmbedderHost) {}

  NotificationPermissionBrowserTest(const NotificationPermissionBrowserTest&) =
      delete;
  NotificationPermissionBrowserTest& operator=(
      const NotificationPermissionBrowserTest&) = delete;
  ~NotificationPermissionBrowserTest() override {
    CHECK_EQ(&partitioning_client_,
             SetBrowserClientForTesting(original_client_));
  }

  void SetUpOnMainThread() override {
    host_resolver()->AddRule("*", "127.0.0.1");
    mock_cert_verifier_.mock_cert_verifier()->set_default_result(net::OK);

    https_server_ = std::make_unique<net::EmbeddedTestServer>(
        net::EmbeddedTestServer::TYPE_HTTPS);
    https_server_->ServeFilesFromSourceDirectory(server_root_);
    EXPECT_TRUE(https_server_->Start());

    original_client_ = SetBrowserClientForTesting(&partitioning_client_);
  }

  void SetUpCommandLine(base::CommandLine* command_line) override {
    mock_cert_verifier_.SetUpCommandLine(command_line);
  }

  void SetUpInProcessBrowserTestFixture() override {
    mock_cert_verifier_.SetUpInProcessBrowserTestFixture();
  }

  void TearDownInProcessBrowserTestFixture() override {
    mock_cert_verifier_.TearDownInProcessBrowserTestFixture();
  }

 protected:
  void GrantNotificationPermissionForTest(const GURL& url) const {
    NotificationPermissionContext::UpdatePermission(
        browser()->profile(), url.DeprecatedGetOriginAsURL(),
        CONTENT_SETTING_ALLOW);
  }

  GURL TesterUrl() const {
    return https_server_->GetURL(kTesterHost, kTestFilePath);
  }

  GURL IsolatedEmbedderUrl() const {
    return https_server_->GetURL(kIsolatedEmbedderHost, kTestFilePath);
  }

  GURL EmbedderUrl() const {
    return https_server_->GetURL(kEmbedderHost, kTestFilePath);
  }

  content::WebContents* GetActiveWebContents() const {
    return browser()->tab_strip_model()->GetActiveWebContents();
  }

  content::RenderFrameHost* CreateChildIframe(
      content::RenderFrameHost* parent_rfh,
      const GURL& iframe_src) {
    // For now assume this is the only child iframe.
    EXPECT_FALSE(ChildFrameAt(parent_rfh, 0));

    EXPECT_EQ("iframe loaded",
              EvalJs(parent_rfh, content::JsReplace(R"(
                new Promise((resolve, reject) => {
                  const iframe = document.createElement('iframe');
                  iframe.id = 'child_iframe';
                  iframe.src = $1;
                  iframe.onload = _ => { resolve('iframe loaded') };
                  iframe.onerror = e => { reject(e) };
                  document.body.appendChild(iframe);
                }))",
                                                    iframe_src)));

    content::RenderFrameHost* iframe = ChildFrameAt(parent_rfh, 0);
    EXPECT_TRUE(iframe);
    EXPECT_EQ(iframe_src, iframe->GetLastCommittedURL());
    return iframe;
  }

 private:
  const base::FilePath server_root_{FILE_PATH_LITERAL("chrome/test/data")};
  std::unique_ptr<net::EmbeddedTestServer> https_server_;
  content::ContentMockCertVerifier mock_cert_verifier_;

  raw_ptr<content::ContentBrowserClient> original_client_ = nullptr;
  StoragePartitioningChromeContentBrowserClient partitioning_client_;
};

// Tests that undelegated permissions which have their default/prompt value on
// an origin are automatically denied in documents from that origin when
// loaded as a cross-origin iframe.
IN_PROC_BROWSER_TEST_F(NotificationPermissionBrowserTest,
                       UndelegatedPermissionDeniedIfNotGrantedToOrigin) {
  EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), TesterUrl()));
  content::RenderFrameHost* main_frame =
      GetActiveWebContents()->GetPrimaryMainFrame();
  EXPECT_EQ("default", EvalJs(main_frame, "getNotificationPermission()"));
  EXPECT_EQ("denied",
            EvalJs(main_frame, "getServiceWorkerNotificationPermission()"));

  EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), EmbedderUrl()));
  main_frame = GetActiveWebContents()->GetPrimaryMainFrame();
  EXPECT_EQ("default", EvalJs(main_frame, "getNotificationPermission()"));

  content::RenderFrameHost* iframe = CreateChildIframe(main_frame, TesterUrl());
  EXPECT_EQ("denied", EvalJs(iframe, "getNotificationPermission()"));
  EXPECT_EQ("denied",
            EvalJs(iframe, "getServiceWorkerNotificationPermission()"));
  EXPECT_EQ("denied", EvalJs(iframe, "getPushPermission()"));
  // TODO(crbug.com/40254041): This should return 'denied'.
  EXPECT_EQ("prompt", EvalJs(iframe, "getServiceWorkerPushPermission()"));
}

// Tests that undelegated permissions aren't delegated to an embedded frame
// as other permissions are. If 'example.com' was granted notification
// permissions by the user when it was a top-level frame, then it retains that
// permission when iframed in another page, regardless of the other page's
// permission status.
IN_PROC_BROWSER_TEST_F(NotificationPermissionBrowserTest,
                       UndelegatedPermissionsAreNotDelegated) {
  GrantNotificationPermissionForTest(TesterUrl());

  EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), TesterUrl()));
  content::RenderFrameHost* main_frame =
      GetActiveWebContents()->GetPrimaryMainFrame();
  EXPECT_EQ("granted", EvalJs(main_frame, "getNotificationPermission()"));
  EXPECT_EQ("granted",
            EvalJs(main_frame, "getServiceWorkerNotificationPermission()"));

  EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), EmbedderUrl()));
  main_frame = GetActiveWebContents()->GetPrimaryMainFrame();
  EXPECT_EQ("default", EvalJs(main_frame, "getNotificationPermission()"));
  EXPECT_EQ("denied",
            EvalJs(main_frame, "getServiceWorkerNotificationPermission()"));
  EXPECT_EQ("prompt", EvalJs(main_frame, "getPushPermission()"));
  // TODO(crbug.com/40254041): This should return 'denied'.
  EXPECT_EQ("prompt", EvalJs(main_frame, "getServiceWorkerPushPermission()"));

  content::RenderFrameHost* iframe = CreateChildIframe(main_frame, TesterUrl());
  EXPECT_EQ("granted", EvalJs(iframe, "getNotificationPermission()"));
  EXPECT_EQ("granted",
            EvalJs(iframe, "getServiceWorkerNotificationPermission()"));
  EXPECT_EQ("granted", EvalJs(iframe, "getPushPermission()"));
  EXPECT_EQ("granted", EvalJs(iframe, "getServiceWorkerPushPermission()"));
}

// Tests that iframes not using their normal StoragePartition don't have
// notification permission, even if they would have permission outside of an
// isolated app.
IN_PROC_BROWSER_TEST_F(NotificationPermissionBrowserTest,
                       IframesInNonDefaultPartitionDontGetPermission) {
  GrantNotificationPermissionForTest(TesterUrl());

  // Verify that TesterUrl() has notification/push permission.
  EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), TesterUrl()));
  content::RenderFrameHost* main_frame =
      GetActiveWebContents()->GetPrimaryMainFrame();
  EXPECT_EQ("granted", EvalJs(main_frame, "getNotificationPermission()"));
  EXPECT_EQ("granted",
            EvalJs(main_frame, "getServiceWorkerNotificationPermission()"));
  EXPECT_EQ("granted", EvalJs(main_frame, "queryNotificationPermission()"));
  EXPECT_EQ("granted",
            EvalJs(main_frame, "queryServiceWorkerNotificationPermission()"));
  EXPECT_EQ("granted", EvalJs(main_frame, "getPushPermission()"));
  EXPECT_EQ("granted", EvalJs(main_frame, "getServiceWorkerPushPermission()"));

  // Load a site that uses a dedicated StoragePartition and verify that it has
  // default notification/push permissions.
  EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), IsolatedEmbedderUrl()));
  main_frame = GetActiveWebContents()->GetPrimaryMainFrame();
  EXPECT_EQ("default", EvalJs(main_frame, "getNotificationPermission()"));
  EXPECT_EQ("denied",
            EvalJs(main_frame, "getServiceWorkerNotificationPermission()"));
  EXPECT_EQ("prompt", EvalJs(main_frame, "queryNotificationPermission()"));
  EXPECT_EQ("prompt",
            EvalJs(main_frame, "queryServiceWorkerNotificationPermission()"));
  EXPECT_EQ("prompt", EvalJs(main_frame, "getPushPermission()"));
  EXPECT_EQ("prompt", EvalJs(main_frame, "getServiceWorkerPushPermission()"));

  // Load TesterUrl() in an iframe inside the dedicated StoragePartition page.
  // Even though TesterUrl() has notification/push permission when in a main
  // frame, it shouldn't when it's embedded in a different StoragePartition.
  content::RenderFrameHost* iframe = CreateChildIframe(main_frame, TesterUrl());
  EXPECT_EQ("denied", EvalJs(iframe, "getNotificationPermission()"));
  EXPECT_EQ("denied",
            EvalJs(iframe, "getServiceWorkerNotificationPermission()"));
  EXPECT_EQ("denied", EvalJs(iframe, "queryNotificationPermission()"));
  EXPECT_EQ("denied",
            EvalJs(iframe, "queryServiceWorkerNotificationPermission()"));
  EXPECT_EQ("denied", EvalJs(iframe, "requestNotificationPermission()"));
  EXPECT_EQ("denied", EvalJs(iframe, "getPushPermission()"));
  EXPECT_EQ("denied", EvalJs(iframe, "getServiceWorkerPushPermission()"));
  EXPECT_EQ(
      "a JavaScript error: \"NotAllowedError: "
      "Registration failed - permission denied\"\n",
      EvalJs(iframe, "requestPushPermission()").error);
}

// Test that the Notifications.NonPersistentNotificationThirdPartyCount metric
// triggers in third-party contexts. Note: This test doesn't exactly fit with
// the others in this class, but the helper methods here are exactly what we
// needed and this test will be removed once the metric is removed.
IN_PROC_BROWSER_TEST_F(NotificationPermissionBrowserTest,
                       NonPersistentNotificationThirdPartyCountMetricTest) {
  GrantNotificationPermissionForTest(TesterUrl());

  EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), TesterUrl()));
  content::RenderFrameHost* main_frame =
      GetActiveWebContents()->GetPrimaryMainFrame();

  base::HistogramTester histogram_tester;
  const std::string histogram_name =
      "Notifications.NonPersistentNotificationThirdPartyCount";

  const std::string show_notification_js = R"(new Promise((resolve) => {
     const notification = new Notification("done");
     notification.onshow = () => {
       const title = notification.title;
       notification.close();
       resolve(title);
     };
   });)";

  EXPECT_EQ("done", EvalJs(main_frame, show_notification_js));

  histogram_tester.ExpectBucketCount(histogram_name, false, 1);
  histogram_tester.ExpectBucketCount(histogram_name, true, 0);

  content::RenderFrameHost* iframe = CreateChildIframe(main_frame, TesterUrl());

  EXPECT_EQ("done", EvalJs(iframe, show_notification_js));

  histogram_tester.ExpectBucketCount(histogram_name, false, 2);
  histogram_tester.ExpectBucketCount(histogram_name, true, 0);

  EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), EmbedderUrl()));
  main_frame = GetActiveWebContents()->GetPrimaryMainFrame();
  iframe = CreateChildIframe(main_frame, TesterUrl());

  EXPECT_EQ("done", EvalJs(iframe, show_notification_js));

  histogram_tester.ExpectBucketCount(histogram_name, false, 2);
  histogram_tester.ExpectBucketCount(histogram_name, true, 1);
}

// Tests that non-persistent notifications (i.e. doesn't use
// the Push API) records PermissionUsage and Notification UKMs.
IN_PROC_BROWSER_TEST_F(NotificationPermissionBrowserTest,
                       NonPersistentNotificationRecordsUkms) {
  GrantNotificationPermissionForTest(TesterUrl());

  EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), TesterUrl()));
  content::RenderFrameHost* main_frame =
      GetActiveWebContents()->GetPrimaryMainFrame();

  ukm::TestAutoSetUkmRecorder ukm_recorder;

  const std::string show_notification_js = R"(new Promise((resolve) => {
     const notification = new Notification("done");
     notification.onshow = () => {
       const title = notification.title;
       notification.close();
       resolve(title);
     };
   });)";

  EXPECT_EQ("done", EvalJs(main_frame, show_notification_js));
  const auto usage_entries = ukm_recorder.GetEntriesByName("PermissionUsage");
  ASSERT_EQ(1u, usage_entries.size());
}

IN_PROC_BROWSER_TEST_F(NotificationPermissionBrowserTest,
                       DisablePermissionRecordsUkms) {
  ukm::TestAutoSetUkmRecorder ukm_recorder;

  auto* manager = permissions::PermissionRequestManager::FromWebContents(
      GetActiveWebContents());
  std::unique_ptr<permissions::MockPermissionPromptFactory> bubble_factory =
      std::make_unique<permissions::MockPermissionPromptFactory>(manager);
  EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), TesterUrl()));
  manager->AddRequest(GetActiveWebContents()->GetPrimaryMainFrame(),
                      std::make_unique<permissions::MockPermissionRequest>(
                          permissions::RequestType::kNotifications));
  bubble_factory->WaitForPermissionBubble();
  manager->Accept();

  GrantNotificationPermissionForTest(TesterUrl());

  std::unique_ptr<NotificationHandler> handler =
      std::make_unique<NonPersistentNotificationHandler>();
  handler->DisableNotifications(browser()->profile(), TesterUrl());

  const auto action_entries = ukm_recorder.GetEntriesByName("Permission");
  ASSERT_EQ(2u, action_entries.size());

  // The revocation event uses the notification source_id type
  EXPECT_EQ(ukm::SourceIdType::NOTIFICATION_ID,
            ukm::GetSourceIdType(action_entries[1]->source_id));

  // Expect one GRANT and one REVOKE event
  ukm_recorder.ExpectEntryMetric(
      action_entries[0], Permission::kActionName,
      static_cast<int>(permissions::PermissionAction::GRANTED));
  ukm_recorder.ExpectEntryMetric(
      action_entries[1], Permission::kActionName,
      static_cast<int>(permissions::PermissionAction::REVOKED));
}