summaryrefslogtreecommitdiff
path: root/chromium/components/autofill/core/browser/payments/payments_client.cc
blob: 06cd9bfdf626b5a5628e87292a5fe8efe4afbdad (plain)
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
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/autofill/core/browser/payments/payments_client.h"

#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>

#include "base/bind.h"
#include "base/command_line.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "build/build_config.h"
#include "components/autofill/core/browser/autofill_experiments.h"
#include "components/autofill/core/browser/autofill_type.h"
#include "components/autofill/core/browser/data_model/autofill_data_model.h"
#include "components/autofill/core/browser/data_model/credit_card.h"
#include "components/autofill/core/browser/payments/account_info_getter.h"
#include "components/autofill/core/browser/payments/local_card_migration_manager.h"
#include "components/autofill/core/browser/payments/payments_request.h"
#include "components/autofill/core/browser/payments/payments_service_url.h"
#include "components/autofill/core/common/autofill_features.h"
#include "components/autofill/core/common/autofill_payments_features.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/signin/public/identity_manager/primary_account_access_token_fetcher.h"
#include "components/signin/public/identity_manager/scope_set.h"
#include "components/variations/net/variations_http_headers.h"
#include "net/base/escape.h"
#include "net/base/load_flags.h"
#include "net/http/http_status_code.h"
#include "net/traffic_annotation/network_traffic_annotation.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/cpp/simple_url_loader.h"

namespace autofill {
namespace payments {

namespace {

const char kGetUnmaskDetailsRequestPath[] =
    "payments/apis/chromepaymentsservice/getdetailsforgetrealpan";

const char kUnmaskCardRequestPath[] =
    "payments/apis-secure/creditcardservice/getrealpan?s7e_suffix=chromewallet";
const char kUnmaskCardRequestFormat[] =
    "requestContentType=application/json; charset=utf-8&request=%s"
    "&s7e_13_cvc=%s";
const char kUnmaskCardRequestFormatWithoutCvc[] =
    "requestContentType=application/json; charset=utf-8&request=%s";

const char kOptChangeRequestPath[] =
    "payments/apis/chromepaymentsservice/updateautofilluserpreference";

const char kGetUploadDetailsRequestPath[] =
    "payments/apis/chromepaymentsservice/getdetailsforsavecard";

const char kUploadCardRequestPath[] =
    "payments/apis-secure/chromepaymentsservice/savecard"
    "?s7e_suffix=chromewallet";
const char kUploadCardRequestFormat[] =
    "requestContentType=application/json; charset=utf-8&request=%s"
    "&s7e_1_pan=%s&s7e_13_cvc=%s";
const char kUploadCardRequestFormatWithoutCvc[] =
    "requestContentType=application/json; charset=utf-8&request=%s"
    "&s7e_1_pan=%s";

const char kMigrateCardsRequestPath[] =
    "payments/apis-secure/chromepaymentsservice/migratecards"
    "?s7e_suffix=chromewallet";
const char kMigrateCardsRequestFormat[] =
    "requestContentType=application/json; charset=utf-8&request=%s";

const char kTokenFetchId[] = "wallet_client";
const char kPaymentsOAuth2Scope[] =
    "https://www.googleapis.com/auth/wallet.chrome";

GURL GetRequestUrl(const std::string& path) {
  if (base::CommandLine::ForCurrentProcess()->HasSwitch("sync-url")) {
    if (IsPaymentsProductionEnabled()) {
      LOG(ERROR) << "You are using production Payments but you specified a "
                    "--sync-url. You likely want to disable the sync sandbox "
                    "or switch to sandbox Payments. Both are controlled in "
                    "about:flags.";
    }
  } else if (!IsPaymentsProductionEnabled()) {
    LOG(ERROR) << "You are using sandbox Payments but you didn't specify a "
                  "--sync-url. You likely want to enable the sync sandbox "
                  "or switch to production Payments. Both are controlled in "
                  "about:flags.";
  }

  return GetBaseSecureUrl().Resolve(path);
}

base::Value BuildCustomerContextDictionary(int64_t external_customer_id) {
  base::Value customer_context(base::Value::Type::DICTIONARY);
  customer_context.SetKey("external_customer_id",
                          base::Value(std::to_string(external_customer_id)));
  return customer_context;
}

base::Value BuildRiskDictionary(const std::string& encoded_risk_data) {
  base::Value risk_data(base::Value::Type::DICTIONARY);
#if defined(OS_IOS)
  // Browser fingerprinting is not available on iOS. Instead, we generate
  // RiskAdvisoryData.
  risk_data.SetKey("message_type", base::Value("RISK_ADVISORY_DATA"));
  risk_data.SetKey("encoding_type", base::Value("BASE_64_URL"));
#else
  risk_data.SetKey("message_type",
                   base::Value("BROWSER_NATIVE_FINGERPRINTING"));
  risk_data.SetKey("encoding_type", base::Value("BASE_64"));
#endif

  risk_data.SetKey("value", base::Value(encoded_risk_data));

  return risk_data;
}

void SetStringIfNotEmpty(const AutofillDataModel& profile,
                         const ServerFieldType& type,
                         const std::string& app_locale,
                         const std::string& path,
                         base::Value& dictionary) {
  const base::string16 value = profile.GetInfo(AutofillType(type), app_locale);
  if (!value.empty())
    dictionary.SetKey(path, base::Value(value));
}

void AppendStringIfNotEmpty(const AutofillProfile& profile,
                            const ServerFieldType& type,
                            const std::string& app_locale,
                            base::Value& list) {
  const base::string16 value = profile.GetInfo(type, app_locale);
  if (!value.empty())
    list.Append(value);
}

// Returns a dictionary with the structure expected by Payments RPCs, containing
// each of the fields in |profile|, formatted according to |app_locale|. If
// |include_non_location_data| is false, the name and phone number in |profile|
// are not included.
base::Value BuildAddressDictionary(const AutofillProfile& profile,
                                   const std::string& app_locale,
                                   bool include_non_location_data) {
  base::Value postal_address(base::Value::Type::DICTIONARY);

  if (include_non_location_data) {
    SetStringIfNotEmpty(profile, NAME_FULL, app_locale,
                        PaymentsClient::kRecipientName, postal_address);
  }

  base::Value address_lines(base::Value::Type::LIST);
  AppendStringIfNotEmpty(profile, ADDRESS_HOME_LINE1, app_locale,
                         address_lines);
  AppendStringIfNotEmpty(profile, ADDRESS_HOME_LINE2, app_locale,
                         address_lines);
  AppendStringIfNotEmpty(profile, ADDRESS_HOME_LINE3, app_locale,
                         address_lines);
  if (!address_lines.GetList().empty())
    postal_address.SetKey("address_line", std::move(address_lines));

  SetStringIfNotEmpty(profile, ADDRESS_HOME_CITY, app_locale, "locality_name",
                      postal_address);
  SetStringIfNotEmpty(profile, ADDRESS_HOME_STATE, app_locale,
                      "administrative_area_name", postal_address);
  SetStringIfNotEmpty(profile, ADDRESS_HOME_ZIP, app_locale,
                      "postal_code_number", postal_address);

  // Use GetRawInfo to get a country code instead of the country name:
  const base::string16 country_code = profile.GetRawInfo(ADDRESS_HOME_COUNTRY);
  if (!country_code.empty())
    postal_address.SetKey("country_name_code", base::Value(country_code));

  base::Value address(base::Value::Type::DICTIONARY);
  address.SetKey("postal_address", std::move(postal_address));

  if (include_non_location_data) {
    SetStringIfNotEmpty(profile, PHONE_HOME_WHOLE_NUMBER, app_locale,
                        PaymentsClient::kPhoneNumber, address);
  }

  return address;
}

// Returns a dictionary of the credit card with the structure expected by
// Payments RPCs, containing expiration month, expiration year and cardholder
// name (if any) fields in |credit_card|, formatted according to |app_locale|.
// |pan_field_name| is the field name for the encrypted pan. We use each credit
// card's guid as the unique id.
base::Value BuildCreditCardDictionary(const CreditCard& credit_card,
                                      const std::string& app_locale,
                                      const std::string& pan_field_name) {
  base::Value card(base::Value::Type::DICTIONARY);
  card.SetKey("unique_id", base::Value(credit_card.guid()));

  const base::string16 exp_month =
      credit_card.GetInfo(AutofillType(CREDIT_CARD_EXP_MONTH), app_locale);
  const base::string16 exp_year = credit_card.GetInfo(
      AutofillType(CREDIT_CARD_EXP_4_DIGIT_YEAR), app_locale);
  int value = 0;
  if (base::StringToInt(exp_month, &value))
    card.SetKey("expiration_month", base::Value(value));
  if (base::StringToInt(exp_year, &value))
    card.SetKey("expiration_year", base::Value(value));
  SetStringIfNotEmpty(credit_card, CREDIT_CARD_NAME_FULL, app_locale,
                      "cardholder_name", card);

  if (credit_card.HasNonEmptyValidNickname())
    card.SetKey("nickname", base::Value(credit_card.nickname()));

  card.SetKey("encrypted_pan", base::Value("__param:" + pan_field_name));
  return card;
}

// Populates the list of active experiments that affect either the data sent in
// payments RPCs or whether the RPCs are sent or not.
void SetActiveExperiments(const std::vector<const char*>& active_experiments,
                          base::Value& request_dict) {
  if (active_experiments.empty())
    return;

  base::Value active_chrome_experiments(base::Value::Type::LIST);
  for (const char* it : active_experiments)
    active_chrome_experiments.Append(it);

  request_dict.SetKey("active_chrome_experiments",
                      std::move(active_chrome_experiments));
}

class GetUnmaskDetailsRequest : public PaymentsRequest {
 public:
  GetUnmaskDetailsRequest(
      base::OnceCallback<void(AutofillClient::PaymentsRpcResult,
                              PaymentsClient::UnmaskDetails&)> callback,
      const std::string& app_locale,
      const bool full_sync_enabled)
      : callback_(std::move(callback)),
        app_locale_(app_locale),
        full_sync_enabled_(full_sync_enabled) {}
  ~GetUnmaskDetailsRequest() override {}

