File: user_verifying_key_win.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 (752 lines) | stat: -rw-r--r-- 28,496 bytes parent folder | download | duplicates (9)
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
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/351564777): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif

#include "crypto/user_verifying_key.h"

#include <windows.h>

#include <windows.foundation.h>
#include <windows.security.credentials.h>
#include <windows.security.cryptography.core.h>
#include <windows.storage.streams.h>

#include <atomic>
#include <functional>
#include <utility>

#include "base/functional/callback_helpers.h"
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_refptr.h"
#include "base/memory/weak_ptr.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/synchronization/atomic_flag.h"
#include "base/task/bind_post_task.h"
#include "base/task/single_thread_task_runner.h"
#include "base/task/thread_pool.h"
#include "base/threading/scoped_thread_priority.h"
#include "base/win/core_winrt_util.h"
#include "base/win/post_async_results.h"
#include "base/win/scoped_hstring.h"
#include "base/win/winrt_storage_util.h"
#include "crypto/random.h"

using ABI::Windows::Foundation::IAsyncAction;
using ABI::Windows::Foundation::IAsyncOperation;
using ABI::Windows::Security::Credentials::IKeyCredential;
using ABI::Windows::Security::Credentials::IKeyCredentialManagerStatics;
using ABI::Windows::Security::Credentials::IKeyCredentialOperationResult;
using ABI::Windows::Security::Credentials::IKeyCredentialRetrievalResult;
using ABI::Windows::Security::Credentials::KeyCredentialCreationOption;
using ABI::Windows::Security::Credentials::KeyCredentialOperationResult;
using ABI::Windows::Security::Credentials::KeyCredentialRetrievalResult;
using ABI::Windows::Security::Credentials::KeyCredentialStatus;
using ABI::Windows::Security::Credentials::
    KeyCredentialStatus_CredentialAlreadyExists;
using ABI::Windows::Security::Credentials::KeyCredentialStatus_NotFound;
using ABI::Windows::Security::Credentials::KeyCredentialStatus_Success;
using ABI::Windows::Security::Credentials::KeyCredentialStatus_UserCanceled;
using ABI::Windows::Security::Credentials::
    KeyCredentialStatus_UserPrefersPassword;
using ABI::Windows::Security::Cryptography::Core::
    CryptographicPublicKeyBlobType_X509SubjectPublicKeyInfo;
using ABI::Windows::Storage::Streams::IBuffer;
using Microsoft::WRL::ComPtr;

namespace crypto {

namespace {

// Possible outcomes for WinRT API calls. These are recorded for signing
// and key creation.
// Do not delete or reorder entries, this must be kept in sync with the
// corresponding metrics enum.
enum class KeyCredentialCreateResult {
  kSucceeded = 0,
  kAPIReturnedError = 1,
  kNoActivationFactory = 2,
  kRequestCreateAsyncFailed = 3,
  kPostAsyncHandlersFailed = 4,
  kInvalidStatusReturned = 5,
  kInvalidResultReturned = 6,
  kInvalidCredentialReturned = 7,

  kMaxValue = 7,
};

enum class KeyCredentialSignResult {
  kSucceeded = 0,
  kAPIReturnedError = 1,
  kRequestSignAsyncFailed = 2,
  kPostAsyncHandlersFailed = 3,
  kIBufferCreationFailed = 4,
  kInvalidStatusReturned = 5,
  kInvalidResultReturned = 6,
  kInvalidSignatureBufferReturned = 7,

