File: android_payment_app_factory_unittest.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (645 lines) | stat: -rw-r--r-- 27,796 bytes parent folder | download | duplicates (6)
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
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/payments/content/android_payment_app_factory.h"

#include <memory>
#include <utility>

#include "base/containers/contains.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/run_loop.h"
#include "base/test/gmock_callback_support.h"
#include "components/payments/content/android_app_communication.h"
#include "components/payments/content/android_app_communication_test_support.h"
#include "components/payments/content/mock_android_app_communication.h"
#include "components/payments/content/mock_payment_app_factory_delegate.h"
#include "components/payments/content/payment_app_factory.h"
#include "components/payments/content/payment_manifest_web_data_service.h"
#include "components/payments/content/payment_request_spec.h"
#include "components/payments/core/android_app_description.h"
#include "components/webauthn/core/browser/internal_authenticator.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/test_browser_context.h"
#include "content/public/test/test_web_contents_factory.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
#include "url/origin.h"

namespace content {
class BrowserContext;
}  // namespace content

namespace payments {
namespace {

using base::test::RunOnceCallback;

// The scaffolding for testing the Android payment app factory.
class AndroidPaymentAppFactoryTest : public testing::Test {
 public:
  AndroidPaymentAppFactoryTest()
      : mock_communication_(
            std::make_unique<MockAndroidAppCommunication>(&context_)),
        factory_(mock_communication_->GetWeakPtr()) {
    auto method_data = mojom::PaymentMethodData::New();
    method_data->supported_method = "https://play.google.com/billing";
    method_data->stringified_data = "{}";
    delegate_ = std::make_unique<MockPaymentAppFactoryDelegate>(
        web_contents_factory_.CreateWebContents(&context_),
        std::move(method_data));
  }

 protected:
  content::BrowserTaskEnvironment task_environment_;
  content::TestBrowserContext context_;
  content::TestWebContentsFactory web_contents_factory_;
  std::unique_ptr<MockPaymentAppFactoryDelegate> delegate_;
  std::unique_ptr<MockAndroidAppCommunication> mock_communication_;
  AndroidPaymentAppFactory factory_;
};

// This is a regression test for crbug.com/1414738. A mismatch in early-return
// checks could result in calling IsReadyToPay with a null RenderFrameHost in a
// loop - however the first call would end up deleting |this| and cause a UAF.
TEST_F(AndroidPaymentAppFactoryTest, NullRenderFrameHost) {
  EXPECT_CALL(*delegate_, GetTwaPackageName)
      .WillRepeatedly(
          base::test::RunOnceCallbackRepeatedly<0>("com.example.app"));

  // In order to reach the problematic code, we need a null RenderFrameHost and
  // also to be in off the record mode.
  EXPECT_CALL(*delegate_, GetInitiatorRenderFrameHost)
      .WillRepeatedly(testing::Return(nullptr));
  delegate_->set_is_off_the_record();

  // Return an app with multiple activities. This causes multiple iterations
  // when looping over `single_activity_apps` - the UAF would trigger on the
  // second iteration.
  EXPECT_CALL(*mock_communication_, GetAppDescriptions)
      .WillRepeatedly(
          [](const std::string& twa_package_name,
             MockAndroidAppCommunication::GetAppDescriptionsCallback callback) {
            std::vector<std::unique_ptr<AndroidAppDescription>> apps;
            apps.emplace_back(std::make_unique<AndroidAppDescription>());
            apps.back()->package = "com.example.app";
            apps.back()->service_names.push_back("com.example.app.Service");
            apps.back()->activities.emplace_back(
                std::make_unique<AndroidActivityDescription>());
            apps.back()->activities.back()->name = "com.example.app.Activity";
            apps.back()->activities.back()->default_payment_method =
                "https://play.google.com/billing";
            apps.back()->activities.emplace_back(
                std::make_unique<AndroidActivityDescription>());
            apps.back()->activities.back()->name = "com.example.app.Activity2";
            apps.back()->activities.back()->default_payment_method =
                "https://play.google.com/billing";
            std::move(callback).Run(std::nullopt, std::move(apps));
          });

  // Now trigger app finding. This should near immediately bail in
  // AppFinder::OnGetAppDescriptions and not make it to IsReadyToPay.
  factory_.Create(delegate_->GetWeakPtr());
}

// This test class uses a deeper integration into the underlying app support,
// and as such some tests may only run on certain platforms (e.g., ChromeOS).
class AndroidPaymentAppFactoryIntegrationTest : public testing::Test {
 public:
  AndroidPaymentAppFactoryIntegrationTest()
      : support_(AndroidAppCommunicationTestSupport::Create()),
        factory_(GetCommunication(support_->context())) {
    auto method_data = mojom::PaymentMethodData::New();
    method_data->supported_method = "https://play.google.com/billing";
    method_data->stringified_data = "{}";
    delegate_ = std::make_unique<MockPaymentAppFactoryDelegate>(
        web_contents_factory_.CreateWebContents(support_->context()),
        std::move(method_data));

    EXPECT_CALL(*delegate_, GetInitiatorRenderFrameHost())
        .WillRepeatedly(testing::Return(
            delegate_->GetWebContents()->GetPrimaryMainFrame()));
  }

