File: chrome_authenticator_request_delegate.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1270 lines) | stat: -rw-r--r-- 49,244 bytes parent folder | download | duplicates (3)
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
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/webauthn/chrome_authenticator_request_delegate.h"

#include <algorithm>
#include <array>
#include <cstdint>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

#include "base/check.h"
#include "base/check_op.h"
#include "base/compiler_specific.h"
#include "base/containers/contains.h"
#include "base/containers/span.h"
#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/i18n/time_formatting.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
#include "base/memory/weak_ptr.h"
#include "base/strings/string_util.h"
#include "base/values.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/extensions/api/web_authentication_proxy/web_authentication_proxy_service.h"
#include "chrome/browser/net/system_network_context_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_observer.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/sync/sync_service_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "chrome/browser/ui/browser_navigator_params.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/passwords/passwords_client_ui_delegate.h"
#include "chrome/browser/ui/webauthn/user_actions.h"
#include "chrome/browser/webauthn/authenticator_request_dialog_controller.h"
#include "chrome/browser/webauthn/authenticator_request_dialog_model.h"
#include "chrome/browser/webauthn/cablev2_devices.h"
#include "chrome/browser/webauthn/enclave_manager.h"
#include "chrome/browser/webauthn/gpm_enclave_controller.h"
#include "chrome/browser/webauthn/immediate_request_rate_limiter_factory.h"
#include "chrome/browser/webauthn/passkey_model_factory.h"
#include "chrome/browser/webauthn/webauthn_metrics_util.h"
#include "chrome/browser/webauthn/webauthn_pref_names.h"
#include "chrome/common/chrome_version.h"
#include "chrome/common/pref_names.h"
#include "components/device_event_log/device_event_log.h"
#include "components/password_manager/core/common/password_manager_pref_names.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/pref_service.h"
#include "components/signin/public/base/consent_level.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/sync/protocol/webauthn_credential_specifics.pb.h"
#include "components/sync/service/sync_service.h"
#include "components/trusted_vault/frontend_trusted_vault_connection.h"
#include "components/user_prefs/user_prefs.h"
#include "components/webauthn/core/browser/immediate_request_rate_limiter.h"
#include "components/webauthn/core/browser/passkey_model.h"
#include "content/public/browser/authenticator_request_client_delegate.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_authentication_request_proxy.h"
#include "content/public/browser/web_contents.h"
#include "crypto/random.h"
#include "device/fido/authenticator_get_assertion_response.h"
#include "device/fido/cable/cable_discovery_data.h"
#include "device/fido/cable/v2_constants.h"
#include "device/fido/cable/v2_handshake.h"
#include "device/fido/discoverable_credential_metadata.h"
#include "device/fido/features.h"
#include "device/fido/fido_authenticator.h"
#include "device/fido/fido_constants.h"
#include "device/fido/fido_discovery_base.h"
#include "device/fido/fido_discovery_factory.h"
#include "device/fido/fido_request_handler_base.h"
#include "device/fido/fido_transport_protocol.h"
#include "device/fido/fido_types.h"
#include "device/fido/public_key_credential_descriptor.h"
#include "device/fido/public_key_credential_user_entity.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/permissions/permissions_data.h"
#include "extensions/common/url_pattern.h"
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
#include "net/base/url_util.h"
#include "third_party/blink/public/mojom/credentialmanagement/credential_type_flags.mojom.h"
#include "third_party/icu/source/common/unicode/locid.h"
#include "ui/base/page_transition_types.h"
#include "ui/base/window_open_disposition.h"
#include "ui/gfx/native_widget_types.h"

#if BUILDFLAG(IS_MAC)
#include "chrome/browser/webauthn/chrome_authenticator_request_delegate_mac.h"
#include "device/fido/mac/credential_metadata.h"
#include "third_party/icu/source/i18n/unicode/timezone.h"
#include "ui/views/widget/widget.h"
#endif

#if BUILDFLAG(IS_WIN)
#include "chrome/browser/webauthn/local_credential_management_win.h"
#include "device/fido/win/authenticator.h"
#endif

#if BUILDFLAG(IS_CHROMEOS)
#include "chromeos/components/webauthn/webauthn_request_registrar.h"
#include "ui/aura/window.h"
#endif

using PasswordCredentials = PasswordCredentialController::PasswordCredentials;
using UIPresentation = ChromeAuthenticatorRequestDelegate::UIPresentation;
using TransportAvailabilityInfo =
    device::FidoRequestHandlerBase::TransportAvailabilityInfo;

namespace {

ChromeAuthenticatorRequestDelegate::TestObserver* g_observer = nullptr;

static constexpr char kGoogleRpId[] = "google.com";

// Returns true iff the credential is reported as being present on the platform
// authenticator (i.e. it is not a phone or icloud credential).
bool IsCredentialFromPlatformAuthenticator(
    device::DiscoverableCredentialMetadata cred) {
  return cred.source != device::AuthenticatorType::kICloudKeychain &&
         cred.source != device::AuthenticatorType::kPhone;
}

// Returns true iff |user_id| starts with the prefix reserved for passkeys used
// to authenticate to Google services.
bool UserIdHasGooglePasskeyAuthPrefix(const std::vector<uint8_t>& user_id) {
  constexpr std::string_view kPrefix = "GOOGLE_ACCOUNT:";
  if (user_id.size() < kPrefix.size()) {
    return false;
  }
  return UNSAFE_TODO(memcmp(user_id.data(), kPrefix.data(), kPrefix.size())) ==
         0;
}

// Filters |passkeys| to only contain credentials that are used to authenticate
// to Google services.
void FilterGoogleAuthPasskeys(
    std::vector<device::DiscoverableCredentialMetadata>* passkeys) {
  std::erase_if(*passkeys, [](const auto& passkey) {
    return IsCredentialFromPlatformAuthenticator(passkey) &&
           !UserIdHasGooglePasskeyAuthPrefix(passkey.user.id);
  });
}

#if BUILDFLAG(IS_MAC)
const char kWebAuthnTouchIdLastUsed[] = "webauthn.touchid.last_used";

// kMacOsRecentlyUsedMaxDays specifies how recently the macOS profile
// authenticator must have been used (for the current profile) to be considered
// "actively" used. Chrome may default to the profile authenticator in more
// cases if it is being actively used.
const int kMacOsRecentlyUsedMaxDays = 31;
#endif

// CableLinkingEventHandler handles linking information sent by caBLEv2
// authenticators. This linking information can come after the WebAuthn
// operation has resolved and thus after the
// `ChromeAuthenticatorRequestDelegate` has been destroyed. Thus this object is
// owned by the callback itself, and can save linking information until the
// point where the `Profile` itself is destroyed.
class CableLinkingEventHandler : public ProfileObserver {
 public:
  explicit CableLinkingEventHandler(Profile* profile) : profile_(profile) {
    profile_->AddObserver(this);
  }