  kMaxValue = 7,
};

void RecordCreateAsyncResult(KeyCredentialCreateResult result) {
  base::UmaHistogramEnumeration(
      "WebAuthentication.Windows.KeyCredentialCreation", result);
}

void RecordSignAsyncResult(KeyCredentialSignResult result) {
  base::UmaHistogramEnumeration("WebAuthentication.Windows.KeyCredentialSign",
                                result);
}

// Due to a Windows bug (http://task.ms/49689617), the system UI for
// KeyCredentialManager appears under all other windows, at least when invoked
// from a Win32 app. Therefore this code polls the visible windows and
// foregrounds the correct window when it appears.
class HelloDialogForegrounder
    : public base::RefCountedThreadSafe<HelloDialogForegrounder> {
 public:
  HelloDialogForegrounder() = default;
  HelloDialogForegrounder(const HelloDialogForegrounder&) = delete;
  HelloDialogForegrounder& operator=(const HelloDialogForegrounder&) = delete;

  void Start() {
    CHECK_EQ(state_, State::kNotStarted);
    state_ = State::kPollingForFirstAppearance;
    BringHelloDialogToFront(/*iteration=*/0);
  }

  void Stop() { stopping_.Set(); }

 private:
  friend class base::RefCountedThreadSafe<HelloDialogForegrounder>;
  ~HelloDialogForegrounder() = default;

  // Values to report the results of attempts to bring the Windows Hello
  // user verification dialog to the foreground.
  // Do not delete or reorder entries, this must be kept in sync with the
  // corresponding metrics enum.
  enum class ForegroundHelloDialogResult {
    kSucceeded = 0,
    kForegroundingFailed = 1,
    kWindowNotFound = 2,
    kAbortedWithoutFindingWindow = 3,

    kMaxValue = 3,
  };

  enum class State {
    kNotStarted,
    kPollingForFirstAppearance,
    kPollingForAuthRetry,
  };

  void RecordForegroundingOutcome(ForegroundHelloDialogResult result) {
    base::UmaHistogramEnumeration(
        "WebAuthentication.Windows.ForegroundedWindowsHelloDialog", result);
  }

  void BringHelloDialogToFront(int iteration) {
    int interval = 100;

    if (stopping_.IsSet()) {
      if (state_ == State::kPollingForFirstAppearance) {
        // In State::kPollingForAuthRetry, success has already been reported.
        RecordForegroundingOutcome(
            ForegroundHelloDialogResult::kAbortedWithoutFindingWindow);
      }
      return;
    }

    constexpr wchar_t kTargetWindowName[] = L"Windows Security";
    constexpr wchar_t kTargetClassName[] = L"Credential Dialog Xaml Host";
    if (state_ == State::kPollingForFirstAppearance) {
      constexpr int kMaxIterations = 40;
      if (iteration > kMaxIterations) {
        RecordForegroundingOutcome(
            ForegroundHelloDialogResult::kWindowNotFound);
        return;
      }

      if (HWND hwnd = FindWindowW(kTargetClassName, kTargetWindowName)) {
        base::UmaHistogramExactLinear(
            "WebAuthentication.Windows.FindHelloDialogIterationCount",
            iteration,
            /*exclusive_max=*/kMaxIterations + 1);
        if (SetForegroundWindow(hwnd)) {
          RecordForegroundingOutcome(ForegroundHelloDialogResult::kSucceeded);
        } else {
          RecordForegroundingOutcome(
              ForegroundHelloDialogResult::kForegroundingFailed);
        }
        state_ = State::kPollingForAuthRetry;
      }
    } else {
      CHECK_EQ(state_, State::kPollingForAuthRetry);
      if (HWND hwnd = FindWindowW(kTargetClassName, kTargetWindowName)) {
        SetForegroundWindow(hwnd);
      }
      interval = 500;
    }
    base::ThreadPool::PostDelayedTask(
        FROM_HERE, {base::TaskPriority::USER_BLOCKING, base::MayBlock()},
        base::BindOnce(&HelloDialogForegrounder::BringHelloDialogToFront,
                       base::WrapRefCounted<HelloDialogForegrounder>(this),
                       iteration + 1),
        base::Milliseconds(interval));
  }

  State state_ = State::kNotStarted;
  base::AtomicFlag stopping_;
};

enum KeyCredentialManagerAvailability {
  kUnknown = 0,
  kAvailable = 1,
  kUnavailable = 2,
};

std::string FormatError(std::string message, HRESULT hr) {
  return base::StrCat(
      {message, " (hr = ", logging::SystemErrorCodeToString(hr), ")"});
}

// This helper splits OnceCallback three ways for use with `PostAsyncHandlers`,
// which has three separate paths to outcomes: Invoke a success callback, invoke
// an error callback, or return an error.
template <typename... Args>
std::tuple<base::OnceCallback<void(Args...)>,
           base::OnceCallback<void(Args...)>,
           base::OnceCallback<void(Args...)>>
SplitOnceCallbackIntoThree(base::OnceCallback<void(Args...)> callback) {
  auto first_split = base::SplitOnceCallback(std::move(callback));
  auto second_split = base::SplitOnceCallback(std::move(first_split.first));
  return {std::move(first_split.second), std::move(second_split.first),
          std::move(second_split.second)};
}

void OnSigningSuccess(
    UserVerifyingSigningKey::UserVerifyingKeySignatureCallback callback,
    scoped_refptr<HelloDialogForegrounder> foregrounder,
    ComPtr<IKeyCredentialOperationResult> sign_result) {
  foregrounder->Stop();

  KeyCredentialStatus status;
  HRESULT hr = sign_result->get_Status(&status);
  if (FAILED(hr) || status != KeyCredentialStatus_Success) {
    LOG(ERROR) << FormatError(
        "Failed to obtain Status from IKeyCredentialOperationResult", hr);
    RecordSignAsyncResult(KeyCredentialSignResult::kInvalidStatusReturned);
    UserVerifyingKeySigningError sign_error;
    switch (status) {
      case KeyCredentialStatus_UserCanceled:
      case KeyCredentialStatus_UserPrefersPassword:
        sign_error = UserVerifyingKeySigningError::kUserCancellation;
        break;
      default:
        sign_error = UserVerifyingKeySigningError::kUnknownError;
    }
    std::move(callback).Run(base::unexpected(sign_error));
    return;
  }

  ComPtr<IBuffer> signature_buffer;
  hr = sign_result->get_Result(&signature_buffer);
  if (FAILED(hr)) {
    LOG(ERROR) << FormatError(
        "Failed to obtain Result from IKeyCredentialOperationResult", hr);
    RecordSignAsyncResult(KeyCredentialSignResult::kInvalidResultReturned);
    std::move(callback).Run(
        base::unexpected(UserVerifyingKeySigningError::kPlatformApiError));
    return;
  }

  uint8_t* signature_data = nullptr;
  uint32_t signature_length = 0;
  hr = base::win::GetPointerToBufferData(signature_buffer.Get(),
                                         &signature_data, &signature_length);
  if (FAILED(hr)) {
    LOG(ERROR) << FormatError("Failed to obtain data from signature buffer",
                              hr);
    RecordSignAsyncResult(
        KeyCredentialSignResult::kInvalidSignatureBufferReturned);
    std::move(callback).Run(
        base::unexpected(UserVerifyingKeySigningError::kPlatformApiError));
    return;
  }

  RecordSignAsyncResult(KeyCredentialSignResult::kSucceeded);
  std::move(callback).Run(base::ok(
      std::vector<uint8_t>(signature_data, signature_data + signature_length)));
}

void OnSigningError(
    UserVerifyingSigningKey::UserVerifyingKeySignatureCallback callback,
    scoped_refptr<HelloDialogForegrounder> foregrounder,
    HRESULT hr) {
  foregrounder->Stop();
  LOG(ERROR) << FormatError("Failed to sign with user-verifying signature", hr);
  RecordSignAsyncResult(KeyCredentialSignResult::kAPIReturnedError);
  std::move(callback).Run(
      base::unexpected(UserVerifyingKeySigningError::kPlatformApiError));
}

void SignInternal(
    std::vector<uint8_t> data,
    ComPtr<IKeyCredential> credential,
    UserVerifyingSigningKey::UserVerifyingKeySignatureCallback callback) {
  Microsoft::WRL::ComPtr<IBuffer> signing_buf;
  HRESULT hr =
      base::win::CreateIBufferFromData(data.data(), data.size(), &signing_buf);
  if (FAILED(hr)) {
    LOG(ERROR) << FormatError("SignInternal: IBuffer creation failed", hr);
    RecordSignAsyncResult(KeyCredentialSignResult::kIBufferCreationFailed);
    std::move(callback).Run(
        base::unexpected(UserVerifyingKeySigningError::kPlatformApiError));
    return;
  }

  ComPtr<IAsyncOperation<KeyCredentialOperationResult*>> sign_result;
  hr = credential->RequestSignAsync(signing_buf.Get(), &sign_result);
  if (FAILED(hr)) {
    LOG(ERROR) << FormatError("SignInternal: Call to RequestSignAsync failed",
                              hr);
    RecordSignAsyncResult(KeyCredentialSignResult::kRequestSignAsyncFailed);
    std::move(callback).Run(
        base::unexpected(UserVerifyingKeySigningError::kPlatformApiError));
    return;
  }

  auto foregrounder = base::MakeRefCounted<HelloDialogForegrounder>();
  auto callback_splits = SplitOnceCallbackIntoThree(std::move(callback));
  hr = base::win::PostAsyncHandlers(
      sign_result.Get(),
      base::BindOnce(&OnSigningSuccess, std::move(std::get<0>(callback_splits)),
                     foregrounder),
      base::BindOnce(&OnSigningError, std::move(std::get<1>(callback_splits)),
                     foregrounder));
  if (FAILED(hr)) {
    LOG(ERROR) << FormatError("SignInternal: Call to PostAsyncHandlers failed",
                              hr);
    RecordSignAsyncResult(KeyCredentialSignResult::kPostAsyncHandlersFailed);
    std::move(std::get<2>(callback_splits))
        .Run(base::unexpected(UserVerifyingKeySigningError::kPlatformApiError));
    return;
  }

  foregrounder->Start();
}

class UserVerifyingSigningKeyWin : public UserVerifyingSigningKey {
 public:
  UserVerifyingSigningKeyWin(std::string key_name,
                             ComPtr<IKeyCredential> credential)
      : key_name_(std::move(key_name)), credential_(std::move(credential)) {}
  ~UserVerifyingSigningKeyWin() override = default;

