Upload upstream chromium 114.0.5735.31
[platform/framework/web/chromium-efl.git] / components / permissions / permission_request_manager_unittest.cc
1 // Copyright 2014 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include <stddef.h>
6 #include <memory>
7 #include <string>
8
9 #include "base/command_line.h"
10 #include "base/functional/bind.h"
11 #include "base/memory/raw_ptr.h"
12 #include "base/run_loop.h"
13 #include "base/task/sequenced_task_runner.h"
14 #include "base/test/bind.h"
15 #include "base/test/metrics/histogram_tester.h"
16 #include "base/test/scoped_feature_list.h"
17 #include "build/build_config.h"
18 #include "components/permissions/features.h"
19 #include "components/permissions/permission_request.h"
20 #include "components/permissions/permission_request_manager.h"
21 #include "components/permissions/permission_ui_selector.h"
22 #include "components/permissions/permission_uma_util.h"
23 #include "components/permissions/request_type.h"
24 #include "components/permissions/test/mock_permission_prompt_factory.h"
25 #include "components/permissions/test/mock_permission_request.h"
26 #include "components/permissions/test/test_permissions_client.h"
27 #include "content/public/test/test_renderer_host.h"
28 #include "testing/gtest/include/gtest/gtest.h"
29 #include "third_party/abseil-cpp/absl/types/optional.h"
30
31 namespace permissions {
32
33 namespace {
34 using QuietUiReason = PermissionUiSelector::QuietUiReason;
35 }
36
37 class PermissionRequestManagerTest
38     : public content::RenderViewHostTestHarness,
39       public ::testing::WithParamInterface<bool> {
40  public:
41   PermissionRequestManagerTest()
42       : RenderViewHostTestHarness(
43             base::test::TaskEnvironment::TimeSource::MOCK_TIME),
44         request1_(RequestType::kGeolocation,
45                   PermissionRequestGestureType::GESTURE),
46         request2_(RequestType::kMultipleDownloads,
47                   PermissionRequestGestureType::NO_GESTURE),
48         request_mic_(RequestType::kMicStream,
49                      PermissionRequestGestureType::NO_GESTURE),
50         request_camera_(RequestType::kCameraStream,
51                         PermissionRequestGestureType::NO_GESTURE),
52 #if !BUILDFLAG(IS_ANDROID)
53         request_ptz_(RequestType::kCameraPanTiltZoom,
54                      PermissionRequestGestureType::NO_GESTURE),
55 #endif
56         iframe_request_same_domain_(GURL("https://www.google.com/some/url"),
57                                     RequestType::kMidiSysex),
58         iframe_request_other_domain_(GURL("https://www.youtube.com"),
59                                      RequestType::kGeolocation),
60         iframe_request_camera_other_domain_(GURL("https://www.youtube.com"),
61                                             RequestType::kStorageAccess),
62         iframe_request_mic_other_domain_(GURL("https://www.youtube.com"),
63                                          RequestType::kMicStream) {
64
65     if (GetParam()) {
66       feature_list_.InitWithFeatures(
67           {permissions::features::kPermissionChip},
68           {permissions::features::kPermissionQuietChip});
69     } else {
70       feature_list_.InitWithFeatures(
71           {}, {permissions::features::kPermissionChip,
72                permissions::features::kPermissionQuietChip});
73     }
74   }
75
76   void SetUp() override {
77     content::RenderViewHostTestHarness::SetUp();
78     SetContents(CreateTestWebContents());
79     NavigateAndCommit(GURL(permissions::MockPermissionRequest::kDefaultOrigin));
80
81     PermissionRequestManager::CreateForWebContents(web_contents());
82     manager_ = PermissionRequestManager::FromWebContents(web_contents());
83     manager_->set_enabled_app_level_notification_permission_for_testing(true);
84     prompt_factory_ = std::make_unique<MockPermissionPromptFactory>(manager_);
85   }
86
87   void TearDown() override {
88     prompt_factory_ = nullptr;
89     content::RenderViewHostTestHarness::TearDown();
90   }
91
92   void Accept() {
93     manager_->Accept();
94     task_environment()->RunUntilIdle();
95   }
96
97   void Deny() {
98     manager_->Deny();
99     task_environment()->RunUntilIdle();
100   }
101
102   void Closing() {
103     manager_->Dismiss();
104     task_environment()->RunUntilIdle();
105   }
106
107   void WaitForFrameLoad() {
108     // PermissionRequestManager ignores all parameters. Yay?
109     manager_->DOMContentLoaded(nullptr);
110     task_environment()->RunUntilIdle();
111   }
112
113   void WaitForBubbleToBeShown() {
114     manager_->DocumentOnLoadCompletedInPrimaryMainFrame();
115     task_environment()->RunUntilIdle();
116   }
117
118   void MockTabSwitchAway() {
119     manager_->OnVisibilityChanged(content::Visibility::HIDDEN);
120   }
121
122   void MockTabSwitchBack() {
123     manager_->OnVisibilityChanged(content::Visibility::VISIBLE);
124   }
125
126   virtual void NavigationEntryCommitted(
127       const content::LoadCommittedDetails& details) {
128     manager_->NavigationEntryCommitted(details);
129   }
130
131   std::unique_ptr<MockPermissionRequest> CreateAndAddRequest(
132       RequestType type,
133       bool should_be_seen,
134       int expected_request_count) {
135     std::unique_ptr<MockPermissionRequest> request =
136         std::make_unique<MockPermissionRequest>(
137             type, PermissionRequestGestureType::GESTURE);
138     manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), request.get());
139     WaitForBubbleToBeShown();
140     if (should_be_seen) {
141       EXPECT_TRUE(prompt_factory_->RequestTypeSeen(type));
142     } else {
143       EXPECT_FALSE(prompt_factory_->RequestTypeSeen(type));
144     }
145     EXPECT_EQ(prompt_factory_->TotalRequestCount(), expected_request_count);
146
147     return request;
148   }
149
150   void WaitAndAcceptPromptForRequest(MockPermissionRequest* request) {
151     WaitForBubbleToBeShown();
152
153     EXPECT_FALSE(request->finished());
154     EXPECT_TRUE(prompt_factory_->is_visible());
155     ASSERT_EQ(prompt_factory_->request_count(), 1);
156
157     Accept();
158     EXPECT_TRUE(request->granted());
159   }
160
161  protected:
162   MockPermissionRequest request1_;
163   MockPermissionRequest request2_;
164   MockPermissionRequest request_mic_;
165   MockPermissionRequest request_camera_;
166 #if !BUILDFLAG(IS_ANDROID)
167   MockPermissionRequest request_ptz_;
168 #endif
169   MockPermissionRequest iframe_request_same_domain_;
170   MockPermissionRequest iframe_request_other_domain_;
171   MockPermissionRequest iframe_request_camera_other_domain_;
172   MockPermissionRequest iframe_request_mic_other_domain_;
173   raw_ptr<PermissionRequestManager> manager_;
174   std::unique_ptr<MockPermissionPromptFactory> prompt_factory_;
175   TestPermissionsClient client_;
176   base::test::ScopedFeatureList feature_list_;
177 };
178
179 ////////////////////////////////////////////////////////////////////////////////
180 // General
181 ////////////////////////////////////////////////////////////////////////////////
182
183 TEST_P(PermissionRequestManagerTest, NoRequests) {
184   WaitForBubbleToBeShown();
185   EXPECT_FALSE(prompt_factory_->is_visible());
186 }
187
188 TEST_P(PermissionRequestManagerTest, SingleRequest) {
189   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
190   WaitForBubbleToBeShown();
191
192   EXPECT_TRUE(prompt_factory_->is_visible());
193   ASSERT_EQ(prompt_factory_->request_count(), 1);
194
195   Accept();
196   EXPECT_TRUE(request1_.granted());
197 }
198
199 TEST_P(PermissionRequestManagerTest, SequentialRequests) {
200   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
201   WaitForBubbleToBeShown();
202   EXPECT_TRUE(prompt_factory_->is_visible());
203
204   Accept();
205   EXPECT_TRUE(request1_.granted());
206   EXPECT_FALSE(prompt_factory_->is_visible());
207
208   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request2_);
209   WaitForBubbleToBeShown();
210   EXPECT_TRUE(prompt_factory_->is_visible());
211   Accept();
212   EXPECT_FALSE(prompt_factory_->is_visible());
213   EXPECT_TRUE(request2_.granted());
214 }
215
216 TEST_P(PermissionRequestManagerTest, ForgetRequestsOnPageNavigation) {
217   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
218   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request2_);
219   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(),
220                        &iframe_request_other_domain_);
221   WaitForBubbleToBeShown();
222
223   EXPECT_TRUE(prompt_factory_->is_visible());
224   ASSERT_EQ(prompt_factory_->request_count(), 1);
225
226   NavigateAndCommit(GURL("http://www2.google.com/"));
227   WaitForBubbleToBeShown();
228
229   EXPECT_FALSE(prompt_factory_->is_visible());
230   EXPECT_TRUE(request1_.finished());
231   EXPECT_TRUE(request2_.finished());
232   EXPECT_TRUE(iframe_request_other_domain_.finished());
233 }
234
235 TEST_P(PermissionRequestManagerTest, RequestsDontNeedUserGesture) {
236   WaitForFrameLoad();
237   WaitForBubbleToBeShown();
238   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
239   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(),
240                        &iframe_request_other_domain_);
241   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request2_);
242   task_environment()->RunUntilIdle();
243
244   EXPECT_TRUE(prompt_factory_->is_visible());
245 }
246
247 TEST_P(PermissionRequestManagerTest, RequestsNotSupported) {
248   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
249   WaitForBubbleToBeShown();
250   Accept();
251   EXPECT_TRUE(request1_.granted());
252
253   manager_->set_web_contents_supports_permission_requests(false);
254
255   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request2_);
256   EXPECT_TRUE(request2_.cancelled());
257 }
258
259 ////////////////////////////////////////////////////////////////////////////////
260 // Requests grouping
261 ////////////////////////////////////////////////////////////////////////////////
262
263 // Most requests should never be grouped.
264 TEST_P(PermissionRequestManagerTest, TwoRequestsUngrouped) {
265   // Grouping for chip feature is tested in ThreeRequestsStackOrderChip.
266   if (GetParam())
267     return;
268
269   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
270   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request2_);
271
272   WaitForBubbleToBeShown();
273   EXPECT_TRUE(prompt_factory_->is_visible());
274   ASSERT_EQ(prompt_factory_->request_count(), 1);
275   Accept();
276   EXPECT_TRUE(request1_.granted());
277
278   WaitForBubbleToBeShown();
279   EXPECT_TRUE(prompt_factory_->is_visible());
280   ASSERT_EQ(prompt_factory_->request_count(), 1);
281   Accept();
282   EXPECT_TRUE(request2_.granted());
283
284   ASSERT_EQ(prompt_factory_->show_count(), 2);
285 }
286
287 TEST_P(PermissionRequestManagerTest, ThreeRequestsStackOrderChip) {
288   if (!GetParam())
289     return;
290
291   // Test new permissions order, requests shouldn't be grouped.
292   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
293   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request2_);
294   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_mic_);
295   WaitForBubbleToBeShown();
296
297   EXPECT_TRUE(prompt_factory_->is_visible());
298   EXPECT_EQ(prompt_factory_->request_count(), 1);
299   Accept();
300   EXPECT_TRUE(request_mic_.granted());
301   EXPECT_FALSE(request2_.granted());
302   EXPECT_FALSE(request1_.granted());
303   WaitForBubbleToBeShown();
304
305   EXPECT_TRUE(prompt_factory_->is_visible());
306   EXPECT_EQ(prompt_factory_->request_count(), 1);
307   Accept();
308   EXPECT_TRUE(request2_.granted());
309   EXPECT_FALSE(request1_.granted());
310   WaitForBubbleToBeShown();
311
312   EXPECT_TRUE(prompt_factory_->is_visible());
313   EXPECT_EQ(prompt_factory_->request_count(), 1);
314   Accept();
315   EXPECT_TRUE(request1_.granted());
316 }
317
318 // Test new permissions order by adding requests one at a time.
319 TEST_P(PermissionRequestManagerTest, ThreeRequestsOneByOneStackOrderChip) {
320   if (!GetParam())
321     return;
322
323   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
324   WaitForBubbleToBeShown();
325
326   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request2_);
327   WaitForBubbleToBeShown();
328
329   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_mic_);
330   WaitForBubbleToBeShown();
331
332   EXPECT_TRUE(prompt_factory_->is_visible());
333   EXPECT_EQ(prompt_factory_->request_count(), 1);
334   Accept();
335   EXPECT_TRUE(request_mic_.granted());
336   EXPECT_FALSE(request2_.granted());
337   EXPECT_FALSE(request1_.granted());
338   WaitForBubbleToBeShown();
339
340   EXPECT_TRUE(prompt_factory_->is_visible());
341   EXPECT_EQ(prompt_factory_->request_count(), 1);
342   Accept();
343   EXPECT_TRUE(request2_.granted());
344   EXPECT_FALSE(request1_.granted());
345   WaitForBubbleToBeShown();
346
347   EXPECT_TRUE(prompt_factory_->is_visible());
348   EXPECT_EQ(prompt_factory_->request_count(), 1);
349   Accept();
350   EXPECT_TRUE(request1_.granted());
351 }
352
353 // Only mic/camera requests from the same origin should be grouped.
354 TEST_P(PermissionRequestManagerTest, MicCameraGrouped) {
355   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_mic_);
356   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_camera_);
357   WaitForBubbleToBeShown();
358
359   EXPECT_TRUE(prompt_factory_->is_visible());
360   ASSERT_EQ(prompt_factory_->request_count(), 2);
361
362   Accept();
363   EXPECT_TRUE(request_mic_.granted());
364   EXPECT_TRUE(request_camera_.granted());
365 }
366
367 // If mic/camera requests come from different origins, they should not be
368 // grouped.
369 TEST_P(PermissionRequestManagerTest, MicCameraDifferentOrigins) {
370   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(),
371                        &iframe_request_mic_other_domain_);
372   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_camera_);
373   WaitForBubbleToBeShown();
374
375   EXPECT_TRUE(prompt_factory_->is_visible());
376   ASSERT_EQ(prompt_factory_->request_count(), 1);
377 }
378
379 #if !BUILDFLAG(IS_ANDROID)
380 // Only camera/ptz requests from the same origin should be grouped.
381 TEST_P(PermissionRequestManagerTest, CameraPtzGrouped) {
382   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_camera_);
383   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_ptz_);
384   WaitForBubbleToBeShown();
385
386   EXPECT_TRUE(prompt_factory_->is_visible());
387   ASSERT_EQ(prompt_factory_->request_count(), 2);
388
389   Accept();
390   EXPECT_TRUE(request_camera_.granted());
391   EXPECT_TRUE(request_ptz_.granted());
392 }
393
394 TEST_P(PermissionRequestManagerTest, CameraPtzDifferentOrigins) {
395   // If camera/ptz requests come from different origins, they should not be
396   // grouped.
397   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(),
398                        &iframe_request_camera_other_domain_);
399   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_ptz_);
400   WaitForBubbleToBeShown();
401
402   EXPECT_TRUE(prompt_factory_->is_visible());
403   ASSERT_EQ(prompt_factory_->request_count(), 1);
404 }
405
406 // Only mic/camera/ptz requests from the same origin should be grouped.
407 TEST_P(PermissionRequestManagerTest, MicCameraPtzGrouped) {
408   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_mic_);
409   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_camera_);
410   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_ptz_);
411   WaitForBubbleToBeShown();
412
413   EXPECT_TRUE(prompt_factory_->is_visible());
414   ASSERT_EQ(prompt_factory_->request_count(), 3);
415
416   Accept();
417   EXPECT_TRUE(request_mic_.granted());
418   EXPECT_TRUE(request_camera_.granted());
419   EXPECT_TRUE(request_ptz_.granted());
420 }
421
422 // If mic/camera/ptz requests come from different origins, they should not be
423 // grouped.
424 TEST_P(PermissionRequestManagerTest, MicCameraPtzDifferentOrigins) {
425   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(),
426                        &iframe_request_mic_other_domain_);
427   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_camera_);
428   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_ptz_);
429   WaitForBubbleToBeShown();
430
431   // Requests should be split into two groups and each one will contain less
432   // than 3 requests (1 request + 2 request for current logic and 2 requests + 1
433   // request for chip).
434   EXPECT_TRUE(prompt_factory_->is_visible());
435   ASSERT_LT(prompt_factory_->request_count(), 3);
436   Accept();
437
438   EXPECT_TRUE(prompt_factory_->is_visible());
439   ASSERT_LT(prompt_factory_->request_count(), 3);
440 }
441 #endif  // !BUILDFLAG(IS_ANDROID)
442
443 // Tests mix of grouped media requests and non-groupable request.
444 TEST_P(PermissionRequestManagerTest, MixOfMediaAndNotMediaRequests) {
445   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
446   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_camera_);
447   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_mic_);
448   WaitForBubbleToBeShown();
449
450   // Requests should be split into two groups and each one will contain less
451   // than 3 requests (1 request + 2 request for current logic and 2 requests + 1
452   // request for chip).
453   EXPECT_TRUE(prompt_factory_->is_visible());
454   ASSERT_LT(prompt_factory_->request_count(), 3);
455   Accept();
456   WaitForBubbleToBeShown();
457
458   EXPECT_TRUE(prompt_factory_->is_visible());
459   ASSERT_LT(prompt_factory_->request_count(), 3);
460   Accept();
461 }
462
463 ////////////////////////////////////////////////////////////////////////////////
464 // Tab switching
465 ////////////////////////////////////////////////////////////////////////////////
466
467 #if BUILDFLAG(IS_ANDROID)
468 TEST_P(PermissionRequestManagerTest, TwoRequestsTabSwitch) {
469   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_mic_);
470   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_camera_);
471   WaitForBubbleToBeShown();
472
473   EXPECT_TRUE(prompt_factory_->is_visible());
474   ASSERT_EQ(prompt_factory_->request_count(), 2);
475
476   MockTabSwitchAway();
477   EXPECT_TRUE(prompt_factory_->is_visible());
478
479   MockTabSwitchBack();
480   WaitForBubbleToBeShown();
481   EXPECT_TRUE(prompt_factory_->is_visible());
482   ASSERT_EQ(prompt_factory_->request_count(), 2);
483
484   Accept();
485   EXPECT_TRUE(request_mic_.granted());
486   EXPECT_TRUE(request_camera_.granted());
487 }
488 #endif  // BUILDFLAG(IS_ANDROID)
489
490 TEST_P(PermissionRequestManagerTest, PermissionRequestWhileTabSwitchedAway) {
491   MockTabSwitchAway();
492   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
493   WaitForBubbleToBeShown();
494   EXPECT_FALSE(prompt_factory_->is_visible());
495
496   MockTabSwitchBack();
497   WaitForBubbleToBeShown();
498   EXPECT_TRUE(prompt_factory_->is_visible());
499 }
500
501 ////////////////////////////////////////////////////////////////////////////////
502 // Duplicated requests
503 ////////////////////////////////////////////////////////////////////////////////
504
505 TEST_P(PermissionRequestManagerTest, SameRequestRejected) {
506   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
507   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
508   EXPECT_FALSE(request1_.finished());
509
510   WaitForBubbleToBeShown();
511   EXPECT_TRUE(prompt_factory_->is_visible());
512   ASSERT_EQ(prompt_factory_->request_count(), 1);
513   Accept();
514   task_environment()->RunUntilIdle();
515   EXPECT_TRUE(request1_.granted());
516   EXPECT_FALSE(prompt_factory_->is_visible());
517 }
518
519 TEST_P(PermissionRequestManagerTest, WeakDuplicateRequests) {
520   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
521   WaitForBubbleToBeShown();
522   auto dupe_request_1 = request1_.CreateDuplicateRequest();
523   auto dupe_request_2 = request1_.CreateDuplicateRequest();
524   auto dupe_request_3 = request1_.CreateDuplicateRequest();
525   auto dupe_request_4 = request1_.CreateDuplicateRequest();
526   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(),
527                        dupe_request_1.get());
528   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(),
529                        dupe_request_2.get());
530   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(),
531                        dupe_request_3.get());
532   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(),
533                        dupe_request_4.get());
534   dupe_request_1.reset();
535   dupe_request_3.reset();
536   EXPECT_EQ(4ul, manager_->duplicate_requests_.front().size());
537   EXPECT_EQ(1ul, manager_->duplicate_requests_.size());
538   auto request_list = manager_->FindDuplicateRequestList(&request1_);
539   EXPECT_NE(request_list, manager_->duplicate_requests_.end());
540   EXPECT_EQ(3ul, manager_->duplicate_requests_.front().size());
541   dupe_request_4.reset();
542   manager_->VisitDuplicateRequests(
543       base::BindRepeating(
544           [](const base::WeakPtr<PermissionRequest>& weak_request) {}),
545       &request1_);
546   EXPECT_EQ(1ul, manager_->duplicate_requests_.front().size());
547   EXPECT_EQ(1ul, manager_->duplicate_requests_.size());
548   Accept();
549   EXPECT_EQ(0ul, manager_->duplicate_requests_.size());
550 }
551
552 class QuicklyDeletedRequest : public PermissionRequest {
553  public:
554   QuicklyDeletedRequest(const GURL& requesting_origin,
555                         RequestType request_type,
556                         PermissionRequestGestureType gesture_type)
557       : PermissionRequest(requesting_origin,
558                           request_type,
559                           gesture_type == PermissionRequestGestureType::GESTURE,
560                           base::BindLambdaForTesting(
561                               [](ContentSetting result,
562                                  bool is_one_time,
563                                  bool is_final_decision) { NOTREACHED(); }),
564                           base::NullCallback()) {}
565
566   static std::unique_ptr<QuicklyDeletedRequest> CreateRequest(
567       MockPermissionRequest* request) {
568     return std::make_unique<QuicklyDeletedRequest>(request->requesting_origin(),
569                                                    request->request_type(),
570                                                    request->GetGestureType());
571   }
572 };
573
574 TEST_P(PermissionRequestManagerTest, WeakDuplicateRequestsAccept) {
575   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
576   WaitForBubbleToBeShown();
577   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request2_);
578   auto dupe_request_1 = QuicklyDeletedRequest::CreateRequest(&request1_);
579   auto dupe_request_2 = request1_.CreateDuplicateRequest();
580   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(),
581                        dupe_request_1.get());
582   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(),
583                        dupe_request_2.get());
584   auto dupe_request_3 = QuicklyDeletedRequest::CreateRequest(&request2_);
585   auto dupe_request_4 = request2_.CreateDuplicateRequest();
586   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(),
587                        dupe_request_3.get());
588   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(),
589                        dupe_request_4.get());
590   dupe_request_1.reset();
591   dupe_request_3.reset();
592   EXPECT_EQ(2ul, manager_->duplicate_requests_.size());
593   EXPECT_EQ(2ul, manager_->duplicate_requests_.front().size());
594   EXPECT_EQ(2ul, manager_->duplicate_requests_.back().size());
595   WaitForBubbleToBeShown();
596   Accept();
597   EXPECT_EQ(1ul, manager_->duplicate_requests_.size());
598   WaitForBubbleToBeShown();
599   Accept();
600   EXPECT_EQ(0ul, manager_->duplicate_requests_.size());
601 }
602
603 TEST_P(PermissionRequestManagerTest, DuplicateRequest) {
604   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
605   WaitForBubbleToBeShown();
606   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request2_);
607
608   auto dupe_request = request1_.CreateDuplicateRequest();
609   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(),
610                        dupe_request.get());
611   EXPECT_FALSE(dupe_request->finished());
612   EXPECT_FALSE(request1_.finished());
613
614   auto dupe_request2 = request2_.CreateDuplicateRequest();
615   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(),
616                        dupe_request2.get());
617   EXPECT_FALSE(dupe_request2->finished());
618   EXPECT_FALSE(request2_.finished());
619
620   WaitForBubbleToBeShown();
621   Accept();
622   if (GetParam()) {
623     EXPECT_TRUE(dupe_request2->finished());
624     EXPECT_TRUE(request2_.finished());
625   } else {
626     EXPECT_TRUE(dupe_request->finished());
627     EXPECT_TRUE(request1_.finished());
628   }
629
630   WaitForBubbleToBeShown();
631   Accept();
632   if (GetParam()) {
633     EXPECT_TRUE(dupe_request->finished());
634     EXPECT_TRUE(request1_.finished());
635   } else {
636     EXPECT_TRUE(dupe_request2->finished());
637     EXPECT_TRUE(request2_.finished());
638   }
639 }
640
641 ////////////////////////////////////////////////////////////////////////////////
642 // Requests from iframes
643 ////////////////////////////////////////////////////////////////////////////////
644
645 TEST_P(PermissionRequestManagerTest, MainFrameNoRequestIFrameRequest) {
646   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(),
647                        &iframe_request_same_domain_);
648   WaitForBubbleToBeShown();
649   WaitForFrameLoad();
650
651   EXPECT_TRUE(prompt_factory_->is_visible());
652   Closing();
653   EXPECT_TRUE(iframe_request_same_domain_.finished());
654 }
655
656 TEST_P(PermissionRequestManagerTest, MainFrameAndIFrameRequestSameDomain) {
657   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
658   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(),
659                        &iframe_request_same_domain_);
660   WaitForFrameLoad();
661   WaitForBubbleToBeShown();
662
663   EXPECT_TRUE(prompt_factory_->is_visible());
664   ASSERT_EQ(1, prompt_factory_->request_count());
665   Closing();
666   if (GetParam()) {
667     EXPECT_TRUE(iframe_request_same_domain_.finished());
668     EXPECT_FALSE(request1_.finished());
669   } else {
670     EXPECT_TRUE(request1_.finished());
671     EXPECT_FALSE(iframe_request_same_domain_.finished());
672   }
673
674   WaitForBubbleToBeShown();
675   EXPECT_TRUE(prompt_factory_->is_visible());
676   ASSERT_EQ(1, prompt_factory_->request_count());
677
678   Closing();
679   EXPECT_FALSE(prompt_factory_->is_visible());
680   if (GetParam())
681     EXPECT_TRUE(request1_.finished());
682   else
683     EXPECT_TRUE(iframe_request_same_domain_.finished());
684 }
685
686 TEST_P(PermissionRequestManagerTest, MainFrameAndIFrameRequestOtherDomain) {
687   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
688   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(),
689                        &iframe_request_other_domain_);
690   WaitForFrameLoad();
691   WaitForBubbleToBeShown();
692
693   EXPECT_TRUE(prompt_factory_->is_visible());
694   Closing();
695   if (GetParam()) {
696     EXPECT_TRUE(iframe_request_other_domain_.finished());
697     EXPECT_FALSE(request1_.finished());
698   } else {
699     EXPECT_TRUE(request1_.finished());
700     EXPECT_FALSE(iframe_request_other_domain_.finished());
701   }
702
703   EXPECT_TRUE(prompt_factory_->is_visible());
704   Closing();
705   EXPECT_TRUE(iframe_request_other_domain_.finished());
706   if (GetParam())
707     EXPECT_TRUE(request1_.finished());
708   else
709     EXPECT_TRUE(iframe_request_other_domain_.finished());
710 }
711
712 TEST_P(PermissionRequestManagerTest, IFrameRequestWhenMainRequestVisible) {
713   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
714   WaitForBubbleToBeShown();
715   EXPECT_TRUE(prompt_factory_->is_visible());
716
717   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(),
718                        &iframe_request_same_domain_);
719   WaitForFrameLoad();
720   ASSERT_EQ(prompt_factory_->request_count(), 1);
721   Closing();
722   if (GetParam()) {
723     EXPECT_TRUE(iframe_request_same_domain_.finished());
724     EXPECT_FALSE(request1_.finished());
725   } else {
726     EXPECT_TRUE(request1_.finished());
727     EXPECT_FALSE(iframe_request_same_domain_.finished());
728   }
729
730   EXPECT_TRUE(prompt_factory_->is_visible());
731   ASSERT_EQ(prompt_factory_->request_count(), 1);
732   Closing();
733   EXPECT_TRUE(iframe_request_same_domain_.finished());
734   if (GetParam())
735     EXPECT_TRUE(request1_.finished());
736   else
737     EXPECT_TRUE(iframe_request_same_domain_.finished());
738 }
739
740 TEST_P(PermissionRequestManagerTest,
741        IFrameRequestOtherDomainWhenMainRequestVisible) {
742   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
743   WaitForBubbleToBeShown();
744   EXPECT_TRUE(prompt_factory_->is_visible());
745
746   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(),
747                        &iframe_request_other_domain_);
748   WaitForFrameLoad();
749   Closing();
750   if (GetParam()) {
751     EXPECT_TRUE(iframe_request_other_domain_.finished());
752     EXPECT_FALSE(request1_.finished());
753   } else {
754     EXPECT_TRUE(request1_.finished());
755     EXPECT_FALSE(iframe_request_other_domain_.finished());
756   }
757
758   EXPECT_TRUE(prompt_factory_->is_visible());
759   Closing();
760   if (GetParam())
761     EXPECT_TRUE(request1_.finished());
762   else
763     EXPECT_TRUE(iframe_request_other_domain_.finished());
764 }
765
766 ////////////////////////////////////////////////////////////////////////////////
767 // UMA logging
768 ////////////////////////////////////////////////////////////////////////////////
769
770 // This code path (calling Accept on a non-merged bubble, with no accepted
771 // permission) would never be used in actual Chrome, but its still tested for
772 // completeness.
773 TEST_P(PermissionRequestManagerTest, UMAForSimpleDeniedBubbleAlternatePath) {
774   base::HistogramTester histograms;
775
776   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
777   WaitForBubbleToBeShown();
778   // No need to test UMA for showing prompts again, they were tested in
779   // UMAForSimpleAcceptedBubble.
780
781   Deny();
782   histograms.ExpectUniqueSample(PermissionUmaUtil::kPermissionsPromptDenied,
783                                 static_cast<base::HistogramBase::Sample>(
784                                     RequestTypeForUma::PERMISSION_GEOLOCATION),
785                                 1);
786 }
787
788 TEST_P(PermissionRequestManagerTest, UMAForTabSwitching) {
789   base::HistogramTester histograms;
790
791   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
792   WaitForBubbleToBeShown();
793   histograms.ExpectUniqueSample(PermissionUmaUtil::kPermissionsPromptShown,
794                                 static_cast<base::HistogramBase::Sample>(
795                                     RequestTypeForUma::PERMISSION_GEOLOCATION),
796                                 1);
797
798   MockTabSwitchAway();
799   MockTabSwitchBack();
800   histograms.ExpectUniqueSample(PermissionUmaUtil::kPermissionsPromptShown,
801                                 static_cast<base::HistogramBase::Sample>(
802                                     RequestTypeForUma::PERMISSION_GEOLOCATION),
803                                 1);
804 }
805
806 ////////////////////////////////////////////////////////////////////////////////
807 // UI selectors
808 ////////////////////////////////////////////////////////////////////////////////
809
810 // Simulate a PermissionUiSelector that simply returns a predefined |ui_to_use|
811 // every time.
812 class MockNotificationPermissionUiSelector : public PermissionUiSelector {
813  public:
814   explicit MockNotificationPermissionUiSelector(
815       absl::optional<QuietUiReason> quiet_ui_reason,
816       absl::optional<PermissionUmaUtil::PredictionGrantLikelihood>
817           prediction_likelihood,
818       absl::optional<base::TimeDelta> async_delay)
819       : quiet_ui_reason_(quiet_ui_reason),
820         prediction_likelihood_(prediction_likelihood),
821         async_delay_(async_delay) {}
822
823   void SelectUiToUse(PermissionRequest* request,
824                      DecisionMadeCallback callback) override {
825     selected_ui_to_use_ = true;
826     Decision decision(quiet_ui_reason_, Decision::ShowNoWarning());
827     if (async_delay_) {
828       base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
829           FROM_HERE, base::BindOnce(std::move(callback), decision),
830           async_delay_.value());
831     } else {
832       std::move(callback).Run(decision);
833     }
834   }
835
836   bool IsPermissionRequestSupported(RequestType request_type) override {
837     return request_type == RequestType::kNotifications ||
838            request_type == RequestType::kGeolocation;
839   }
840
841   absl::optional<PermissionUmaUtil::PredictionGrantLikelihood>
842   PredictedGrantLikelihoodForUKM() override {
843     return prediction_likelihood_;
844   }
845
846   static void CreateForManager(
847       PermissionRequestManager* manager,
848       absl::optional<QuietUiReason> quiet_ui_reason,
849       absl::optional<base::TimeDelta> async_delay,
850       absl::optional<PermissionUmaUtil::PredictionGrantLikelihood>
851           prediction_likelihood = absl::nullopt) {
852     manager->add_permission_ui_selector_for_testing(
853         std::make_unique<MockNotificationPermissionUiSelector>(
854             quiet_ui_reason, prediction_likelihood, async_delay));
855   }
856
857   bool selected_ui_to_use() const { return selected_ui_to_use_; }
858
859  private:
860   absl::optional<QuietUiReason> quiet_ui_reason_;
861   absl::optional<PermissionUmaUtil::PredictionGrantLikelihood>
862       prediction_likelihood_;
863   absl::optional<base::TimeDelta> async_delay_;
864   bool selected_ui_to_use_ = false;
865 };
866
867 // Same as the MockNotificationPermissionUiSelector but handling only the
868 // Camera stream request type
869 class MockCameraStreamPermissionUiSelector
870     : public MockNotificationPermissionUiSelector {
871  public:
872   explicit MockCameraStreamPermissionUiSelector(
873       absl::optional<QuietUiReason> quiet_ui_reason,
874       absl::optional<PermissionUmaUtil::PredictionGrantLikelihood>
875           prediction_likelihood,
876       absl::optional<base::TimeDelta> async_delay)
877       : MockNotificationPermissionUiSelector(quiet_ui_reason,
878                                              prediction_likelihood,
879                                              async_delay) {}
880
881   bool IsPermissionRequestSupported(RequestType request_type) override {
882     return request_type == RequestType::kCameraStream;
883   }
884
885   static void CreateForManager(
886       PermissionRequestManager* manager,
887       absl::optional<QuietUiReason> quiet_ui_reason,
888       absl::optional<base::TimeDelta> async_delay,
889       absl::optional<PermissionUmaUtil::PredictionGrantLikelihood>
890           prediction_likelihood = absl::nullopt) {
891     manager->add_permission_ui_selector_for_testing(
892         std::make_unique<MockCameraStreamPermissionUiSelector>(
893             quiet_ui_reason, prediction_likelihood, async_delay));
894   }
895 };
896
897 TEST_P(PermissionRequestManagerTest,
898        UiSelectorNotUsedForPermissionsOtherThanNotification) {
899   manager_->clear_permission_ui_selector_for_testing();
900   MockNotificationPermissionUiSelector::CreateForManager(
901       manager_, PermissionUiSelector::QuietUiReason::kEnabledInPrefs,
902       absl::nullopt /* async_delay */);
903
904   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_camera_);
905   WaitForBubbleToBeShown();
906
907   ASSERT_TRUE(prompt_factory_->is_visible());
908   ASSERT_TRUE(prompt_factory_->RequestTypeSeen(request_camera_.request_type()));
909   EXPECT_FALSE(manager_->ShouldCurrentRequestUseQuietUI());
910   Accept();
911
912   EXPECT_TRUE(request_camera_.granted());
913 }
914
915 TEST_P(PermissionRequestManagerTest, UiSelectorUsedForNotifications) {
916   const struct {
917     absl::optional<PermissionUiSelector::QuietUiReason> quiet_ui_reason;
918     absl::optional<base::TimeDelta> async_delay;
919   } kTests[] = {
920       {QuietUiReason::kEnabledInPrefs, absl::make_optional<base::TimeDelta>()},
921       {PermissionUiSelector::Decision::UseNormalUi(),
922        absl::make_optional<base::TimeDelta>()},
923       {QuietUiReason::kEnabledInPrefs, absl::nullopt},
924       {PermissionUiSelector::Decision::UseNormalUi(), absl::nullopt},
925   };
926
927   for (const auto& test : kTests) {
928     manager_->clear_permission_ui_selector_for_testing();
929     MockNotificationPermissionUiSelector::CreateForManager(
930         manager_, test.quiet_ui_reason, test.async_delay);
931
932     MockPermissionRequest request(RequestType::kNotifications,
933                                   PermissionRequestGestureType::GESTURE);
934
935     manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request);
936     WaitForBubbleToBeShown();
937
938     EXPECT_TRUE(prompt_factory_->is_visible());
939     EXPECT_TRUE(prompt_factory_->RequestTypeSeen(request.request_type()));
940     EXPECT_EQ(!!test.quiet_ui_reason,
941               manager_->ShouldCurrentRequestUseQuietUI());
942     Accept();
943
944     EXPECT_TRUE(request.granted());
945   }
946 }
947
948 TEST_P(PermissionRequestManagerTest,
949        UiSelectionHappensSeparatelyForEachRequest) {
950   manager_->clear_permission_ui_selector_for_testing();
951   MockNotificationPermissionUiSelector::CreateForManager(
952       manager_, QuietUiReason::kEnabledInPrefs,
953       absl::make_optional<base::TimeDelta>());
954   MockPermissionRequest request1(RequestType::kNotifications,
955                                  PermissionRequestGestureType::GESTURE);
956   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1);
957   WaitForBubbleToBeShown();
958   EXPECT_TRUE(manager_->ShouldCurrentRequestUseQuietUI());
959   Accept();
960
961   MockPermissionRequest request2(RequestType::kNotifications,
962                                  PermissionRequestGestureType::GESTURE);
963   manager_->clear_permission_ui_selector_for_testing();
964   MockNotificationPermissionUiSelector::CreateForManager(
965       manager_, PermissionUiSelector::Decision::UseNormalUi(),
966       absl::make_optional<base::TimeDelta>());
967   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request2);
968   WaitForBubbleToBeShown();
969   EXPECT_FALSE(manager_->ShouldCurrentRequestUseQuietUI());
970   Accept();
971 }
972
973 TEST_P(PermissionRequestManagerTest, SkipNextUiSelector) {
974   manager_->clear_permission_ui_selector_for_testing();
975   MockNotificationPermissionUiSelector::CreateForManager(
976       manager_, QuietUiReason::kEnabledInPrefs,
977       /* async_delay */ absl::nullopt);
978   MockNotificationPermissionUiSelector::CreateForManager(
979       manager_, PermissionUiSelector::Decision::UseNormalUi(),
980       /* async_delay */ absl::nullopt);
981   MockPermissionRequest request1(RequestType::kNotifications,
982                                  PermissionRequestGestureType::GESTURE);
983   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1);
984   WaitForBubbleToBeShown();
985   auto* next_selector =
986       manager_->get_permission_ui_selectors_for_testing().back().get();
987   EXPECT_FALSE(static_cast<MockNotificationPermissionUiSelector*>(next_selector)
988                    ->selected_ui_to_use());
989   EXPECT_TRUE(manager_->ShouldCurrentRequestUseQuietUI());
990   Accept();
991 }
992
993 TEST_P(PermissionRequestManagerTest, MultipleUiSelectors) {
994   const struct {
995     std::vector<absl::optional<QuietUiReason>> quiet_ui_reasons;
996     std::vector<bool> simulate_delayed_decision;
997     absl::optional<QuietUiReason> expected_reason;
998   } kTests[] = {
999       // Simple sync selectors, first one should take priority.
1000       {{QuietUiReason::kTriggeredByCrowdDeny, QuietUiReason::kEnabledInPrefs},
1001        {false, false},
1002        QuietUiReason::kTriggeredByCrowdDeny},
1003       {{QuietUiReason::kTriggeredDueToDisruptiveBehavior,
1004         QuietUiReason::kEnabledInPrefs},
1005        {false, false},
1006        QuietUiReason::kTriggeredDueToDisruptiveBehavior},
1007       {{QuietUiReason::kTriggeredDueToDisruptiveBehavior,
1008         QuietUiReason::kServicePredictedVeryUnlikelyGrant},
1009        {false, false},
1010        QuietUiReason::kTriggeredDueToDisruptiveBehavior},
1011       {{QuietUiReason::kTriggeredDueToDisruptiveBehavior,
1012         QuietUiReason::kTriggeredByCrowdDeny},
1013        {false, false},
1014        QuietUiReason::kTriggeredDueToDisruptiveBehavior},
1015       // First selector is async but should still take priority even if it
1016       // returns later.
1017       {{QuietUiReason::kTriggeredByCrowdDeny, QuietUiReason::kEnabledInPrefs},
1018        {true, false},
1019        QuietUiReason::kTriggeredByCrowdDeny},
1020       {{QuietUiReason::kTriggeredDueToDisruptiveBehavior,
1021         QuietUiReason::kEnabledInPrefs},
1022        {true, false},
1023        QuietUiReason::kTriggeredDueToDisruptiveBehavior},
1024       // The first selector that has a quiet ui decision should be used.
1025       {{absl::nullopt, absl::nullopt,
1026         QuietUiReason::kTriggeredDueToAbusiveContent,
1027         QuietUiReason::kEnabledInPrefs},
1028        {false, true, true, false},
1029        QuietUiReason::kTriggeredDueToAbusiveContent},
1030       // If all selectors return a normal ui, it should use a normal ui.
1031       {{absl::nullopt, absl::nullopt}, {false, true}, absl::nullopt},
1032
1033       // Use a bunch of selectors both async and sync.
1034       {{absl::nullopt, absl::nullopt, absl::nullopt, absl::nullopt,
1035         absl::nullopt, QuietUiReason::kTriggeredDueToAbusiveRequests,
1036         absl::nullopt, QuietUiReason::kEnabledInPrefs},
1037        {false, true, false, true, true, true, false, false},
1038        QuietUiReason::kTriggeredDueToAbusiveRequests},
1039       // Use a bunch of selectors all sync.
1040       {{absl::nullopt, absl::nullopt, absl::nullopt, absl::nullopt,
1041         absl::nullopt, QuietUiReason::kTriggeredDueToAbusiveRequests,
1042         absl::nullopt, QuietUiReason::kEnabledInPrefs},
1043        {false, false, false, false, false, false, false, false},
1044        QuietUiReason::kTriggeredDueToAbusiveRequests},
1045       // Use a bunch of selectors all async.
1046       {{absl::nullopt, absl::nullopt, absl::nullopt, absl::nullopt,
1047         absl::nullopt, QuietUiReason::kTriggeredDueToAbusiveRequests,
1048         absl::nullopt, QuietUiReason::kEnabledInPrefs},
1049        {true, true, true, true, true, true, true, true},
1050        QuietUiReason::kTriggeredDueToAbusiveRequests},
1051       // Use a bunch of selectors both async and sync.
1052       {{absl::nullopt, absl::nullopt, absl::nullopt, absl::nullopt,
1053         absl::nullopt, QuietUiReason::kTriggeredDueToDisruptiveBehavior,
1054         absl::nullopt, QuietUiReason::kEnabledInPrefs},
1055        {true, false, false, true, true, true, false, false},
1056        QuietUiReason::kTriggeredDueToDisruptiveBehavior},
1057   };
1058
1059   for (const auto& test : kTests) {
1060     manager_->clear_permission_ui_selector_for_testing();
1061     for (size_t i = 0; i < test.quiet_ui_reasons.size(); ++i) {
1062       MockNotificationPermissionUiSelector::CreateForManager(
1063           manager_, test.quiet_ui_reasons[i],
1064           test.simulate_delayed_decision[i]
1065               ? absl::make_optional<base::TimeDelta>()
1066               : absl::nullopt);
1067     }
1068
1069     MockPermissionRequest request(RequestType::kNotifications,
1070                                   PermissionRequestGestureType::GESTURE);
1071
1072     manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request);
1073     WaitForBubbleToBeShown();
1074
1075     EXPECT_TRUE(prompt_factory_->is_visible());
1076     EXPECT_TRUE(prompt_factory_->RequestTypeSeen(request.request_type()));
1077     if (test.expected_reason.has_value()) {
1078       EXPECT_EQ(test.expected_reason, manager_->ReasonForUsingQuietUi());
1079     } else {
1080       EXPECT_FALSE(manager_->ShouldCurrentRequestUseQuietUI());
1081     }
1082
1083     Accept();
1084     EXPECT_TRUE(request.granted());
1085   }
1086 }
1087
1088 TEST_P(PermissionRequestManagerTest, SelectorsPredictionLikelihood) {
1089   using PredictionLikelihood = PermissionUmaUtil::PredictionGrantLikelihood;
1090   const auto VeryLikely = PredictionLikelihood::
1091       PermissionPrediction_Likelihood_DiscretizedLikelihood_VERY_LIKELY;
1092   const auto Neutral = PredictionLikelihood::
1093       PermissionPrediction_Likelihood_DiscretizedLikelihood_NEUTRAL;
1094
1095   const struct {
1096     std::vector<bool> enable_quiet_uis;
1097     std::vector<absl::optional<PredictionLikelihood>> prediction_likelihoods;
1098     absl::optional<PredictionLikelihood> expected_prediction_likelihood;
1099   } kTests[] = {
1100       // Sanity check: prediction likelihood is populated correctly.
1101       {{true}, {VeryLikely}, VeryLikely},
1102       {{false}, {Neutral}, Neutral},
1103
1104       // Prediction likelihood is populated only if the selector was considered.
1105       {{true, true}, {absl::nullopt, VeryLikely}, absl::nullopt},
1106       {{false, true}, {absl::nullopt, VeryLikely}, VeryLikely},
1107       {{false, false}, {absl::nullopt, VeryLikely}, VeryLikely},
1108
1109       // First considered selector is preserved.
1110       {{true, true}, {Neutral, VeryLikely}, Neutral},
1111       {{false, true}, {Neutral, VeryLikely}, Neutral},
1112       {{false, false}, {Neutral, VeryLikely}, Neutral},
1113   };
1114
1115   for (const auto& test : kTests) {
1116     manager_->clear_permission_ui_selector_for_testing();
1117     for (size_t i = 0; i < test.enable_quiet_uis.size(); ++i) {
1118       MockNotificationPermissionUiSelector::CreateForManager(
1119           manager_,
1120           test.enable_quiet_uis[i]
1121               ? absl::optional<QuietUiReason>(QuietUiReason::kEnabledInPrefs)
1122               : absl::nullopt,
1123           absl::nullopt /* async_delay */, test.prediction_likelihoods[i]);
1124     }
1125
1126     MockPermissionRequest request(RequestType::kNotifications,
1127                                   PermissionRequestGestureType::GESTURE);
1128
1129     manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request);
1130     WaitForBubbleToBeShown();
1131
1132     EXPECT_TRUE(prompt_factory_->is_visible());
1133     EXPECT_TRUE(prompt_factory_->RequestTypeSeen(request.request_type()));
1134     EXPECT_EQ(test.expected_prediction_likelihood,
1135               manager_->prediction_grant_likelihood_for_testing());
1136
1137     Accept();
1138     EXPECT_TRUE(request.granted());
1139   }
1140 }
1141
1142 TEST_P(PermissionRequestManagerTest, SelectorRequestTypes) {
1143   const struct {
1144     RequestType request_type;
1145     bool should_request_use_quiet_ui;
1146   } kTests[] = {
1147       {RequestType::kNotifications, true},
1148       {RequestType::kGeolocation, true},
1149       {RequestType::kCameraStream, false},
1150   };
1151   manager_->clear_permission_ui_selector_for_testing();
1152   MockNotificationPermissionUiSelector::CreateForManager(
1153       manager_, QuietUiReason::kEnabledInPrefs,
1154       absl::make_optional<base::TimeDelta>());
1155   for (const auto& test : kTests) {
1156     MockPermissionRequest request(test.request_type,
1157                                   PermissionRequestGestureType::GESTURE);
1158     manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request);
1159     WaitForBubbleToBeShown();
1160     EXPECT_EQ(test.should_request_use_quiet_ui,
1161               manager_->ShouldCurrentRequestUseQuietUI());
1162     Accept();
1163   }
1164   // Adding a mock PermissionUiSelector that handles Camera stream.
1165   MockCameraStreamPermissionUiSelector::CreateForManager(
1166       manager_, QuietUiReason::kEnabledInPrefs,
1167       absl::make_optional<base::TimeDelta>());
1168   // Now the RequestType::kCameraStream should show a quiet UI as well
1169   MockPermissionRequest request2(RequestType::kCameraStream,
1170                                  PermissionRequestGestureType::GESTURE);
1171   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request2);
1172   WaitForBubbleToBeShown();
1173   EXPECT_TRUE(manager_->ShouldCurrentRequestUseQuietUI());
1174   Accept();
1175 }
1176
1177 ////////////////////////////////////////////////////////////////////////////////
1178 // Quiet UI chip. Low priority for Notifications & Geolocation.
1179 ////////////////////////////////////////////////////////////////////////////////
1180
1181 TEST_P(PermissionRequestManagerTest, NotificationsSingleBubbleAndChipRequest) {
1182   MockPermissionRequest request(RequestType::kNotifications,
1183                                 PermissionRequestGestureType::GESTURE);
1184
1185   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request);
1186   WaitForBubbleToBeShown();
1187
1188   EXPECT_TRUE(prompt_factory_->is_visible());
1189   ASSERT_EQ(prompt_factory_->request_count(), 1);
1190
1191   Accept();
1192   EXPECT_TRUE(request.granted());
1193   EXPECT_EQ(prompt_factory_->show_count(), 1);
1194 }
1195
1196 // Quiet UI feature is disabled. Chip is disabled. No low priority requests, the
1197 // first request is always shown.
1198 //
1199 // Permissions requested in order:
1200 // 1. Notification (non abusive)
1201 // 2. Geolocation
1202 // 3. Camera
1203 //
1204 // Prompt display order:
1205 // 1. Notification request shown
1206 // 2. Geolocation request shown
1207 // 3. Camera request shown
1208 TEST_P(PermissionRequestManagerTest,
1209        NotificationsGeolocationCameraBubbleRequest) {
1210   // permissions::features::kPermissionChip is enabled based on `GetParam()`.
1211   // That test is only for the default bubble.
1212   if (GetParam())
1213     return;
1214
1215   std::unique_ptr<MockPermissionRequest> request_notifications =
1216       CreateAndAddRequest(RequestType::kNotifications, /*should_be_seen=*/true,
1217                           1);
1218   std::unique_ptr<MockPermissionRequest> request_geolocation =
1219       CreateAndAddRequest(RequestType::kGeolocation, /*should_be_seen=*/false,
1220                           1);
1221   std::unique_ptr<MockPermissionRequest> request_camera = CreateAndAddRequest(
1222       RequestType::kCameraStream, /*should_be_seen=*/false, 1);
1223
1224   for (auto* kRequest : {request_notifications.get(), request_geolocation.get(),
1225                          request_camera.get()}) {
1226     WaitAndAcceptPromptForRequest(kRequest);
1227   }
1228
1229   EXPECT_EQ(prompt_factory_->show_count(), 3);
1230 }
1231
1232 // Quiet UI feature is disabled, no low priority requests, the last request is
1233 // always shown.
1234 //
1235 // Permissions requested in order:
1236 // 1. Notification (non abusive)
1237 // 2. Geolocation
1238 // 3. Camera
1239 //
1240 // Prompt display order:
1241 // 1. Notifications request shown but is preempted
1242 // 2. Geolocation request shown but is preempted
1243 // 3. Camera request shown
1244 // 4. Geolocation request shown again
1245 // 5. Notifications request shown again
1246 TEST_P(PermissionRequestManagerTest,
1247        NotificationsGeolocationCameraChipRequest) {
1248   // permissions::features::kPermissionChip is enabled based on `GetParam()`.
1249   // That test is only for the chip UI.
1250   if (!GetParam())
1251     return;
1252
1253   std::unique_ptr<MockPermissionRequest> request_notifications =
1254       CreateAndAddRequest(RequestType::kNotifications, /*should_be_seen=*/true,
1255                           1);
1256   std::unique_ptr<MockPermissionRequest> request_geolocation =
1257       CreateAndAddRequest(RequestType::kGeolocation, /*should_be_seen=*/true,
1258                           2);
1259   std::unique_ptr<MockPermissionRequest> request_camera = CreateAndAddRequest(
1260       RequestType::kCameraStream, /*should_be_seen=*/true, 3);
1261
1262   for (auto* kRequest : {request_camera.get(), request_geolocation.get(),
1263                          request_notifications.get()}) {
1264     WaitAndAcceptPromptForRequest(kRequest);
1265   }
1266
1267   EXPECT_EQ(prompt_factory_->show_count(), 5);
1268 }
1269
1270 // Quiet UI feature is disabled, no low priority requests, the last request is
1271 // always shown.
1272 //
1273 // Permissions requested in order:
1274 // 1. Camera
1275 // 2. Notification (non abusive)
1276 // 3. Geolocation
1277 //
1278 // Prompt display order:
1279 // 1. Camera request shown but is preempted
1280 // 2. Notifications request shown but is preempted
1281 // 3. Geolocation request shown
1282 // 4. Notifications request shown again
1283 // 5. Camera request shown again
1284 TEST_P(PermissionRequestManagerTest,
1285        CameraNotificationsGeolocationChipRequest) {
1286   // permissions::features::kPermissionChip is enabled based on `GetParam()`.
1287   // That test is only for the chip.
1288   if (!GetParam())
1289     return;
1290
1291   std::unique_ptr<MockPermissionRequest> request_camera = CreateAndAddRequest(
1292       RequestType::kCameraStream, /*should_be_seen=*/true, 1);
1293   std::unique_ptr<MockPermissionRequest> request_notifications =
1294       CreateAndAddRequest(RequestType::kNotifications, /*should_be_seen=*/true,
1295                           2);
1296   std::unique_ptr<MockPermissionRequest> request_geolocation =
1297       CreateAndAddRequest(RequestType::kGeolocation, /*should_be_seen=*/true,
1298                           3);
1299
1300   for (auto* kRequest : {request_geolocation.get(), request_notifications.get(),
1301                          request_camera.get()}) {
1302     WaitAndAcceptPromptForRequest(kRequest);
1303   }
1304
1305   EXPECT_EQ(prompt_factory_->show_count(), 5);
1306 }
1307
1308 // Verifies order of simultaneous requests, with quiet chip enabled.
1309 // Simultaneous new requests are coming while we are waiting for UI selector
1310 // decisions.
1311 //
1312 // Permissions requested in order:
1313 // 1. Geolocation, UI selector takes 2 seconds to decide.
1314 // 2. Notification then mic. Notification will preempt geolocation
1315 //
1316 // Prompt display order:
1317 // 1. Mic
1318 // 2. Notification
1319 // 3. Geolocation
1320 TEST_P(PermissionRequestManagerTest, NewHighPriorityRequestDuringUIDecision) {
1321   if (!GetParam())
1322     return;
1323
1324   manager_->clear_permission_ui_selector_for_testing();
1325   MockNotificationPermissionUiSelector::CreateForManager(
1326       manager_, QuietUiReason::kTriggeredDueToAbusiveRequests,
1327       absl::make_optional<base::TimeDelta>(base::Seconds(2)));
1328   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
1329
1330   task_environment()->FastForwardBy(base::Seconds(1));
1331
1332   MockPermissionRequest request(RequestType::kNotifications,
1333                                 PermissionRequestGestureType::GESTURE);
1334   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request);
1335   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_mic_);
1336   WaitForBubbleToBeShown();
1337   manager_->clear_permission_ui_selector_for_testing();
1338
1339   EXPECT_TRUE(prompt_factory_->is_visible());
1340   EXPECT_EQ(prompt_factory_->request_count(), 1);
1341   Accept();
1342   EXPECT_TRUE(request_mic_.granted());
1343   EXPECT_FALSE(request.granted());
1344   EXPECT_FALSE(request1_.granted());
1345   WaitForBubbleToBeShown();
1346
1347   EXPECT_TRUE(prompt_factory_->is_visible());
1348   EXPECT_EQ(prompt_factory_->request_count(), 1);
1349   Accept();
1350   EXPECT_TRUE(request.granted());
1351   EXPECT_FALSE(request1_.granted());
1352   WaitForBubbleToBeShown();
1353
1354   EXPECT_TRUE(prompt_factory_->is_visible());
1355   EXPECT_EQ(prompt_factory_->request_count(), 1);
1356   Accept();
1357   EXPECT_TRUE(request1_.granted());
1358 }
1359
1360 class PermissionRequestManagerTestQuietChip
1361     : public PermissionRequestManagerTest {
1362  public:
1363   PermissionRequestManagerTestQuietChip() {
1364     feature_list_.InitWithFeatureState(
1365         permissions::features::kPermissionQuietChip, true);
1366   }
1367
1368  private:
1369   base::test::ScopedFeatureList feature_list_;
1370 };
1371
1372 // Verifies that the quiet UI chip is not ignored if another request came in
1373 // less than 8.5 seconds after.
1374 // Permissions requested in order:
1375 // 1. Notification (abusive)
1376 // 2. After less than 8.5 seconds Geolocation
1377 //
1378 // Prompt display order:
1379 // 1. Notifications request shown but is preempted because of quiet UI.
1380 // 2. Geolocation request shown
1381 // 3. Notifications request shown again
1382 TEST_P(PermissionRequestManagerTestQuietChip,
1383        AbusiveNotificationsGeolocationQuietUIChipRequest) {
1384   MockNotificationPermissionUiSelector::CreateForManager(
1385       manager_,
1386       PermissionUiSelector::QuietUiReason::kTriggeredDueToAbusiveRequests,
1387       absl::nullopt /* async_delay */);
1388
1389   std::unique_ptr<MockPermissionRequest> request_notifications =
1390       CreateAndAddRequest(RequestType::kNotifications, /*should_be_seen=*/true,
1391                           1);
1392
1393   // Less then 8.5 seconds.
1394   manager_->set_current_request_first_display_time_for_testing(
1395       base::Time::Now() - base::Milliseconds(5000));
1396
1397   std::unique_ptr<MockPermissionRequest> request_geolocation =
1398       CreateAndAddRequest(RequestType::kGeolocation, /*should_be_seen=*/true,
1399                           2);
1400
1401   WaitAndAcceptPromptForRequest(request_geolocation.get());
1402   WaitAndAcceptPromptForRequest(request_notifications.get());
1403
1404   EXPECT_EQ(prompt_factory_->show_count(), 3);
1405 }
1406
1407 // Verifies that the quiet UI chip is ignored if another request came in more
1408 // than 8.5 seconds after.
1409 //
1410 // Permissions requested in order:
1411 // 1. Notification (abusive)
1412 // 2. After more than 8.5 seconds Geolocation
1413 //
1414 // Prompt display order:
1415 // 1. Notifications request shown but is preempted because of quiet UI.
1416 // 2. Geolocation request shown
1417 TEST_P(PermissionRequestManagerTestQuietChip,
1418        AbusiveNotificationsShownLongEnough) {
1419   MockNotificationPermissionUiSelector::CreateForManager(
1420       manager_,
1421       PermissionUiSelector::QuietUiReason::kTriggeredDueToAbusiveRequests,
1422       absl::nullopt /* async_delay */);
1423
1424   std::unique_ptr<MockPermissionRequest> request_notifications =
1425       CreateAndAddRequest(RequestType::kNotifications, /*should_be_seen=*/true,
1426                           1);
1427
1428   // More then 8.5 seconds.
1429   manager_->set_current_request_first_display_time_for_testing(
1430       base::Time::Now() - base::Milliseconds(9000));
1431
1432   std::unique_ptr<MockPermissionRequest> request_geolocation =
1433       CreateAndAddRequest(RequestType::kGeolocation, /*should_be_seen=*/true,
1434                           2);
1435
1436   // The second permission was requested after 8.5 second window, the quiet UI
1437   // Notifiations request for an abusive origin is automatically ignored.
1438   EXPECT_FALSE(request_notifications->granted());
1439   EXPECT_TRUE(request_notifications->finished());
1440
1441   WaitAndAcceptPromptForRequest(request_geolocation.get());
1442
1443   EXPECT_EQ(prompt_factory_->show_count(), 2);
1444 }
1445
1446 // Verifies that the quiet UI chip is not ignored if another request came in
1447 // more than 8.5 seconds after. Verify different requests priority. Camera
1448 // request is shown despite being requested last.
1449 //
1450 // Permissions requested in order:
1451 // 1. Notification (abusive)
1452 // 2. After less than 8.5 seconds Geolocation
1453 // 3. Camera
1454 //
1455 // Prompt display order:
1456 // 1. Notifications request shown but is preempted because of quiet UI.
1457 // 2. Geolocation request shown but is preempted because of low priority.
1458 // 3. Camera request shown
1459 // 4. Geolocation request shown again
1460 // 5. Notifications quiet UI request shown again
1461 TEST_P(PermissionRequestManagerTestQuietChip,
1462        AbusiveNotificationsShownLongEnoughCamera) {
1463   MockNotificationPermissionUiSelector::CreateForManager(
1464       manager_,
1465       PermissionUiSelector::QuietUiReason::kTriggeredDueToAbusiveRequests,
1466       absl::nullopt /* async_delay */);
1467
1468   std::unique_ptr<MockPermissionRequest> request_notifications =
1469       CreateAndAddRequest(RequestType::kNotifications, /*should_be_seen=*/true,
1470                           1);
1471   // Less then 8.5 seconds.
1472   manager_->set_current_request_first_display_time_for_testing(
1473       base::Time::Now() - base::Milliseconds(5000));
1474
1475   std::unique_ptr<MockPermissionRequest> request_geolocation =
1476       CreateAndAddRequest(RequestType::kGeolocation, /*should_be_seen=*/true,
1477                           2);
1478   std::unique_ptr<MockPermissionRequest> request_camera = CreateAndAddRequest(
1479       RequestType::kCameraStream, /*should_be_seen=*/true, 3);
1480
1481   // The second permission was requested in 8.5 second window, the quiet UI
1482   // Notifiations request for an abusive origin is not automatically ignored.
1483   EXPECT_FALSE(request_notifications->granted());
1484   EXPECT_FALSE(request_notifications->finished());
1485
1486   for (auto* kRequest : {request_camera.get(), request_geolocation.get(),
1487                          request_notifications.get()}) {
1488     WaitAndAcceptPromptForRequest(kRequest);
1489   }
1490
1491   EXPECT_EQ(prompt_factory_->show_count(), 5);
1492 }
1493
1494 // Verifies that the quiet UI chip is not ignored if another request came in
1495 // more than 8.5 seconds after. Verify different requests priority. Camera
1496 // request is not preemted.
1497 //
1498 // Permissions requested in order:
1499 // 1. Camera
1500 // 2. Notification (abusive)
1501 // 3. After less than 8.5 seconds Geolocation
1502 //
1503 // Prompt display order:
1504 // 1. Camera request shown
1505 // 2. Geolocation request shown
1506 // 3. Camera request shown
1507 TEST_P(PermissionRequestManagerTestQuietChip,
1508        CameraAbusiveNotificationsGeolocation) {
1509   MockNotificationPermissionUiSelector::CreateForManager(
1510       manager_,
1511       PermissionUiSelector::QuietUiReason::kTriggeredDueToAbusiveRequests,
1512       absl::nullopt /* async_delay */);
1513
1514   std::unique_ptr<MockPermissionRequest> request_camera = CreateAndAddRequest(
1515       RequestType::kCameraStream, /*should_be_seen=*/true, 1);
1516
1517   // Quiet UI is not shown because Camera has higher priority.
1518   std::unique_ptr<MockPermissionRequest> request_notifications =
1519       CreateAndAddRequest(RequestType::kNotifications, /*should_be_seen=*/false,
1520                           1);
1521   // Less then 8.5 seconds.
1522   manager_->set_current_request_first_display_time_for_testing(
1523       base::Time::Now() - base::Milliseconds(5000));
1524
1525   // Geolocation is not shown because Camera has higher priority.
1526   std::unique_ptr<MockPermissionRequest> request_geolocation =
1527       CreateAndAddRequest(RequestType::kGeolocation, /*should_be_seen=*/false,
1528                           1);
1529
1530   // The second permission after quiet UI was requested in 8.5 second window,
1531   // the quiet UI Notifiations request for an abusive origin is not
1532   // automatically ignored.
1533   EXPECT_FALSE(request_notifications->granted());
1534   EXPECT_FALSE(request_notifications->finished());
1535
1536   for (auto* kRequest : {request_camera.get(), request_geolocation.get(),
1537                          request_notifications.get()}) {
1538     WaitAndAcceptPromptForRequest(kRequest);
1539   }
1540
1541   EXPECT_EQ(prompt_factory_->show_count(), 3);
1542 }
1543
1544 // Verifies that the quiet UI chip is not ignored if another request came in
1545 // more than 8.5 seconds after. Verify different requests priority. Camera
1546 // request is not preemted.
1547 //
1548 // Permissions requested in order:
1549 // 1. Camera
1550 // 2. Notification (abusive)
1551 // 3. After less than 8.5 seconds Geolocation
1552 // 4. MIDI
1553 //
1554 // Prompt display order:
1555 // 1. Camera request shown
1556 // 2. MIDI request shown (or MIDI and then Camera, the order depends on
1557 // `GetParam()`)
1558 // 3. Geolocation request shown
1559 // 4. Notifications request shown
1560 // If Chip is enabled MIDI will replace Camera, hence 5 prompts will be
1561 // shown. Otherwise 4.
1562 TEST_P(PermissionRequestManagerTestQuietChip,
1563        CameraAbusiveNotificationsGeolocationMIDI) {
1564   MockNotificationPermissionUiSelector::CreateForManager(
1565       manager_,
1566       PermissionUiSelector::QuietUiReason::kTriggeredDueToAbusiveRequests,
1567       absl::nullopt /* async_delay */);
1568
1569   std::unique_ptr<MockPermissionRequest> request_camera = CreateAndAddRequest(
1570       RequestType::kCameraStream, /*should_be_seen=*/true, 1);
1571
1572   // Quiet UI is not shown because Camera has higher priority.
1573   std::unique_ptr<MockPermissionRequest> request_notifications =
1574       CreateAndAddRequest(RequestType::kNotifications, /*should_be_seen=*/false,
1575                           1);
1576   // Less then 8.5 seconds.
1577   manager_->set_current_request_first_display_time_for_testing(
1578       base::Time::Now() - base::Milliseconds(5000));
1579
1580   // Geolocation is not shown because Camera has higher priority.
1581   std::unique_ptr<MockPermissionRequest> request_geolocation =
1582       CreateAndAddRequest(RequestType::kGeolocation, /*should_be_seen=*/false,
1583                           1);
1584
1585   std::unique_ptr<MockPermissionRequest> request_midi;
1586
1587   // If Chip is enabled, MIDI should be shown, otherwise MIDI should not be
1588   // shown.
1589   if (GetParam()) {
1590     request_midi = CreateAndAddRequest(RequestType::kMidiSysex,
1591                                        /*should_be_seen=*/true, 2);
1592   } else {
1593     request_midi = CreateAndAddRequest(RequestType::kMidiSysex,
1594                                        /*should_be_seen=*/false, 1);
1595   }
1596
1597   // The second permission after quiet UI was requested in 8.5 second window,
1598   // the quiet UI Notifiations request for an abusive origin is not
1599   // automatically ignored.
1600   EXPECT_FALSE(request_notifications->granted());
1601   EXPECT_FALSE(request_notifications->finished());
1602
1603   WaitAndAcceptPromptForRequest(GetParam() ? request_midi.get()
1604                                            : request_camera.get());
1605   WaitAndAcceptPromptForRequest(GetParam() ? request_camera.get()
1606                                            : request_midi.get());
1607   WaitAndAcceptPromptForRequest(request_geolocation.get());
1608   WaitAndAcceptPromptForRequest(request_notifications.get());
1609
1610   EXPECT_EQ(prompt_factory_->show_count(), GetParam() ? 5 : 4);
1611 }
1612
1613 // Verifies that non abusive chip behaves similar to others when Quiet UI Chip
1614 // is enabled.
1615 //
1616 // Permissions requested in order:
1617 // 1. Camera
1618 // 2. Notification (non abusive)
1619 // 3. After less than 8.5 seconds Geolocation
1620 // 4. MIDI
1621 //
1622 // Prompt display order:
1623 // 1. Camera request shown
1624 // 2. MIDI request shown (or MIDI and then Camera, the order depends on
1625 // `GetParam()`)
1626 // 3. Geolocation request shown
1627 // 4. Notifications request shown
1628 // If Chip is enabled MIDI will replace Camera, hence 5 prompts will be
1629 // shown. Otherwise 4.
1630 TEST_P(PermissionRequestManagerTestQuietChip,
1631        CameraNonAbusiveNotificationsGeolocationMIDI) {
1632   std::unique_ptr<MockPermissionRequest> request_camera = CreateAndAddRequest(
1633       RequestType::kCameraStream, /*should_be_seen=*/true, 1);
1634
1635   // Quiet UI is not shown because Camera has higher priority.
1636   std::unique_ptr<MockPermissionRequest> request_notifications =
1637       CreateAndAddRequest(RequestType::kNotifications, /*should_be_seen=*/false,
1638                           1);
1639   // Less then 8.5 seconds.
1640   manager_->set_current_request_first_display_time_for_testing(
1641       base::Time::Now() - base::Milliseconds(5000));
1642
1643   // Geolocation is not shown because Camera has higher priority.
1644   std::unique_ptr<MockPermissionRequest> request_geolocation =
1645       CreateAndAddRequest(RequestType::kGeolocation, /*should_be_seen=*/false,
1646                           1);
1647
1648   std::unique_ptr<MockPermissionRequest> request_midi;
1649
1650   // If Chip is enabled, MIDI should be shown, otherwise MIDI should not be
1651   // shown.
1652   if (GetParam()) {
1653     request_midi = CreateAndAddRequest(RequestType::kMidiSysex,
1654                                        /*should_be_seen=*/true, 2);
1655   } else {
1656     request_midi = CreateAndAddRequest(RequestType::kMidiSysex,
1657                                        /*should_be_seen=*/false, 1);
1658   }
1659
1660   // The second permission after quiet UI was requested in 8.5 second window,
1661   // the quiet UI Notifiations request for an abusive origin is not
1662   // automatically ignored.
1663   EXPECT_FALSE(request_notifications->granted());
1664   EXPECT_FALSE(request_notifications->finished());
1665
1666   WaitAndAcceptPromptForRequest(GetParam() ? request_midi.get()
1667                                            : request_camera.get());
1668   WaitAndAcceptPromptForRequest(GetParam() ? request_camera.get()
1669                                            : request_midi.get());
1670   WaitAndAcceptPromptForRequest(request_geolocation.get());
1671   WaitAndAcceptPromptForRequest(request_notifications.get());
1672
1673   EXPECT_EQ(prompt_factory_->show_count(), GetParam() ? 5 : 4);
1674 }
1675
1676 INSTANTIATE_TEST_SUITE_P(All,
1677                          PermissionRequestManagerTest,
1678                          ::testing::Values(false, true));
1679 INSTANTIATE_TEST_SUITE_P(All,
1680                          PermissionRequestManagerTestQuietChip,
1681                          ::testing::Values(false, true));
1682
1683 // Verifies order of requests with mixed low-high priority requests input, with
1684 // both chip and quiet chip enabled. New permissions are added and accepted one
1685 // by one.
1686 //
1687 // Permissions requested in order:
1688 // 1. Multiple Download (high)
1689 // 2. Geolocation (low)
1690 // 3. Mic (high)
1691 //
1692 // Prompt display order:
1693 // 1. Mic
1694 // 2. Multiple Download
1695 // 3. Geolocation
1696 TEST_P(PermissionRequestManagerTestQuietChip, Mixed1Low2HighPriorityRequests) {
1697   if (!GetParam())
1698     return;
1699
1700   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request2_);
1701   WaitForBubbleToBeShown();
1702
1703   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
1704   WaitForBubbleToBeShown();
1705
1706   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_mic_);
1707   WaitForBubbleToBeShown();
1708
1709   EXPECT_TRUE(prompt_factory_->is_visible());
1710   EXPECT_EQ(prompt_factory_->request_count(), 1);
1711   Accept();
1712   EXPECT_TRUE(request_mic_.granted());
1713   EXPECT_FALSE(request2_.granted());
1714   EXPECT_FALSE(request1_.granted());
1715   WaitForBubbleToBeShown();
1716
1717   EXPECT_TRUE(prompt_factory_->is_visible());
1718   EXPECT_EQ(prompt_factory_->request_count(), 1);
1719   Accept();
1720   EXPECT_TRUE(request2_.granted());
1721   EXPECT_FALSE(request1_.granted());
1722   WaitForBubbleToBeShown();
1723
1724   EXPECT_TRUE(prompt_factory_->is_visible());
1725   EXPECT_EQ(prompt_factory_->request_count(), 1);
1726   Accept();
1727   EXPECT_TRUE(request1_.granted());
1728 }
1729
1730 // Verifies order of requests with mixed low-high priority requests input, with
1731 // both chip and quiet chip enabled. New permissions are added and accepted one
1732 // by one.
1733 //
1734 // Permissions requested in order:
1735 // 1. Geolocation (low)
1736 // 2. Mic (high)
1737 // 3. Notification (low)
1738 //
1739 // Prompt display order:
1740 // 1. Mic
1741 // 2. Notification
1742 // 3. Geolocation
1743 TEST_P(PermissionRequestManagerTestQuietChip, Mixed2Low1HighRequests) {
1744   if (!GetParam())
1745     return;
1746
1747   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
1748   WaitForBubbleToBeShown();
1749
1750   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_mic_);
1751   WaitForBubbleToBeShown();
1752
1753   MockPermissionRequest request(RequestType::kNotifications,
1754                                 PermissionRequestGestureType::GESTURE);
1755   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request);
1756   WaitForBubbleToBeShown();
1757
1758   EXPECT_TRUE(prompt_factory_->is_visible());
1759   EXPECT_EQ(prompt_factory_->request_count(), 1);
1760   Accept();
1761   EXPECT_TRUE(request_mic_.granted());
1762   EXPECT_FALSE(request.granted());
1763   EXPECT_FALSE(request1_.granted());
1764   WaitForBubbleToBeShown();
1765
1766   EXPECT_TRUE(prompt_factory_->is_visible());
1767   EXPECT_EQ(prompt_factory_->request_count(), 1);
1768   Accept();
1769   EXPECT_TRUE(request.granted());
1770   EXPECT_FALSE(request1_.granted());
1771   WaitForBubbleToBeShown();
1772
1773   EXPECT_TRUE(prompt_factory_->is_visible());
1774   EXPECT_EQ(prompt_factory_->request_count(), 1);
1775   Accept();
1776   EXPECT_TRUE(request1_.granted());
1777 }
1778
1779 // Verifies order of requests with mixed low-high priority requests input, added
1780 // simultaneously, with both chip and quiet chip enabled.
1781 //
1782 // Permissions requested in order:
1783 // 1. Geolocation (low)
1784 // 2. Mic (high)
1785 // 3. Notification (low)
1786 //
1787 // Prompt display order:
1788 // 1. Mic
1789 // 2. Notification
1790 // 3. Geolocation
1791 TEST_P(PermissionRequestManagerTestQuietChip,
1792        MultipleSimultaneous2Low1HighRequests) {
1793   if (!GetParam())
1794     return;
1795
1796   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
1797   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_mic_);
1798   MockPermissionRequest request(RequestType::kNotifications,
1799                                 PermissionRequestGestureType::GESTURE);
1800   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request);
1801   WaitForBubbleToBeShown();
1802
1803   EXPECT_TRUE(prompt_factory_->is_visible());
1804   EXPECT_EQ(prompt_factory_->request_count(), 1);
1805   Accept();
1806   EXPECT_TRUE(request_mic_.granted());
1807   EXPECT_FALSE(request.granted());
1808   EXPECT_FALSE(request1_.granted());
1809   WaitForBubbleToBeShown();
1810
1811   EXPECT_TRUE(prompt_factory_->is_visible());
1812   EXPECT_EQ(prompt_factory_->request_count(), 1);
1813   Accept();
1814   EXPECT_TRUE(request.granted());
1815   EXPECT_FALSE(request1_.granted());
1816   WaitForBubbleToBeShown();
1817
1818   EXPECT_TRUE(prompt_factory_->is_visible());
1819   EXPECT_EQ(prompt_factory_->request_count(), 1);
1820   Accept();
1821   EXPECT_TRUE(request1_.granted());
1822 }
1823
1824 // Verifies order of requests with mixed low-high priority requests input,
1825 // added simultaneously, with both chip and quiet chip enabled.
1826 //
1827 // Permissions requested in order:
1828 // 1. MIDI (high)
1829 // 2. Geolocation (low)
1830 // 3. Mic (high)
1831 // 4. Notification (low)
1832 // 5. Multiple Download (high)
1833 //
1834 // Prompt display order:
1835 // 1. Multiple Download
1836 // 2. Mic
1837 // 3. Midi
1838 // 4. Notification
1839 // 5. Geolocation
1840 TEST_P(PermissionRequestManagerTestQuietChip,
1841        MultipleSimultaneous2Low3HighRequests) {
1842   if (!GetParam())
1843     return;
1844   MockPermissionRequest request_midi(RequestType::kMidiSysex,
1845                                      PermissionRequestGestureType::GESTURE);
1846   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_midi);
1847   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
1848   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_mic_);
1849   MockPermissionRequest request_notification(
1850       RequestType::kNotifications, PermissionRequestGestureType::GESTURE);
1851   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(),
1852                        &request_notification);
1853   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request2_);
1854   WaitForBubbleToBeShown();
1855
1856   EXPECT_TRUE(prompt_factory_->is_visible());
1857   EXPECT_EQ(prompt_factory_->request_count(), 1);
1858   Accept();
1859   EXPECT_FALSE(request_mic_.granted());
1860   EXPECT_TRUE(request2_.granted());
1861   EXPECT_FALSE(request_notification.granted());
1862   EXPECT_FALSE(request1_.granted());
1863   EXPECT_FALSE(request_midi.granted());
1864   WaitForBubbleToBeShown();
1865
1866   EXPECT_TRUE(prompt_factory_->is_visible());
1867   EXPECT_EQ(prompt_factory_->request_count(), 1);
1868   Accept();
1869   EXPECT_TRUE(request_mic_.granted());
1870   EXPECT_FALSE(request_notification.granted());
1871   EXPECT_FALSE(request1_.granted());
1872   EXPECT_FALSE(request_midi.granted());
1873   WaitForBubbleToBeShown();
1874
1875   EXPECT_TRUE(prompt_factory_->is_visible());
1876   EXPECT_EQ(prompt_factory_->request_count(), 1);
1877   Accept();
1878   EXPECT_FALSE(request_notification.granted());
1879   EXPECT_FALSE(request1_.granted());
1880   EXPECT_TRUE(request_midi.granted());
1881   WaitForBubbleToBeShown();
1882
1883   EXPECT_TRUE(prompt_factory_->is_visible());
1884   EXPECT_EQ(prompt_factory_->request_count(), 1);
1885   Accept();
1886   EXPECT_TRUE(request_notification.granted());
1887   EXPECT_FALSE(request1_.granted());
1888   WaitForBubbleToBeShown();
1889
1890   EXPECT_TRUE(prompt_factory_->is_visible());
1891   EXPECT_EQ(prompt_factory_->request_count(), 1);
1892   Accept();
1893   EXPECT_TRUE(request1_.granted());
1894 }
1895
1896 // Verifies order of requests with mixed low-high priority requests input, added
1897 // simultaneously several times, with both chip and quiet chip enabled.
1898 //
1899 // Permissions requested in order:
1900 // 1. Geolocation(low) then Notification(low)
1901 // 2. Mic (high) then multiple downloads (high)
1902 // Prompt display order:
1903 // 1. Multiple Download
1904 // 2. Mic
1905 // 3. Notification
1906 // 4. Geolocation
1907 TEST_P(PermissionRequestManagerTestQuietChip,
1908        MultipleSimultaneous2Low2HighRequests) {
1909   if (!GetParam())
1910     return;
1911
1912   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
1913   MockPermissionRequest request(RequestType::kNotifications,
1914                                 PermissionRequestGestureType::GESTURE);
1915   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request);
1916   WaitForBubbleToBeShown();
1917
1918   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_mic_);
1919   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request2_);
1920   WaitForBubbleToBeShown();
1921
1922   EXPECT_TRUE(prompt_factory_->is_visible());
1923   EXPECT_EQ(prompt_factory_->request_count(), 1);
1924   Accept();
1925   EXPECT_TRUE(request2_.granted());
1926   EXPECT_FALSE(request_mic_.granted());
1927   EXPECT_FALSE(request.granted());
1928   EXPECT_FALSE(request1_.granted());
1929   WaitForBubbleToBeShown();
1930
1931   EXPECT_TRUE(prompt_factory_->is_visible());
1932   EXPECT_EQ(prompt_factory_->request_count(), 1);
1933   Accept();
1934   EXPECT_TRUE(request_mic_.granted());
1935   EXPECT_FALSE(request.granted());
1936   EXPECT_FALSE(request1_.granted());
1937   WaitForBubbleToBeShown();
1938
1939   EXPECT_TRUE(prompt_factory_->is_visible());
1940   EXPECT_EQ(prompt_factory_->request_count(), 1);
1941   Accept();
1942   EXPECT_TRUE(request.granted());
1943   EXPECT_FALSE(request1_.granted());
1944   WaitForBubbleToBeShown();
1945
1946   EXPECT_TRUE(prompt_factory_->is_visible());
1947   EXPECT_EQ(prompt_factory_->request_count(), 1);
1948   Accept();
1949   EXPECT_TRUE(request1_.granted());
1950 }
1951
1952 // Verifies order of requests with mixed low-high priority requests input, with
1953 // both chip and quiet chip enabled. Simultaneous new requests are coming while
1954 // we are waiting for UI selector decisions.
1955 //
1956 // Permissions requested in order:
1957 // 1. Geolocation (low), UI selector takes 2 seconds to decide.
1958 // 2. Notification(low) then mic (high)
1959 //
1960 // Prompt display order:
1961 // 1. Mic
1962 // 2. Geolocation will get delayed 2 seconds, then preempted to front of queue
1963 // 3. Notification
1964 TEST_P(PermissionRequestManagerTestQuietChip,
1965        NewHighPriorityRequestDuringUIDecision) {
1966   if (!GetParam())
1967     return;
1968
1969   manager_->clear_permission_ui_selector_for_testing();
1970   MockNotificationPermissionUiSelector::CreateForManager(
1971       manager_, QuietUiReason::kTriggeredDueToAbusiveRequests,
1972       absl::make_optional<base::TimeDelta>(base::Seconds(2)));
1973   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request1_);
1974
1975   task_environment()->FastForwardBy(base::Seconds(1));
1976
1977   MockPermissionRequest request(RequestType::kNotifications,
1978                                 PermissionRequestGestureType::GESTURE);
1979   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request);
1980   manager_->AddRequest(web_contents()->GetPrimaryMainFrame(), &request_mic_);
1981   WaitForBubbleToBeShown();
1982   manager_->clear_permission_ui_selector_for_testing();
1983
1984   EXPECT_TRUE(prompt_factory_->is_visible());
1985   EXPECT_EQ(prompt_factory_->request_count(), 1);
1986   Accept();
1987   EXPECT_TRUE(request_mic_.granted());
1988   EXPECT_FALSE(request.granted());
1989   EXPECT_FALSE(request1_.granted());
1990   WaitForBubbleToBeShown();
1991
1992   EXPECT_TRUE(prompt_factory_->is_visible());
1993   EXPECT_EQ(prompt_factory_->request_count(), 1);
1994   Accept();
1995   EXPECT_TRUE(request1_.granted());
1996   EXPECT_FALSE(request.granted());
1997   WaitForBubbleToBeShown();
1998
1999   EXPECT_TRUE(prompt_factory_->is_visible());
2000   EXPECT_EQ(prompt_factory_->request_count(), 1);
2001   Accept();
2002   EXPECT_TRUE(request.granted());
2003 }
2004
2005 }  // namespace permissions