  std::string GetRequestUrlPath() override {
    return kGetUnmaskDetailsRequestPath;
  }

  std::string GetRequestContentType() override { return "application/json"; }

  std::string GetRequestContent() override {
    base::Value request_dict(base::Value::Type::DICTIONARY);
    base::Value context(base::Value::Type::DICTIONARY);
    context.SetKey("language_code", base::Value(app_locale_));
    context.SetKey("billable_service",
                   base::Value(kUnmaskCardBillableServiceNumber));
    request_dict.SetKey("context", std::move(context));

    base::Value chrome_user_context(base::Value::Type::DICTIONARY);
    chrome_user_context.SetKey("full_sync_enabled",
                               base::Value(full_sync_enabled_));
    request_dict.SetKey("chrome_user_context", std::move(chrome_user_context));

    std::string request_content;
    base::JSONWriter::Write(request_dict, &request_content);
    VLOG(3) << "getdetailsforgetrealpan request body: " << request_content;
    return request_content;
  }

  void ParseResponse(const base::Value& response) override {
    const auto* method = response.FindStringKey("authentication_method");
    if (method) {
      if (*method == "CVC") {
        unmask_details_.unmask_auth_method =
            AutofillClient::UnmaskAuthMethod::CVC;
      } else if (*method == "FIDO") {
        unmask_details_.unmask_auth_method =
            AutofillClient::UnmaskAuthMethod::FIDO;
      }
    }

    const auto* offer_fido_opt_in =
        response.FindKeyOfType("offer_fido_opt_in", base::Value::Type::BOOLEAN);
    unmask_details_.offer_fido_opt_in =
        offer_fido_opt_in && offer_fido_opt_in->GetBool();

    const auto* dictionary_value = response.FindKeyOfType(
        "fido_request_options", base::Value::Type::DICTIONARY);
    if (dictionary_value)
      unmask_details_.fido_request_options = dictionary_value->Clone();

    const auto* fido_eligible_card_ids = response.FindKeyOfType(
        "fido_eligible_card_id", base::Value::Type::LIST);
    if (fido_eligible_card_ids) {
      for (const base::Value& result : fido_eligible_card_ids->GetList()) {
        unmask_details_.fido_eligible_card_ids.insert(result.GetString());
      }
    }
  }

  bool IsResponseComplete() override {
    return unmask_details_.unmask_auth_method !=
           AutofillClient::UnmaskAuthMethod::UNKNOWN;
  }

  void RespondToDelegate(AutofillClient::PaymentsRpcResult result) override {
    std::move(callback_).Run(result, unmask_details_);
  }

 private:
  base::OnceCallback<void(AutofillClient::PaymentsRpcResult,
                          PaymentsClient::UnmaskDetails&)>
      callback_;
  std::string app_locale_;
  const bool full_sync_enabled_;

  // Suggested authentication method and other information to facilitate card
  // unmasking.
  payments::PaymentsClient::UnmaskDetails unmask_details_;
  DISALLOW_COPY_AND_ASSIGN(GetUnmaskDetailsRequest);
};

class UnmaskCardRequest : public PaymentsRequest {
 public:
  UnmaskCardRequest(
      const PaymentsClient::UnmaskRequestDetails& request_details,
      const bool full_sync_enabled,
      base::OnceCallback<void(AutofillClient::PaymentsRpcResult,
                              PaymentsClient::UnmaskResponseDetails&)> callback)
      : request_details_(request_details),
        full_sync_enabled_(full_sync_enabled),
        callback_(std::move(callback)) {
    DCHECK(
        CreditCard::MASKED_SERVER_CARD == request_details.card.record_type() ||
        CreditCard::FULL_SERVER_CARD == request_details.card.record_type());
  }
  ~UnmaskCardRequest() override {}

  std::string GetRequestUrlPath() override { return kUnmaskCardRequestPath; }