  void Sign(base::span<const uint8_t> data,
            UserVerifyingKeySignatureCallback callback) override {
    scoped_refptr<base::SequencedTaskRunner> task_runner =
        base::ThreadPool::CreateSequencedTaskRunner(
            {base::MayBlock(), base::TaskPriority::USER_BLOCKING});
    std::vector<uint8_t> vec_data(data.begin(), data.end());
    task_runner->PostTask(
        FROM_HERE,
        base::BindOnce(
            &SignInternal, std::move(vec_data), credential_,
            base::BindPostTaskToCurrentDefault(std::move(callback))));
  }

  std::vector<uint8_t> GetPublicKey() const override {
    ComPtr<IBuffer> key_buf;
    HRESULT hr = credential_->RetrievePublicKeyWithBlobType(
        CryptographicPublicKeyBlobType_X509SubjectPublicKeyInfo, &key_buf);
    CHECK(SUCCEEDED(hr)) << FormatError(
        "Failed to obtain public key from KeyCredential", hr);

    uint8_t* pub_key_data = nullptr;
    uint32_t pub_key_length = 0;
    hr = base::win::GetPointerToBufferData(key_buf.Get(), &pub_key_data,
                                           &pub_key_length);
    CHECK(SUCCEEDED(hr)) << FormatError(
        "Failed to access public key buffer data", hr);
    return std::vector<uint8_t>(pub_key_data, pub_key_data + pub_key_length);
  }

