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
|
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/webauthn/chrome_authenticator_request_delegate.h"
#include <algorithm>
#include <array>
#include <cstdint>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <variant>
#include <vector>
#include "base/containers/span.h"
#include "base/functional/bind.h"
#include "base/functional/callback_forward.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/test/mock_callback.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/test_future.h"
#include "build/build_config.h"
#include "chrome/browser/password_manager/chrome_webauthn_credentials_delegate_factory.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/sync/sync_service_factory.h"
#include "chrome/browser/webauthn/authenticator_request_dialog_model.h"
#include "chrome/browser/webauthn/chrome_web_authentication_delegate.h"
#include "chrome/browser/webauthn/immediate_request_rate_limiter_factory.h"
#include "chrome/browser/webauthn/passkey_model_factory.h"
#include "chrome/browser/webauthn/password_credential_controller.h"
#include "chrome/browser/webauthn/webauthn_pref_names.h"
#include "chrome/browser/webauthn/webauthn_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "components/keyed_service/core/keyed_service.h"
#include "components/prefs/pref_service.h"
#include "components/signin/public/base/consent_level.h"
#include "components/signin/public/identity_manager/identity_test_utils.h"
#include "components/sync/base/user_selectable_type.h"
#include "components/sync/protocol/webauthn_credential_specifics.pb.h"
#include "components/sync/test/test_sync_service.h"
#include "components/webauthn/core/browser/immediate_request_rate_limiter.h"
#include "components/webauthn/core/browser/passkey_model.h"
#include "components/webauthn/core/browser/test_passkey_model.h"
#include "content/public/browser/authenticator_request_client_delegate.h"
#include "content/public/browser/browser_context.h"
#include "content/public/test/web_contents_tester.h"
#include "crypto/scoped_fake_unexportable_key_provider.h"
#include "device/fido/cable/cable_discovery_data.h"
#include "device/fido/cable/v2_constants.h"
#include "device/fido/discoverable_credential_metadata.h"
#include "device/fido/features.h"
#include "device/fido/fido_constants.h"
#include "device/fido/fido_discovery_factory.h"
#include "device/fido/fido_request_handler_base.h"
#include "device/fido/fido_types.h"
#include "device/fido/public_key_credential_user_entity.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/permissions/permissions_data.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/mojom/credentialmanagement/credential_type_flags.mojom.h"
#include "url/gurl.h"
#include "url/origin.h"
#if BUILDFLAG(IS_MAC)
#include "chrome/test/base/testing_profile.h"
#endif // BUILDFLAG(IS_MAC)
namespace {
static constexpr char kRpId[] = "example.com";
static constexpr char kOrigin[] = "https://example.com";
constexpr int kRequestPassword =
static_cast<int>(blink::mojom::CredentialTypeFlags::kPassword);
constexpr int kRequestPublicKey =
static_cast<int>(blink::mojom::CredentialTypeFlags::kPublicKey);
using TransportAvailabilityInfo =
device::FidoRequestHandlerBase::TransportAvailabilityInfo;
using UIPresentation =
content::AuthenticatorRequestClientDelegate::UIPresentation;
class Observer : public testing::NiceMock<
ChromeAuthenticatorRequestDelegate::TestObserver> {
public:
MOCK_METHOD(void,
Created,
(ChromeAuthenticatorRequestDelegate * delegate),
(override));
MOCK_METHOD(void,
OnTransportAvailabilityEnumerated,
(ChromeAuthenticatorRequestDelegate * delegate,
TransportAvailabilityInfo* tai),
(override));
MOCK_METHOD(void,
UIShown,
(ChromeAuthenticatorRequestDelegate * delegate),
(override));
MOCK_METHOD(void,
CableV2ExtensionSeen,
(base::span<const uint8_t> server_link_data),
(override));
};
class MockPasswordCredentialController : public PasswordCredentialController {
public:
MockPasswordCredentialController(
content::GlobalRenderFrameHostId render_frame_host_id,
AuthenticatorRequestDialogModel* model)
: PasswordCredentialController(render_frame_host_id, model) {}
MOCK_METHOD(
void,
FetchPasswords,
(const GURL&,
PasswordCredentialController::PasswordCredentialsReceivedCallback),
(override));
MOCK_METHOD(
void,
SetPasswordSelectedCallback,
(content::AuthenticatorRequestClientDelegate::PasswordSelectedCallback),
(override));
};
class MockCableDiscoveryFactory : public device::FidoDiscoveryFactory {
public:
void set_cable_data(
device::FidoRequestType request_type,
std::vector<device::CableDiscoveryData> data,
const std::optional<std::array<uint8_t, device::cablev2::kQRKeySize>>&
qr_generator_key) override {
cable_data = std::move(data);
qr_key = qr_generator_key;
}
std::vector<device::CableDiscoveryData> cable_data;
std::optional<std::array<uint8_t, device::cablev2::kQRKeySize>> qr_key;
};
class ChromeAuthenticatorRequestDelegateTest
: public ChromeRenderViewHostTestHarness {
public:
ChromeAuthenticatorRequestDelegateTest()
: ChromeRenderViewHostTestHarness(
base::test::TaskEnvironment::TimeSource::MOCK_TIME) {}
void SetUp() override {
ChromeRenderViewHostTestHarness::SetUp();
PasskeyModelFactory::GetInstance()->SetTestingFactoryAndUse(
profile(),
base::BindRepeating(
[](content::BrowserContext*) -> std::unique_ptr<KeyedService> {
return std::make_unique<webauthn::TestPasskeyModel>();
}));
ChromeAuthenticatorRequestDelegate::SetGlobalObserverForTesting(&observer_);
ImmediateRequestRateLimiterFactory::GetInstance()->SetTestingFactoryAndUse(
profile(), base::BindRepeating([](content::BrowserContext* context)
-> std::unique_ptr<KeyedService> {
return std::make_unique<webauthn::ImmediateRequestRateLimiter>();
}));
}
void TearDown() override {
ChromeAuthenticatorRequestDelegate::SetGlobalObserverForTesting(nullptr);
ChromeRenderViewHostTestHarness::TearDown();
}
protected:
Observer observer_;
};
class TestAuthenticatorModelObserver final
: public AuthenticatorRequestDialogModel::Observer {
public:
explicit TestAuthenticatorModelObserver(
AuthenticatorRequestDialogModel* model)
: model_(model) {
last_step_ = model_->step();
}
~TestAuthenticatorModelObserver() override {
if (model_) {
model_->observers.RemoveObserver(this);
}
}
AuthenticatorRequestDialogModel::Step last_step() { return last_step_; }
// AuthenticatorRequestDialogModel::Observer:
void OnStepTransition() override { last_step_ = model_->step(); }
void OnModelDestroyed(AuthenticatorRequestDialogModel* model) override {
model_ = nullptr;
}
private:
raw_ptr<AuthenticatorRequestDialogModel> model_;
AuthenticatorRequestDialogModel::Step last_step_;
};
TEST_F(ChromeAuthenticatorRequestDelegateTest, CableConfiguration) {
const std::array<uint8_t, 16> eid = {1, 2, 3, 4};
const std::array<uint8_t, 32> prekey = {5, 6, 7, 8};
const device::CableDiscoveryData v1_extension(
device::CableDiscoveryData::Version::V1, eid, eid, prekey);
device::CableDiscoveryData v2_extension;
v2_extension.version = device::CableDiscoveryData::Version::V2;
v2_extension.v2.emplace(std::vector<uint8_t>(prekey.begin(), prekey.end()),
std::vector<uint8_t>());
enum class Result {
kNone,
kV1,
kServerLink,
k3rdParty,
};
#if BUILDFLAG(IS_LINUX)
// On Linux, some configurations aren't supported because of bluez
// limitations. This macro maps the expected result in that case.
#define NONE_ON_LINUX(r) (Result::kNone)
#else
#define NONE_ON_LINUX(r) (r)
#endif
const struct {
const char* origin;
std::vector<device::CableDiscoveryData> extensions;
device::FidoRequestType request_type;
std::optional<device::ResidentKeyRequirement> resident_key_requirement;
Result expected_result;
} kTests[] = {
{
"https://example.com",
{},
device::FidoRequestType::kGetAssertion,
std::nullopt,
Result::k3rdParty,
},
{
// Extensions should be ignored on a 3rd-party site.
"https://example.com",
{v1_extension},
device::FidoRequestType::kGetAssertion,
std::nullopt,
Result::k3rdParty,
},
{
// Extensions should be ignored on a 3rd-party site.
"https://example.com",
{v2_extension},
device::FidoRequestType::kGetAssertion,
std::nullopt,
Result::k3rdParty,
},
{
// a.g.c should still be able to get 3rd-party caBLE
// if it doesn't send an extension in an assertion request.
"https://accounts.google.com",
{},
device::FidoRequestType::kGetAssertion,
std::nullopt,
Result::k3rdParty,
},
{
// ... but not for non-discoverable registration.
"https://accounts.google.com",
{},
device::FidoRequestType::kMakeCredential,
device::ResidentKeyRequirement::kDiscouraged,
Result::kNone,
},
{
// ... but yes for rk=preferred
"https://accounts.google.com",
{},
device::FidoRequestType::kMakeCredential,
device::ResidentKeyRequirement::kPreferred,
Result::k3rdParty,
},
{
// ... or rk=required.
"https://accounts.google.com",
{},
device::FidoRequestType::kMakeCredential,
device::ResidentKeyRequirement::kRequired,
Result::k3rdParty,
},
{
"https://accounts.google.com",
{v1_extension},
device::FidoRequestType::kGetAssertion,
std::nullopt,
NONE_ON_LINUX(Result::kV1),
},
{
"https://accounts.google.com",
{v2_extension},
device::FidoRequestType::kGetAssertion,
std::nullopt,
Result::kServerLink,
},
};
unsigned test_case = 0;
for (const auto& test : kTests) {
SCOPED_TRACE(test_case);
test_case++;
MockCableDiscoveryFactory discovery_factory;
ChromeAuthenticatorRequestDelegate delegate(main_rfh());
delegate.SetRelyingPartyId(kRpId);
delegate.ConfigureDiscoveries(
url::Origin::Create(GURL(test.origin)), test.origin,
content::AuthenticatorRequestClientDelegate::RequestSource::
kWebAuthentication,
test.request_type, test.resident_key_requirement,
device::UserVerificationRequirement::kRequired,
/*user_name=*/std::nullopt, test.extensions,
/*is_enclave_authenticator_available=*/false, &discovery_factory);
switch (test.expected_result) {
case Result::kNone:
EXPECT_FALSE(discovery_factory.qr_key.has_value());
EXPECT_TRUE(discovery_factory.cable_data.empty());
break;
case Result::kV1:
EXPECT_FALSE(discovery_factory.qr_key.has_value());
EXPECT_FALSE(discovery_factory.cable_data.empty());
EXPECT_EQ(delegate.dialog_model()->cable_ui_type,
AuthenticatorRequestDialogModel::CableUIType::CABLE_V1);
break;
case Result::kServerLink:
EXPECT_TRUE(discovery_factory.qr_key.has_value());
EXPECT_FALSE(discovery_factory.cable_data.empty());
EXPECT_EQ(
delegate.dialog_model()->cable_ui_type,
AuthenticatorRequestDialogModel::CableUIType::CABLE_V2_SERVER_LINK);
break;
case Result::k3rdParty:
EXPECT_TRUE(discovery_factory.qr_key.has_value());
EXPECT_TRUE(discovery_factory.cable_data.empty());
EXPECT_EQ(
delegate.dialog_model()->cable_ui_type,
AuthenticatorRequestDialogModel::CableUIType::CABLE_V2_2ND_FACTOR);
break;
}
}
}
TEST_F(ChromeAuthenticatorRequestDelegateTest, NoExtraDiscoveriesWithoutUI) {
for (const bool disable_ui : {false, true}) {
SCOPED_TRACE(disable_ui);
ChromeAuthenticatorRequestDelegate delegate(main_rfh());
delegate.SetRelyingPartyId(kRpId);
if (disable_ui) {
delegate.SetUIPresentation(UIPresentation::kDisabled);
}
MockCableDiscoveryFactory discovery_factory;
delegate.ConfigureDiscoveries(
url::Origin::Create(GURL(kOrigin)), kOrigin,
content::AuthenticatorRequestClientDelegate::RequestSource::
kWebAuthentication,
device::FidoRequestType::kMakeCredential,
device::ResidentKeyRequirement::kPreferred,
device::UserVerificationRequirement::kRequired,
/*user_name=*/std::nullopt, {},
/*is_enclave_authenticator_available=*/false, &discovery_factory);
EXPECT_EQ(discovery_factory.qr_key.has_value(), !disable_ui);
// `discovery_factory.nswindow_` won't be set in any case because it depends
// on the `RenderFrameHost` having a `BrowserWindow`, which it doesn't in
// this context.
}
}
TEST_F(ChromeAuthenticatorRequestDelegateTest, ConditionalUI) {
// The RenderFrame has to be live for the ChromeWebAuthnCredentialsDelegate to
// be created.
content::WebContentsTester::For(web_contents())
->NavigateAndCommit(GURL("https://example.com"));
ChromeWebAuthnCredentialsDelegateFactory::CreateForWebContents(
web_contents());
// Enabling conditional mode should cause the modal dialog to stay hidden at
// the beginning of a request. An omnibar icon might be shown instead.
for (bool conditional_ui : {true, false}) {
ChromeAuthenticatorRequestDelegate delegate(main_rfh());
delegate.SetUIPresentation(conditional_ui ? UIPresentation::kAutofill
: UIPresentation::kModal);
delegate.SetRelyingPartyId(kRpId);
AuthenticatorRequestDialogModel* model = delegate.dialog_model();
TestAuthenticatorModelObserver observer(model);
model->observers.AddObserver(&observer);
EXPECT_EQ(observer.last_step(),
AuthenticatorRequestDialogModel::Step::kNotStarted);
TransportAvailabilityInfo transports_info;
transports_info.request_type = device::FidoRequestType::kGetAssertion;
delegate.OnTransportAvailabilityEnumerated(std::move(transports_info));
EXPECT_EQ(observer.last_step() ==
AuthenticatorRequestDialogModel::Step::kPasskeyAutofill,
conditional_ui);
}
}
TEST_F(ChromeAuthenticatorRequestDelegateTest, FilterGoogleComPasskeys) {
auto HasCreds = device::FidoRequestHandlerBase::RecognizedCredential::
kHasRecognizedCredential;
auto NoCreds = device::FidoRequestHandlerBase::RecognizedCredential::
kNoRecognizedCredential;
auto UnknownCreds =
device::FidoRequestHandlerBase::RecognizedCredential::kUnknown;
constexpr char kGoogle[] = "google.com";
constexpr char kOtherRpId[] = "example.com";
struct {
std::string rp_id;
device::FidoRequestHandlerBase::RecognizedCredential recognized_credential;
std::vector<std::string> user_ids;
device::FidoRequestHandlerBase::RecognizedCredential
expected_recognized_credential;
std::vector<std::string> expected_user_ids;
} kTests[] = {
{kOtherRpId,
HasCreds,
{"GOOGLE_ACCOUNT:c1", "c2"},
HasCreds,
{"GOOGLE_ACCOUNT:c1", "c2"}},
{kGoogle,
HasCreds,
{"GOOGLE_ACCOUNT:c1", "c2", "AUTOFILL_AUTH:c3"},
HasCreds,
{"GOOGLE_ACCOUNT:c1"}},
{kGoogle, HasCreds, {"c2", "AUTOFILL_AUTH:c3"}, NoCreds, {}},
{kGoogle, UnknownCreds, {}, UnknownCreds, {}},
{kGoogle, HasCreds, {}, HasCreds, {}},
};
for (const auto& test : kTests) {
SCOPED_TRACE(::testing::Message() << "rp_id=" << test.rp_id);
SCOPED_TRACE(::testing::Message()
<< "creds=" << base::JoinString(test.user_ids, ","));
TransportAvailabilityInfo data;
data.has_empty_allow_list = true;
data.request_type = device::FidoRequestType::kGetAssertion;
TransportAvailabilityInfo result;
EXPECT_CALL(observer_, OnTransportAvailabilityEnumerated)
.WillOnce([&result](const auto* _, const auto* new_tai) {
result = std::move(*new_tai);
});
for (const std::string& user_id : test.user_ids) {
data.recognized_credentials.emplace_back(
device::AuthenticatorType::kOther, test.rp_id,
std::vector<uint8_t>{0},
device::PublicKeyCredentialUserEntity(
std::vector<uint8_t>(user_id.begin(), user_id.end())),
/*provider_name=*/std::nullopt);
}
data.has_platform_authenticator_credential = test.recognized_credential;
// Mix in an icloud keychain credential. These should not be filtered or
// affect setting the recognized credentials flag.
data.recognized_credentials.emplace_back(
device::AuthenticatorType::kICloudKeychain, test.rp_id,
std::vector<uint8_t>{0}, device::PublicKeyCredentialUserEntity({1}),
/*provider_name=*/std::nullopt);
data.has_icloud_keychain_credential = device::FidoRequestHandlerBase::
RecognizedCredential::kHasRecognizedCredential;
ChromeAuthenticatorRequestDelegate delegate(main_rfh());
delegate.SetRelyingPartyId(test.rp_id);
delegate.RegisterActionCallbacks(
base::DoNothing(), base::DoNothing(), base::DoNothing(),
base::DoNothing(), base::DoNothing(), base::DoNothing(),
base::DoNothing(), base::DoNothing(), base::DoNothing());
delegate.OnTransportAvailabilityEnumerated(std::move(data));
EXPECT_EQ(result.has_platform_authenticator_credential,
test.expected_recognized_credential);
EXPECT_EQ(result.has_icloud_keychain_credential,
device::FidoRequestHandlerBase::RecognizedCredential::
kHasRecognizedCredential);
ASSERT_EQ(result.recognized_credentials.size(),
test.expected_user_ids.size() + 1);
for (size_t i = 0; i < test.expected_user_ids.size(); ++i) {
std::string expected_id = test.expected_user_ids[i];
EXPECT_EQ(result.recognized_credentials[i].user.id,
std::vector<uint8_t>(expected_id.begin(), expected_id.end()));
}
EXPECT_EQ(result.recognized_credentials.back().source,
device::AuthenticatorType::kICloudKeychain);
testing::Mock::VerifyAndClearExpectations(&observer_);
}
}
TEST_F(ChromeAuthenticatorRequestDelegateTest,
FilterGoogleComPasskeysWithNonEmptyAllowList) {
// Regression test for crbug.com/40071851, b/366128135.
constexpr char kGoogleRpId[] = "google.com";
TransportAvailabilityInfo data;
data.has_empty_allow_list = false;
data.request_type = device::FidoRequestType::kGetAssertion;
TransportAvailabilityInfo result;
EXPECT_CALL(observer_, OnTransportAvailabilityEnumerated)
.WillOnce([&result](const auto* _, const auto* new_tai) {
result = std::move(*new_tai);
});
// User ID doesn't start with the `GOOGLE_ACCOUNT:` prefix that distinguishes
// them as suitable for login auth.
std::string user_id = "test user id";
data.recognized_credentials.emplace_back(
device::AuthenticatorType::kOther, kGoogleRpId, std::vector<uint8_t>{0},
device::PublicKeyCredentialUserEntity(
std::vector<uint8_t>(user_id.begin(), user_id.end())),
/*provider_name=*/std::nullopt);
data.has_platform_authenticator_credential = device::FidoRequestHandlerBase::
RecognizedCredential::kHasRecognizedCredential;
ChromeAuthenticatorRequestDelegate delegate(main_rfh());
delegate.SetRelyingPartyId(kGoogleRpId);
delegate.RegisterActionCallbacks(
base::DoNothing(), base::DoNothing(), base::DoNothing(),
base::DoNothing(), base::DoNothing(), base::DoNothing(),
base::DoNothing(), base::DoNothing(), base::DoNothing());
delegate.OnTransportAvailabilityEnumerated(std::move(data));
// Despite lacking the user ID prefix, credentials are not filtered from
// `recognized_credentials` because the request has a non-empty allow list.
// The RecognizedCredential status isn't adjusted either.
ASSERT_EQ(result.recognized_credentials.size(), 1u);
EXPECT_EQ(result.has_platform_authenticator_credential,
device::FidoRequestHandlerBase::RecognizedCredential::
kHasRecognizedCredential);
testing::Mock::VerifyAndClearExpectations(&observer_);
}
class EnclaveAuthenticatorRequestDelegateTest
: public ChromeAuthenticatorRequestDelegateTest {
public:
void SetUp() override {
ChromeAuthenticatorRequestDelegateTest::SetUp();
SyncServiceFactory::GetInstance()->SetTestingFactory(
browser_context(),
base::BindRepeating([](content::BrowserContext* context)
-> std::unique_ptr<KeyedService> {
return std::make_unique<syncer::TestSyncService>();
}));
}
};
TEST_F(EnclaveAuthenticatorRequestDelegateTest,
BrowserProvidedPasskeysAvailable) {
signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfile(profile());
signin::MakePrimaryAccountAvailable(identity_manager, "hikari@example.com",
signin::ConsentLevel::kSignin);
struct {
bool is_syncing_passwords;
bool has_unexportable_keys;
bool expected_passkeys_available;
} kTestCases[] = {
// sync unexp result
{true, true, true},
{false, true, false},
{true, false, false},
};
for (const auto& test : kTestCases) {
SCOPED_TRACE(testing::Message()
<< "is_syncing_passwords=" << test.is_syncing_passwords);
SCOPED_TRACE(testing::Message()
<< "has_unexportable_keys=" << test.has_unexportable_keys);
ChromeWebAuthenticationDelegate delegate;
auto* test_sync_service = static_cast<syncer::TestSyncService*>(
SyncServiceFactory::GetInstance()->GetForProfile(profile()));
test_sync_service->GetUserSettings()->SetSelectedType(
syncer::UserSelectableType::kPasswords, test.is_syncing_passwords);
std::variant<crypto::ScopedNullUnexportableKeyProvider,
crypto::ScopedFakeUnexportableKeyProvider>
unexportable_key_provider;
if (test.has_unexportable_keys) {
unexportable_key_provider
.emplace<crypto::ScopedFakeUnexportableKeyProvider>();
}
base::test::TestFuture<bool> future;
delegate.BrowserProvidedPasskeysAvailable(browser_context(),
future.GetCallback());
EXPECT_TRUE(future.Wait());
EXPECT_EQ(future.Get(), test.expected_passkeys_available);
}
}
// This test is separated from BrowserProvidedPasskeysAvailable because ChromeOS
// does not support clearing the primary account once Chrome is running.
TEST_F(EnclaveAuthenticatorRequestDelegateTest,
BrowserProvidedPasskeysAvailable_NoAccount) {
signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfile(profile());
auto* test_sync_service = static_cast<syncer::TestSyncService*>(
SyncServiceFactory::GetInstance()->GetForProfile(profile()));
test_sync_service->GetUserSettings()->SetSelectedType(
syncer::UserSelectableType::kPasswords, true);
crypto::ScopedFakeUnexportableKeyProvider unexportable_key_provider;
{
base::test::TestFuture<bool> future;
ChromeWebAuthenticationDelegate delegate;
delegate.BrowserProvidedPasskeysAvailable(browser_context(),
future.GetCallback());
ASSERT_TRUE(future.Wait());
EXPECT_FALSE(future.Get());
}
signin::MakePrimaryAccountAvailable(identity_manager, "hikari@example.com",
signin::ConsentLevel::kSignin);
{
base::test::TestFuture<bool> future;
ChromeWebAuthenticationDelegate delegate;
delegate.BrowserProvidedPasskeysAvailable(browser_context(),
future.GetCallback());
ASSERT_TRUE(future.Wait());
EXPECT_TRUE(future.Get());
}
}
// Regression test for crbug.com/377724726.
// Tests that being signed in is enough to have
// BrowserProvidedPasskeysAvailable() return true. Sync-the-feature should not
// be necessary as long as the user consented to using passwords and passkeys
// from their Google account.
TEST_F(EnclaveAuthenticatorRequestDelegateTest,
BrowserProvidedPasskeysAvailableForSignedInUsers) {
signin::IdentityManager* identity_manager =
IdentityManagerFactory::GetForProfile(profile());
signin::MakePrimaryAccountAvailable(identity_manager, "hikari@example.com",
signin::ConsentLevel::kSignin);
auto* test_sync_service = static_cast<syncer::TestSyncService*>(
SyncServiceFactory::GetInstance()->GetForProfile(profile()));
// ConsentLevel::kSignin + passwords syncing should be enough.
test_sync_service->SetSignedIn(signin::ConsentLevel::kSignin);
test_sync_service->GetUserSettings()->SetSelectedType(
syncer::UserSelectableType::kPasswords, true);
crypto::ScopedFakeUnexportableKeyProvider unexportable_key_provider;
base::test::TestFuture<bool> future;
ChromeWebAuthenticationDelegate delegate;
delegate.BrowserProvidedPasskeysAvailable(browser_context(),
future.GetCallback());
ASSERT_TRUE(future.Wait());
EXPECT_TRUE(future.Get());
}
#if BUILDFLAG(IS_MAC)
std::string TouchIdMetadataSecret(ChromeWebAuthenticationDelegate& delegate,
content::BrowserContext* browser_context) {
return delegate.GetTouchIdAuthenticatorConfig(browser_context)
->metadata_secret;
}
TEST_F(ChromeAuthenticatorRequestDelegateTest, TouchIdMetadataSecret) {
ChromeWebAuthenticationDelegate delegate;
std::string secret = TouchIdMetadataSecret(delegate, GetBrowserContext());
EXPECT_EQ(secret.size(), 32u);
// The secret should be stable.
EXPECT_EQ(secret, TouchIdMetadataSecret(delegate, GetBrowserContext()));
}
TEST_F(ChromeAuthenticatorRequestDelegateTest,
TouchIdMetadataSecret_EqualForSameProfile) {
// Different delegates on the same BrowserContext (Profile) should return
// the same secret.
ChromeWebAuthenticationDelegate delegate1;
ChromeWebAuthenticationDelegate delegate2;
EXPECT_EQ(TouchIdMetadataSecret(delegate1, GetBrowserContext()),
TouchIdMetadataSecret(delegate2, GetBrowserContext()));
}
TEST_F(ChromeAuthenticatorRequestDelegateTest,
TouchIdMetadataSecret_NotEqualForDifferentProfiles) {
// Different profiles have different secrets.
auto other_browser_context = CreateBrowserContext();
ChromeWebAuthenticationDelegate delegate;
EXPECT_NE(TouchIdMetadataSecret(delegate, GetBrowserContext()),
TouchIdMetadataSecret(delegate, other_browser_context.get()));
// Ensure this second secret is actually valid.
EXPECT_EQ(
32u, TouchIdMetadataSecret(delegate, other_browser_context.get()).size());
}
#endif // BUILDFLAG(IS_MAC)
TEST_F(ChromeAuthenticatorRequestDelegateTest, DiscoverPasswords) {
for (const auto enable_password : {false, true}) {
content::WebContentsTester::For(web_contents())
->NavigateAndCommit(GURL(kOrigin));
ChromeAuthenticatorRequestDelegate delegate(main_rfh());
auto password_controller =
std::make_unique<testing::NiceMock<MockPasswordCredentialController>>(
main_rfh()->GetGlobalId(), delegate.dialog_model());
auto raw_password_controller = password_controller.get();
delegate.SetPasswordControllerForTesting(std::move(password_controller));
delegate.SetUIPresentation(enable_password ? UIPresentation::kModalImmediate
: UIPresentation::kModal);
delegate.SetCredentialTypes((enable_password
? (kRequestPassword | kRequestPublicKey)
: (kRequestPublicKey)));
delegate.SetRelyingPartyId(kRpId);
MockCableDiscoveryFactory discovery_factory;
EXPECT_CALL(*raw_password_controller, FetchPasswords)
.Times(enable_password);
delegate.ConfigureDiscoveries(
url::Origin::Create(GURL(kOrigin)), kOrigin,
content::AuthenticatorRequestClientDelegate::RequestSource::
kWebAuthentication,
device::FidoRequestType::kGetAssertion,
device::ResidentKeyRequirement::kPreferred,
device::UserVerificationRequirement::kRequired,
/*user_name=*/std::nullopt, {},
/*is_enclave_authenticator_available=*/false, &discovery_factory);
}
}
TEST_F(ChromeAuthenticatorRequestDelegateTest,
TryToShowUiNoImmediateCredentials) {
content::WebContentsTester::For(web_contents())
->NavigateAndCommit(GURL(kOrigin));
ChromeAuthenticatorRequestDelegate delegate(main_rfh());
auto password_controller =
std::make_unique<testing::NiceMock<MockPasswordCredentialController>>(
main_rfh()->GetGlobalId(), delegate.dialog_model());
auto raw_password_controller = password_controller.get();
delegate.SetPasswordControllerForTesting(std::move(password_controller));
base::MockCallback<base::OnceClosure> mock_closure;
delegate.RegisterActionCallbacks(
base::DoNothing(), mock_closure.Get(), base::DoNothing(),
base::DoNothing(), base::DoNothing(), base::DoNothing(),
base::DoNothing(), base::DoNothing(), base::DoNothing());
delegate.SetUIPresentation(UIPresentation::kModalImmediate);
delegate.SetCredentialTypes(kRequestPassword | kRequestPublicKey);
delegate.SetRelyingPartyId(kRpId);
MockCableDiscoveryFactory discovery_factory;
PasswordCredentialController::PasswordCredentialsReceivedCallback callback;
EXPECT_CALL(*raw_password_controller, FetchPasswords)
.WillOnce([&callback](auto _, auto receive_callback) {
callback = std::move(receive_callback);
});
delegate.ConfigureDiscoveries(url::Origin::Create(GURL(kOrigin)), kOrigin,
content::AuthenticatorRequestClientDelegate::
RequestSource::kWebAuthentication,
device::FidoRequestType::kGetAssertion,
device::ResidentKeyRequirement::kPreferred,
device::UserVerificationRequirement::kRequired,
/*user_name=*/std::nullopt, {},
/*is_enclave_authenticator_available=*/false,
&discovery_factory);
TransportAvailabilityInfo transports_info;
transports_info.request_type = device::FidoRequestType::kGetAssertion;
// still waiting for passwords.
EXPECT_CALL(mock_closure, Run).Times(0);
delegate.OnTransportAvailabilityEnumerated(std::move(transports_info));
EXPECT_CALL(mock_closure, Run).Times(1);
std::move(callback).Run({});
}
TEST_F(ChromeAuthenticatorRequestDelegateTest,
TryToShowUiHasImmediateCredentials) {
content::WebContentsTester::For(web_contents())
->NavigateAndCommit(GURL(kOrigin));
ChromeAuthenticatorRequestDelegate delegate(main_rfh());
auto password_controller =
std::make_unique<testing::NiceMock<MockPasswordCredentialController>>(
main_rfh()->GetGlobalId(), delegate.dialog_model());
auto raw_password_controller = password_controller.get();
delegate.SetPasswordControllerForTesting(std::move(password_controller));
base::MockCallback<base::OnceClosure> mock_closure;
delegate.RegisterActionCallbacks(
base::DoNothing(), mock_closure.Get(), base::DoNothing(),
base::DoNothing(), base::DoNothing(), base::DoNothing(),
base::DoNothing(), base::DoNothing(), base::DoNothing());
delegate.SetUIPresentation(UIPresentation::kModalImmediate);
delegate.SetCredentialTypes(kRequestPassword | kRequestPublicKey);
delegate.SetRelyingPartyId(kRpId);
MockCableDiscoveryFactory discovery_factory;
PasswordCredentialController::PasswordCredentialsReceivedCallback callback;
EXPECT_CALL(*raw_password_controller, FetchPasswords)
.WillOnce([&callback](auto _, auto receive_callback) {
callback = std::move(receive_callback);
});
delegate.ConfigureDiscoveries(url::Origin::Create(GURL(kOrigin)), kOrigin,
content::AuthenticatorRequestClientDelegate::
RequestSource::kWebAuthentication,
device::FidoRequestType::kGetAssertion,
device::ResidentKeyRequirement::kPreferred,
device::UserVerificationRequirement::kRequired,
/*user_name=*/std::nullopt, {},
/*is_enclave_authenticator_available=*/false,
&discovery_factory);
TransportAvailabilityInfo transports_info;
transports_info.request_type = device::FidoRequestType::kGetAssertion;
transports_info.recognized_credentials = {
device::DiscoverableCredentialMetadata(
device::AuthenticatorType::kEnclave, kRpId, {},
device::PublicKeyCredentialUserEntity(),
/*provider_name=*/std::nullopt)};
// still waiting for passwords.
EXPECT_CALL(mock_closure, Run).Times(0);
EXPECT_CALL(observer_, OnTransportAvailabilityEnumerated).Times(0);
delegate.OnTransportAvailabilityEnumerated(std::move(transports_info));
EXPECT_CALL(mock_closure, Run).Times(0);
EXPECT_CALL(observer_, OnTransportAvailabilityEnumerated).Times(1);
std::move(callback).Run({});
}
TEST_F(ChromeAuthenticatorRequestDelegateTest, ImmediateMediationRateLimit) {
constexpr base::TimeDelta kWindowSize = base::Minutes(1);
constexpr int kMaxRequestsPerWindow = 2;
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitAndEnableFeatureWithParameters(
device::kWebAuthnImmediateRequestRateLimit,
{{"max_requests", base::NumberToString(kMaxRequestsPerWindow)},
{"window_seconds", "60"}});
// Navigate to commit the origin.
content::WebContentsTester::For(web_contents())
->NavigateAndCommit(GURL(kOrigin));
ChromeAuthenticatorRequestDelegate delegate(main_rfh());
delegate.SetRelyingPartyId(kRpId);
delegate.SetUIPresentation(UIPresentation::kModalImmediate);
// Register a mock callback for the immediate_not_found case.
// This is called when MaybeHandleImmediateMediation returns true (e.g., rate
// limited).
base::MockCallback<base::OnceClosure> mock_immediate_not_found_callback;
delegate.RegisterActionCallbacks(
/*cancel_callback=*/base::DoNothing(),
mock_immediate_not_found_callback.Get(),
/*start_over_callback=*/base::DoNothing(),
/*account_preselected_callback=*/base::DoNothing(),
/*password_selected_callback=*/base::DoNothing(),
/*request_callback=*/base::DoNothing(),
/*cancel_ui_timeout_callback=*/base::DoNothing(),
/*bluetooth_adapter_power_on_callback=*/base::DoNothing(),
/*bluetooth_query_status_callback=*/base::DoNothing());
TransportAvailabilityInfo transports_info;
transports_info.request_type = device::FidoRequestType::kGetAssertion;
transports_info.recognized_credentials = {
device::DiscoverableCredentialMetadata(
device::AuthenticatorType::kEnclave, kRpId, {},
device::PublicKeyCredentialUserEntity(),
/*provider_name=*/std::nullopt)};
for (int i = 0; i < kMaxRequestsPerWindow; ++i) {
SCOPED_TRACE(testing::Message() << "Request " << i + 1);
EXPECT_CALL(mock_immediate_not_found_callback, Run).Times(0);
// Need to pass a copy as OnTransportAvailabilityEnumerated takes by value.
TransportAvailabilityInfo info_copy = transports_info;
delegate.OnTransportAvailabilityEnumerated(std::move(info_copy));
testing::Mock::VerifyAndClearExpectations(
&mock_immediate_not_found_callback);
}
// The next request should be rate-limited (callback is called).
{
SCOPED_TRACE(testing::Message() << "Request " << kMaxRequestsPerWindow + 1);
EXPECT_CALL(mock_immediate_not_found_callback, Run).Times(1);
TransportAvailabilityInfo info_copy = transports_info;
delegate.OnTransportAvailabilityEnumerated(std::move(info_copy));
testing::Mock::VerifyAndClearExpectations(
&mock_immediate_not_found_callback);
}
// Advance time beyond the window.
task_environment()->FastForwardBy(kWindowSize + base::Seconds(1));
// The next request should be allowed again (callback not called).
{
SCOPED_TRACE(testing::Message() << "Request after time window");
EXPECT_CALL(mock_immediate_not_found_callback, Run).Times(0);
TransportAvailabilityInfo info_copy = transports_info;
delegate.OnTransportAvailabilityEnumerated(std::move(info_copy));
testing::Mock::VerifyAndClearExpectations(
&mock_immediate_not_found_callback);
}
}
} // namespace
#if BUILDFLAG(IS_MAC)
// These test functions are outside of the anonymous namespace so that
// `FRIEND_TEST_ALL_PREFIXES` works to let them test private functions.
class ChromeAuthenticatorRequestDelegatePrivateTest : public testing::Test {
// A `BrowserTaskEnvironment` needs to be in-scope in order to create a
// `TestingProfile`.
content::BrowserTaskEnvironment task_environment_;
};
TEST_F(ChromeAuthenticatorRequestDelegatePrivateTest, DaysSinceDate) {
const base::Time now = base::Time::FromTimeT(1691188997); // 2023-08-04
const struct {
char input[16];
std::optional<int> expected_result;
} kTestCases[] = {
{"", std::nullopt}, //
{"2023-08-", std::nullopt}, //
{"2023-08-04", 0}, //
{"2023-08-03", 1}, //
{"2023-8-3", 1}, //
{"2023-07-04", 31}, //
{"2001-11-23", 7924}, //
};
for (const auto& test : kTestCases) {
SCOPED_TRACE(test.input);
const std::optional<int> result =
ChromeAuthenticatorRequestDelegate::DaysSinceDate(test.input, now);
EXPECT_EQ(result, test.expected_result);
}
}
TEST_F(ChromeAuthenticatorRequestDelegatePrivateTest, GetICloudKeychainPref) {
TestingProfile profile;
// We use a boolean preference as a tristate, so it's worth checking that
// an unset preference is recognised as such.
EXPECT_FALSE(ChromeAuthenticatorRequestDelegate::GetICloudKeychainPref(
profile.GetPrefs())
.has_value());
profile.GetPrefs()->SetBoolean(prefs::kCreatePasskeysInICloudKeychain, true);
EXPECT_EQ(*ChromeAuthenticatorRequestDelegate::GetICloudKeychainPref(
profile.GetPrefs()),
true);
}
TEST_F(ChromeAuthenticatorRequestDelegatePrivateTest,
ShouldCreateInICloudKeychain) {
// Safety check that SPC requests never default to iCloud Keychain.
EXPECT_FALSE(ChromeAuthenticatorRequestDelegate::ShouldCreateInICloudKeychain(
ChromeAuthenticatorRequestDelegate::RequestSource::
kSecurePaymentConfirmation,
/*is_active_profile_authenticator_user=*/false,
/*has_icloud_drive_enabled=*/true, /*request_is_for_google_com=*/true,
/*preference=*/true));
// For the valid request type, the preference should be controlling if set.
for (const bool preference : {false, true}) {
EXPECT_EQ(preference,
ChromeAuthenticatorRequestDelegate::ShouldCreateInICloudKeychain(
ChromeAuthenticatorRequestDelegate::RequestSource::
kWebAuthentication,
/*is_active_profile_authenticator_user=*/false,
/*has_icloud_drive_enabled=*/true,
/*request_is_for_google_com=*/true,
/*preference=*/preference));
// Otherwise the default is controlled by several feature flags. Testing
// them would just be a change detector.
}
}
#endif
|