  ~CableLinkingEventHandler() override {
    if (profile_) {
      profile_->RemoveObserver(this);
      profile_ = nullptr;
    }
  }

  // ProfileObserver:
  void OnProfileWillBeDestroyed(Profile* profile) override {
    DCHECK_EQ(profile, profile_);
    profile_->RemoveObserver(this);
    profile_ = nullptr;
  }

 private:
  raw_ptr<Profile> profile_;
};

bool SkipGpmPasskeyCreationForOwnAccount(
    device::FidoRequestType request_type,
    const std::string& rp_id,
    std::string_view user_name,
    const CoreAccountInfo& primary_account_info) {
  // Don't let GPM create a passkey for its own account within itself.
  //
  // The request username is either the full email address (GAIA users) or just
  // the local part (google.com users).
  //
  // Note that if the string does not contain an '@', `substr(0, npos)` will
  // return the whole string.
  const std::string account_email_local_part =
      primary_account_info.email.substr(0,
                                        primary_account_info.email.find('@'));
  return request_type == device::FidoRequestType::kMakeCredential &&
         rp_id == kGoogleRpId &&
         (user_name == primary_account_info.email ||
          user_name == account_email_local_part);
}

bool PasswordsUsable(int credential_types, UIPresentation ui_presentation) {
  if (!(credential_types &
        static_cast<int>(blink::mojom::CredentialTypeFlags::kPassword))) {
    return false;
  }

  if (base::FeatureList::IsEnabled(device::kWebAuthnAmbientSignin) &&
      ui_presentation == UIPresentation::kAutofill) {
    // TODO(https://crbug.com/358119268): This will probably get its own
    // mediation type, but for prototyping we assume any conditional request
    // with passwords uses ambient.
    return true;
  }

  return ui_presentation == UIPresentation::kModalImmediate;
}

}  // namespace

// static
void ChromeAuthenticatorRequestDelegate::RegisterProfilePrefs(
    user_prefs::PrefRegistrySyncable* registry) {
  registry->RegisterListPref(prefs::kSecurityKeyPermitAttestation);
  registry->RegisterIntegerPref(
      webauthn::pref_names::kEnclaveDeclinedGPMCredentialCreationCount, 0);
  registry->RegisterIntegerPref(
      webauthn::pref_names::kEnclaveDeclinedGPMBootstrappingCount, 0);
#if BUILDFLAG(IS_WIN)
  LocalCredentialManagementWin::RegisterProfilePrefs(registry);
#endif
#if BUILDFLAG(IS_MAC)
  registry->RegisterStringPref(
      webauthn::pref_names::kWebAuthnTouchIdMetadataSecretPrefName,
      std::string());
  registry->RegisterStringPref(kWebAuthnTouchIdLastUsed, std::string());
  // This boolean preference is used as a tristate. If unset, whether or not to
  // default to iCloud is determined based on several factors.
  // (See `ShouldCreateInICloudKeychain`.) If set, then this preference is
  // controlling.
  //
  // The default value of this preference only determines whether the toggle
  // in settings will show as set or not when the preference hasn't been
  // explicitly set. Since the behaviour is actually more complex than can be
  // expressed in a boolean, this is always an approximation.
  registry->RegisterBooleanPref(
      prefs::kCreatePasskeysInICloudKeychain,
      ShouldCreateInICloudKeychain(
          RequestSource::kWebAuthentication,
          // Whether or not the user is actively using the profile authenticator
          // is stored in preferences, which aren't available at this time while
          // we're still registering them. Thus we assume that they are not.
          /*is_active_profile_authenticator_user=*/false,
          IsICloudDriveEnabled(),
          /*request_is_for_google_com=*/false, /*preference=*/std::nullopt));
#endif
  // TODO(crbug.com/372493822): remove and clean up prefs.
  cablev2::RegisterProfilePrefs(registry);
}

ChromeAuthenticatorRequestDelegate::ChromeAuthenticatorRequestDelegate(
    content::RenderFrameHost* render_frame_host)
    : render_frame_host_id_(render_frame_host->GetGlobalId()),
      dialog_model_(base::MakeRefCounted<AuthenticatorRequestDialogModel>(
          GetRenderFrameHost())),
      dialog_controller_(std::make_unique<AuthenticatorRequestDialogController>(
          dialog_model_.get(),
          GetRenderFrameHost())) {
  dialog_model_->observers.AddObserver(this);
  if (g_observer) {
    g_observer->Created(this);
  }
}

ChromeAuthenticatorRequestDelegate::~ChromeAuthenticatorRequestDelegate() {
  // Currently, completion of the request is indicated by //content destroying
  // this delegate.
  dialog_model_->OnRequestComplete();
  dialog_model_->observers.RemoveObserver(this);

  if (g_observer) {
    g_observer->OnDestroy(this);
  }
}

// static
void ChromeAuthenticatorRequestDelegate::SetGlobalObserverForTesting(
    TestObserver* observer) {
  CHECK(!observer || !g_observer);
  g_observer = observer;
}

base::WeakPtr<ChromeAuthenticatorRequestDelegate>
ChromeAuthenticatorRequestDelegate::AsWeakPtr() {
  return weak_ptr_factory_.GetWeakPtr();
}

GPMEnclaveController*
ChromeAuthenticatorRequestDelegate::enclave_controller_for_testing() const {
  return enclave_controller_.get();
}

void ChromeAuthenticatorRequestDelegate::SetRelyingPartyId(
    const std::string& rp_id) {
  dialog_model_->relying_party_id = rp_id;
}

void ChromeAuthenticatorRequestDelegate::SetUIPresentation(
    UIPresentation ui_presentation) {
  dialog_controller_->SetUIPresentation(ui_presentation);
}