  std::string GetRequestContentType() override {
    return "application/x-www-form-urlencoded";
  }

  std::string GetRequestContent() override {
    base::Value request_dict(base::Value::Type::DICTIONARY);
    request_dict.SetKey("credit_card_id",
                        base::Value(request_details_.card.server_id()));
    if (base::FeatureList::IsEnabled(
            features::kAutofillAlwaysReturnCloudTokenizedCard)) {
      // See b/140727361.
      request_dict.SetKey("instrument_token",
                          base::Value("INSTRUMENT_TOKEN_FOR_TEST"));
    }
    request_dict.SetKey("risk_data_encoded",
                        BuildRiskDictionary(request_details_.risk_data));
    base::Value context(base::Value::Type::DICTIONARY);
    context.SetKey("billable_service",
                   base::Value(kUnmaskCardBillableServiceNumber));
    if (request_details_.billing_customer_number != 0) {
      context.SetKey("customer_context",
                     BuildCustomerContextDictionary(
                         request_details_.billing_customer_number));
    }
    request_dict.SetKey("context", std::move(context));

    base::Value chrome_user_context(base::Value::Type::DICTIONARY);
    chrome_user_context.SetKey("full_sync_enabled",
                               base::Value(full_sync_enabled_));
    request_dict.SetKey("chrome_user_context", std::move(chrome_user_context));

    int value = 0;
    if (base::StringToInt(request_details_.user_response.exp_month, &value))
      request_dict.SetKey("expiration_month", base::Value(value));
    if (base::StringToInt(request_details_.user_response.exp_year, &value))
      request_dict.SetKey("expiration_year", base::Value(value));

    request_dict.SetKey(
        "opt_in_fido_auth",
        base::Value(request_details_.user_response.enable_fido_auth));

    // Either FIDO assertion info is set or CVC is set, never both.
    bool is_cvc_auth = !request_details_.user_response.cvc.empty();
    bool is_fido_auth = request_details_.fido_assertion_info.has_value();

    DCHECK_NE(is_cvc_auth, is_fido_auth);
    if (is_cvc_auth) {
      request_dict.SetKey("encrypted_cvc", base::Value("__param:s7e_13_cvc"));
    } else {
      request_dict.SetKey(
          "fido_assertion_info",
          std::move(request_details_.fido_assertion_info.value()));
    }

    std::string json_request;
    base::JSONWriter::Write(request_dict, &json_request);
    std::string request_content;
    if (is_cvc_auth) {
      request_content = base::StringPrintf(
          kUnmaskCardRequestFormat,
          net::EscapeUrlEncodedData(json_request, true).c_str(),
          net::EscapeUrlEncodedData(
              base::UTF16ToASCII(request_details_.user_response.cvc), true)
              .c_str());
    } else {
      request_content = base::StringPrintf(
          kUnmaskCardRequestFormatWithoutCvc,
          net::EscapeUrlEncodedData(json_request, true).c_str());
    }

    // Payments is reporting receiving blank or non-standard-length CVCs.
    // Log CVC length being sent to gauge how often this is happening.
    if (request_details_.reason == AutofillClient::UNMASK_FOR_AUTOFILL) {
      base::UmaHistogramCounts1000("Autofill.CardUnmask.CvcLength.ForAutofill",
                                   request_details_.user_response.cvc.length());
    } else if (request_details_.reason ==
               AutofillClient::UNMASK_FOR_PAYMENT_REQUEST) {
      base::UmaHistogramCounts1000(
          "Autofill.CardUnmask.CvcLength.ForPaymentRequest",
          request_details_.user_response.cvc.length());
    }

    VLOG(3) << "getrealpan request body: " << request_content;
    return request_content;
  }

  void ParseResponse(const base::Value& response) override {
    const auto* pan = response.FindStringKey("pan");
    response_details_.real_pan = pan ? *pan : std::string();

    const auto* dcvv = response.FindStringKey("dcvv");
    response_details_.dcvv = dcvv ? *dcvv : std::string();

    const auto* creation_options = response.FindKeyOfType(
        "fido_creation_options", base::Value::Type::DICTIONARY);
    if (creation_options)
      response_details_.fido_creation_options = creation_options->Clone();

    const auto* request_options = response.FindKeyOfType(
        "fido_request_options", base::Value::Type::DICTIONARY);
    if (request_options)
      response_details_.fido_request_options = request_options->Clone();

    const auto* token = response.FindStringKey("card_authorization_token");
    response_details_.card_authorization_token = token ? *token : std::string();
  }

  bool IsResponseComplete() override {
    return !response_details_.real_pan.empty();
  }

  void RespondToDelegate(AutofillClient::PaymentsRpcResult result) override {
    std::move(callback_).Run(result, response_details_);
  }

 private:
  PaymentsClient::UnmaskRequestDetails request_details_;
  const bool full_sync_enabled_;
  base::OnceCallback<void(AutofillClient::PaymentsRpcResult,
                          PaymentsClient::UnmaskResponseDetails&)>
      callback_;
  PaymentsClient::UnmaskResponseDetails response_details_;

  DISALLOW_COPY_AND_ASSIGN(UnmaskCardRequest);
};

class OptChangeRequest : public PaymentsRequest {
 public:
  OptChangeRequest(
      const PaymentsClient::OptChangeRequestDetails& request_details,
      base::OnceCallback<void(AutofillClient::PaymentsRpcResult,
                              PaymentsClient::OptChangeResponseDetails&)>
          callback,
      const bool full_sync_enabled)
      : request_details_(request_details),
        callback_(std::move(callback)),
        full_sync_enabled_(full_sync_enabled) {}
  ~OptChangeRequest() override {}

  std::string GetRequestUrlPath() override { return kOptChangeRequestPath; }

  std::string GetRequestContentType() override { return "application/json"; }

  std::string GetRequestContent() override {
    base::Value request_dict(base::Value::Type::DICTIONARY);
    base::Value context(base::Value::Type::DICTIONARY);
    context.SetKey("language_code", base::Value(request_details_.app_locale));
    context.SetKey("billable_service",
                   base::Value(kUnmaskCardBillableServiceNumber));
    request_dict.SetKey("context", std::move(context));

    base::Value chrome_user_context(base::Value::Type::DICTIONARY);
    chrome_user_context.SetKey("full_sync_enabled",
                               base::Value(full_sync_enabled_));
    request_dict.SetKey("chrome_user_context", std::move(chrome_user_context));

    std::string reason;
    switch (request_details_.reason) {
      case PaymentsClient::OptChangeRequestDetails::ENABLE_FIDO_AUTH:
        reason = "ENABLE_FIDO_AUTH";
        break;
      case PaymentsClient::OptChangeRequestDetails::DISABLE_FIDO_AUTH:
        reason = "DISABLE_FIDO_AUTH";
        break;
      case PaymentsClient::OptChangeRequestDetails::ADD_CARD_FOR_FIDO_AUTH:
        reason = "ADD_CARD_FOR_FIDO_AUTH";
        break;
      default:
        NOTREACHED();
        break;
    }
    request_dict.SetKey("reason", base::Value(reason));

    if (request_details_.fido_authenticator_response.has_value()) {
      base::Value fido_authentication_info(base::Value::Type::DICTIONARY);

      fido_authentication_info.SetKey(
          "fido_authenticator_response",
          std::move(request_details_.fido_authenticator_response.value()));

      if (!request_details_.card_authorization_token.empty()) {
        fido_authentication_info.SetKey(
            "card_authorization_token",
            base::Value(request_details_.card_authorization_token));
      }

      request_dict.SetKey("fido_authentication_info",
                          std::move(fido_authentication_info));
    }

    std::string request_content;
    base::JSONWriter::Write(request_dict, &request_content);
    VLOG(3) << "updateautofilluserpreference request body: " << request_content;
    return request_content;
  }

