1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
|
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/sms/webotp_service.h"
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include "base/command_line.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/run_loop.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/bind.h"
#include "base/test/metrics/histogram_tester.h"
#include "components/ukm/test_ukm_recorder.h"
#include "content/browser/sms/sms_fetcher_impl.h"
#include "content/browser/sms/test/mock_sms_provider.h"
#include "content/browser/sms/test/mock_sms_web_contents_delegate.h"
#include "content/browser/sms/test/mock_user_consent_handler.h"
#include "content/browser/sms/user_consent_handler.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/sms_fetcher.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/navigation_simulator.h"
#include "content/public/test/test_browser_context.h"
#include "content/public/test/test_renderer_host.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/test_support/test_utils.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "services/service_manager/public/cpp/bind_source_info.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/sms/webotp_service_outcome.h"
#include "third_party/blink/public/mojom/sms/webotp_service.mojom-shared.h"
#include "third_party/blink/public/mojom/sms/webotp_service.mojom.h"
using base::BindLambdaForTesting;
using blink::mojom::SmsStatus;
using blink::mojom::WebOTPService;
using std::optional;
using std::string;
using ::testing::_;
using ::testing::ByMove;
using ::testing::Invoke;
using ::testing::NiceMock;
using ::testing::Return;
using ::testing::StrictMock;
using url::Origin;
namespace content {
class RenderFrameHost;
using Entry = ukm::builders::SMSReceiver;
using FailureType = SmsFetchFailureType;
using UserConsent = SmsFetcher::UserConsent;
namespace {
const char kTestUrl[] = "https://www.google.com";
class StubWebContentsDelegate : public WebContentsDelegate {};
// Service encapsulates a WebOTPService endpoint, with all of its dependencies
// mocked out (and the common plumbing needed to inject them), and a
// mojo::Remote<WebOTPService> endpoint that tests can use to make requests.
// It exposes some common methods, like MakeRequest and NotifyReceive, but it
// also exposes the low level mocks that enables tests to set expectations and
// control the testing environment.
class Service {
protected:
Service(WebContents* web_contents,
const Origin& origin,
std::unique_ptr<UserConsentHandler> user_consent_handler)
: fetcher_(&provider_),
consent_handler_(std::move(user_consent_handler)) {
// Set a stub delegate because sms service checks existence of delegate and
// cancels requests early if one does not exist.
web_contents->SetDelegate(&contents_delegate_);
// WebOTPService is a DocumentService and normally self-deletes. For the
// purposes of the test, `~Service` is responsible for manually cleaning
// up `service_`. A normal std::unique_ptr<T> is not allowed here, since a
// DocumentService implementation must be deleted by calling one of the
// `*AndDeleteThis()` methods.
service_ = &WebOTPService::CreateForTesting(
&fetcher_, WebOTPService::OriginList{origin},
*web_contents->GetPrimaryMainFrame(),
service_remote_.BindNewPipeAndPassReceiver());
service_->SetConsentHandlerForTesting(consent_handler_.get());
}
public:
explicit Service(WebContents* web_contents)
: Service(web_contents,
web_contents->GetPrimaryMainFrame()->GetLastCommittedOrigin(),
/* avoid showing user prompts */
std::make_unique<NoopUserConsentHandler>()) {}
~Service() { Dispose(); }
NiceMock<MockSmsProvider>* provider() { return &provider_; }
SmsFetcher* fetcher() { return &fetcher_; }
UserConsentHandler* consent_handler() { return consent_handler_.get(); }
void MakeRequest(WebOTPService::ReceiveCallback callback) {
service_remote_->Receive(std::move(callback));
}
void AbortRequest() { service_remote_->Abort(); }
void NotifyReceive(const GURL& url,
const string& otp,
/* avoid showing user prompts */
UserConsent consent_requirement = UserConsent::kObtained) {
provider_.NotifyReceive(WebOTPService::OriginList{Origin::Create(url)}, otp,
consent_requirement);
}
void NotifyFailure(FailureType failure_type) {
service_->OnFailure(failure_type);
}
void ActivateTimer() { service_->OnTimeout(); }
protected:
void Dispose() {
if (!service_) {
return;
}
// WebOTPService sends IPCs in its destructor, so for the unit test, pretend
// that this works.
service_->WillBeDestroyed(
DocumentServiceDestructionReason::kEndOfDocumentLifetime);
service_.ExtractAsDangling()->ResetAndDeleteThis();
}
private:
StubWebContentsDelegate contents_delegate_;
NiceMock<MockSmsProvider> provider_;
SmsFetcherImpl fetcher_;
std::unique_ptr<UserConsentHandler> consent_handler_;
mojo::Remote<blink::mojom::WebOTPService> service_remote_;
raw_ptr<WebOTPService> service_;
};
class WebOTPServiceTest : public RenderViewHostTestHarness {
public:
WebOTPServiceTest(const WebOTPServiceTest&) = delete;
WebOTPServiceTest& operator=(const WebOTPServiceTest&) = delete;
protected:
WebOTPServiceTest() {
ukm_recorder_ = std::make_unique<ukm::TestAutoSetUkmRecorder>();
}
~WebOTPServiceTest() override = default;
const base::HistogramTester& histogram_tester() const {
return histogram_tester_;
}
ukm::TestAutoSetUkmRecorder* ukm_recorder() { return ukm_recorder_.get(); }
void ExpectOutcomeUKM(const GURL& url, blink::WebOTPServiceOutcome outcome) {
auto entries = ukm_recorder()->GetEntriesByName(Entry::kEntryName);
if (entries.empty())
FAIL() << "No WebOTPServiceOutcome was recorded";
// There are non-outcome metrics under the same entry of SMSReceiver UKM. We
// need to make sure that the outcome metric only includes the expected one.
for (const ukm::mojom::UkmEntry* const entry : entries) {
const int64_t* metric = ukm_recorder()->GetEntryMetric(entry, "Outcome");
if (metric && *metric != static_cast<int>(outcome))
FAIL() << "Unexpected outcome was recorded";
}
SUCCEED();
}
void ExpectTimingUKM(const std::string& metric_name) {
auto entries = ukm_recorder()->GetEntriesByName(Entry::kEntryName);
ASSERT_FALSE(entries.empty());
for (const ukm::mojom::UkmEntry* const entry : entries) {
if (ukm_recorder()->GetEntryMetric(entry, metric_name)) {
SUCCEED();
return;
}
}
FAIL() << "Expected UKM was not recorded";
}
void ExpectNoOutcomeUKM() {
EXPECT_TRUE(ukm_recorder()->GetEntriesByName(Entry::kEntryName).empty());
}
void RecordFailureOutcomeWithTimerActivation(
FailureType failure_type,
blink::WebOTPServiceOutcome expected_outcome) {
GURL url = GURL(kTestUrl);
NavigateAndCommit(url);
Service service(web_contents());
base::RunLoop ukm_loop;
ukm_recorder()->SetOnAddEntryCallback(Entry::kEntryName,
ukm_loop.QuitClosure());
EXPECT_CALL(*service.provider(), Retrieve(_, _)).WillOnce(Invoke([&]() {
service.NotifyFailure(failure_type);
// Triggers the timer immediately to emulate the timeout behavior.
service.ActivateTimer();
}));
service.MakeRequest(base::DoNothing());
ukm_loop.Run();
ExpectOutcomeUKM(url, expected_outcome);
ASSERT_FALSE(service.fetcher()->HasSubscribers());
}
void NotRecordFailureOutcomeWithoutTimerActivation(FailureType failure_type) {
GURL url = GURL(kTestUrl);
NavigateAndCommit(url);
Service service(web_contents());
base::RunLoop loop;
EXPECT_CALL(*service.provider(), Retrieve(_, _)).WillOnce(Invoke([&]() {
service.NotifyFailure(failure_type);
loop.Quit();
}));
service.MakeRequest(base::DoNothing());
loop.Run();
ExpectNoOutcomeUKM();
ASSERT_FALSE(service.fetcher()->HasSubscribers());
}
void RecordFailureOutcomeUponPreviousRequestCancelled(
FailureType failure_type,
blink::WebOTPServiceOutcome expected_outcome) {
GURL url = GURL(kTestUrl);
NavigateAndCommit(url);
Service service(web_contents());
base::RunLoop loop;
EXPECT_CALL(*service.provider(), Retrieve(_, _)).WillOnce(Invoke([&]() {
service.NotifyFailure(failure_type);
loop.Quit();
}));
service.MakeRequest(base::DoNothing());
loop.Run();
::testing::Mock::VerifyAndClear(&service);
base::RunLoop loop2;
EXPECT_CALL(*service.provider(), Retrieve(_, _)).WillOnce(Invoke([&]() {
loop2.Quit();
}));
// The second request to the same service cancels the previous outstanding
// request.
service.MakeRequest(base::DoNothing());
loop2.Run();
ExpectOutcomeUKM(url, expected_outcome);
}
void RecordFailureOutcomeUponDestruction(
FailureType failure_type,
blink::WebOTPServiceOutcome expected_outcome) {
GURL url = GURL(kTestUrl);
NavigateAndCommit(url);
{
Service service(web_contents());
base::RunLoop loop;
EXPECT_CALL(*service.provider(), Retrieve(_, _)).WillOnce(Invoke([&]() {
service.NotifyFailure(failure_type);
loop.Quit();
}));
service.MakeRequest(base::DoNothing());
loop.Run();
}
// |service| going out of scope means that the outstanding request would be
// considered failed with |kUnhandledRequest|.
ExpectOutcomeUKM(url, expected_outcome);
}
private:
base::HistogramTester histogram_tester_;
std::unique_ptr<ukm::TestAutoSetUkmRecorder> ukm_recorder_;
};
} // namespace
TEST_F(WebOTPServiceTest, Basic) {
NavigateAndCommit(GURL(kTestUrl));
Service service(web_contents());
base::RunLoop loop;
EXPECT_CALL(*service.provider(), Retrieve(_, _))
.WillOnce(Invoke(
[&service]() { service.NotifyReceive(GURL(kTestUrl), "hi"); }));
service.MakeRequest(BindLambdaForTesting(
[&loop](SmsStatus status, const optional<string>& otp) {
EXPECT_EQ(SmsStatus::kSuccess, status);
EXPECT_EQ("hi", otp.value());
loop.Quit();
}));
loop.Run();
ASSERT_FALSE(service.fetcher()->HasSubscribers());
}
TEST_F(WebOTPServiceTest, HandlesMultipleCalls) {
NavigateAndCommit(GURL(kTestUrl));
Service service(web_contents());
{
base::RunLoop loop;
EXPECT_CALL(*service.provider(), Retrieve(_, _))
.WillOnce(Invoke(
[&service]() { service.NotifyReceive(GURL(kTestUrl), "first"); }));
service.MakeRequest(BindLambdaForTesting(
[&loop](SmsStatus status, const optional<string>& otp) {
EXPECT_EQ("first", otp.value());
EXPECT_EQ(SmsStatus::kSuccess, status);
loop.Quit();
}));
loop.Run();
}
{
base::RunLoop loop;
EXPECT_CALL(*service.provider(), Retrieve(_, _))
.WillOnce(Invoke(
[&service]() { service.NotifyReceive(GURL(kTestUrl), "second"); }));
service.MakeRequest(BindLambdaForTesting(
[&loop](SmsStatus status, const optional<string>& otp) {
EXPECT_EQ("second", otp.value());
EXPECT_EQ(SmsStatus::kSuccess, status);
loop.Quit();
}));
loop.Run();
}
}
TEST_F(WebOTPServiceTest, IgnoreFromOtherOrigins) {
NavigateAndCommit(GURL(kTestUrl));
Service service(web_contents());
SmsStatus sms_status;
optional<string> response;
base::RunLoop sms_loop;
EXPECT_CALL(*service.provider(), Retrieve(_, _))
.WillOnce(Invoke([&service]() {
// Delivers an SMS from an unrelated origin first and expect the
// receiver to ignore it.
service.NotifyReceive(GURL("http://b.com"), "wrong");
service.NotifyReceive(GURL(kTestUrl), "right");
}));
service.MakeRequest(
BindLambdaForTesting([&sms_status, &response, &sms_loop](
SmsStatus status, const optional<string>& otp) {
sms_status = status;
response = otp;
sms_loop.Quit();
}));
sms_loop.Run();
EXPECT_EQ("right", response.value());
EXPECT_EQ(SmsStatus::kSuccess, sms_status);
}
TEST_F(WebOTPServiceTest, ExpectOneReceiveTwo) {
NavigateAndCommit(GURL(kTestUrl));
Service service(web_contents());
SmsStatus sms_status;
optional<string> response;
base::RunLoop sms_loop;
EXPECT_CALL(*service.provider(), Retrieve(_, _))
.WillOnce(Invoke([&service]() {
// Delivers two SMSes for the same origin, even if only one was being
// expected.
ASSERT_TRUE(service.fetcher()->HasSubscribers());
service.NotifyReceive(GURL(kTestUrl), "first");
ASSERT_FALSE(service.fetcher()->HasSubscribers());
service.NotifyReceive(GURL(kTestUrl), "second");
}));
service.MakeRequest(
BindLambdaForTesting([&sms_status, &response, &sms_loop](
SmsStatus status, const optional<string>& otp) {
sms_status = status;
response = otp;
sms_loop.Quit();
}));
sms_loop.Run();
EXPECT_EQ("first", response.value());
EXPECT_EQ(SmsStatus::kSuccess, sms_status);
}
TEST_F(WebOTPServiceTest, AtMostOneSmsRequestPerOrigin) {
NavigateAndCommit(GURL(kTestUrl));
Service service(web_contents());
SmsStatus sms_status1;
optional<string> response1;
SmsStatus sms_status2;
optional<string> response2;
base::RunLoop sms1_loop, sms2_loop;
EXPECT_CALL(*service.provider(), Retrieve(_, _))
.WillOnce(Return())
.WillOnce(Invoke(
[&service]() { service.NotifyReceive(GURL(kTestUrl), "second"); }));
service.MakeRequest(
BindLambdaForTesting([&sms_status1, &response1, &sms1_loop](
SmsStatus status, const optional<string>& otp) {
sms_status1 = status;
response1 = otp;
sms1_loop.Quit();
}));
// Make the 2nd SMS request which will cancel the 1st request because only
// one request can be pending per origin per tab.
service.MakeRequest(
BindLambdaForTesting([&sms_status2, &response2, &sms2_loop](
SmsStatus status, const optional<string>& otp) {
sms_status2 = status;
response2 = otp;
sms2_loop.Quit();
}));
sms1_loop.Run();
sms2_loop.Run();
EXPECT_EQ(std::nullopt, response1);
EXPECT_EQ(SmsStatus::kCancelled, sms_status1);
EXPECT_EQ("second", response2.value());
EXPECT_EQ(SmsStatus::kSuccess, sms_status2);
}
TEST_F(WebOTPServiceTest, CleansUp) {
NavigateAndCommit(GURL(kTestUrl));
NiceMock<MockSmsWebContentsDelegate> delegate;
WebContentsImpl* web_contents_impl =
static_cast<WebContentsImpl*>(web_contents());
web_contents_impl->SetDelegate(&delegate);
NiceMock<MockSmsProvider> provider;
SmsFetcherImpl fetcher(&provider);
mojo::Remote<blink::mojom::WebOTPService> service;
EXPECT_TRUE(WebOTPService::Create(&fetcher, main_rfh(),
service.BindNewPipeAndPassReceiver()));
base::RunLoop navigate;
EXPECT_CALL(provider, Retrieve(_, _)).WillOnce(Invoke([&navigate]() {
navigate.Quit();
}));
base::RunLoop reload;
service->Receive(base::BindLambdaForTesting(
[&reload](SmsStatus status, const optional<string>& otp) {
EXPECT_EQ(SmsStatus::kUnhandledRequest, status);
EXPECT_EQ(std::nullopt, otp);
reload.Quit();
}));
navigate.Run();
// Simulates the user reloading the page and navigating away, which
// destructs the service.
NavigateAndCommit(GURL(kTestUrl));
reload.Run();
ASSERT_FALSE(fetcher.HasSubscribers());
}
TEST_F(WebOTPServiceTest, Abort) {
NavigateAndCommit(GURL(kTestUrl));
Service service(web_contents());
base::RunLoop loop;
service.MakeRequest(BindLambdaForTesting(
[&loop](SmsStatus status, const optional<string>& otp) {
EXPECT_EQ(SmsStatus::kAborted, status);
EXPECT_EQ(std::nullopt, otp);
loop.Quit();
}));
service.AbortRequest();
loop.Run();
ASSERT_FALSE(service.fetcher()->HasSubscribers());
}
// Following tests exercise parts of sms service logic that depend on user
// prompting. In particular how we handle incoming request while there is an
// active in-flight prompts.
class ServiceWithPrompt : public Service {
public:
explicit ServiceWithPrompt(WebContents* web_contents)
: Service(web_contents,
web_contents->GetPrimaryMainFrame()->GetLastCommittedOrigin(),
std::make_unique<NiceMock<MockUserConsentHandler>>()) {
mock_handler_ =
static_cast<NiceMock<MockUserConsentHandler>*>(consent_handler());
}
~ServiceWithPrompt() {
// At destruction, WebOTPService calls into `MockUserConsentHandler`, which
// can reference `on_complete_callback_`. Preemptively tear it down so
// `on_complete_callback_` is not destroyed before it is used.
Dispose();
}
void ExpectRequestUserConsent() {
EXPECT_CALL(*mock_handler_, RequestUserConsent(_, _))
.WillOnce(Invoke(
[=, this](const std::string&, CompletionCallback on_complete) {
on_complete_callback_ = std::move(on_complete);
}));
EXPECT_CALL(*mock_handler_, is_async()).WillRepeatedly(Return(true));
EXPECT_CALL(*mock_handler_, is_active()).WillRepeatedly(Invoke([=, this]() {
return !on_complete_callback_.is_null();
}));
}
void ConfirmPrompt() {
if (on_complete_callback_.is_null()) {
FAIL() << "User prompt is not available";
}
std::move(on_complete_callback_).Run(UserConsentResult::kApproved);
on_complete_callback_.Reset();
}
void DismissPrompt() {
if (on_complete_callback_.is_null()) {
FAIL() << "User prompt is not available";
}
std::move(on_complete_callback_).Run(UserConsentResult::kDenied);
ActivateTimer();
on_complete_callback_.Reset();
}
bool IsPromptOpen() const { return !on_complete_callback_.is_null(); }
private:
// The actual consent handler is owned by WebOTPService but we keep a ptr to
// it so it can be used to set expectations for it. It is safe since the
// sms service lifetime is the same as this object.
raw_ptr<NiceMock<MockUserConsentHandler>> mock_handler_;
CompletionCallback on_complete_callback_;
};
TEST_F(WebOTPServiceTest, SecondRequestDuringPrompt) {
NavigateAndCommit(GURL(kTestUrl));
ServiceWithPrompt service(web_contents());
SmsStatus sms_status1;
optional<string> response1;
SmsStatus sms_status2;
optional<string> response2;
base::RunLoop sms_loop;
// Expect SMS Prompt to be created once.
service.ExpectRequestUserConsent();
EXPECT_CALL(*service.provider(), Retrieve(_, _))
.WillOnce(Invoke([&service]() {
service.NotifyReceive(GURL(kTestUrl), "second",
UserConsent::kNotObtained);
}));
// First request.
service.MakeRequest(
BindLambdaForTesting([&sms_status1, &response1, &service](
SmsStatus status, const optional<string>& otp) {
sms_status1 = status;
response1 = otp;
service.ConfirmPrompt();
}));
// Make second request before confirming prompt.
service.MakeRequest(
BindLambdaForTesting([&sms_status2, &response2, &sms_loop](
SmsStatus status, const optional<string>& otp) {
sms_status2 = status;
response2 = otp;
sms_loop.Quit();
}));
sms_loop.Run();
EXPECT_EQ(std::nullopt, response1);
EXPECT_EQ(SmsStatus::kCancelled, sms_status1);
EXPECT_EQ("second", response2.value());
EXPECT_EQ(SmsStatus::kSuccess, sms_status2);
}
TEST_F(WebOTPServiceTest, AbortWhilePrompt) {
NavigateAndCommit(GURL(kTestUrl));
ServiceWithPrompt service(web_contents());
base::RunLoop loop;
service.ExpectRequestUserConsent();
service.MakeRequest(BindLambdaForTesting(
[&loop](SmsStatus status, const optional<string>& otp) {
EXPECT_EQ(SmsStatus::kAborted, status);
EXPECT_EQ(std::nullopt, otp);
loop.Quit();
}));
EXPECT_CALL(*service.provider(), Retrieve(_, _))
.WillOnce(Invoke([&service]() {
service.NotifyReceive(GURL(kTestUrl), "ABC", UserConsent::kNotObtained);
EXPECT_TRUE(service.IsPromptOpen());
service.AbortRequest();
}));
loop.Run();
ASSERT_FALSE(service.fetcher()->HasSubscribers());
service.ConfirmPrompt();
}
TEST_F(WebOTPServiceTest, RequestAfterAbortWhilePrompt) {
NavigateAndCommit(GURL(kTestUrl));
ServiceWithPrompt service(web_contents());
{
base::RunLoop loop;
service.ExpectRequestUserConsent();
service.MakeRequest(BindLambdaForTesting(
[&loop](SmsStatus status, const optional<string>& otp) {
EXPECT_EQ(SmsStatus::kAborted, status);
EXPECT_EQ(std::nullopt, otp);
loop.Quit();
}));
EXPECT_CALL(*service.provider(), Retrieve(_, _))
.WillOnce(Invoke([&service]() {
service.NotifyReceive(GURL(kTestUrl), "hi",
UserConsent::kNotObtained);
EXPECT_TRUE(service.IsPromptOpen());
service.AbortRequest();
}));
loop.Run();
}
ASSERT_FALSE(service.fetcher()->HasSubscribers());
// Confirm to dismiss prompt for a request that has already aborted.
service.ConfirmPrompt();
{
base::RunLoop loop;
service.ExpectRequestUserConsent();
service.MakeRequest(BindLambdaForTesting(
[&loop](SmsStatus status, const optional<string>& otp) {
// Verify that the 2nd request completes successfully after prompt
// confirmation.
EXPECT_EQ(SmsStatus::kSuccess, status);
EXPECT_EQ("hi2", otp.value());
loop.Quit();
}));
EXPECT_CALL(*service.provider(), Retrieve(_, _))
.WillOnce(Invoke([&service]() {
service.NotifyReceive(GURL(kTestUrl), "hi2",
UserConsent::kNotObtained);
service.ConfirmPrompt();
}));
loop.Run();
}
}
TEST_F(WebOTPServiceTest, SecondRequestWhilePrompt) {
NavigateAndCommit(GURL(kTestUrl));
ServiceWithPrompt service(web_contents());
base::RunLoop callback_loop1, callback_loop2, req_loop;
service.ExpectRequestUserConsent();
service.MakeRequest(BindLambdaForTesting(
[&callback_loop1](SmsStatus status, const optional<string>& otp) {
EXPECT_EQ(SmsStatus::kAborted, status);
EXPECT_EQ(std::nullopt, otp);
callback_loop1.Quit();
}));
EXPECT_CALL(*service.provider(), Retrieve(_, _))
.WillOnce(Invoke([&service]() {
service.NotifyReceive(GURL(kTestUrl), "hi", UserConsent::kNotObtained);
service.AbortRequest();
}));
callback_loop1.Run();
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTaskAndReply(
FROM_HERE, BindLambdaForTesting([&]() {
service.MakeRequest(BindLambdaForTesting(
[&callback_loop2](SmsStatus status, const optional<string>& otp) {
EXPECT_EQ(SmsStatus::kSuccess, status);
EXPECT_EQ("hi", otp.value());
callback_loop2.Quit();
}));
}),
req_loop.QuitClosure());
req_loop.Run();
// Simulate pressing 'Verify' on Infobar.
service.ConfirmPrompt();
callback_loop2.Run();
ASSERT_FALSE(service.fetcher()->HasSubscribers());
}
TEST_F(WebOTPServiceTest, RecordTimeMetricsForContinueOnSuccess) {
NavigateAndCommit(GURL(kTestUrl));
ServiceWithPrompt service(web_contents());
base::RunLoop loop;
service.ExpectRequestUserConsent();
EXPECT_CALL(*service.provider(), Retrieve(_, _))
.WillOnce(Invoke([&service]() {
service.NotifyReceive(GURL(kTestUrl), "ABC", UserConsent::kNotObtained);
service.ConfirmPrompt();
}));
service.MakeRequest(BindLambdaForTesting(
[&loop](SmsStatus status, const optional<string>& otp) { loop.Quit(); }));
loop.Run();
histogram_tester().ExpectTotalCount("Blink.Sms.Receive.TimeContinueOnSuccess",
1);
histogram_tester().ExpectTotalCount("Blink.Sms.Receive.TimeSmsReceive", 1);
}
TEST_F(WebOTPServiceTest, RecordMetricsForCancelOnSuccess) {
NavigateAndCommit(GURL(kTestUrl));
ServiceWithPrompt service(web_contents());
// Histogram will be recorded if the SMS has already arrived.
base::RunLoop loop;
service.ExpectRequestUserConsent();
EXPECT_CALL(*service.provider(), Retrieve(_, _))
.WillOnce(Invoke([&service]() {
service.NotifyReceive(GURL(kTestUrl), "hi", UserConsent::kNotObtained);
service.DismissPrompt();
}));
service.MakeRequest(BindLambdaForTesting(
[&loop](SmsStatus status, const optional<string>& otp) { loop.Quit(); }));
loop.Run();
histogram_tester().ExpectTotalCount("Blink.Sms.Receive.TimeCancelOnSuccess",
1);
histogram_tester().ExpectTotalCount("Blink.Sms.Receive.TimeSmsReceive", 1);
}
TEST_F(WebOTPServiceTest, RecordTimeoutAsOutcomeWithoutFailure) {
GURL url = GURL(kTestUrl);
NavigateAndCommit(url);
ServiceWithPrompt service(web_contents());
base::RunLoop ukm_loop;
ukm_recorder()->SetOnAddEntryCallback(Entry::kEntryName,
ukm_loop.QuitClosure());
service.ExpectRequestUserConsent();
EXPECT_CALL(*service.provider(), Retrieve(_, _))
.WillOnce(Invoke([&service]() {
service.NotifyReceive(GURL(kTestUrl), "hi", UserConsent::kNotObtained);
service.ActivateTimer();
}));
service.MakeRequest(base::DoNothing());
ukm_loop.Run();
ExpectOutcomeUKM(url, blink::WebOTPServiceOutcome::kTimeout);
}
TEST_F(WebOTPServiceTest, RecordTimeoutAsOutcomeWithTimerActivation) {
RecordFailureOutcomeWithTimerActivation(
FailureType::kPromptTimeout, blink::WebOTPServiceOutcome::kTimeout);
}
TEST_F(WebOTPServiceTest, NotRecordTimeoutAsOutcomeWithoutTimerActivation) {
NotRecordFailureOutcomeWithoutTimerActivation(FailureType::kPromptTimeout);
}
TEST_F(WebOTPServiceTest, RecordTimeoutAsOutcomeUponPreviousRequestCancelled) {
RecordFailureOutcomeUponPreviousRequestCancelled(
FailureType::kPromptTimeout, blink::WebOTPServiceOutcome::kTimeout);
}
TEST_F(WebOTPServiceTest, RecordTimeoutAsOutcomeUponDestruction) {
RecordFailureOutcomeUponDestruction(FailureType::kPromptTimeout,
blink::WebOTPServiceOutcome::kTimeout);
}
TEST_F(WebOTPServiceTest, RecordUserCancelledAsOutcome) {
RecordFailureOutcomeWithTimerActivation(
FailureType::kPromptCancelled,
blink::WebOTPServiceOutcome::kUserCancelled);
ExpectTimingUKM("TimeUserCancelMs");
histogram_tester().ExpectTotalCount("Blink.Sms.Receive.TimeUserCancel", 1);
}
TEST_F(WebOTPServiceTest,
NotRecordUserCancelledAsOutcomeWithoutTimerActivation) {
NotRecordFailureOutcomeWithoutTimerActivation(FailureType::kPromptCancelled);
}
TEST_F(WebOTPServiceTest,
RecordUserCancelledAsOutcomeUponPreviousRequestCancelled) {
RecordFailureOutcomeUponPreviousRequestCancelled(
FailureType::kPromptCancelled,
blink::WebOTPServiceOutcome::kUserCancelled);
}
TEST_F(WebOTPServiceTest, RecordUserCancelledAsOutcomeUponDestruction) {
RecordFailureOutcomeUponDestruction(
FailureType::kPromptCancelled,
blink::WebOTPServiceOutcome::kUserCancelled);
}
TEST_F(WebOTPServiceTest, RecordUserDismissPrompt) {
GURL url = GURL(kTestUrl);
NavigateAndCommit(url);
ServiceWithPrompt service(web_contents());
base::RunLoop ukm_loop;
ukm_recorder()->SetOnAddEntryCallback(Entry::kEntryName,
ukm_loop.QuitClosure());
service.ExpectRequestUserConsent();
EXPECT_CALL(*service.provider(), Retrieve(_, _))
.WillOnce(Invoke([&service]() {
service.NotifyReceive(GURL(kTestUrl), "hi", UserConsent::kNotObtained);
service.DismissPrompt();
}));
service.MakeRequest(base::DoNothing());
ukm_loop.Run();
ExpectOutcomeUKM(url, blink::WebOTPServiceOutcome::kUserCancelled);
ExpectTimingUKM("TimeUserCancelMs");
histogram_tester().ExpectTotalCount("Blink.Sms.Receive.TimeUserCancel", 1);
}
TEST_F(WebOTPServiceTest, RecordUnhandledRequestOnNavigation) {
web_contents()->GetController().GetBackForwardCache().DisableForTesting(
content::BackForwardCache::TEST_REQUIRES_NO_CACHING);
NavigateAndCommit(GURL(kTestUrl));
NiceMock<MockSmsWebContentsDelegate> delegate;
WebContentsImpl* web_contents_impl =
static_cast<WebContentsImpl*>(web_contents());
web_contents_impl->SetDelegate(&delegate);
NiceMock<MockSmsProvider> provider;
SmsFetcherImpl fetcher(&provider);
mojo::Remote<blink::mojom::WebOTPService> service;
EXPECT_TRUE(WebOTPService::Create(&fetcher, main_rfh(),
service.BindNewPipeAndPassReceiver()));
base::RunLoop ukm_loop;
ukm_recorder()->SetOnAddEntryCallback(Entry::kEntryName,
ukm_loop.QuitClosure());
base::RunLoop navigate;
EXPECT_CALL(provider, Retrieve(_, _)).WillOnce(Invoke([&navigate]() {
navigate.Quit();
}));
base::RunLoop reload;
service->Receive(base::BindLambdaForTesting(
[&reload](SmsStatus status, const optional<string>& otp) {
EXPECT_EQ(SmsStatus::kUnhandledRequest, status);
EXPECT_EQ(std::nullopt, otp);
reload.Quit();
}));
navigate.Run();
// Simulates the user navigating to a new page.
NavigateAndCommit(GURL("https://www.example.com"));
reload.Run();
ukm_loop.Run();
ExpectOutcomeUKM(GURL(kTestUrl),
blink::WebOTPServiceOutcome::kUnhandledRequest);
}
TEST_F(WebOTPServiceTest, NotRecordUnhandledRequestWhenThereIsNoRequest) {
GURL url = GURL(kTestUrl);
NavigateAndCommit(url);
{
ServiceWithPrompt service(web_contents());
ASSERT_FALSE(service.fetcher()->HasSubscribers());
}
ExpectNoOutcomeUKM();
}
TEST_F(WebOTPServiceTest, NotRecordUnhandledRequestWhenRequestIsHandled) {
GURL url = GURL(kTestUrl);
NavigateAndCommit(url);
{
ServiceWithPrompt service(web_contents());
base::RunLoop ukm_loop;
ukm_recorder()->SetOnAddEntryCallback(Entry::kEntryName,
ukm_loop.QuitClosure());
service.ExpectRequestUserConsent();
EXPECT_CALL(*service.provider(), Retrieve(_, _))
.WillOnce(Invoke([&service]() {
service.NotifyReceive(GURL(kTestUrl), "hi",
UserConsent::kNotObtained);
service.DismissPrompt();
}));
service.MakeRequest(base::DoNothing());
ukm_loop.Run();
}
ExpectOutcomeUKM(url, blink::WebOTPServiceOutcome::kUserCancelled);
}
TEST_F(WebOTPServiceTest, RecordWebContentsVisibilityForUserConsentAPI) {
NavigateAndCommit(GURL(kTestUrl));
base::HistogramTester histogram_tester;
// Sets the WebContents to visible
WebContentsImpl* web_contents_impl =
static_cast<WebContentsImpl*>(web_contents());
web_contents_impl->UpdateWebContentsVisibility(Visibility::VISIBLE);
ASSERT_EQ(web_contents_impl->GetVisibility(), Visibility::VISIBLE);
Service service1(web_contents_impl);
base::RunLoop loop1;
EXPECT_CALL(*service1.provider(), Retrieve(_, _))
.WillOnce(Invoke([&service1]() {
service1.NotifyReceive(GURL(kTestUrl), "ABC", UserConsent::kObtained);
}));
service1.MakeRequest(BindLambdaForTesting(
[&loop1](SmsStatus status, const optional<string>& otp) {
loop1.Quit();
}));
loop1.Run();
histogram_tester.ExpectBucketCount("Blink.Sms.WebContentsVisibleOnReceive", 1,
1);
histogram_tester.ExpectTotalCount("Blink.Sms.WebContentsVisibleOnReceive", 1);
// Sets the WebContents to invisible
web_contents_impl->UpdateWebContentsVisibility(Visibility::HIDDEN);
ASSERT_NE(web_contents_impl->GetVisibility(), Visibility::VISIBLE);
Service service2(web_contents_impl);
base::RunLoop loop2;
EXPECT_CALL(*service2.provider(), Retrieve(_, _))
.WillOnce(Invoke([&service2]() {
service2.NotifyReceive(GURL(kTestUrl), "ABC", UserConsent::kObtained);
}));
service2.MakeRequest(BindLambdaForTesting(
[&loop2](SmsStatus status, const optional<string>& otp) {
loop2.Quit();
}));
loop2.Run();
histogram_tester.ExpectBucketCount("Blink.Sms.WebContentsVisibleOnReceive", 0,
1);
histogram_tester.ExpectTotalCount("Blink.Sms.WebContentsVisibleOnReceive", 2);
}
TEST_F(WebOTPServiceTest, RecordCancelledAsOutcome) {
GURL url = GURL(kTestUrl);
NavigateAndCommit(url);
ServiceWithPrompt service(web_contents());
base::RunLoop sms1_loop, sms2_loop;
base::RunLoop ukm_loop;
ukm_recorder()->SetOnAddEntryCallback(Entry::kEntryName,
ukm_loop.QuitClosure());
EXPECT_CALL(*service.provider(), Retrieve(_, _))
.WillOnce(Return())
.WillOnce(Invoke([&sms2_loop]() { sms2_loop.Quit(); }));
service.MakeRequest(BindLambdaForTesting(
[&sms1_loop](SmsStatus status, const optional<string>& otp) {
sms1_loop.Quit();
}));
// The 2nd request will cancel the 1st one.
service.MakeRequest(base::DoNothing());
sms1_loop.Run();
sms2_loop.Run();
ukm_loop.Run();
ExpectOutcomeUKM(url, blink::WebOTPServiceOutcome::kCancelled);
}
TEST_F(WebOTPServiceTest,
RecordCrossDeviceFailureAsOutcomeUponPreviousRequestCancelled) {
RecordFailureOutcomeUponPreviousRequestCancelled(
FailureType::kCrossDeviceFailure,
blink::WebOTPServiceOutcome::kCrossDeviceFailure);
}
TEST_F(WebOTPServiceTest, RecordCrossDeviceFailureAsOutcomeUponDestruction) {
RecordFailureOutcomeUponDestruction(
FailureType::kCrossDeviceFailure,
blink::WebOTPServiceOutcome::kCrossDeviceFailure);
}
} // namespace content
|