bool ChromeAuthenticatorRequestDelegate::DoesBlockRequestOnFailure(
    InterestingFailureReason reason) {
  if (!webauthn_ui_enabled()) {
    return false;
  }

  // If the UI was already in the state where we asked the user to complete the
  // transaction on the other device then any errors are immediately resolved.
  // Very likely the user canceled on the phone and doesn't want to see another
  // error UI on the desktop.
  if (cable_device_ready_) {
    return false;
  }

  switch (reason) {
    case InterestingFailureReason::kTimeout:
      dialog_controller_->OnRequestTimeout();
      break;
    case InterestingFailureReason::kKeyNotRegistered:
      dialog_controller_->OnActivatedKeyNotRegistered();
      break;
    case InterestingFailureReason::kKeyAlreadyRegistered:
      dialog_controller_->OnActivatedKeyAlreadyRegistered();
      break;
    case InterestingFailureReason::kSoftPINBlock:
      dialog_controller_->OnSoftPINBlock();
      break;
    case InterestingFailureReason::kHardPINBlock:
      dialog_controller_->OnHardPINBlock();
      break;
    case InterestingFailureReason::kAuthenticatorRemovedDuringPINEntry:
      dialog_controller_->OnAuthenticatorRemovedDuringPINEntry();
      break;
    case InterestingFailureReason::kAuthenticatorMissingResidentKeys:
      dialog_controller_->OnAuthenticatorMissingResidentKeys();
      break;
    case InterestingFailureReason::kAuthenticatorMissingUserVerification:
      dialog_controller_->OnAuthenticatorMissingUserVerification();
      break;
    case InterestingFailureReason::kAuthenticatorMissingLargeBlob:
      dialog_controller_->OnAuthenticatorMissingLargeBlob();
      break;
    case InterestingFailureReason::kNoCommonAlgorithms:
      dialog_controller_->OnNoCommonAlgorithms();
      break;
    case InterestingFailureReason::kStorageFull:
      dialog_controller_->OnAuthenticatorStorageFull();
      break;
    case InterestingFailureReason::kUserConsentDenied:
      dialog_controller_->OnUserConsentDenied();
      break;
    case InterestingFailureReason::kWinUserCancelled:
      return dialog_controller_->OnWinUserCancelled();
    case InterestingFailureReason::kHybridTransportError:
      return dialog_controller_->OnHybridTransportError();
    case InterestingFailureReason::kNoPasskeys:
      return dialog_controller_->OnNoPasskeys();
    case InterestingFailureReason::kEnclaveError:
      return dialog_controller_->OnEnclaveError();
    case InterestingFailureReason::kEnclaveCancel:
      dialog_model_->CancelAuthenticatorRequest();
      break;
    case InterestingFailureReason::kChallengeUrlFailure:
      dialog_controller_->OnChallengeUrlFailure();
  }
  return true;
}

void ChromeAuthenticatorRequestDelegate::OnTransactionSuccessful(
    RequestSource request_source,
    device::FidoRequestType request_type,
    device::AuthenticatorType authenticator_type) {
  if (request_source != RequestSource::kWebAuthentication) {
    return;
  }
#if BUILDFLAG(IS_MAC)
  if (authenticator_type == device::AuthenticatorType::kTouchID) {
    profile()->GetPrefs()->SetString(
        kWebAuthnTouchIdLastUsed,
        base::UnlocalizedTimeFormatWithPattern(base::Time::Now(), "yyyy-MM-dd",
                                               icu::TimeZone::getGMT()));
    webauthn::user_actions::RecordChromeProfileSuccess();
  }
  if (authenticator_type == device::AuthenticatorType::kICloudKeychain) {
    webauthn::user_actions::RecordICloudSuccess();
  }

  dialog_controller_->RecordMacOsSuccessHistogram(request_type,
                                                  authenticator_type);
#elif BUILDFLAG(IS_WIN)
  if (authenticator_type == device::AuthenticatorType::kWinNative) {
    webauthn::user_actions::RecordWindowsHelloSuccess();
  }
#endif  // BUILDFLAG(IS_MAC)
  if (authenticator_type == device::AuthenticatorType::kEnclave) {
    if (dialog_model_->in_onboarding_flow) {
      RecordOnboardingEvent(webauthn::metrics::OnboardingEvents::kSucceeded);
    }
    switch (request_type) {
      case device::FidoRequestType::kGetAssertion:
        RecordGPMGetAssertionEvent(
            webauthn::metrics::GPMGetAssertionEvents::kSuccess);
        break;
      case device::FidoRequestType::kMakeCredential:
        RecordGPMMakeCredentialEvent(
            webauthn::metrics::GPMMakeCredentialEvents::kSuccess);
        break;
    }
    webauthn::user_actions::RecordGpmSuccess();
  }
}

void ChromeAuthenticatorRequestDelegate::RegisterActionCallbacks(
    base::OnceClosure cancel_callback,
    base::OnceClosure immediate_not_found_callback,
    base::RepeatingClosure start_over_callback,
    AccountPreselectedCallback account_preselected_callback,
    PasswordSelectedCallback password_selected_callback,
    device::FidoRequestHandlerBase::RequestCallback request_callback,
    base::OnceClosure cancel_ui_timeout_callback,
    base::RepeatingClosure bluetooth_adapter_power_on_callback,
    base::RepeatingCallback<
        void(device::FidoRequestHandlerBase::BlePermissionCallback)>
        request_ble_permission_callback) {
  cancel_callback_ = std::move(cancel_callback);
  immediate_not_found_callback_ = std::move(immediate_not_found_callback);
  start_over_callback_ = std::move(start_over_callback);
  account_preselected_callback_ = std::move(account_preselected_callback);
  password_selected_callback_ = std::move(password_selected_callback);
  request_callback_ = request_callback;
  cancel_ui_timeout_callback_ = std::move(cancel_ui_timeout_callback);

  dialog_controller_->SetRequestCallback(request_callback);
  dialog_controller_->SetAccountPreselectedCallback(
      account_preselected_callback_);
  dialog_controller_->SetBluetoothAdapterPowerOnCallback(
      bluetooth_adapter_power_on_callback);
  dialog_controller_->SetRequestBlePermissionCallback(
      request_ble_permission_callback);
  if (password_controller_) {
    password_controller_->SetPasswordSelectedCallback(
        password_selected_callback_);
  }
}