  const UserVerifyingKeyLabel& GetKeyLabel() const override {
    return key_name_;
  }

  bool IsHardwareBacked() const override { return true; }

 private:
  std::string key_name_;
  ComPtr<IKeyCredential> credential_;
};

void OnKeyCreationCompletionSuccess(
    UserVerifyingKeyProvider::UserVerifyingKeyCreationCallback callback,
    std::string key_name,
    scoped_refptr<HelloDialogForegrounder> foregrounder,
    ComPtr<IKeyCredentialRetrievalResult> key_result) {
  if (foregrounder) {
    foregrounder->Stop();
  }

  KeyCredentialStatus status;
  HRESULT hr = key_result->get_Status(&status);
  if (FAILED(hr)) {
    LOG(ERROR) << FormatError(
        "Failed to obtain Status from IKeyCredentialRetrievalResult", hr);
    RecordCreateAsyncResult(KeyCredentialCreateResult::kInvalidStatusReturned);
    std::move(callback).Run(
        base::unexpected(UserVerifyingKeyCreationError::kPlatformApiError));
    return;
  } else if (status != KeyCredentialStatus_Success) {
    LOG(ERROR) << "IKeyCredentialRetrievalResult failed with status "
               << static_cast<uint32_t>(status);
    RecordCreateAsyncResult(KeyCredentialCreateResult::kInvalidResultReturned);
    UserVerifyingKeyCreationError uv_key_error;
    switch (status) {
      case KeyCredentialStatus_CredentialAlreadyExists:
        uv_key_error = UserVerifyingKeyCreationError::kDuplicateCredential;
        break;
      case KeyCredentialStatus_NotFound:
        uv_key_error = UserVerifyingKeyCreationError::kNotFound;
        break;
      case KeyCredentialStatus_UserCanceled:
      case KeyCredentialStatus_UserPrefersPassword:
        uv_key_error = UserVerifyingKeyCreationError::kUserCancellation;
        break;
      default:
        uv_key_error = UserVerifyingKeyCreationError::kUnknownError;
    }
    std::move(callback).Run(base::unexpected(uv_key_error));
    return;
  }

  ComPtr<IKeyCredential> credential;
  hr = key_result->get_Credential(&credential);
  if (FAILED(hr)) {
    LOG(ERROR) << FormatError(
        "Failed to obtain KeyCredential from KeyCredentialRetrievalResult", hr);
    RecordCreateAsyncResult(
        KeyCredentialCreateResult::kInvalidCredentialReturned);
    std::move(callback).Run(
        base::unexpected(UserVerifyingKeyCreationError::kPlatformApiError));
    return;
  }

  RecordCreateAsyncResult(KeyCredentialCreateResult::kSucceeded);
  auto key = std::make_unique<UserVerifyingSigningKeyWin>(
      std::move(key_name), std::move(credential));
  std::move(callback).Run(base::ok(std::move(key)));
}

void OnKeyCreationCompletionError(
    UserVerifyingKeyProvider::UserVerifyingKeyCreationCallback callback,
    scoped_refptr<HelloDialogForegrounder> foregrounder,
    HRESULT hr) {
  if (foregrounder) {
    foregrounder->Stop();
  }
  LOG(ERROR) << FormatError("Failed to obtain user-verifying key from system",
                            hr);
  RecordCreateAsyncResult(KeyCredentialCreateResult::kAPIReturnedError);
  std::move(callback).Run(
      base::unexpected(UserVerifyingKeyCreationError::kPlatformApiError));
}

void GenerateUserVerifyingSigningKeyInternal(
    std::string key_label,
    UserVerifyingKeyProvider::UserVerifyingKeyCreationCallback callback) {
  SCOPED_MAY_LOAD_LIBRARY_AT_BACKGROUND_PRIORITY();
  auto key_name = base::win::ScopedHString::Create(key_label);

  ComPtr<IKeyCredentialManagerStatics> factory;
  HRESULT hr = base::win::GetActivationFactory<
      IKeyCredentialManagerStatics,
      RuntimeClass_Windows_Security_Credentials_KeyCredentialManager>(&factory);
  if (FAILED(hr)) {
    LOG(ERROR) << FormatError(
        "GenerateUserVerifyingSigningKeyInternal: Failed to obtain activation "
        "factory for KeyCredentialManager",
        hr);
    RecordCreateAsyncResult(KeyCredentialCreateResult::kNoActivationFactory);
    std::move(callback).Run(
        base::unexpected(UserVerifyingKeyCreationError::kPlatformApiError));
    return;
  }
  ComPtr<IAsyncOperation<KeyCredentialRetrievalResult*>> create_result;
  hr = factory->RequestCreateAsync(
      key_name.get(),
      KeyCredentialCreationOption::KeyCredentialCreationOption_ReplaceExisting,
      &create_result);
  if (FAILED(hr)) {
    LOG(ERROR) << FormatError(
        "GenerateUserVerifyingSigningKeyInternal: Call to RequestCreateAsync "
        "failed",
        hr);
    RecordCreateAsyncResult(
        KeyCredentialCreateResult::kRequestCreateAsyncFailed);
    std::move(callback).Run(
        base::unexpected(UserVerifyingKeyCreationError::kPlatformApiError));
    return;
  }

  auto foregrounder = base::MakeRefCounted<HelloDialogForegrounder>();
  auto callback_splits = SplitOnceCallbackIntoThree(std::move(callback));
  hr = base::win::PostAsyncHandlers(
      create_result.Get(),
      base::BindOnce(&OnKeyCreationCompletionSuccess,
                     std::move(std::get<0>(callback_splits)),
                     std::move(key_label), foregrounder),
      base::BindOnce(&OnKeyCreationCompletionError,
                     std::move(std::get<1>(callback_splits)), foregrounder));
  if (FAILED(hr)) {
    LOG(ERROR) << FormatError(
        "GenerateUserVerifyingSigningKeyInternal: Call to PostAsyncHandlers "
        "failed",
        hr);
    RecordCreateAsyncResult(
        KeyCredentialCreateResult::kPostAsyncHandlersFailed);
    std::move(std::get<2>(callback_splits))
        .Run(
            base::unexpected(UserVerifyingKeyCreationError::kPlatformApiError));
    return;
  }

  foregrounder->Start();
}

void GetUserVerifyingSigningKeyInternal(
    std::string key_label,
    UserVerifyingKeyProvider::UserVerifyingKeyCreationCallback callback) {
  SCOPED_MAY_LOAD_LIBRARY_AT_BACKGROUND_PRIORITY();
  auto key_name = base::win::ScopedHString::Create(key_label);

  ComPtr<IKeyCredentialManagerStatics> factory;
  HRESULT hr = base::win::GetActivationFactory<
      IKeyCredentialManagerStatics,
      RuntimeClass_Windows_Security_Credentials_KeyCredentialManager>(&factory);
  if (FAILED(hr)) {
    LOG(ERROR) << FormatError(
        "GetUserVerifyingSigningKeyInternal: Failed to obtain activation "
        "factory for KeyCredentialManager",
        hr);
    std::move(callback).Run(
        base::unexpected(UserVerifyingKeyCreationError::kPlatformApiError));
    return;
  }

  ComPtr<IAsyncOperation<KeyCredentialRetrievalResult*>> open_result;
  hr = factory->OpenAsync(key_name.get(), &open_result);
  if (FAILED(hr)) {
    LOG(ERROR) << FormatError(
        "GetUserVerifyingSigningKeyInternal: Call to OpenAsync failed", hr);
    std::move(callback).Run(
        base::unexpected(UserVerifyingKeyCreationError::kPlatformApiError));
    return;
  }

  auto callback_splits = SplitOnceCallbackIntoThree(std::move(callback));
  hr = base::win::PostAsyncHandlers(
      open_result.Get(),
      base::BindOnce(&OnKeyCreationCompletionSuccess,
                     std::move(std::get<0>(callback_splits)),
                     std::move(key_label),
                     /*HelloDialogForegrounder=*/nullptr),
      base::BindOnce(&OnKeyCreationCompletionError,
                     std::move(std::get<1>(callback_splits)),
                     /*HelloDialogForegrounder=*/nullptr));
  if (FAILED(hr)) {
    LOG(ERROR) << FormatError(
        "GetUserVerifyingSigningKeyInternal: Call to PostAsyncHandlers failed",
        hr);
    std::move(std::get<2>(callback_splits))
        .Run(
            base::unexpected(UserVerifyingKeyCreationError::kPlatformApiError));
    return;
  }
}

void DeleteUserVerifyingKeyInternal(UserVerifyingKeyLabel key_label,
                                    base::OnceCallback<void(bool)> callback) {
  SCOPED_MAY_LOAD_LIBRARY_AT_BACKGROUND_PRIORITY();

  ComPtr<IKeyCredentialManagerStatics> factory;
  HRESULT hr = base::win::GetActivationFactory<
      IKeyCredentialManagerStatics,
      RuntimeClass_Windows_Security_Credentials_KeyCredentialManager>(&factory);
  if (FAILED(hr)) {
    LOG(ERROR) << FormatError(
        "DeleteUserVerifyingKeyInternal: Failed to obtain activation "
        "factory for KeyCredentialManager",
        hr);
    std::move(callback).Run(false);
    return;
  }

  ComPtr<IAsyncAction> delete_operation;
  auto key_name = base::win::ScopedHString::Create(key_label);
  hr = factory->DeleteAsync(key_name.get(), &delete_operation);
  if (FAILED(hr)) {
    LOG(ERROR) << FormatError(
        "DeleteUserVerifyingKeyInternal: Call to DeleteAsync failed", hr);
    std::move(callback).Run(false);
    return;
  }

  // DeleteAsync does not report a value, so we have to assume success.
  std::move(callback).Run(true);
}

std::optional<SignatureVerifier::SignatureAlgorithm> SelectAlgorithm(
    base::span<const SignatureVerifier::SignatureAlgorithm>
        acceptable_algorithms) {
  // Windows keys come in any algorithm you want, as long as it's RSA 2048.
  for (auto algorithm : acceptable_algorithms) {
    if (algorithm == SignatureVerifier::SignatureAlgorithm::RSA_PKCS1_SHA256) {
      return algorithm;
    }
  }
  return std::nullopt;
}

class UserVerifyingKeyProviderWin : public UserVerifyingKeyProvider {
 public:
  UserVerifyingKeyProviderWin() = default;
  ~UserVerifyingKeyProviderWin() override = default;