  void ParseResponse(const base::Value& response) override {
    const auto* fido_authentication_info = response.FindKeyOfType(
        "fido_authentication_info", base::Value::Type::DICTIONARY);
    if (!fido_authentication_info)
      return;

    const auto* user_status =
        fido_authentication_info->FindStringKey("user_status");
    if (user_status && *user_status != "UNKNOWN_USER_STATUS")
      response_details_.user_is_opted_in =
          (*user_status == "FIDO_AUTH_ENABLED");

    const auto* fido_creation_options = fido_authentication_info->FindKeyOfType(
        "fido_creation_options", base::Value::Type::DICTIONARY);
    if (fido_creation_options)
      response_details_.fido_creation_options = fido_creation_options->Clone();

    const auto* fido_request_options = fido_authentication_info->FindKeyOfType(
        "fido_request_options", base::Value::Type::DICTIONARY);
    if (fido_request_options)
      response_details_.fido_request_options = fido_request_options->Clone();
  }

  bool IsResponseComplete() override {
    return response_details_.user_is_opted_in.has_value();
  }

  void RespondToDelegate(AutofillClient::PaymentsRpcResult result) override {
    std::move(callback_).Run(result, response_details_);
  }

 private:
  PaymentsClient::OptChangeRequestDetails request_details_;
  base::OnceCallback<void(AutofillClient::PaymentsRpcResult,
                          PaymentsClient::OptChangeResponseDetails&)>
      callback_;
  const bool full_sync_enabled_;
  PaymentsClient::OptChangeResponseDetails response_details_;

  DISALLOW_COPY_AND_ASSIGN(OptChangeRequest);
};

class GetUploadDetailsRequest : public PaymentsRequest {
 public:
  GetUploadDetailsRequest(
      const std::vector<AutofillProfile>& addresses,
      const int detected_values,
      const std::vector<const char*>& active_experiments,
      const bool full_sync_enabled,
      const std::string& app_locale,
      base::OnceCallback<void(AutofillClient::PaymentsRpcResult,
                              const base::string16&,
                              std::unique_ptr<base::Value>,
                              std::vector<std::pair<int, int>>)> callback,
      const int billable_service_number,
      PaymentsClient::UploadCardSource upload_card_source)
      : addresses_(addresses),
        detected_values_(detected_values),
        active_experiments_(active_experiments),
        full_sync_enabled_(full_sync_enabled),
        app_locale_(app_locale),
        callback_(std::move(callback)),
        billable_service_number_(billable_service_number),
        upload_card_source_(upload_card_source) {}
  ~GetUploadDetailsRequest() override {}

  std::string GetRequestUrlPath() override {
    return kGetUploadDetailsRequestPath;
  }

  std::string GetRequestContentType() override { return "application/json"; }

  std::string GetRequestContent() override {
    base::Value request_dict(base::Value::Type::DICTIONARY);
    base::Value context(base::Value::Type::DICTIONARY);
    context.SetKey("language_code", base::Value(app_locale_));
    context.SetKey("billable_service", base::Value(billable_service_number_));
    request_dict.SetKey("context", std::move(context));

    base::Value chrome_user_context(base::Value::Type::DICTIONARY);
    chrome_user_context.SetKey("full_sync_enabled",
                               base::Value(full_sync_enabled_));
    request_dict.SetKey("chrome_user_context", std::move(chrome_user_context));

    base::Value addresses(base::Value::Type::LIST);
    for (const AutofillProfile& profile : addresses_) {
      // These addresses are used by Payments to (1) accurately determine the
      // user's country in order to show the correct legal documents and (2) to
      // verify that the addresses are valid for their purposes so that we don't
      // offer save in a case where it would definitely fail (e.g. P.O. boxes if
      // min address is not possible). The final parameter directs
      // BuildAddressDictionary to omit names and phone numbers, which aren't
      // useful for these purposes.
      addresses.Append(BuildAddressDictionary(profile, app_locale_, false));
    }
    request_dict.SetKey("address", std::move(addresses));

    // It's possible we may not have found name/address/CVC in the checkout
    // flow. The detected_values_ bitmask tells Payments what *was* found, and
    // Payments will decide if the provided data is enough to offer upload save.
    request_dict.SetKey("detected_values", base::Value(detected_values_));

    SetActiveExperiments(active_experiments_, request_dict);

    switch (upload_card_source_) {
      case PaymentsClient::UploadCardSource::UNKNOWN_UPLOAD_CARD_SOURCE:
        request_dict.SetKey("upload_card_source",
                            base::Value("UNKNOWN_UPLOAD_CARD_SOURCE"));
        break;
      case PaymentsClient::UploadCardSource::UPSTREAM_CHECKOUT_FLOW:
        request_dict.SetKey("upload_card_source",
                            base::Value("UPSTREAM_CHECKOUT_FLOW"));
        break;
      case PaymentsClient::UploadCardSource::UPSTREAM_SETTINGS_PAGE:
        request_dict.SetKey("upload_card_source",
                            base::Value("UPSTREAM_SETTINGS_PAGE"));
        break;
      case PaymentsClient::UploadCardSource::UPSTREAM_CARD_OCR:
        request_dict.SetKey("upload_card_source",
                            base::Value("UPSTREAM_CARD_OCR"));
        break;
      case PaymentsClient::UploadCardSource::LOCAL_CARD_MIGRATION_CHECKOUT_FLOW:
        request_dict.SetKey("upload_card_source",
                            base::Value("LOCAL_CARD_MIGRATION_CHECKOUT_FLOW"));
        break;
      case PaymentsClient::UploadCardSource::LOCAL_CARD_MIGRATION_SETTINGS_PAGE:
        request_dict.SetKey("upload_card_source",
                            base::Value("LOCAL_CARD_MIGRATION_SETTINGS_PAGE"));
        break;
      default:
        NOTREACHED();
    }

    std::string request_content;
    base::JSONWriter::Write(request_dict, &request_content);
    VLOG(3) << "getdetailsforsavecard request body: " << request_content;
    return request_content;
  }