void ChromeAuthenticatorRequestDelegate::ConfigureDiscoveries(
    const url::Origin& origin,
    const std::string& rp_id,
    RequestSource request_source,
    device::FidoRequestType request_type,
    std::optional<device::ResidentKeyRequirement> resident_key_requirement,
    device::UserVerificationRequirement user_verification_requirement,
    std::optional<std::string_view> user_name,
    base::span<const device::CableDiscoveryData> pairings_from_extension,
    bool browser_provided_passkeys_available,
    device::FidoDiscoveryFactory* discovery_factory) {
  DCHECK(request_type == device::FidoRequestType::kGetAssertion ||
         resident_key_requirement.has_value());

  // Without the UI enabled, discoveries like caBLE, Android AOA, iCloud
  // keychain, and the enclave, don't make sense.
  if (!webauthn_ui_enabled()) {
    return;
  }

  // Configure the enclave authenticator.
  if (browser_provided_passkeys_available && !IsVirtualEnvironmentEnabled() &&
      request_source == RequestSource::kWebAuthentication) {
    // Creating credentials in GPM can be disabled by policy, but get() is
    // always allowed.
    const bool enclave_create_enabled =
        profile()->GetPrefs()->GetBoolean(
            password_manager::prefs::kCredentialsEnableService) &&
        profile()->GetPrefs()->GetBoolean(
            password_manager::prefs::kCredentialsEnablePasskeys);
    if (dialog_controller_->ui_presentation() ==
            UIPresentation::kPasskeyUpgrade &&
        enclave_create_enabled) {
      // PasskeyUpgradeRequestController will handle enclave transactions in
      // place of the "regular" GPMEnclaveController.
      CHECK(!enclave_controller_);
      dialog_controller_->InitializeEnclaveRequestCallback(discovery_factory);
      discovery_factory->set_network_context_factory(base::BindRepeating([]() {
        return SystemNetworkContextManager::GetInstance()->GetContext();
      }));
    } else if (request_type == device::FidoRequestType::kGetAssertion ||
               enclave_create_enabled) {
      // Set up the "regular" enclave controller.
      auto* const identity_manager = IdentityManagerFactory::GetForProfile(
          profile()->GetOriginalProfile());
      const auto consent = signin::ConsentLevel::kSignin;
      if (identity_manager->HasPrimaryAccount(consent)) {
        CoreAccountInfo account_info =
            identity_manager->GetPrimaryAccountInfo(consent);
        if (SkipGpmPasskeyCreationForOwnAccount(
                request_type, rp_id, user_name.value_or(""), account_info)) {
          FIDO_LOG(EVENT)
              << "Creation in GPM not offered (same primary account)";
        } else {
          enclave_controller_ = std::make_unique<GPMEnclaveController>(
              GetRenderFrameHost(), dialog_model_.get(), rp_id, request_type,
              user_verification_requirement);
        }
      }
    } else {
      FIDO_LOG(EVENT)
          << "Enclave unavailable for creating passkeys due to policy.";
    }
  }

  const bool cable_extension_permitted = ShouldPermitCableExtension(origin);
  const bool cable_extension_provided =
      cable_extension_permitted && !pairings_from_extension.empty();

  if (g_observer) {
    for (const auto& pairing : pairings_from_extension) {
      if (pairing.version == device::CableDiscoveryData::Version::V2) {
        g_observer->CableV2ExtensionSeen(pairing.v2->server_link_data);
      }
    }

    g_observer->ConfiguringCable(request_type);
  }

#if BUILDFLAG(IS_LINUX)
  // No caBLEv1 on Linux. It tends to crash bluez.
  if (base::Contains(pairings_from_extension,
                     device::CableDiscoveryData::Version::V1,
                     &device::CableDiscoveryData::version)) {
    pairings_from_extension = base::span<const device::CableDiscoveryData>();
  }
#endif

  std::vector<device::CableDiscoveryData> pairings;
  if (cable_extension_permitted) {
    pairings.insert(pairings.end(), pairings_from_extension.begin(),
                    pairings_from_extension.end());
  }
  const bool cable_extension_accepted = !pairings.empty();
  const bool cablev2_extension_provided =
      base::Contains(pairings, device::CableDiscoveryData::Version::V2,
                     &device::CableDiscoveryData::version);

  const bool non_extension_cablev2_enabled =
      (!cable_extension_permitted ||
       (!cable_extension_provided &&
        request_type == device::FidoRequestType::kGetAssertion) ||
       (request_type == device::FidoRequestType::kMakeCredential &&
        resident_key_requirement.has_value() &&
        resident_key_requirement.value() !=
            device::ResidentKeyRequirement::kDiscouraged) ||
       base::FeatureList::IsEnabled(device::kWebAuthCableExtensionAnywhere));

  std::optional<std::array<uint8_t, device::cablev2::kQRKeySize>>
      qr_generator_key;
  std::optional<std::string> qr_string;
  if (non_extension_cablev2_enabled || cablev2_extension_provided) {
    // A QR key is generated for all caBLEv2 cases but whether the QR code is
    // displayed is up to the UI.
    qr_generator_key.emplace();
    crypto::RandBytes(*qr_generator_key);
    qr_string = device::cablev2::qr::Encode(*qr_generator_key, request_type);

    auto linking_handler =
        std::make_unique<CableLinkingEventHandler>(profile());
    discovery_factory->set_cable_event_callback(
        base::BindRepeating(&ChromeAuthenticatorRequestDelegate::OnCableEvent,
                            weak_ptr_factory_.GetWeakPtr()));
  }

  if (SystemNetworkContextManager::GetInstance()) {
    // caBLE and the enclave depend on the network context factory.
    // TODO(nsatragno): this should probably use a storage partition network
    // context instead. See the SystemNetworkContextManager class comments.
    discovery_factory->set_network_context_factory(base::BindRepeating([]() {
      return SystemNetworkContextManager::GetInstance()->GetContext();
    }));
  }

  if (cable_extension_accepted || non_extension_cablev2_enabled) {
    std::optional<bool> extension_is_v2;
    if (cable_extension_provided) {
      extension_is_v2 = cablev2_extension_provided;
    }
    dialog_controller_->set_cable_transport_info(extension_is_v2, qr_string);
    discovery_factory->set_cable_data(request_type, std::move(pairings),
                                      qr_generator_key);
  }

#if BUILDFLAG(IS_MAC)
  ConfigureNSWindow(discovery_factory);
#endif

  if (enclave_controller_) {
    enclave_controller_->ConfigureDiscoveries(discovery_factory);
  }

  dialog_controller_->set_is_non_webauthn_request(
      request_source != RequestSource::kWebAuthentication);

#if BUILDFLAG(IS_MAC)
  ConfigureICloudKeychain(request_source, rp_id);
#endif

  if (PasswordsUsable(credential_types_,
                      dialog_controller_->ui_presentation())) {
    // Only valid for the main frame.
    if (!password_controller_ && GetRenderFrameHost()->IsInPrimaryMainFrame()) {
      password_controller_ = std::make_unique<PasswordCredentialController>(
          render_frame_host_id_, dialog_model_.get());
    }
    if (!password_controller_) {
      return;
    }
    password_controller_->FetchPasswords(
        origin.GetURL(),
        base::BindOnce(
            &ChromeAuthenticatorRequestDelegate::OnPasswordCredentialsReceived,
            AsWeakPtr()));
  }
}