  void GenerateUserVerifyingSigningKey(
      base::span<const SignatureVerifier::SignatureAlgorithm>
          acceptable_algorithms,
      UserVerifyingKeyCreationCallback callback) override {
    // Ignore the non-empty return value of `SelectAlgorithm` unless in the
    // future Windows supports more algorithms.
    if (!SelectAlgorithm(acceptable_algorithms)) {
      LOG(ERROR) << "Key generation does not include a supported algorithm.";
      std::move(callback).Run(base::unexpected(
          UserVerifyingKeyCreationError::kNoMatchingAlgorithm));
      return;
    }

    std::vector<uint8_t> random(16);
    crypto::RandBytes(random);
    UserVerifyingKeyLabel key_label =
        base::StrCat({"uvkey-", base::HexEncode(random)});

    scoped_refptr<base::SequencedTaskRunner> task_runner =
        base::ThreadPool::CreateSequencedTaskRunner(
            {base::MayBlock(), base::TaskPriority::USER_BLOCKING});
    task_runner->PostTask(
        FROM_HERE,
        base::BindOnce(
            &GenerateUserVerifyingSigningKeyInternal, std::move(key_label),
            base::BindPostTaskToCurrentDefault(std::move(callback))));
  }

  void GetUserVerifyingSigningKey(
      UserVerifyingKeyLabel key_label,
      UserVerifyingKeyCreationCallback callback) override {
    scoped_refptr<base::SequencedTaskRunner> task_runner =
        base::ThreadPool::CreateSequencedTaskRunner(
            {base::MayBlock(), base::TaskPriority::USER_BLOCKING});
    task_runner->PostTask(
        FROM_HERE,
        base::BindOnce(
            &GetUserVerifyingSigningKeyInternal, key_label,
            base::BindPostTaskToCurrentDefault(std::move(callback))));
  }