  void ParseResponse(const base::Value& response) override {
    const auto* context_token = response.FindStringKey("context_token");
    context_token_ =
        context_token ? base::UTF8ToUTF16(*context_token) : base::string16();

    const base::Value* dictionary_value =
        response.FindKeyOfType("legal_message", base::Value::Type::DICTIONARY);
    if (dictionary_value)
      legal_message_ = std::make_unique<base::Value>(dictionary_value->Clone());

    const auto* supported_card_bin_ranges_string =
        response.FindStringKey("supported_card_bin_ranges_string");
    supported_card_bin_ranges_ = ParseSupportedCardBinRangesString(
        supported_card_bin_ranges_string ? *supported_card_bin_ranges_string
                                         : base::EmptyString());
  }

  bool IsResponseComplete() override {
    return !context_token_.empty() && legal_message_;
  }

  void RespondToDelegate(AutofillClient::PaymentsRpcResult result) override {
    std::move(callback_).Run(result, context_token_, std::move(legal_message_),
                             supported_card_bin_ranges_);
  }

 private:
  // Helper for ParseResponse(). Input format should be :"1234,30000-55555,765",
  // where ranges are separated by commas and items separated with a dash means
  // the start and ends of the range. Items without a dash have the same start
  // and end (ex. 1234-1234)
  std::vector<std::pair<int, int>> ParseSupportedCardBinRangesString(
      const std::string& supported_card_bin_ranges_string) {
    std::vector<std::pair<int, int>> supported_card_bin_ranges;
    std::vector<std::string> range_strings =
        base::SplitString(supported_card_bin_ranges_string, ",",
                          base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);

    for (std::string& range_string : range_strings) {
      std::vector<std::string> range = base::SplitString(
          range_string, "-", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
      DCHECK(range.size() <= 2);
      int start;
      base::StringToInt(range[0], &start);
      if (range.size() == 1) {
        supported_card_bin_ranges.push_back(std::make_pair(start, start));
      } else {
        int end;
        base::StringToInt(range[1], &end);
        DCHECK_LE(start, end);
        supported_card_bin_ranges.push_back(std::make_pair(start, end));
      }
    }
    return supported_card_bin_ranges;
  }

  const std::vector<AutofillProfile> addresses_;
  const int detected_values_;
  const std::vector<const char*> active_experiments_;
  const bool full_sync_enabled_;
  std::string app_locale_;
  base::OnceCallback<void(AutofillClient::PaymentsRpcResult,
                          const base::string16&,
                          std::unique_ptr<base::Value>,
                          std::vector<std::pair<int, int>>)>
      callback_;
  base::string16 context_token_;
  std::unique_ptr<base::Value> legal_message_;
  std::vector<std::pair<int, int>> supported_card_bin_ranges_;
  const int billable_service_number_;
  PaymentsClient::UploadCardSource upload_card_source_;

  DISALLOW_COPY_AND_ASSIGN(GetUploadDetailsRequest);
};

class UploadCardRequest : public PaymentsRequest {
 public:
  UploadCardRequest(const PaymentsClient::UploadRequestDetails& request_details,
                    const bool full_sync_enabled,
                    base::OnceCallback<void(AutofillClient::PaymentsRpcResult,
                                            const std::string&)> callback)
      : request_details_(request_details),
        full_sync_enabled_(full_sync_enabled),
        callback_(std::move(callback)) {}
  ~UploadCardRequest() override {}

  std::string GetRequestUrlPath() override { return kUploadCardRequestPath; }

  std::string GetRequestContentType() override {
    return "application/x-www-form-urlencoded";
  }

  std::string GetRequestContent() override {
    base::Value request_dict(base::Value::Type::DICTIONARY);
    request_dict.SetKey("encrypted_pan", base::Value("__param:s7e_1_pan"));
    if (!request_details_.cvc.empty())
      request_dict.SetKey("encrypted_cvc", base::Value("__param:s7e_13_cvc"));
    request_dict.SetKey("risk_data_encoded",
                        BuildRiskDictionary(request_details_.risk_data));

    const std::string& app_locale = request_details_.app_locale;
    base::Value context(base::Value::Type::DICTIONARY);
    context.SetKey("language_code", base::Value(app_locale));
    context.SetKey("billable_service",
                   base::Value(kUploadCardBillableServiceNumber));
    if (request_details_.billing_customer_number != 0) {
      context.SetKey("customer_context",
                     BuildCustomerContextDictionary(
                         request_details_.billing_customer_number));
    }
    request_dict.SetKey("context", std::move(context));

    base::Value chrome_user_context(base::Value::Type::DICTIONARY);
    chrome_user_context.SetKey("full_sync_enabled",
                               base::Value(full_sync_enabled_));
    request_dict.SetKey("chrome_user_context", std::move(chrome_user_context));

    SetStringIfNotEmpty(request_details_.card, CREDIT_CARD_NAME_FULL,
                        app_locale, "cardholder_name", request_dict);

    base::Value addresses(base::Value::Type::LIST);
    for (const AutofillProfile& profile : request_details_.profiles) {
      addresses.Append(BuildAddressDictionary(profile, app_locale, true));
    }
    request_dict.SetKey("address", std::move(addresses));

    request_dict.SetKey("context_token",
                        base::Value(request_details_.context_token));

    int value = 0;
    const base::string16 exp_month = request_details_.card.GetInfo(
        AutofillType(CREDIT_CARD_EXP_MONTH), app_locale);
    const base::string16 exp_year = request_details_.card.GetInfo(
        AutofillType(CREDIT_CARD_EXP_4_DIGIT_YEAR), app_locale);
    if (base::StringToInt(exp_month, &value))
      request_dict.SetKey("expiration_month", base::Value(value));
    if (base::StringToInt(exp_year, &value))
      request_dict.SetKey("expiration_year", base::Value(value));

    if (request_details_.card.HasNonEmptyValidNickname()) {
      request_dict.SetKey("nickname",
                          base::Value(request_details_.card.nickname()));
    }

    SetActiveExperiments(request_details_.active_experiments, request_dict);

    const base::string16 pan = request_details_.card.GetInfo(
        AutofillType(CREDIT_CARD_NUMBER), app_locale);
    std::string json_request;
    base::JSONWriter::Write(request_dict, &json_request);
    std::string request_content;
    if (request_details_.cvc.empty()) {
      request_content = base::StringPrintf(
          kUploadCardRequestFormatWithoutCvc,
          net::EscapeUrlEncodedData(json_request, true).c_str(),
          net::EscapeUrlEncodedData(base::UTF16ToASCII(pan), true).c_str());
    } else {
      request_content = base::StringPrintf(
          kUploadCardRequestFormat,
          net::EscapeUrlEncodedData(json_request, true).c_str(),
          net::EscapeUrlEncodedData(base::UTF16ToASCII(pan), true).c_str(),
          net::EscapeUrlEncodedData(base::UTF16ToASCII(request_details_.cvc),
                                    true)
              .c_str());
    }
    VLOG(3) << "savecard request body: " << request_content;
    return request_content;
  }

  void ParseResponse(const base::Value& response) override {
    const std::string* credit_card_id =
        response.FindStringKey("credit_card_id");
    server_id_ = credit_card_id ? *credit_card_id : std::string();
  }