void ChromeAuthenticatorRequestDelegate::SetHints(
    const AuthenticatorRequestClientDelegate::Hints& hints) {
  if (g_observer) {
    g_observer->HintsSet(hints);
  }
  dialog_controller_->SetHints(hints);
}

void ChromeAuthenticatorRequestDelegate::SelectAccount(
    std::vector<device::AuthenticatorGetAssertionResponse> responses,
    base::OnceCallback<void(device::AuthenticatorGetAssertionResponse)>
        callback) {
  if (!webauthn_ui_enabled()) {
    // Requests with UI disabled should never reach account selection.
    DCHECK(IsVirtualEnvironmentEnabled());

    // The browser is being automated. Select the first credential to support
    // automation of discoverable credentials.
    // TODO(crbug.com/40639383): Provide a way to determine which account gets
    // picked.
    std::move(callback).Run(std::move(responses.at(0)));
    return;
  }

  if (g_observer) {
    g_observer->AccountSelectorShown(responses);
    std::move(callback).Run(std::move(responses.at(0)));
    return;
  }

  dialog_controller_->SelectAccount(std::move(responses), std::move(callback));
}

bool ChromeAuthenticatorRequestDelegate::webauthn_ui_enabled() const {
  return dialog_controller_->ui_presentation() != UIPresentation::kDisabled;
}

void ChromeAuthenticatorRequestDelegate::SetCredentialTypes(
    int credential_type_flags) {
  credential_types_ = credential_type_flags;
}

void ChromeAuthenticatorRequestDelegate::SetCredentialIdFilter(
    std::vector<device::PublicKeyCredentialDescriptor> credential_list) {
  credential_filter_ = std::move(credential_list);
}

void ChromeAuthenticatorRequestDelegate::SetUserEntityForMakeCredentialRequest(
    const device::PublicKeyCredentialUserEntity& user_entity) {
  dialog_model_->user_entity = user_entity;
}

void ChromeAuthenticatorRequestDelegate::ProvideChallengeUrl(
    const GURL& url,
    base::OnceCallback<void(std::optional<base::span<const uint8_t>>)>
        callback) {
  dialog_controller_->ProvideChallengeUrl(url, std::move(callback));
}

void ChromeAuthenticatorRequestDelegate::OnTransportAvailabilityEnumerated(
    TransportAvailabilityInfo data) {
  if (g_observer) {
    g_observer->OnPreTransportAvailabilityEnumerated(this);
  }

  if (!webauthn_ui_enabled()) {
    return;
  }

  pending_transport_availability_info_ = std::make_unique<
      device::FidoRequestHandlerBase::TransportAvailabilityInfo>(
      std::move(data));
  TryToShowUI();
}

bool ChromeAuthenticatorRequestDelegate::EmbedderControlsAuthenticatorDispatch(
    const device::FidoAuthenticator& authenticator) {
  // Decide whether the //device/fido code should dispatch the current
  // request to an authenticator immediately after it has been
  // discovered, or whether the embedder/UI takes charge of that by
  // invoking its RequestCallback.
  if (!webauthn_ui_enabled()) {
    // There is no UI to handle request dispatch.
    return false;
  }
  if (authenticator.GetType() == device::AuthenticatorType::kEnclave) {
    return false;
  }

  if (dialog_controller_->ui_presentation() == UIPresentation::kAutofill &&
      (dialog_model_->step() ==
           AuthenticatorRequestDialogModel::Step::kPasskeyAutofill ||
       dialog_model_->step() ==
           AuthenticatorRequestDialogModel::Step::kNotStarted)) {
    // There is an active conditional request that is not showing any UI. The UI
    // will dispatch to any plugged in authenticators after the user selects an
    // option.
    return true;
  }
  auto transport = authenticator.AuthenticatorTransport();
  return !transport ||  // Windows
         *transport == device::FidoTransportProtocol::kInternal;
}

void ChromeAuthenticatorRequestDelegate::FidoAuthenticatorAdded(
    const device::FidoAuthenticator& authenticator) {
  if (!webauthn_ui_enabled()) {
    return;
  }

  dialog_controller_->AddAuthenticator(authenticator);
}

void ChromeAuthenticatorRequestDelegate::FidoAuthenticatorRemoved(
    std::string_view authenticator_id) {
  if (!webauthn_ui_enabled()) {
    return;
  }

  dialog_controller_->RemoveAuthenticator(authenticator_id);
}

void ChromeAuthenticatorRequestDelegate::BluetoothAdapterStatusChanged(
    device::FidoRequestHandlerBase::BleStatus ble_status) {
  dialog_controller_->BluetoothAdapterStatusChanged(ble_status);
}

bool ChromeAuthenticatorRequestDelegate::SupportsPIN() const {
  return true;
}

void ChromeAuthenticatorRequestDelegate::CollectPIN(
    CollectPINOptions options,
    base::OnceCallback<void(std::u16string)> provide_pin_cb) {
  dialog_controller_->CollectPIN(options.reason, options.error,
                                 options.min_pin_length, options.attempts,
                                 std::move(provide_pin_cb));
}

void ChromeAuthenticatorRequestDelegate::StartBioEnrollment(
    base::OnceClosure next_callback) {
  dialog_controller_->StartInlineBioEnrollment(std::move(next_callback));
}

