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
|
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/json/json_reader.h"
#include "base/test/bind.h"
#include "base/test/scoped_feature_list.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/payments/secure_payment_confirmation_browsertest.h"
#include "components/autofill/core/browser/test_utils/test_event_waiter.h"
#include "components/payments/content/secure_payment_confirmation_app.h"
#include "components/payments/core/journey_logger.h"
#include "components/payments/core/secure_payment_confirmation_metrics.h"
#include "content/public/browser/scoped_authenticator_environment_for_testing.h"
#include "content/public/test/browser_test.h"
#include "device/fido/virtual_fido_device_factory.h"
#include "testing/gtest/include/gtest/gtest.h"
// Authenticator tests do not work on Android because there is not currently a
// way to install a virtual authenticator.
#if BUILDFLAG(IS_ANDROID)
#error "These tests are unsupported on Android"
#endif
// TODO(crbug.com/40870879): Temporarily disable the tests on macOS since they
// do not yet work with current WebAuthn UI.
#if !BUILDFLAG(IS_MAC)
namespace payments {
namespace {
using Event2 = payments::JourneyLogger::Event2;
struct PaymentCredentialInfo {
std::string webidl_type;
std::string type;
std::string id;
};
// Base class for Secure Payment Confirmation tests that use a virtual FIDO
// authenticator in order to test the end-to-end flow.
class SecurePaymentConfirmationAuthenticatorTestBase
: public SecurePaymentConfirmationTest,
public content::WebContentsObserver {
public:
enum Event : int {
AUTHENTICATOR_REQUEST,
WEB_CONTENTS_DESTROYED,
};
// Installs a virtual FIDO authenticator device for the tests.
std::unique_ptr<content::ScopedAuthenticatorEnvironmentForTesting>
ReplaceFidoDiscoveryFactory(bool should_succeed, bool should_hang = false) {
auto virtual_device_factory =
std::make_unique<device::test::VirtualFidoDeviceFactory>();
virtual_device_factory->SetTransport(
device::FidoTransportProtocol::kInternal);
virtual_device_factory->SetSupportedProtocol(
device::ProtocolVersion::kCtap2);
virtual_device_factory->mutable_state()->fingerprints_enrolled = true;
if (should_hang) {
virtual_device_factory->mutable_state()->simulate_press_callback =
base::BindLambdaForTesting([&](device::VirtualFidoDevice* device) {
event_waiter_->OnEvent(AUTHENTICATOR_REQUEST);
return false;
});
}
// Currently this only supports tests relying on user-verifying platform
// authenticators.
device::VirtualCtap2Device::Config config;
config.is_platform_authenticator = true;
config.internal_uv_support = true;
config.user_verification_succeeds = should_succeed;
virtual_device_factory->SetCtap2Config(config);
return std::make_unique<content::ScopedAuthenticatorEnvironmentForTesting>(
std::move(virtual_device_factory));
}
// Creates an SPC-enabled WebAuthn credential, and places information about it
// in `out_info`. The `out_info` parameter may be nullptr, in which case the
// credential is created and checked to have succeeded, but no information is
// returned.
//
// The optional input `user_id` parameter comes after the output parameter as
// most callers will want to set `out_info` but not `user_id`.
void CreatePaymentCredential(PaymentCredentialInfo* out_info = nullptr,
const std::string& user_id = "user_123") {
std::string response =
content::EvalJs(
GetActiveWebContents(),
content::JsReplace("createPaymentCredential($1)", user_id))
.ExtractString();
ASSERT_EQ(std::string::npos, response.find("Error")) << response;
std::optional<base::Value> value = base::JSONReader::Read(response);
ASSERT_TRUE(value.has_value());
ASSERT_TRUE(value->is_dict());
const auto& value_dict = value->GetDict();
const std::string* webidl_type = value_dict.FindString("webIdlType");
ASSERT_NE(nullptr, webidl_type) << response;
const std::string* type = value_dict.FindString("type");
ASSERT_NE(nullptr, type) << response;
const std::string* id = value_dict.FindString("id");
ASSERT_NE(nullptr, id) << response;
if (out_info) {
*out_info = {*webidl_type, *type, *id};
}
}
void ObserveEvent(Event event) {
event_waiter_ =
std::make_unique<autofill::EventWaiter<Event>>(std::list<Event>{event});
}
void ObserveWebContentsDestroyed() {
ObserveEvent(WEB_CONTENTS_DESTROYED);
Observe(GetActiveWebContents());
}
// content::WebContentsObserver:
void WebContentsDestroyed() override {
event_waiter_->OnEvent(WEB_CONTENTS_DESTROYED);
}
std::unique_ptr<autofill::EventWaiter<Event>> event_waiter_;
};
using SecurePaymentConfirmationAuthenticatorCreateTest =
SecurePaymentConfirmationAuthenticatorTestBase;
IN_PROC_BROWSER_TEST_F(SecurePaymentConfirmationAuthenticatorCreateTest,
CreatePaymentCredential) {
auto scoped_auth_env = ReplaceFidoDiscoveryFactory(/*should_succeed=*/true);
NavigateTo("a.com", "/secure_payment_confirmation.html");
PaymentCredentialInfo info;
CreatePaymentCredential(&info);
// The created credential should be a normal WebAuthn credential, of the right
// WebIDL and internal type.
EXPECT_EQ("PublicKeyCredential", info.webidl_type);
EXPECT_EQ("webauthn.create", info.type);
// Check that we can create a second credential successfully.
CreatePaymentCredential();
}
// b.com cannot create a credential with RP = "a.com".
IN_PROC_BROWSER_TEST_F(SecurePaymentConfirmationAuthenticatorCreateTest,
RelyingPartyIsEnforced) {
auto scoped_auth_env = ReplaceFidoDiscoveryFactory(/*should_succeed=*/true);
NavigateTo("b.com", "/secure_payment_confirmation.html");
EXPECT_THAT(
content::EvalJs(GetActiveWebContents(), "createPaymentCredential()")
.ExtractString(),
testing::HasSubstr("SecurityError: The relying party ID is not"));
}
IN_PROC_BROWSER_TEST_F(SecurePaymentConfirmationAuthenticatorCreateTest,
WebContentsClosedDuringEnrollmentOSPrompt) {
auto scoped_auth_env = ReplaceFidoDiscoveryFactory(/*should_succeed=*/true,
/*should_hang=*/true);
NavigateTo("a.com", "/secure_payment_confirmation.html");
std::list<Event> expected_events_ =
std::list<Event>{Event::AUTHENTICATOR_REQUEST};
event_waiter_ =
std::make_unique<autofill::EventWaiter<Event>>(expected_events_);
ExecuteScriptAsync(GetActiveWebContents(), "createPaymentCredential()");
ASSERT_TRUE(event_waiter_->Wait());
// Expect no crash when the web contents is destroyed during enrollment while
// the OS enrollment prompt is showing.
ObserveWebContentsDestroyed();
GetActiveWebContents()->Close();
ASSERT_TRUE(event_waiter_->Wait());
}
class SecurePaymentConfirmationAuthenticatorCreateDisableDebugTest
: public SecurePaymentConfirmationAuthenticatorCreateTest {
public:
SecurePaymentConfirmationAuthenticatorCreateDisableDebugTest() {
feature_list_.InitWithFeatures(
/*enabled_features=*/{::features::kSecurePaymentConfirmation},
/*disabled_features=*/{::features::kSecurePaymentConfirmationDebug});
}
private:
base::test::ScopedFeatureList feature_list_;
};
IN_PROC_BROWSER_TEST_F(
SecurePaymentConfirmationAuthenticatorCreateDisableDebugTest,
RequireUserVerifyingPlatformAuthenticator) {
test_controller()->SetHasAuthenticator(false);
auto scoped_auth_env = ReplaceFidoDiscoveryFactory(/*should_succeed=*/true);
NavigateTo("a.com", "/secure_payment_confirmation.html");
EXPECT_EQ(
"NotSupportedError: A user verifying platform authenticator with "
"resident key support is required for 'payment' extension.",
content::EvalJs(GetActiveWebContents(), "createPaymentCredential()"));
}
using SecurePaymentConfirmationAuthenticatorGetTest =
SecurePaymentConfirmationAuthenticatorTestBase;
IN_PROC_BROWSER_TEST_F(SecurePaymentConfirmationAuthenticatorGetTest,
ConfirmPaymentInCrossOriginIframe) {
NavigateTo("a.com", "/secure_payment_confirmation.html");
auto scoped_auth_env = ReplaceFidoDiscoveryFactory(/*should_succeed=*/true);
PaymentCredentialInfo credential_info;
CreatePaymentCredential(&credential_info);
// Load a cross-origin iframe that can initiate SPC.
content::WebContents* tab = GetActiveWebContents();
GURL iframe_url = https_server()->GetURL(
"b.com", "/secure_payment_confirmation_iframe.html");
EXPECT_TRUE(content::NavigateIframeToURL(tab, "test", iframe_url));
test_controller()->SetHasAuthenticator(true);
confirm_payment_ = true;
// Trigger SPC and capture the response.
// EvalJs waits for JavaScript promise to resolve.
content::RenderFrameHost* iframe = content::FrameMatchingPredicate(
tab->GetPrimaryPage(),
base::BindRepeating(&content::FrameHasSourceUrl, iframe_url));
std::string response =
content::EvalJs(
iframe, content::JsReplace("requestPayment($1);", credential_info.id))
.ExtractString();
ASSERT_EQ(std::string::npos, response.find("Error"));
std::optional<base::Value> value = base::JSONReader::Read(response);
ASSERT_TRUE(value.has_value());
ASSERT_TRUE(value->is_dict());
const base::Value::Dict& value_dict = value->GetDict();
const std::string* type = value_dict.FindString("type");
ASSERT_NE(nullptr, type) << response;
EXPECT_EQ("payment.get", *type);
const std::string* origin = value_dict.FindString("origin");
ASSERT_NE(nullptr, origin) << response;
EXPECT_EQ(https_server()->GetURL("b.com", "/"), GURL(*origin));
std::optional<bool> cross_origin = value_dict.FindBool("crossOrigin");
ASSERT_TRUE(cross_origin.has_value()) << response;
EXPECT_TRUE(cross_origin.value());
const std::string* payee_name =
value_dict.FindStringByDottedPath("payment.payeeName");
ASSERT_EQ(nullptr, payee_name) << response;
const std::string* payee_origin =
value_dict.FindStringByDottedPath("payment.payeeOrigin");
ASSERT_NE(nullptr, payee_origin) << response;
EXPECT_EQ(GURL("https://example-payee-origin.test"), GURL(*payee_origin));
const std::string* top_origin =
value_dict.FindStringByDottedPath("payment.topOrigin");
ASSERT_NE(nullptr, top_origin) << response;
EXPECT_EQ(https_server()->GetURL("a.com", "/"), GURL(*top_origin));
const std::string* rpId = value_dict.FindStringByDottedPath("payment.rpId");
ASSERT_NE(nullptr, rpId) << response;
EXPECT_EQ("a.com", *rpId);
ExpectEvent2Histogram({Event2::kInitiated, Event2::kShown, Event2::kCompleted,
Event2::kPayClicked, Event2::kHadInitialFormOfPayment,
Event2::kRequestMethodSecurePaymentConfirmation,
Event2::kSelectedSecurePaymentConfirmation});
}
IN_PROC_BROWSER_TEST_F(SecurePaymentConfirmationAuthenticatorGetTest,
ConfirmPaymentInCrossOriginIframeWithPayeeName) {
NavigateTo("a.com", "/secure_payment_confirmation.html");
auto scoped_auth_env = ReplaceFidoDiscoveryFactory(/*should_succeed=*/true);
PaymentCredentialInfo credential_info;
CreatePaymentCredential(&credential_info);
// Load a cross-origin iframe that can initiate SPC.
content::WebContents* tab = GetActiveWebContents();
GURL iframe_url = https_server()->GetURL(
"b.com", "/secure_payment_confirmation_iframe.html");
EXPECT_TRUE(content::NavigateIframeToURL(tab, "test", iframe_url));
test_controller()->SetHasAuthenticator(true);
confirm_payment_ = true;
// Trigger SPC and capture the response.
// EvalJs waits for JavaScript promise to resolve.
content::RenderFrameHost* iframe = content::FrameMatchingPredicate(
tab->GetPrimaryPage(),
base::BindRepeating(&content::FrameHasSourceUrl, iframe_url));
std::string response =
content::EvalJs(iframe,
content::JsReplace("requestPaymentWithPayeeName($1);",
credential_info.id))
.ExtractString();
ASSERT_EQ(std::string::npos, response.find("Error"));
std::optional<base::Value> value = base::JSONReader::Read(response);
ASSERT_TRUE(value.has_value());
ASSERT_TRUE(value->is_dict());
const base::Value::Dict& dict = value->GetDict();
const std::string* payee_name =
dict.FindStringByDottedPath("payment.payeeName");
ASSERT_NE(nullptr, payee_name) << response;
EXPECT_EQ("Example Payee", *payee_name);
const std::string* payee_origin =
dict.FindStringByDottedPath("payment.payeeOrigin");
ASSERT_EQ(nullptr, payee_origin) << response;
ExpectEvent2Histogram({Event2::kInitiated, Event2::kShown, Event2::kCompleted,
Event2::kPayClicked, Event2::kHadInitialFormOfPayment,
Event2::kRequestMethodSecurePaymentConfirmation,
Event2::kSelectedSecurePaymentConfirmation});
}
IN_PROC_BROWSER_TEST_F(
SecurePaymentConfirmationAuthenticatorGetTest,
ConfirmPaymentInCrossOriginIframeWithPayeeNameAndOrigin) {
NavigateTo("a.com", "/secure_payment_confirmation.html");
auto scoped_auth_env = ReplaceFidoDiscoveryFactory(/*should_succeed=*/true);
PaymentCredentialInfo credential_info;
CreatePaymentCredential(&credential_info);
// Load a cross-origin iframe that can initiate SPC.
content::WebContents* tab = GetActiveWebContents();
GURL iframe_url = https_server()->GetURL(
"b.com", "/secure_payment_confirmation_iframe.html");
EXPECT_TRUE(content::NavigateIframeToURL(tab, "test", iframe_url));
test_controller()->SetHasAuthenticator(true);
confirm_payment_ = true;
// Trigger SPC and capture the response.
// EvalJs waits for JavaScript promise to resolve.
content::RenderFrameHost* iframe = content::FrameMatchingPredicate(
tab->GetPrimaryPage(),
base::BindRepeating(&content::FrameHasSourceUrl, iframe_url));
std::string response =
content::EvalJs(iframe, content::JsReplace(
"requestPaymentWithPayeeNameAndOrigin($1);",
credential_info.id))
.ExtractString();
ASSERT_EQ(std::string::npos, response.find("Error"));
std::optional<base::Value> value = base::JSONReader::Read(response);
ASSERT_TRUE(value.has_value());
ASSERT_TRUE(value->is_dict());
const base::Value::Dict& dict = value->GetDict();
const std::string* payee_name =
dict.FindStringByDottedPath("payment.payeeName");
ASSERT_NE(nullptr, payee_name) << response;
EXPECT_EQ("Example Payee", *payee_name);
const std::string* payee_origin =
dict.FindStringByDottedPath("payment.payeeOrigin");
ASSERT_NE(nullptr, payee_origin) << response;
EXPECT_EQ(GURL("https://example-payee-origin.test"), GURL(*payee_origin));
ExpectEvent2Histogram({Event2::kInitiated, Event2::kShown, Event2::kCompleted,
Event2::kPayClicked, Event2::kHadInitialFormOfPayment,
Event2::kRequestMethodSecurePaymentConfirmation,
Event2::kSelectedSecurePaymentConfirmation});
}
// Test allowing a failed icon download with iconMustBeShown option
IN_PROC_BROWSER_TEST_F(SecurePaymentConfirmationAuthenticatorGetTest,
IconMustBeShownFalse) {
auto scoped_auth_env = ReplaceFidoDiscoveryFactory(/*should_succeed=*/true);
test_controller()->SetHasAuthenticator(true);
confirm_payment_ = true;
NavigateTo("a.com", "/secure_payment_confirmation.html");
PaymentCredentialInfo credential_info;
CreatePaymentCredential(&credential_info);
// First ensure the icon URL is successfully parsed from clientData for a
// valid icon.
std::string icon_data =
"data:image/"
"png;base64,"
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAXRS"
"TlMAQObYZgAAAApJREFUCNdjYAAAAAIAAeIhvDMAAAAASUVORK5CYII=";
EXPECT_EQ(icon_data,
content::EvalJs(
GetActiveWebContents(),
content::JsReplace(
"getSecurePaymentConfirmationResponseIconWithInstrument({"
" displayName: 'display_name_for_instrument',"
" icon: $1,"
" iconMustBeShown: false,"
"}, $2)",
icon_data, credential_info.id)));
// Now verify that the icon string is cleared from clientData for an invalid
// icon.
EXPECT_EQ("",
content::EvalJs(
GetActiveWebContents(),
content::JsReplace(
"getSecurePaymentConfirmationResponseIconWithInstrument({"
" displayName: 'display_name_for_instrument',"
" icon: 'https://example.test/invalid-icon.png',"
" iconMustBeShown: false,"
"}, $1)",
credential_info.id)));
}
IN_PROC_BROWSER_TEST_F(SecurePaymentConfirmationAuthenticatorGetTest,
MultipleRegisteredCredentials) {
auto scoped_auth_env = ReplaceFidoDiscoveryFactory(/*should_succeed=*/true);
NavigateTo("a.com", "/secure_payment_confirmation.html");
PaymentCredentialInfo first_info;
CreatePaymentCredential(&first_info, "user_123");
PaymentCredentialInfo second_info;
CreatePaymentCredential(&second_info, "user_456");
ASSERT_NE(first_info.id, second_info.id);
NavigateTo("b.com", "/get_challenge.html");
test_controller()->SetHasAuthenticator(true);
confirm_payment_ = true;
std::string expected_result = "0.01";
EXPECT_EQ(expected_result,
content::EvalJs(
GetActiveWebContents(),
content::JsReplace("getTotalAmountFromClientData($1, $2);",
first_info.id, "0.01")));
EXPECT_EQ(expected_result,
content::EvalJs(
GetActiveWebContents(),
content::JsReplace("getTotalAmountFromClientData($1, $2);",
second_info.id, "0.01")));
}
IN_PROC_BROWSER_TEST_F(SecurePaymentConfirmationAuthenticatorGetTest,
UserVerificationFails) {
NavigateTo("a.com", "/secure_payment_confirmation.html");
PaymentCredentialInfo credential_info;
{
auto scoped_auth_env = ReplaceFidoDiscoveryFactory(/*should_succeed=*/true);
CreatePaymentCredential(&credential_info);
}
NavigateTo("b.com", "/get_challenge.html");
test_controller()->SetHasAuthenticator(true);
// Make the authenticator fail to simulate the user cancelling out of the
// WebAuthn dialog.
auto scoped_auth_env = ReplaceFidoDiscoveryFactory(/*should_succeed=*/false);
confirm_payment_ = true;
// EvalJs waits for JavaScript promise to resolve.
EXPECT_EQ(
"The operation either timed out or was not allowed. See: "
"https://www.w3.org/TR/webauthn-2/#sctn-privacy-considerations-client.",
content::EvalJs(
GetActiveWebContents(),
content::JsReplace("getTotalAmountFromClientData($1, $2);",
credential_info.id, "0.01")));
// WebAuthn dialog failure is recorded as kOtherAborted. Since we made it
// past the Transaction UX to the WebAuthn dialog, we should still log
// kPayClicked and kSelectedSecurePaymentConfirmation.
ExpectEvent2Histogram({Event2::kInitiated, Event2::kShown,
Event2::kOtherAborted, Event2::kPayClicked,
Event2::kHadInitialFormOfPayment,
Event2::kRequestMethodSecurePaymentConfirmation,
Event2::kSelectedSecurePaymentConfirmation});
}
IN_PROC_BROWSER_TEST_F(SecurePaymentConfirmationAuthenticatorGetTest,
HandlesShowPromisesAndModifiers) {
NavigateTo("a.com", "/secure_payment_confirmation.html");
auto scoped_auth_env = ReplaceFidoDiscoveryFactory(/*should_succeed=*/true);
PaymentCredentialInfo credential_info;
CreatePaymentCredential(&credential_info);
NavigateTo("b.com", "/get_challenge.html");
test_controller()->SetHasAuthenticator(true);
confirm_payment_ = true;
// EvalJs waits for JavaScript promise to resolve.
EXPECT_EQ("0.01", content::EvalJs(GetActiveWebContents(),
content::JsReplace(
"getTotalAmountFromClientData($1, $2);",
credential_info.id, "0.01")));
// Verify that passing a promise into PaymentRequest.show() that updates the
// `total` price will result in the client data price being set only after the
// promise resolves with the finalized price.
EXPECT_EQ("0.02",
content::EvalJs(
GetActiveWebContents(),
content::JsReplace(
"getTotalAmountFromClientDataWithShowPromise($1, $2);",
credential_info.id, "0.02")));
// Verify that the returned client data correctly reflects the modified
// amount.
EXPECT_EQ("0.03", content::EvalJs(
GetActiveWebContents(),
content::JsReplace(
"getTotalAmountFromClientDataWithModifier($1, $2);",
credential_info.id, "0.03")));
// Verify that the returned client data correctly reflects the modified amount
// that is set when the promised passed into PaymentRequest.show() resolves.
EXPECT_EQ(
"0.04",
content::EvalJs(
GetActiveWebContents(),
content::JsReplace(
"getTotalAmountFromClientDataWithModifierAndShowPromise($1, $2);",
credential_info.id, "0.04")));
}
} // namespace
} // namespace payments
#endif // !BUILDFLAG(IS_MAC)
|