  bool IsResponseComplete() override { return true; }

  void RespondToDelegate(AutofillClient::PaymentsRpcResult result) override {
    std::move(callback_).Run(result, server_id_);
  }

 private:
  const PaymentsClient::UploadRequestDetails request_details_;
  const bool full_sync_enabled_;
  base::OnceCallback<void(AutofillClient::PaymentsRpcResult,
                          const std::string&)>
      callback_;
  std::string server_id_;

  DISALLOW_COPY_AND_ASSIGN(UploadCardRequest);
};

class MigrateCardsRequest : public PaymentsRequest {
 public:
  MigrateCardsRequest(
      const PaymentsClient::MigrationRequestDetails& request_details,
      const std::vector<MigratableCreditCard>& migratable_credit_cards,
      const bool full_sync_enabled,
      MigrateCardsCallback callback)
      : request_details_(request_details),
        migratable_credit_cards_(migratable_credit_cards),
        full_sync_enabled_(full_sync_enabled),
        callback_(std::move(callback)) {}
  ~MigrateCardsRequest() override {}

  std::string GetRequestUrlPath() override { return kMigrateCardsRequestPath; }

  std::string GetRequestContentType() override {
    return "application/x-www-form-urlencoded";
  }

  std::string GetRequestContent() override {
    base::Value request_dict(base::Value::Type::DICTIONARY);

    request_dict.SetKey("risk_data_encoded",
                        BuildRiskDictionary(request_details_.risk_data));

    const std::string& app_locale = request_details_.app_locale;
    base::Value context(base::Value::Type::DICTIONARY);
    context.SetKey("language_code", base::Value(app_locale));
    context.SetKey("billable_service",
                   base::Value(kMigrateCardsBillableServiceNumber));
    if (request_details_.billing_customer_number != 0) {
      context.SetKey("customer_context",
                     BuildCustomerContextDictionary(
                         request_details_.billing_customer_number));
    }
    request_dict.SetKey("context", std::move(context));

    base::Value chrome_user_context(base::Value::Type::DICTIONARY);
    chrome_user_context.SetKey("full_sync_enabled",
                               base::Value(full_sync_enabled_));
    request_dict.SetKey("chrome_user_context", std::move(chrome_user_context));

    request_dict.SetKey("context_token",
                        base::Value(request_details_.context_token));

    std::string all_pans_data = std::string();
    base::Value migrate_cards(base::Value::Type::LIST);
    for (size_t index = 0; index < migratable_credit_cards_.size(); ++index) {
      std::string pan_field_name = GetPanFieldName(index);
      // Generate credit card dictionary.
      migrate_cards.Append(BuildCreditCardDictionary(
          migratable_credit_cards_[index].credit_card(), app_locale,
          pan_field_name));
      // Append pan data to the |all_pans_data|.
      all_pans_data +=
          GetAppendPan(migratable_credit_cards_[index].credit_card(),
                       app_locale, pan_field_name);
    }
    request_dict.SetKey("local_card", std::move(migrate_cards));

    std::string json_request;
    base::JSONWriter::Write(request_dict, &json_request);
    std::string request_content = base::StringPrintf(
        kMigrateCardsRequestFormat,
        net::EscapeUrlEncodedData(json_request, true).c_str());
    request_content += all_pans_data;
    return request_content;
  }

  void ParseResponse(const base::Value& response) override {
    const auto* found_list =
        response.FindKeyOfType("save_result", base::Value::Type::LIST);
    if (!found_list)
      return;

    save_result_ =
        std::make_unique<std::unordered_map<std::string, std::string>>();
    for (const base::Value& result : found_list->GetList()) {
      if (result.is_dict()) {
        const std::string* unique_id = result.FindStringKey("unique_id");
        const std::string* status = result.FindStringKey("status");
        save_result_->insert(
            std::make_pair(unique_id ? *unique_id : std::string(),
                           status ? *status : std::string()));
      }
    }

    const std::string* display_text =
        response.FindStringKey("value_prop_display_text");
    display_text_ = display_text ? *display_text : std::string();
  }

  bool IsResponseComplete() override {
    return !display_text_.empty() && save_result_;
  }

  void RespondToDelegate(AutofillClient::PaymentsRpcResult result) override {
    std::move(callback_).Run(result, std::move(save_result_), display_text_);
  }

 private:
  // Return the pan field name for the encrypted pan based on the |index|.
  std::string GetPanFieldName(const size_t& index) {
    return "s7e_1_pan" + std::to_string(index);
  }

  // Return the formatted pan to append to the end of the request.
  std::string GetAppendPan(const CreditCard& credit_card,
                           const std::string& app_locale,
                           const std::string& pan_field_name) {
    const base::string16 pan =
        credit_card.GetInfo(AutofillType(CREDIT_CARD_NUMBER), app_locale);
    std::string pan_str =
        net::EscapeUrlEncodedData(base::UTF16ToASCII(pan), true).c_str();
    std::string append_pan = "&" + pan_field_name + "=" + pan_str;
    return append_pan;
  }

  const PaymentsClient::MigrationRequestDetails request_details_;
  const std::vector<MigratableCreditCard>& migratable_credit_cards_;
  const bool full_sync_enabled_;
  MigrateCardsCallback callback_;
  std::unique_ptr<std::unordered_map<std::string, std::string>> save_result_;
  std::string display_text_;