void ChromeAuthenticatorRequestDelegate::OnSampleCollected(
    int bio_samples_remaining) {
  dialog_controller_->OnSampleCollected(bio_samples_remaining);
}

void ChromeAuthenticatorRequestDelegate::FinishCollectToken() {
  dialog_controller_->FinishCollectToken();
}

void ChromeAuthenticatorRequestDelegate::OnRetryUserVerification(int attempts) {
  dialog_controller_->OnRetryUserVerification(attempts);
}

void ChromeAuthenticatorRequestDelegate::OnStartOver() {
  DCHECK(start_over_callback_);
  dialog_model_->generation++;
  if (g_observer) {
    g_observer->PreStartOver();
  }
  start_over_callback_.Run();
}

void ChromeAuthenticatorRequestDelegate::OnModelDestroyed(
    AuthenticatorRequestDialogModel* model) {
  DCHECK_EQ(model, dialog_model_.get());
}

void ChromeAuthenticatorRequestDelegate::OnCancelRequest() {
  // |cancel_callback_| must be invoked at most once as invocation of
  // |cancel_callback_| will destroy |this|.
  DCHECK(cancel_callback_);
  std::move(cancel_callback_).Run();
}

void ChromeAuthenticatorRequestDelegate::SetPasswordControllerForTesting(
    std::unique_ptr<PasswordCredentialController> controller) {
  password_controller_ = std::move(controller);
}

content::RenderFrameHost*
ChromeAuthenticatorRequestDelegate::GetRenderFrameHost() const {
  content::RenderFrameHost* ret =
      content::RenderFrameHost::FromID(render_frame_host_id_);
  DCHECK(ret);
  return ret;
}

content::BrowserContext* ChromeAuthenticatorRequestDelegate::GetBrowserContext()
    const {
  return GetRenderFrameHost()->GetBrowserContext();
}

Profile* ChromeAuthenticatorRequestDelegate::profile() const {
  return Profile::FromBrowserContext(GetRenderFrameHost()->GetBrowserContext());
}

bool ChromeAuthenticatorRequestDelegate::MaybeHandleImmediateMediation(
    const TransportAvailabilityInfo& data,
    const PasswordCredentials& passwords) {
  if (data.request_type != device::FidoRequestType::kGetAssertion ||
      dialog_controller_->ui_presentation() !=
          UIPresentation::kModalImmediate) {
    return false;
  }

  // Always return not allowed immediate in incognito.
  if (profile()->IsOffTheRecord()) {
    base::UmaHistogramEnumeration(
        "WebAuthentication.GetAssertion.Immediate.RejectionReason",
        content::ImmediateMediationRejectionReason::kIncognito);
    return true;
  }

  if (auto* rate_limiter =
          ImmediateRequestRateLimiterFactory::GetForProfile(profile())) {
    const url::Origin origin = GetRenderFrameHost()->GetLastCommittedOrigin();
    if (!rate_limiter->IsRequestAllowed(origin)) {
      FIDO_LOG(ERROR)
          << "Immediate request rate limit exceeded for the origin.";
      base::UmaHistogramEnumeration(
          "WebAuthentication.GetAssertion.Immediate.RejectionReason",
          content::ImmediateMediationRejectionReason::kRateLimited);
      return true;
    }
  }

  if (data.recognized_credentials.size() + passwords.size() == 0) {
    base::UmaHistogramEnumeration(
        "WebAuthentication.GetAssertion.Immediate.RejectionReason",
        content::ImmediateMediationRejectionReason::kNoCredentials);
    return true;
  }

  return false;
}

void ChromeAuthenticatorRequestDelegate::TryToShowUI() {
  if (!pending_transport_availability_info_) {
    return;
  }
  if (enclave_controller_ && !enclave_controller_->ready_for_ui()) {
    // Delay showing UI until GPM state is loaded. It's only after this
    // point that we know whether GPM will be active for this request or not.
    return;
  }
  if (PasswordsUsable(credential_types_,
                      dialog_controller_->ui_presentation()) &&
      !pending_password_credentials_) {
    return;
  }
  auto tai = std::move(pending_transport_availability_info_);
  auto passwords = pending_password_credentials_
                       ? std::move(pending_password_credentials_)
                       : std::make_unique<PasswordCredentials>();
  MaybeShowUI(std::move(*tai), std::move(*passwords));
}

void ChromeAuthenticatorRequestDelegate::MaybeShowUI(
    TransportAvailabilityInfo tai,
    PasswordCredentials passwords) {
  if (can_use_synced_phone_passkeys_ ||
      (enclave_controller_ && enclave_controller_->is_active())) {
    GetPhoneContactableGpmPasskeysForRpId(
        std::move(tai),
        base::BindOnce(&ChromeAuthenticatorRequestDelegate::FinishMaybeShowUI,
                       weak_ptr_factory_.GetWeakPtr(), std::move(passwords)));
    return;
  }

  FinishMaybeShowUI(std::move(passwords), std::move(tai));
}

void ChromeAuthenticatorRequestDelegate::FinishMaybeShowUI(
    PasswordCredentials passwords,
    TransportAvailabilityInfo tai) {
  FilterRecognizedCredentials(&tai);

  if (MaybeHandleImmediateMediation(tai, passwords)) {
    std::move(immediate_not_found_callback_).Run();
    return;
  }

  if (!cancel_ui_timeout_callback_.is_null()) {
    std::move(cancel_ui_timeout_callback_).Run();
  }

  if (g_observer) {
    g_observer->OnTransportAvailabilityEnumerated(this, &tai);
  }

  if (dialog_model_->step() !=
      AuthenticatorRequestDialogModel::Step::kNotStarted) {
    return;
  }

  dialog_controller_->SetCredentialTypes(credential_types_);
  UpdateModelForTransportAvailability(tai);

  // Precalculate the UV method for immediate mode requests.
  dialog_model_->gpm_uv_method.reset();
  if (enclave_controller_) {
    dialog_model_->gpm_uv_method =
        enclave_controller_->GetEnclaveUserVerificationMethod();
  }

  dialog_controller_->StartFlow(std::move(tai), std::move(passwords));

  if (g_observer) {
    g_observer->UIShown(this);
  }
}

void ChromeAuthenticatorRequestDelegate::OnReadyForUI() {
  TryToShowUI();
}