  void DeleteUserVerifyingKey(
      UserVerifyingKeyLabel key_label,
      base::OnceCallback<void(bool)> callback) override {
    scoped_refptr<base::SequencedTaskRunner> task_runner =
        base::ThreadPool::CreateSequencedTaskRunner(
            {base::MayBlock(), base::TaskPriority::USER_BLOCKING});
    task_runner->PostTask(
        FROM_HERE, base::BindOnce(DeleteUserVerifyingKeyInternal, key_label,
                                  base::BindPostTaskToCurrentDefault(
                                      std::move(callback))));
  }
};

void IsKeyCredentialManagerAvailableInternal(
    base::OnceCallback<void(bool)> callback) {
  SCOPED_MAY_LOAD_LIBRARY_AT_BACKGROUND_PRIORITY();
  // Lookup requires an asynchronous system API call, so cache the value.
  static std::atomic<KeyCredentialManagerAvailability> availability =
      KeyCredentialManagerAvailability::kUnknown;

  // Read once to ensure consistency.
  const KeyCredentialManagerAvailability current_availability = availability;
  if (current_availability != KeyCredentialManagerAvailability::kUnknown) {
    std::move(callback).Run(current_availability ==
                            KeyCredentialManagerAvailability::kAvailable);
    return;
  }

  ComPtr<IKeyCredentialManagerStatics> factory;
  HRESULT hr = base::win::GetActivationFactory<
      IKeyCredentialManagerStatics,
      RuntimeClass_Windows_Security_Credentials_KeyCredentialManager>(&factory);
  if (FAILED(hr)) {
    // Don't cache API call failures, allowing the possibility of trying again
    // if this was a one-time failure.
    std::move(callback).Run(false);
    return;
  }

  ComPtr<IAsyncOperation<bool>> is_supported_operation;
  hr = factory->IsSupportedAsync(&is_supported_operation);
  if (FAILED(hr)) {
    std::move(callback).Run(false);
    return;
  }

  auto callback_splits = SplitOnceCallbackIntoThree(std::move(callback));
  hr = base::win::PostAsyncHandlers(
      is_supported_operation.Get(),
      base::BindOnce(
          [](base::OnceCallback<void(bool)> callback,
             std::atomic<KeyCredentialManagerAvailability>& availability,
             boolean result) {
            availability = result
                               ? KeyCredentialManagerAvailability::kAvailable
                               : KeyCredentialManagerAvailability::kUnavailable;
            std::move(callback).Run(result);
          },
          std::move(std::get<0>(callback_splits)), std::ref(availability)),
      base::BindOnce([](base::OnceCallback<void(bool)> callback,
                        HRESULT) { std::move(callback).Run(false); },
                     std::move(std::get<1>(callback_splits))));
  if (FAILED(hr)) {
    std::move(std::get<2>(callback_splits)).Run(false);
    return;
  }
}

}  // namespace

std::unique_ptr<UserVerifyingKeyProvider> GetUserVerifyingKeyProviderWin() {
  return std::make_unique<UserVerifyingKeyProviderWin>();
}

void IsKeyCredentialManagerAvailable(base::OnceCallback<void(bool)> callback) {
  scoped_refptr<base::SequencedTaskRunner> task_runner =
      base::ThreadPool::CreateSequencedTaskRunner(
          {base::MayBlock(), base::TaskPriority::USER_BLOCKING});
  task_runner->PostTask(
      FROM_HERE,
      base::BindOnce(&IsKeyCredentialManagerAvailableInternal,
                     base::BindPostTaskToCurrentDefault(std::move(callback))));
}

}  // namespace crypto