  DISALLOW_COPY_AND_ASSIGN(MigrateCardsRequest);
};

}  // namespace

const char PaymentsClient::kRecipientName[] = "recipient_name";
const char PaymentsClient::kPhoneNumber[] = "phone_number";

PaymentsClient::UnmaskDetails::UnmaskDetails() = default;
PaymentsClient::UnmaskDetails::~UnmaskDetails() = default;
PaymentsClient::UnmaskDetails& PaymentsClient::UnmaskDetails::operator=(
    const PaymentsClient::UnmaskDetails& other) {
  unmask_auth_method = other.unmask_auth_method;
  offer_fido_opt_in = other.offer_fido_opt_in;
  if (other.fido_request_options.has_value()) {
    fido_request_options = other.fido_request_options->Clone();
  } else {
    fido_request_options.reset();
  }
  fido_eligible_card_ids = other.fido_eligible_card_ids;
  return *this;
}

PaymentsClient::UnmaskRequestDetails::UnmaskRequestDetails() = default;
PaymentsClient::UnmaskRequestDetails::UnmaskRequestDetails(
    const UnmaskRequestDetails& other) {
  billing_customer_number = other.billing_customer_number;
  reason = other.reason;
  card = other.card;
  risk_data = other.risk_data;
  user_response = other.user_response;
  if (other.fido_assertion_info.has_value()) {
    fido_assertion_info = other.fido_assertion_info->Clone();
  } else {
    fido_assertion_info.reset();
  }
}
PaymentsClient::UnmaskRequestDetails::~UnmaskRequestDetails() = default;

PaymentsClient::UnmaskResponseDetails::UnmaskResponseDetails() = default;
PaymentsClient::UnmaskResponseDetails::UnmaskResponseDetails(
    const UnmaskResponseDetails& other) {
  *this = other;
}
PaymentsClient::UnmaskResponseDetails::~UnmaskResponseDetails() = default;
PaymentsClient::UnmaskResponseDetails& PaymentsClient::UnmaskResponseDetails::
operator=(const PaymentsClient::UnmaskResponseDetails& other) {
  real_pan = other.real_pan;
  if (other.fido_creation_options.has_value()) {
    fido_creation_options = other.fido_creation_options->Clone();
  } else {
    fido_creation_options.reset();
  }
  if (other.fido_request_options.has_value()) {
    fido_request_options = other.fido_request_options->Clone();
  } else {
    fido_request_options.reset();
  }
  card_authorization_token = other.card_authorization_token;
  return *this;
}

PaymentsClient::OptChangeRequestDetails::OptChangeRequestDetails() = default;
PaymentsClient::OptChangeRequestDetails::OptChangeRequestDetails(
    const OptChangeRequestDetails& other) {
  app_locale = other.app_locale;
  reason = other.reason;
  if (other.fido_authenticator_response.has_value()) {
    fido_authenticator_response = other.fido_authenticator_response->Clone();
  } else {
    fido_authenticator_response.reset();
  }
  card_authorization_token = other.card_authorization_token;
}
PaymentsClient::OptChangeRequestDetails::~OptChangeRequestDetails() = default;

PaymentsClient::OptChangeResponseDetails::OptChangeResponseDetails() = default;
PaymentsClient::OptChangeResponseDetails::OptChangeResponseDetails(
    const OptChangeResponseDetails& other) {
  user_is_opted_in = other.user_is_opted_in;

  if (other.fido_creation_options.has_value()) {
    fido_creation_options = other.fido_creation_options->Clone();
  } else {
    fido_creation_options.reset();
  }
  if (other.fido_request_options.has_value()) {
    fido_request_options = other.fido_request_options->Clone();
  } else {
    fido_request_options.reset();
  }
}
PaymentsClient::OptChangeResponseDetails::~OptChangeResponseDetails() = default;

PaymentsClient::UploadRequestDetails::UploadRequestDetails() = default;
PaymentsClient::UploadRequestDetails::UploadRequestDetails(
    const UploadRequestDetails& other) = default;
PaymentsClient::UploadRequestDetails::~UploadRequestDetails() = default;

PaymentsClient::MigrationRequestDetails::MigrationRequestDetails() = default;
PaymentsClient::MigrationRequestDetails::MigrationRequestDetails(
    const MigrationRequestDetails& other) = default;
PaymentsClient::MigrationRequestDetails::~MigrationRequestDetails() = default;

PaymentsClient::PaymentsClient(
    scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
    signin::IdentityManager* identity_manager,
    AccountInfoGetter* account_info_getter,
    bool is_off_the_record)
    : url_loader_factory_(url_loader_factory),
      identity_manager_(identity_manager),
      account_info_getter_(account_info_getter),
      is_off_the_record_(is_off_the_record),
      has_retried_authorization_(false) {}

PaymentsClient::~PaymentsClient() = default;

void PaymentsClient::Prepare() {
  if (access_token_.empty())
    StartTokenFetch(false);
}

void PaymentsClient::GetUnmaskDetails(
    base::OnceCallback<void(AutofillClient::PaymentsRpcResult,
                            PaymentsClient::UnmaskDetails&)> callback,
    const std::string& app_locale) {
  IssueRequest(std::make_unique<GetUnmaskDetailsRequest>(
                   std::move(callback), app_locale,
                   account_info_getter_->IsSyncFeatureEnabled()),
               /*authenticate=*/true);
}

void PaymentsClient::UnmaskCard(
    const PaymentsClient::UnmaskRequestDetails& request_details,
    base::OnceCallback<void(AutofillClient::PaymentsRpcResult,
                            PaymentsClient::UnmaskResponseDetails&)> callback) {
  IssueRequest(
      std::make_unique<UnmaskCardRequest>(
          request_details, account_info_getter_->IsSyncFeatureEnabled(),
          std::move(callback)),
      /*authenticate=*/true);
}

void PaymentsClient::OptChange(
    const OptChangeRequestDetails request_details,
    base::OnceCallback<void(AutofillClient::PaymentsRpcResult,
                            PaymentsClient::OptChangeResponseDetails&)>
        callback) {
  IssueRequest(std::make_unique<OptChangeRequest>(
                   request_details, std::move(callback),
                   account_info_getter_->IsSyncFeatureEnabled()),
               /*authenticate=*/true);
}

void PaymentsClient::GetUploadDetails(
    const std::vector<AutofillProfile>& addresses,
    const int detected_values,
    const std::vector<const char*>& active_experiments,
    const std::string& app_locale,
    base::OnceCallback<void(AutofillClient::PaymentsRpcResult,
                            const base::string16&,
                            std::unique_ptr<base::Value>,
                            std::vector<std::pair<int, int>>)> callback,
    const int billable_service_number,
    UploadCardSource upload_card_source) {
  IssueRequest(
      std::make_unique<GetUploadDetailsRequest>(
          addresses, detected_values, active_experiments,
          account_info_getter_->IsSyncFeatureEnabled(), app_locale,
          std::move(callback), billable_service_number, upload_card_source),
      /*authenticate=*/false);
}

void PaymentsClient::UploadCard(
    const PaymentsClient::UploadRequestDetails& request_details,
    base::OnceCallback<void(AutofillClient::PaymentsRpcResult,
                            const std::string&)> callback) {
  IssueRequest(
      std::make_unique<UploadCardRequest>(
          request_details, account_info_getter_->IsSyncFeatureEnabled(),
          std::move(callback)),
      /*authenticate=*/true);
}

void PaymentsClient::MigrateCards(
    const MigrationRequestDetails& request_details,
    const std::vector<MigratableCreditCard>& migratable_credit_cards,
    MigrateCardsCallback callback) {
  IssueRequest(
      std::make_unique<MigrateCardsRequest>(
          request_details, migratable_credit_cards,
          account_info_getter_->IsSyncFeatureEnabled(), std::move(callback)),
      /*authenticate=*/true);
}

void PaymentsClient::CancelRequest() {
  request_.reset();
  resource_request_.reset();
  simple_url_loader_.reset();
  token_fetcher_.reset();
  access_token_.clear();
  has_retried_authorization_ = false;
}

void PaymentsClient::set_url_loader_factory_for_testing(
    scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) {
  url_loader_factory_ = std::move(url_loader_factory);
}

void PaymentsClient::IssueRequest(std::unique_ptr<PaymentsRequest> request,
                                  bool authenticate) {
  request_ = std::move(request);
  has_retried_authorization_ = false;

  InitializeResourceRequest();

  if (!authenticate) {
    StartRequest();
  } else if (access_token_.empty()) {
    StartTokenFetch(false);
  } else {
    SetOAuth2TokenAndStartRequest();
  }
}

void PaymentsClient::InitializeResourceRequest() {
  resource_request_ = std::make_unique<network::ResourceRequest>();
  resource_request_->url = GetRequestUrl(request_->GetRequestUrlPath());
  resource_request_->load_flags = net::LOAD_DISABLE_CACHE;
  resource_request_->credentials_mode = network::mojom::CredentialsMode::kOmit;
  resource_request_->method = "POST";

  // Add Chrome experiment state to the request headers.
  net::HttpRequestHeaders headers;
  // User is always signed-in to be able to upload card to Google Payments.
  variations::AppendVariationsHeader(
      resource_request_->url,
      is_off_the_record_ ? variations::InIncognito::kYes
                         : variations::InIncognito::kNo,
      variations::SignedIn::kYes, resource_request_.get());
}

void PaymentsClient::OnSimpleLoaderComplete(
    std::unique_ptr<std::string> response_body) {
  int response_code = -1;
  if (simple_url_loader_->ResponseInfo() &&
      simple_url_loader_->ResponseInfo()->headers) {
    response_code =
        simple_url_loader_->ResponseInfo()->headers->response_code();
  }
  std::string data;
  if (response_body)
    data = std::move(*response_body);
  OnSimpleLoaderCompleteInternal(response_code, data);
}

void PaymentsClient::OnSimpleLoaderCompleteInternal(int response_code,
                                                    const std::string& data) {
  VLOG(2) << "Got data: " << data;

  AutofillClient::PaymentsRpcResult result = AutofillClient::SUCCESS;

  if (!request_)
    return;

  switch (response_code) {
    // Valid response.
    case net::HTTP_OK: {
      std::string error_code;
      base::Optional<base::Value> message_value = base::JSONReader::Read(data);
      if (message_value && message_value->is_dict()) {
        const auto* found = message_value->FindPathOfType(
            {"error", "code"}, base::Value::Type::STRING);
        if (found)
          error_code = found->GetString();
        request_->ParseResponse(*message_value);
      }

      if (base::LowerCaseEqualsASCII(error_code, "internal"))
        result = AutofillClient::TRY_AGAIN_FAILURE;
      else if (!error_code.empty() || !request_->IsResponseComplete())
        result = AutofillClient::PERMANENT_FAILURE;

      break;
    }

    case net::HTTP_UNAUTHORIZED: {
      if (has_retried_authorization_) {
        result = AutofillClient::PERMANENT_FAILURE;
        break;
      }
      has_retried_authorization_ = true;

      InitializeResourceRequest();
      StartTokenFetch(true);
      return;
    }

    // TODO(estade): is this actually how network connectivity issues are
    // reported?
    case net::HTTP_REQUEST_TIMEOUT: {
      result = AutofillClient::NETWORK_ERROR;
      break;
    }

    // Handle anything else as a generic (permanent) failure.
    default: {
      result = AutofillClient::PERMANENT_FAILURE;
      break;
    }
  }

  if (result != AutofillClient::SUCCESS) {
    VLOG(1) << "Payments returned error: " << response_code
            << " with data: " << data;
  }

  request_->RespondToDelegate(result);
}

void PaymentsClient::AccessTokenFetchFinished(
    GoogleServiceAuthError error,
    signin::AccessTokenInfo access_token_info) {
  DCHECK(token_fetcher_);
  token_fetcher_.reset();

  if (error.state() != GoogleServiceAuthError::NONE) {
    AccessTokenError(error);
    return;
  }

  access_token_ = access_token_info.token;
  if (resource_request_)
    SetOAuth2TokenAndStartRequest();
}

void PaymentsClient::AccessTokenError(const GoogleServiceAuthError& error) {
  VLOG(1) << "Unhandled OAuth2 error: " << error.ToString();
  if (simple_url_loader_)
    simple_url_loader_.reset();
  if (request_)
    request_->RespondToDelegate(AutofillClient::PERMANENT_FAILURE);
}

void PaymentsClient::StartTokenFetch(bool invalidate_old) {
  // We're still waiting for the last request to come back.
  if (!invalidate_old && token_fetcher_)
    return;

  DCHECK(account_info_getter_);

  signin::ScopeSet payments_scopes;
  payments_scopes.insert(kPaymentsOAuth2Scope);
  CoreAccountId account_id =
      account_info_getter_->GetAccountInfoForPaymentsServer().account_id;
  if (invalidate_old) {
    DCHECK(!access_token_.empty());
    identity_manager_->RemoveAccessTokenFromCache(account_id, payments_scopes,
                                                  access_token_);
  }
  access_token_.clear();
  token_fetcher_ = identity_manager_->CreateAccessTokenFetcherForAccount(
      account_id, kTokenFetchId, payments_scopes,
      base::BindOnce(&PaymentsClient::AccessTokenFetchFinished,
                     base::Unretained(this)),
      signin::AccessTokenFetcher::Mode::kImmediate);
}

void PaymentsClient::SetOAuth2TokenAndStartRequest() {
  DCHECK(resource_request_);
  resource_request_->headers.SetHeader(net::HttpRequestHeaders::kAuthorization,
                                       std::string("Bearer ") + access_token_);
  StartRequest();
}

void PaymentsClient::StartRequest() {
  DCHECK(resource_request_);
  net::NetworkTrafficAnnotationTag traffic_annotation =
      net::DefineNetworkTrafficAnnotation("payments_sync_cards", R"(
        semantics {
          sender: "Payments"
          description:
            "This service communicates with Google Payments servers to upload "
            "(save) or receive the user's credit card info."
          trigger:
            "Requests are triggered by a user action, such as selecting a "
            "masked server card from Chromium's credit card autofill dropdown, "
            "submitting a form which has credit card information, or accepting "
            "the prompt to save a credit card to Payments servers."
          data:
            "In case of save, a protocol buffer containing relevant address "
            "and credit card information which should be saved in Google "
            "Payments servers, along with user credentials. In case of load, a "
            "protocol buffer containing the id of the credit card to unmask, "
            "an encrypted cvc value, an optional updated card expiration date, "
            "and user credentials."
          destination: GOOGLE_OWNED_SERVICE
        }
        policy {
          cookies_allowed: NO
          setting:
            "Users can enable or disable this feature in Chromium settings by "
            "toggling 'Credit cards and addresses using Google Payments', "
            "under 'Advanced sync settings...'. This feature is enabled by "
            "default."
          chrome_policy {
            AutoFillEnabled {
              policy_options {mode: MANDATORY}
              AutoFillEnabled: false
            }
          }
        })");
  simple_url_loader_ = network::SimpleURLLoader::Create(
      std::move(resource_request_), traffic_annotation);
  simple_url_loader_->AttachStringForUpload(request_->GetRequestContent(),
                                            request_->GetRequestContentType());

  simple_url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie(
      url_loader_factory_.get(),
      base::BindOnce(&PaymentsClient::OnSimpleLoaderComplete,
                     base::Unretained(this)));
}

}  // namespace payments
}  // namespace autofill