bool ChromeAuthenticatorRequestDelegate::ShouldPermitCableExtension(
    const url::Origin& origin) {
  if (base::FeatureList::IsEnabled(device::kWebAuthCableExtensionAnywhere)) {
    return true;
  }

  // Because the future of the caBLE extension might be that we transition
  // everything to QR-code or sync-based pairing, we don't want use of the
  // extension to spread without consideration. Therefore it's limited to
  // origins that are already depending on it and test sites.
  if (origin.DomainIs("google.com")) {
    return true;
  }

  const GURL test_site("https://webauthndemo.appspot.com");
  DCHECK(test_site.is_valid());
  return origin.IsSameOriginWith(test_site);
}

void ChromeAuthenticatorRequestDelegate::OnCableEvent(
    device::cablev2::Event event) {
  if (event == device::cablev2::Event::kReady) {
    cable_device_ready_ = true;
  }

  dialog_controller_->OnCableEvent(event);
}

void ChromeAuthenticatorRequestDelegate::GetPhoneContactableGpmPasskeysForRpId(
    TransportAvailabilityInfo tai,
    base::OnceCallback<void(TransportAvailabilityInfo)> callback) {
  // For immediate `get()` requests, the enclave might need to do an async check
  // to see if the GPM PIN is still valid before it can be offered for user
  // verification. In this case, the enclave account state will be `kLoading` or
  // `kChecking`. This function waits for that check to complete before adding
  // GPM passkeys to the request. For other request types, this runs
  // synchronously. Note that if the account state check takes longer than the
  // immediate mode timeout, enclave passkeys won't be offered.
  if (dialog_controller_->ui_presentation() ==
          UIPresentation::kModalImmediate &&
      enclave_controller_) {
    switch (enclave_controller_->account_ready_state()) {
      case GPMEnclaveController::AccountReadyState::kLoading:
        enclave_controller_->RunWhenAccountReady(
            base::BindOnce(&ChromeAuthenticatorRequestDelegate::
                               DoGetPhoneContactableGpmPasskeysForRpId,
                           weak_ptr_factory_.GetWeakPtr(), std::move(tai),
                           std::move(callback)));
        return;
      case GPMEnclaveController::AccountReadyState::kReady:
      case GPMEnclaveController::AccountReadyState::kNotReady:
        // Fall through to run synchronously.
        break;
    }
  }

  DoGetPhoneContactableGpmPasskeysForRpId(std::move(tai), std::move(callback));
}

void ChromeAuthenticatorRequestDelegate::
    DoGetPhoneContactableGpmPasskeysForRpId(
        TransportAvailabilityInfo tai,
        base::OnceCallback<void(TransportAvailabilityInfo)> callback) {
  if (!enclave_controller_ || !enclave_controller_->is_active() ||
      enclave_controller_->creds().empty()) {
    std::move(callback).Run(std::move(tai));
    return;
  }
  if (dialog_controller_->ui_presentation() ==
      UIPresentation::kModalImmediate) {
    bool enclave_ready = enclave_controller_->account_ready_state() ==
                         GPMEnclaveController::AccountReadyState::kReady;
    base::UmaHistogramBoolean(
        "WebAuthentication.GetAssertion.Immediate.EnclaveReady", enclave_ready);
    if (!enclave_ready) {
      std::move(callback).Run(std::move(tai));
      return;
    }
  }
  for (const sync_pb::WebauthnCredentialSpecifics& passkey :
       enclave_controller_->creds()) {
    const base::Time last_used_time = base::Time::FromDeltaSinceWindowsEpoch(
        base::Microseconds(passkey.last_used_time_windows_epoch_micros()));
    const base::Time creation_time =
        base::Time::FromMillisecondsSinceUnixEpoch(passkey.creation_time());
    tai.recognized_credentials.emplace_back(
        device::AuthenticatorType::kEnclave, passkey.rp_id(),
        std::vector<uint8_t>(passkey.credential_id().begin(),
                             passkey.credential_id().end()),
        device::PublicKeyCredentialUserEntity(
            std::vector<uint8_t>(passkey.user_id().begin(),
                                 passkey.user_id().end()),
            passkey.user_name(), passkey.user_display_name()),
        /*provider_name=*/std::nullopt,
        last_used_time > creation_time ? last_used_time : creation_time);
  }
  std::move(callback).Run(std::move(tai));
}

void ChromeAuthenticatorRequestDelegate::FilterRecognizedCredentials(
    TransportAvailabilityInfo* tai) {
  if (dialog_model()->relying_party_id == kGoogleRpId &&
      tai->has_empty_allow_list &&
      std::ranges::any_of(tai->recognized_credentials,
                          IsCredentialFromPlatformAuthenticator)) {
    // Regrettably, Chrome will create webauthn credentials for things other
    // than authentication (e.g. credit card autofill auth) under the rp id
    // "google.com". To differentiate those credentials from actual passkeys you
    // can use to sign in, Google adds a prefix to the user id.
    // This code filter passkeys that do not match that prefix.
    FilterGoogleAuthPasskeys(&tai->recognized_credentials);
    if (tai->has_platform_authenticator_credential ==
            device::FidoRequestHandlerBase::RecognizedCredential::
                kHasRecognizedCredential &&
        std::ranges::none_of(tai->recognized_credentials,
                             IsCredentialFromPlatformAuthenticator)) {
      tai->has_platform_authenticator_credential = device::
          FidoRequestHandlerBase::RecognizedCredential::kNoRecognizedCredential;
    }
  }

  if (!credential_filter_.empty()) {
    std::vector<device::DiscoverableCredentialMetadata> filtered_list;
    for (auto& platform_credential : tai->recognized_credentials) {
      for (auto& filter_credential : credential_filter_) {
        if (platform_credential.cred_id == filter_credential.id) {
          filtered_list.push_back(platform_credential);
          break;
        }
      }
    }
    tai->recognized_credentials = std::move(filtered_list);
  }

  const auto kImmediateTypes =
      std::unordered_set{device::AuthenticatorType::kEnclave,
                         device::AuthenticatorType::kICloudKeychain,
                         device::AuthenticatorType::kWinNative,
                         device::AuthenticatorType::kChromeOS,
                         device::AuthenticatorType::kTouchID};
  if (dialog_controller_->ui_presentation() ==
      UIPresentation::kModalImmediate) {
    std::erase_if(tai->recognized_credentials,
                  [&kImmediateTypes](const auto& passkey) {
                    return !kImmediateTypes.contains(passkey.source);
                  });
  }
}