  std::unique_ptr<AndroidAppCommunicationTestSupport> support_;
  content::TestWebContentsFactory web_contents_factory_;
  std::unique_ptr<MockPaymentAppFactoryDelegate> delegate_;
  AndroidPaymentAppFactory factory_;

 private:
  // Returns the Android app communication that can be used in unit tests.
  static base::WeakPtr<AndroidAppCommunication> GetCommunication(
      content::BrowserContext* context) {
    base::WeakPtr<AndroidAppCommunication> communication =
        AndroidAppCommunication::GetForBrowserContext(context);
    communication->SetForTesting();
    return communication;
  }
};

// The payment app factory should return an error if it's unable to invoke
// Android payment apps on a platform that supports such apps, e.g, when ARC is
// disabled on Chrome OS, Lacros cannot connect to payment app instance.
TEST_F(AndroidPaymentAppFactoryIntegrationTest,
       FactoryReturnsErrorWithoutPaymentAppInstance) {
  EXPECT_CALL(*delegate_, GetTwaPackageName)
      .WillRepeatedly(
          base::test::RunOnceCallbackRepeatedly<0>("com.example.app"));
  base::RunLoop runloop;
  EXPECT_CALL(*delegate_, OnDoneCreatingPaymentApps()).WillOnce([&runloop] {
    runloop.Quit();
  });

  EXPECT_CALL(*delegate_, OnPaymentAppCreationError(
                              support_->GetNoInstanceExpectedErrorString(),
                              AppCreationFailureReason::UNKNOWN))
      .Times(support_->AreAndroidAppsSupportedOnThisPlatform() ? 1 : 0);
  EXPECT_CALL(*delegate_, OnPaymentAppCreated(testing::_)).Times(0);
  EXPECT_CALL(*delegate_, GetChromeOSTWAInstanceId()).Times(0);

  support_->ExpectNoListOfPaymentAppsQuery();
  support_->ExpectNoIsReadyToPayQuery();

  factory_.Create(delegate_->GetWeakPtr());
  runloop.Run();
}

// The payment app factory should not return any errors when there're no Android
// payment apps available.
TEST_F(AndroidPaymentAppFactoryIntegrationTest, NoErrorsWhenNoApps) {
  // Enable invoking Android payment apps on those platforms that support it.
  auto scoped_initialization_ = support_->CreateScopedInitialization();

  EXPECT_CALL(*delegate_, GetTwaPackageName)
      .WillRepeatedly(
          base::test::RunOnceCallbackRepeatedly<0>("com.example.app"));
  base::RunLoop runloop;
  EXPECT_CALL(*delegate_, OnDoneCreatingPaymentApps()).WillOnce([&runloop] {
    runloop.Quit();
  });

  EXPECT_CALL(*delegate_, OnPaymentAppCreationError(testing::_, testing::_))
      .Times(0);
  EXPECT_CALL(*delegate_, OnPaymentAppCreated(testing::_)).Times(0);
  EXPECT_CALL(*delegate_, GetChromeOSTWAInstanceId()).Times(0);

  support_->ExpectQueryListOfPaymentAppsAndRespond({});
  support_->ExpectNoIsReadyToPayQuery();

  factory_.Create(delegate_->GetWeakPtr());
  runloop.Run();
}

// The |arg| is of type std::unique_ptr<PaymentApp>.
MATCHER_P3(PaymentAppMatches, type, package, method, "") {
  return arg->type() == type && arg->GetId() == package &&
         base::Contains(arg->GetAppMethodNames(), method);
}

// The payment app factory should return the TWA payment app when running in TWA
// mode, even when it does not have an IS_READY_TO_PAY service.
TEST_F(AndroidPaymentAppFactoryIntegrationTest,
       FindAppsThatDoNotHaveReadyToPayService) {
  // Enable invoking Android payment apps on those platforms that support it.
  auto scoped_initialization_ = support_->CreateScopedInitialization();

  EXPECT_CALL(*delegate_, GetTwaPackageName)
      .WillRepeatedly(
          base::test::RunOnceCallbackRepeatedly<0>("com.example.app"));
  base::RunLoop runloop;
  EXPECT_CALL(*delegate_, OnDoneCreatingPaymentApps()).WillOnce([&runloop] {
    runloop.Quit();
  });

  EXPECT_CALL(*delegate_, OnPaymentAppCreationError(testing::_, testing::_))
      .Times(0);

  EXPECT_CALL(*delegate_,
              OnPaymentAppCreated(PaymentAppMatches(
                  PaymentApp::Type::NATIVE_MOBILE_APP, "com.example.app",
                  "https://play.google.com/billing")))
      .Times(support_->AreAndroidAppsSupportedOnThisPlatform() ? 1 : 0);
  EXPECT_CALL(*delegate_, GetChromeOSTWAInstanceId())
      .Times(support_->AreAndroidAppsSupportedOnThisPlatform() ? 1 : 0);

  // This app does not have an IS_READY_TO_PAY service.
  std::vector<std::unique_ptr<AndroidAppDescription>> apps;
  apps.emplace_back(std::make_unique<AndroidAppDescription>());
  apps.back()->package = "com.example.app";
  apps.back()->activities.emplace_back(
      std::make_unique<AndroidActivityDescription>());
  apps.back()->activities.back()->name = "com.example.app.Activity";
  apps.back()->activities.back()->default_payment_method =
      "https://play.google.com/billing";
  support_->ExpectQueryListOfPaymentAppsAndRespond(std::move(apps));

  // There is no IS_READY_TO_PAY service to invoke.
  support_->ExpectNoIsReadyToPayQuery();

  factory_.Create(delegate_->GetWeakPtr());
  runloop.Run();
}

// The payment app factory should return one payment app and should not query
// the IS_READY_TO_PAY service, because of being off the record.
TEST_F(AndroidPaymentAppFactoryIntegrationTest,
       DoNotQueryReadyToPaySericeWhenOffTheRecord) {
  // Enable invoking Android payment apps on those platforms that support it.
  auto scoped_initialization_ = support_->CreateScopedInitialization();

  // Simulate being off the record.
  delegate_->set_is_off_the_record();

  EXPECT_CALL(*delegate_, GetTwaPackageName)
      .WillRepeatedly(
          base::test::RunOnceCallbackRepeatedly<0>("com.example.app"));
  base::RunLoop runloop;
  EXPECT_CALL(*delegate_, OnDoneCreatingPaymentApps()).WillOnce([&runloop] {
    runloop.Quit();
  });

  EXPECT_CALL(*delegate_, OnPaymentAppCreationError(testing::_, testing::_))
      .Times(0);

  EXPECT_CALL(*delegate_,
              OnPaymentAppCreated(PaymentAppMatches(
                  PaymentApp::Type::NATIVE_MOBILE_APP, "com.example.app",
                  "https://play.google.com/billing")))
      .Times(support_->AreAndroidAppsSupportedOnThisPlatform() ? 1 : 0);

  EXPECT_CALL(*delegate_, GetChromeOSTWAInstanceId())
      .Times(support_->AreAndroidAppsSupportedOnThisPlatform() ? 1 : 0);

  std::vector<std::unique_ptr<AndroidAppDescription>> apps;
  apps.emplace_back(std::make_unique<AndroidAppDescription>());
  apps.back()->package = "com.example.app";
  apps.back()->service_names.push_back("com.example.app.Service");
  apps.back()->activities.emplace_back(
      std::make_unique<AndroidActivityDescription>());
  apps.back()->activities.back()->name = "com.example.app.Activity";
  apps.back()->activities.back()->default_payment_method =
      "https://play.google.com/billing";
  support_->ExpectQueryListOfPaymentAppsAndRespond(std::move(apps));

  // The IS_READY_TO_PAY service should not be invoked when off the record.
  support_->ExpectNoIsReadyToPayQuery();

  factory_.Create(delegate_->GetWeakPtr());
  runloop.Run();
}

// The payment app factory should return the TWA payment app that returns true
// from IS_READY_TO_PAY service when running in TWA mode.
TEST_F(AndroidPaymentAppFactoryIntegrationTest,
       FindTheTwaPaymentAppThatIsReadyToPayInTwaMode) {
  // Enable invoking Android payment apps on those platforms that support it.
  auto scoped_initialization_ = support_->CreateScopedInitialization();

  EXPECT_CALL(*delegate_, GetTwaPackageName)
      .WillRepeatedly(base::test::RunOnceCallbackRepeatedly<0>("com.twa.app"));
  base::RunLoop runloop;
  EXPECT_CALL(*delegate_, OnDoneCreatingPaymentApps()).WillOnce([&runloop] {
    runloop.Quit();
  });

  EXPECT_CALL(*delegate_, OnPaymentAppCreationError(testing::_, testing::_))
      .Times(0);

  EXPECT_CALL(*delegate_,
              OnPaymentAppCreated(PaymentAppMatches(
                  PaymentApp::Type::NATIVE_MOBILE_APP, "com.twa.app",
                  "https://play.google.com/billing")))
      .Times(support_->AreAndroidAppsSupportedOnThisPlatform() ? 1 : 0);
  EXPECT_CALL(*delegate_, GetChromeOSTWAInstanceId())
      .Times(support_->AreAndroidAppsSupportedOnThisPlatform() ? 1 : 0);

  std::vector<std::unique_ptr<AndroidAppDescription>> apps;
  apps.emplace_back(std::make_unique<AndroidAppDescription>());
  apps.back()->package = "com.twa.app";
  apps.back()->service_names.push_back("com.twa.app.Service");
  apps.back()->activities.emplace_back(
      std::make_unique<AndroidActivityDescription>());
  apps.back()->activities.back()->name = "com.twa.app.Activity";
  apps.back()->activities.back()->default_payment_method =
      "https://play.google.com/billing";
  support_->ExpectQueryListOfPaymentAppsAndRespond(std::move(apps));
  support_->ExpectQueryIsReadyToPayAndRespond(/*is_ready_to_pay=*/true);

  factory_.Create(delegate_->GetWeakPtr());
  runloop.Run();
}

// The payment app factory should return no payment apps when IS_READY_TO_PAY
// service returns false.
TEST_F(AndroidPaymentAppFactoryIntegrationTest,
       IgnoreAppsThatAreNotReadyToPay) {
  // Enable invoking Android payment apps on those platforms that support it.
  auto scoped_initialization_ = support_->CreateScopedInitialization();

  EXPECT_CALL(*delegate_, GetTwaPackageName)
      .WillRepeatedly(
          base::test::RunOnceCallbackRepeatedly<0>("com.example.app"));
  base::RunLoop runloop;
  EXPECT_CALL(*delegate_, OnDoneCreatingPaymentApps()).WillOnce([&runloop] {
    runloop.Quit();
  });
  EXPECT_CALL(*delegate_, OnPaymentAppCreationError(testing::_, testing::_))
      .Times(0);
  EXPECT_CALL(*delegate_, OnPaymentAppCreated(testing::_)).Times(0);
  EXPECT_CALL(*delegate_, GetChromeOSTWAInstanceId()).Times(0);

  std::vector<std::unique_ptr<AndroidAppDescription>> apps;
  apps.emplace_back(std::make_unique<AndroidAppDescription>());
  apps.back()->package = "com.example.app";
  apps.back()->service_names.push_back("com.example.app.Service");
  apps.back()->activities.emplace_back(
      std::make_unique<AndroidActivityDescription>());
  apps.back()->activities.back()->name = "com.example.app.Activity";
  apps.back()->activities.back()->default_payment_method =
      "https://play.google.com/billing";
  support_->ExpectQueryListOfPaymentAppsAndRespond(std::move(apps));
  support_->ExpectQueryIsReadyToPayAndRespond(/*is_ready_to_pay=*/false);

  factory_.Create(delegate_->GetWeakPtr());
  runloop.Run();
}

// The payment app factory should return the correct TWA payment app out of two
// installed payment apps, when running in TWA mode.
TEST_F(AndroidPaymentAppFactoryIntegrationTest, FindTheCorrectTwaAppInTwaMode) {
  // Enable invoking Android payment apps on those platforms that support it.
  auto scoped_initialization_ = support_->CreateScopedInitialization();

  EXPECT_CALL(*delegate_, GetTwaPackageName)
      .WillRepeatedly(
          base::test::RunOnceCallbackRepeatedly<0>("com.correct-twa.app"));
  base::RunLoop runloop;
  EXPECT_CALL(*delegate_, OnDoneCreatingPaymentApps()).WillOnce([&runloop] {
    runloop.Quit();
  });

  EXPECT_CALL(*delegate_, OnPaymentAppCreationError(testing::_, testing::_))
      .Times(0);

  EXPECT_CALL(*delegate_,
              OnPaymentAppCreated(PaymentAppMatches(
                  PaymentApp::Type::NATIVE_MOBILE_APP, "com.correct-twa.app",
                  "https://play.google.com/billing")))
      .Times(support_->AreAndroidAppsSupportedOnThisPlatform() ? 1 : 0);
  EXPECT_CALL(*delegate_,
              OnPaymentAppCreated(PaymentAppMatches(
                  PaymentApp::Type::NATIVE_MOBILE_APP, "com.different.app",
                  "https://play.google.com/billing")))
      .Times(0);
  EXPECT_CALL(*delegate_, GetChromeOSTWAInstanceId())
      .Times(support_->AreAndroidAppsSupportedOnThisPlatform() ? 1 : 0);

  std::vector<std::unique_ptr<AndroidAppDescription>> apps;
  apps.emplace_back(std::make_unique<AndroidAppDescription>());
  apps.back()->package = "com.correct-twa.app";
  apps.back()->service_names.push_back("com.correct-twa.app.Service");
  apps.back()->activities.emplace_back(
      std::make_unique<AndroidActivityDescription>());
  apps.back()->activities.back()->name = "com.correct-twa.app.Activity";
  apps.back()->activities.back()->default_payment_method =
      "https://play.google.com/billing";

  apps.emplace_back(std::make_unique<AndroidAppDescription>());
  apps.back()->package = "com.different.app";
  apps.back()->service_names.push_back("com.different.app.Service");
  apps.back()->activities.emplace_back(
      std::make_unique<AndroidActivityDescription>());
  apps.back()->activities.back()->name = "com.different.app.Activity";
  apps.back()->activities.back()->default_payment_method =
      "https://play.google.com/billing";

  support_->ExpectQueryListOfPaymentAppsAndRespond(std::move(apps));
  support_->ExpectQueryIsReadyToPayAndRespond(/*is_ready_to_pay=*/true);

  factory_.Create(delegate_->GetWeakPtr());
  runloop.Run();
}

// The payment app factory does not return non-TWA payment apps when running in
// TWA mode.
TEST_F(AndroidPaymentAppFactoryIntegrationTest, IgnoreNonTwaAppsInTwaMode) {
  // Enable invoking Android payment apps on those platforms that support it.
  auto scoped_initialization_ = support_->CreateScopedInitialization();

  EXPECT_CALL(*delegate_, GetTwaPackageName)
      .WillRepeatedly(base::test::RunOnceCallbackRepeatedly<0>("com.twa.app"));
  base::RunLoop runloop;
  EXPECT_CALL(*delegate_, OnDoneCreatingPaymentApps()).WillOnce([&runloop] {
    runloop.Quit();
  });
  EXPECT_CALL(*delegate_, OnPaymentAppCreationError(testing::_, testing::_))
      .Times(0);
  EXPECT_CALL(*delegate_, OnPaymentAppCreated(testing::_)).Times(0);
  EXPECT_CALL(*delegate_, GetChromeOSTWAInstanceId()).Times(0);

  std::vector<std::unique_ptr<AndroidAppDescription>> apps;
  apps.emplace_back(std::make_unique<AndroidAppDescription>());
  apps.back()->package = "com.non-twa.app";
  apps.back()->service_names.push_back("com.non-twa.app.Service");
  apps.back()->activities.emplace_back(
      std::make_unique<AndroidActivityDescription>());
  apps.back()->activities.back()->name = "com.non-twa.app.Activity";
  apps.back()->activities.back()->default_payment_method =
      "https://play.google.com/billing";
  support_->ExpectQueryListOfPaymentAppsAndRespond(std::move(apps));
  support_->ExpectNoIsReadyToPayQuery();

  factory_.Create(delegate_->GetWeakPtr());
  runloop.Run();
}

// The payment app factory does not return any payment apps when not running
// inside of TWA.
TEST_F(AndroidPaymentAppFactoryIntegrationTest,
       DoNotLookForAppsWhenOutsideOfTwaMode) {
  // Enable invoking Android payment apps on those platforms that support it.
  auto scoped_initialization_ = support_->CreateScopedInitialization();

  EXPECT_CALL(*delegate_, GetTwaPackageName)
      .WillRepeatedly(base::test::RunOnceCallbackRepeatedly<0>(""));
  base::RunLoop runloop;
  EXPECT_CALL(*delegate_, OnDoneCreatingPaymentApps()).WillOnce([&runloop] {
    runloop.Quit();
  });
  EXPECT_CALL(*delegate_, OnPaymentAppCreationError(testing::_, testing::_))
      .Times(0);
  EXPECT_CALL(*delegate_, OnPaymentAppCreated(testing::_)).Times(0);
  EXPECT_CALL(*delegate_, GetChromeOSTWAInstanceId()).Times(0);

  support_->ExpectNoListOfPaymentAppsQuery();

  factory_.Create(delegate_->GetWeakPtr());
  runloop.Run();
}

// The Android payment app factory works only with TWA specific payment methods.
TEST_F(AndroidPaymentAppFactoryIntegrationTest,
       DoNotLookForAppsForNonTwaMethod) {
  // Enable invoking Android payment apps on those platforms that support it.
  auto scoped_initialization_ = support_->CreateScopedInitialization();

  // "https://example.test" is not a TWA specific payment method.
  auto method_data = mojom::PaymentMethodData::New();
  method_data->supported_method = "https://example.test";
  method_data->stringified_data = "{}";
  delegate_->SetRequestedPaymentMethod(std::move(method_data));

  EXPECT_CALL(*delegate_, GetTwaPackageName)
      .WillRepeatedly(
          base::test::RunOnceCallbackRepeatedly<0>("com.example.app"));
  base::RunLoop runloop;
  EXPECT_CALL(*delegate_, OnDoneCreatingPaymentApps()).WillOnce([&runloop] {
    runloop.Quit();
  });
  EXPECT_CALL(*delegate_, OnPaymentAppCreationError(testing::_, testing::_))
      .Times(0);
  EXPECT_CALL(*delegate_, OnPaymentAppCreated(testing::_)).Times(0);
  EXPECT_CALL(*delegate_, GetChromeOSTWAInstanceId()).Times(0);

  support_->ExpectNoListOfPaymentAppsQuery();
  support_->ExpectNoIsReadyToPayQuery();

  factory_.Create(delegate_->GetWeakPtr());
  runloop.Run();
}

// If the TWA supports a non-TWA-specific payment method, then it should be
// ignored.
TEST_F(AndroidPaymentAppFactoryIntegrationTest, IgnoreNonTwaMethodInTheTwa) {
  // Enable invoking Android payment apps on those platforms that support it.
  auto scoped_initialization_ = support_->CreateScopedInitialization();

  EXPECT_CALL(*delegate_, GetTwaPackageName)
      .WillRepeatedly(base::test::RunOnceCallbackRepeatedly<0>("com.twa.app"));
  base::RunLoop runloop;
  EXPECT_CALL(*delegate_, OnDoneCreatingPaymentApps()).WillOnce([&runloop] {
    runloop.Quit();
  });
  EXPECT_CALL(*delegate_, OnPaymentAppCreationError(testing::_, testing::_))
      .Times(0);
  EXPECT_CALL(*delegate_, OnPaymentAppCreated(testing::_)).Times(0);
  EXPECT_CALL(*delegate_, GetChromeOSTWAInstanceId()).Times(0);

  std::vector<std::unique_ptr<AndroidAppDescription>> apps;
  apps.emplace_back(std::make_unique<AndroidAppDescription>());
  apps.back()->package = "com.twa.app";
  apps.back()->service_names.push_back("com.twa.app.Service");
  apps.back()->activities.emplace_back(
      std::make_unique<AndroidActivityDescription>());
  apps.back()->activities.back()->name = "com.twa.app.Activity";
  apps.back()->activities.back()->default_payment_method =
      "https://example.test";
  support_->ExpectQueryListOfPaymentAppsAndRespond(std::move(apps));
  support_->ExpectNoIsReadyToPayQuery();

  factory_.Create(delegate_->GetWeakPtr());
  runloop.Run();
}

// If the TWA supports both a TWA-specific and a non-TWA-specific payment
// method, then only the TWA-specific payment method activity should be
// returned.
TEST_F(AndroidPaymentAppFactoryIntegrationTest,
       FindOnlyActivitiesWithTwaSpecificMethodName) {
  // Enable invoking Android payment apps on those platforms that support it.
  auto scoped_initialization_ = support_->CreateScopedInitialization();

  EXPECT_CALL(*delegate_, GetTwaPackageName)
      .WillRepeatedly(base::test::RunOnceCallbackRepeatedly<0>("com.twa.app"));
  base::RunLoop runloop;
  EXPECT_CALL(*delegate_, OnDoneCreatingPaymentApps()).WillOnce([&runloop] {
    runloop.Quit();
  });
  EXPECT_CALL(*delegate_, OnPaymentAppCreationError(testing::_, testing::_))
      .Times(0);
  EXPECT_CALL(*delegate_,
              OnPaymentAppCreated(PaymentAppMatches(
                  PaymentApp::Type::NATIVE_MOBILE_APP, "com.twa.app",
                  "https://play.google.com/billing")))
      .Times(support_->AreAndroidAppsSupportedOnThisPlatform() ? 1 : 0);
  EXPECT_CALL(*delegate_, OnPaymentAppCreated(PaymentAppMatches(
                              PaymentApp::Type::NATIVE_MOBILE_APP,
                              "com.twa.app", "https://example.test")))
      .Times(0);
  EXPECT_CALL(*delegate_, GetChromeOSTWAInstanceId())
      .Times(support_->AreAndroidAppsSupportedOnThisPlatform() ? 1 : 0);

  std::vector<std::unique_ptr<AndroidAppDescription>> apps;
  apps.emplace_back(std::make_unique<AndroidAppDescription>());
  apps.back()->package = "com.twa.app";
  apps.back()->service_names.push_back("com.twa.app.Service");

  apps.back()->activities.emplace_back(
      std::make_unique<AndroidActivityDescription>());
  apps.back()->activities.back()->name = "com.twa.app.ActivityOne";
  apps.back()->activities.back()->default_payment_method =
      "https://play.google.com/billing";

  apps.back()->activities.emplace_back(
      std::make_unique<AndroidActivityDescription>());
  apps.back()->activities.back()->name = "com.twa.app.ActivityTwo";
  apps.back()->activities.back()->default_payment_method =
      "https://example.test";

  support_->ExpectQueryListOfPaymentAppsAndRespond(std::move(apps));
  support_->ExpectQueryIsReadyToPayAndRespond(/*is_ready_to_pay=*/true);

  factory_.Create(delegate_->GetWeakPtr());
  runloop.Run();
}

// At most one IS_READY_TO_PAY service is allowed in an Android payment app.
TEST_F(AndroidPaymentAppFactoryIntegrationTest,
       ReturnErrorWhenMoreThanOneServiceInApp) {
  // Enable invoking Android payment apps on those platforms that support it.
  auto scoped_initialization_ = support_->CreateScopedInitialization();

  EXPECT_CALL(*delegate_, GetTwaPackageName)
      .WillRepeatedly(
          base::test::RunOnceCallbackRepeatedly<0>("com.example.app"));
  base::RunLoop runloop;
  EXPECT_CALL(*delegate_, OnDoneCreatingPaymentApps()).WillOnce([&runloop] {
    runloop.Quit();
  });

  EXPECT_CALL(*delegate_,
              OnPaymentAppCreationError(
                  "Found more than one IS_READY_TO_PAY service, but "
                  "at most one service is supported.",
                  AppCreationFailureReason::UNKNOWN))
      .Times(support_->AreAndroidAppsSupportedOnThisPlatform() ? 1 : 0);

  EXPECT_CALL(*delegate_, OnPaymentAppCreated(testing::_)).Times(0);
  EXPECT_CALL(*delegate_, GetChromeOSTWAInstanceId()).Times(0);

  std::vector<std::unique_ptr<AndroidAppDescription>> apps;
  apps.emplace_back(std::make_unique<AndroidAppDescription>());
  apps.back()->package = "com.example.app";

  // Two IS_READY_TO_PAY services:
  apps.back()->service_names.push_back("com.example.app.ServiceOne");
  apps.back()->service_names.push_back("com.example.app.ServiceTwo");

  apps.back()->activities.emplace_back(
      std::make_unique<AndroidActivityDescription>());
  apps.back()->activities.back()->name = "com.example.app.Activity";
  apps.back()->activities.back()->default_payment_method =
      "https://play.google.com/billing";
  support_->ExpectQueryListOfPaymentAppsAndRespond(std::move(apps));
  support_->ExpectNoIsReadyToPayQuery();

  factory_.Create(delegate_->GetWeakPtr());
  runloop.Run();
}

}  // namespace
}  // namespace payments