#if BUILDFLAG(IS_MAC)
// static
std::optional<int> ChromeAuthenticatorRequestDelegate::DaysSinceDate(
    const std::string& formatted_date,
    const base::Time now) {
  int year, month, day_of_month;
  // sscanf will ignore trailing garbage, but we don't need to be strict here.
  if (UNSAFE_TODO(sscanf(formatted_date.c_str(), "%u-%u-%u", &year, &month,
                         &day_of_month)) != 3) {
    return std::nullopt;
  }

  const base::Time::Exploded exploded = {
      .year = year, .month = month, .day_of_month = day_of_month};

  base::Time t;
  if (!base::Time::FromUTCExploded(exploded, &t) || now < t) {
    return std::nullopt;
  }

  const base::TimeDelta difference = now - t;
  return difference.InDays();
}

// static
std::optional<bool> ChromeAuthenticatorRequestDelegate::GetICloudKeychainPref(
    const PrefService* prefs) {
  const PrefService::Preference* pref =
      prefs->FindPreference(prefs::kCreatePasskeysInICloudKeychain);
  if (pref->IsDefaultValue()) {
    return std::nullopt;
  }
  return pref->GetValue()->GetBool();
}

// static
bool ChromeAuthenticatorRequestDelegate::IsActiveProfileAuthenticatorUser(
    const PrefService* prefs) {
  const std::string& last_used = prefs->GetString(kWebAuthnTouchIdLastUsed);
  if (last_used.empty()) {
    return false;
  }
  const std::optional<int> days = DaysSinceDate(last_used, base::Time::Now());
  return days.has_value() && days.value() <= kMacOsRecentlyUsedMaxDays;
}

// static
bool ChromeAuthenticatorRequestDelegate::ShouldCreateInICloudKeychain(
    RequestSource request_source,
    bool is_active_profile_authenticator_user,
    bool has_icloud_drive_enabled,
    bool request_is_for_google_com,
    std::optional<bool> preference) {
  // Secure Payment Confirmation and credit-card autofill continue to use
  // the profile authenticator.
  if (request_source != RequestSource::kWebAuthentication) {
    return false;
  }
  if (preference.has_value()) {
    return *preference;
  }
  const base::Feature* feature;
  if (request_is_for_google_com) {
    feature = &device::kWebAuthnICloudKeychainForGoogle;
  } else {
    if (is_active_profile_authenticator_user) {
      if (has_icloud_drive_enabled) {
        feature = &device::kWebAuthnICloudKeychainForActiveWithDrive;
      } else {
        feature = &device::kWebAuthnICloudKeychainForActiveWithoutDrive;
      }
    } else {
      if (has_icloud_drive_enabled) {
        feature = &device::kWebAuthnICloudKeychainForInactiveWithDrive;
      } else {
        feature = &device::kWebAuthnICloudKeychainForInactiveWithoutDrive;
      }
    }
  }

  return base::FeatureList::IsEnabled(*feature);
}

void ChromeAuthenticatorRequestDelegate::ConfigureNSWindow(
    device::FidoDiscoveryFactory* discovery_factory) {
  content::WebContents* web_contents =
      content::WebContents::FromRenderFrameHost(GetRenderFrameHost());
  Browser* browser = chrome::FindBrowserWithTab(web_contents);
  if (browser && browser->is_type_app()) {
    // PWAs render the UI in an out-of-process window, thus there is no valid
    // NSWindow* available in the browser process.
    // TODO: crbug.com/364926914 - potentially do iCloud Keychain operations out
    // of process so that they can work in PWAs.
    return;
  }

  // Not all contexts in which this code runs have a BrowserWindow.
  // Notably the dialog containing a WebContents that is used for signing
  // into a new profile does not. Thus the NSWindow is fetched more directly.
  const views::Widget* widget = views::Widget::GetTopLevelWidgetForNativeView(
      web_contents->GetNativeView());
  if (widget) {
    const gfx::NativeWindow window = widget->GetNativeWindow();
    if (window) {
      discovery_factory->set_nswindow(window);
    }
  }
}
void ChromeAuthenticatorRequestDelegate::ConfigureICloudKeychain(
    RequestSource request_source,
    const std::string& rp_id) {
  const PrefService* prefs = profile()->GetPrefs();
  const bool is_icloud_drive_enabled = IsICloudDriveEnabled();
  const bool is_active_profile_authenticator_user =
      IsActiveProfileAuthenticatorUser(prefs);
  dialog_controller_->set_allow_icloud_keychain(
      request_source == RequestSource::kWebAuthentication);
  dialog_controller_->set_has_icloud_drive_enabled(is_icloud_drive_enabled);
  dialog_controller_->set_is_active_profile_authenticator_user(
      is_active_profile_authenticator_user);
  dialog_controller_->set_should_create_in_icloud_keychain(
      ShouldCreateInICloudKeychain(
          request_source, is_active_profile_authenticator_user,
          is_icloud_drive_enabled, rp_id == "google.com",
          GetICloudKeychainPref(prefs)));
}

#endif

void ChromeAuthenticatorRequestDelegate::OnPasswordCredentialsReceived(
    PasswordCredentials credentials) {
  pending_password_credentials_ =
      std::make_unique<PasswordCredentials>(std::move(credentials));
  TryToShowUI();
}

void ChromeAuthenticatorRequestDelegate::UpdateModelForTransportAvailability(
    const TransportAvailabilityInfo& tai) {
  dialog_model_->request_type = tai.request_type;
  dialog_model_->resident_key_requirement = tai.resident_key_requirement;
  dialog_model_->attestation_conveyance_preference =
      tai.attestation_conveyance_preference;
  dialog_model_->ble_adapter_is_powered =
      tai.ble_status == device::FidoRequestHandlerBase::BleStatus::kOn;
  dialog_model_->show_security_key_on_qr_sheet =
      base::Contains(tai.available_transports,
                     device::FidoTransportProtocol::kUsbHumanInterfaceDevice);
  dialog_model_->is_off_the_record = tai.is_off_the_record_context;
  dialog_model_->platform_has_biometrics = tai.platform_has_biometrics;
}