File: web_authentication_proxy_service.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (645 lines) | stat: -rw-r--r-- 25,479 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
// Copyright 2021 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/extensions/api/web_authentication_proxy/web_authentication_proxy_service.h"

#include <limits>
#include <optional>
#include <string>
#include <variant>

#include "base/functional/overloaded.h"
#include "base/json/json_writer.h"
#include "base/no_destructor.h"
#include "base/rand_util.h"
#include "base/sequence_checker.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/extensions/api/web_authentication_proxy.h"
#include "components/webauthn/json/value_conversions.h"
#include "content/public/browser/browser_context.h"
#include "device/fido/public_key_credential_rp_entity.h"
#include "extensions/browser/event_router.h"
#include "extensions/browser/event_router_factory.h"
#include "extensions/browser/extension_event_histogram_value.h"
#include "extensions/browser/extension_function.h"
#include "extensions/browser/extension_function_histogram_value.h"
#include "extensions/browser/extension_registry_factory.h"
#include "extensions/browser/extension_util.h"
#include "extensions/common/permissions/permissions_data.h"
#include "services/data_decoder/public/cpp/data_decoder.h"
#include "third_party/blink/public/mojom/webauthn/authenticator.mojom-shared.h"
#include "third_party/blink/public/mojom/webauthn/authenticator.mojom.h"
#include "url/gurl.h"

namespace extensions {

namespace {

bool ProxyMayAttachToHost(const Extension& extension,
                          const url::Origin& origin) {
  // Prevent the proxy from being active on policy blocked hosts.
  //
  // We do not consider user restricted hosts here because those require host
  // permissions, and the webAuthenticationProxy permission is granted on all
  // hosts. We also don't block Chrome-restricted hosts in order to allow
  // authentication to the Chrome Web Store from inside a remote desktop
  // session, for example.
  return !extension.permissions_data()->IsPolicyBlockedHost(origin.GetURL());
}

}  // namespace

WebAuthenticationProxyRegistrar::WebAuthenticationProxyRegistrar(
    Profile* profile)
    : profile_(profile), extension_registry_(ExtensionRegistry::Get(profile)) {
  // Extension services such as ExtensionRegistry are shared between
  // off-the-record and regular Profile in the same way as
  // WebAuthenticationProxyRegistrar.
  extension_registry_observation_.Observe(extension_registry_);
  profile_observation_.Observe(profile_);
}

WebAuthenticationProxyRegistrar::~WebAuthenticationProxyRegistrar() = default;

bool WebAuthenticationProxyRegistrar::SetRequestProxy(
    Profile* profile,
    const Extension* extension) {
  // It is invalid to call this method with an unrelated BrowserContext.
  DCHECK(profile->IsSameOrParent(profile_));
  DCHECK(extension);
  DCHECK(extension_registry_->enabled_extensions().Contains(extension->id()));
  DCHECK(!attach_regular_proxy_to_both_contexts_ || active_regular_proxy_);

  if ((active_regular_proxy_ && *active_regular_proxy_ != extension->id()) ||
      (active_otr_split_proxy_ &&
       *active_otr_split_proxy_ != extension->id())) {
    // A different extension is attached. Attaching split mode extensions is
    // only supported for attaching the same extension in both
    // off-the-record/regular mode.
    return false;
  }

  if (profile->IsOffTheRecord()) {
    // Only a split mode extension can pass an off-the-record profile here. All
    // others use the same regular profile.
    active_otr_split_proxy_ = extension->id();
    WebAuthenticationProxyServiceFactory::GetForBrowserContext(profile)
        ->SetRequestProxy(PassKey(), extension);
    return true;
  }

  // Regular browser context.
  active_regular_proxy_ = extension->id();
  WebAuthenticationProxyServiceFactory::GetForBrowserContext(profile)
      ->SetRequestProxy(PassKey(), extension);
  // Also attach spanning mode extensions to the incognito profile. If no
  // incognito profile currently exists, OnOffTheRecordProfileCreated() may
  // attach later.
  if (util::CanCrossIncognito(extension, profile)) {
    attach_regular_proxy_to_both_contexts_ = true;
    if (profile->HasPrimaryOTRProfile()) {
      WebAuthenticationProxyServiceFactory::GetForBrowserContext(
          profile->GetPrimaryOTRProfile(/*create_if_needed=*/false))
          ->SetRequestProxy(PassKey(), extension);
    }
  }
  return true;
}

void WebAuthenticationProxyRegistrar::ClearRequestProxy(Profile* profile) {
  // It is invalid to call this method with an unrelated BrowserContext.
  DCHECK(profile->IsSameOrParent(profile_));

  if (profile->IsOffTheRecord()) {
    // Only a split mode extension can pass an off-the-record profile here. All
    // others use the same regular profile.
    DCHECK(active_otr_split_proxy_);
    DCHECK(!attach_regular_proxy_to_both_contexts_);
    active_otr_split_proxy_.reset();
    WebAuthenticationProxyServiceFactory::GetForBrowserContext(profile)
        ->ClearRequestProxy(PassKey());
    return;
  }

  // Regular browser context.
  DCHECK(active_regular_proxy_);
  active_regular_proxy_.reset();
  WebAuthenticationProxyServiceFactory::GetForBrowserContext(profile)
      ->ClearRequestProxy(PassKey());
  // Also clear spanning mode extensions from the incognito profile, if
  // necessary.
  if (attach_regular_proxy_to_both_contexts_ &&
      profile->HasPrimaryOTRProfile()) {
    WebAuthenticationProxyServiceFactory::GetForBrowserContext(
        profile->GetPrimaryOTRProfile(/*create_if_needed=*/false))
        ->ClearRequestProxy(PassKey());
  }
  attach_regular_proxy_to_both_contexts_ = false;
}

WebAuthenticationProxyRegistrar::ProxyStatus
WebAuthenticationProxyRegistrar::ProxyActiveForProfile(Profile* profile) {
  DCHECK(profile->IsSameOrParent(profile_));
  if (profile->IsOffTheRecord()) {
    if (active_otr_split_proxy_) {
      return ProxyStatus::kActive;
    }
    return active_regular_proxy_ && attach_regular_proxy_to_both_contexts_
               ? ProxyStatus::kActiveUseOriginalProfile
               : ProxyStatus::kInactive;
  }
  return active_regular_proxy_ ? ProxyStatus::kActive : ProxyStatus::kInactive;
}

void WebAuthenticationProxyRegistrar::OnExtensionUnloaded(
    content::BrowserContext* browser_context,
    const Extension* extension,
    UnloadedExtensionReason reason) {
  // ExtensionRegistry redirects to the original profile for incognito, so this
  // only gets called once for the original profile, for both split and spanning
  // mode extensions.
  auto* profile = Profile::FromBrowserContext(browser_context);
  DCHECK_EQ(profile, profile_);
  auto* maybe_incognito_profile =
      profile->GetPrimaryOTRProfile(/*create_if_needed=*/false);

  if (extension->id() == active_regular_proxy_) {
    active_regular_proxy_.reset();
    WebAuthenticationProxyServiceFactory::GetForBrowserContext(profile)
        ->ClearRequestProxy(PassKey());
    if (attach_regular_proxy_to_both_contexts_ && maybe_incognito_profile) {
      WebAuthenticationProxyServiceFactory::GetForBrowserContext(
          maybe_incognito_profile)
          ->ClearRequestProxy(PassKey());
    }
    attach_regular_proxy_to_both_contexts_ = false;
  }
  if (extension->id() == active_otr_split_proxy_) {
    DCHECK(!attach_regular_proxy_to_both_contexts_);
    active_otr_split_proxy_.reset();
    if (maybe_incognito_profile) {
      WebAuthenticationProxyServiceFactory::GetForBrowserContext(
          maybe_incognito_profile)
          ->ClearRequestProxy(PassKey());
    }
  }
}

void WebAuthenticationProxyRegistrar::OnOffTheRecordProfileCreated(
    Profile* otr_profile) {
  if (!attach_regular_proxy_to_both_contexts_) {
    return;
  }
  // A spanning mode extension attached to the regular profile before
  // this OTR profile existed. Attach it to the new OTR profile, too.
  DCHECK(active_regular_proxy_);
  const Extension* extension =
      extension_registry_->enabled_extensions().GetByID(*active_regular_proxy_);
  DCHECK(extension);
  WebAuthenticationProxyServiceFactory::GetForBrowserContext(otr_profile)
      ->SetRequestProxy(PassKey(), extension);
}

void WebAuthenticationProxyRegistrar::OnProfileWillBeDestroyed(
    Profile* profile) {
  // Reset any active split mode proxy if its profile is about to be destroyed.
  // No need to this clean up for regular profiles; this KeyedService will
  // simply be destroyed along with the profile.
  if (profile->IsOffTheRecord()) {
    active_otr_split_proxy_.reset();
  }
}

WebAuthenticationProxyRegistrarFactory*
WebAuthenticationProxyRegistrarFactory::GetInstance() {
  static base::NoDestructor<WebAuthenticationProxyRegistrarFactory> instance;
  return instance.get();
}

WebAuthenticationProxyRegistrarFactory::WebAuthenticationProxyRegistrarFactory()
    : ProfileKeyedServiceFactory(
          "WebAuthentcationProxyRegistrar",
          // Off-the-record profiles such as Incognito use the instance of their
          // original profile. `WebAuthenticationProxyRegistrar::IsActive()`
          // considers the extension's `incognito` manifest value to decide
          // whether proxying is actually effective in the OTR profile.
          //
          // Non-component extensions don't run in some OTR profile types, such
          // as Guest. So while we do return a `WebAuthenticationProxyRegistrar`
          // for those profile types `IsActive()` will always return false
          // there.
          ProfileSelections::Builder()
              .WithRegular(ProfileSelection::kRedirectedToOriginal)
              // TODO(crbug.com/40257657): Audit whether these should be
              // redirected or should have their own instance.
              .WithGuest(ProfileSelection::kRedirectedToOriginal)
              // TODO(crbug.com/41488885): Check if this service is needed for
              // Ash Internals.
              .WithAshInternals(ProfileSelection::kRedirectedToOriginal)
              .Build()) {
  DependsOn(ExtensionRegistryFactory::GetInstance());
}

WebAuthenticationProxyRegistrarFactory::
    ~WebAuthenticationProxyRegistrarFactory() = default;

WebAuthenticationProxyRegistrar*
WebAuthenticationProxyRegistrarFactory::GetForBrowserContext(
    content::BrowserContext* context) {
  return static_cast<WebAuthenticationProxyRegistrar*>(
      WebAuthenticationProxyRegistrarFactory::GetInstance()
          ->GetServiceForBrowserContext(context, true));
}

std::unique_ptr<KeyedService>
WebAuthenticationProxyRegistrarFactory::BuildServiceInstanceForBrowserContext(
    content::BrowserContext* context) const {
  return std::make_unique<WebAuthenticationProxyRegistrar>(
      Profile::FromBrowserContext(context));
}

WebAuthenticationProxyService*
WebAuthenticationProxyService::GetIfProxyAttached(
    content::BrowserContext* browser_context) {
  auto* profile = Profile::FromBrowserContext(browser_context);
  switch (WebAuthenticationProxyRegistrarFactory::GetForBrowserContext(profile)
              ->ProxyActiveForProfile(profile)) {
    case WebAuthenticationProxyRegistrar::ProxyStatus::kActive:
      return WebAuthenticationProxyServiceFactory::GetForBrowserContext(
          profile);
    case WebAuthenticationProxyRegistrar::ProxyStatus::
        kActiveUseOriginalProfile:
      return WebAuthenticationProxyServiceFactory::GetForBrowserContext(
          profile->GetOriginalProfile());
    case WebAuthenticationProxyRegistrar::ProxyStatus::kInactive:
      return nullptr;
  }
}

WebAuthenticationProxyService::WebAuthenticationProxyService(
    content::BrowserContext* browser_context)
    : browser_context_(browser_context),
      event_router_(EventRouter::Get(browser_context)),
      extension_registry_(ExtensionRegistry::Get(browser_context)) {}

WebAuthenticationProxyService::~WebAuthenticationProxyService() = default;

const Extension* WebAuthenticationProxyService::GetActiveRequestProxy() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  if (!active_proxy_) {
    return nullptr;
  }
  const Extension* extension =
      extension_registry_->enabled_extensions().GetByID(*active_proxy_);
  DCHECK(extension);
  return extension;
}

void WebAuthenticationProxyService::CompleteCreateRequest(
    const api::web_authentication_proxy::CreateResponseDetails& details,
    RespondCallback respond_callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  auto callback_it = pending_callbacks_.find(details.request_id);
  if (callback_it == pending_callbacks_.end() ||
      !std::holds_alternative<CreateCallback>(callback_it->second)) {
    std::move(respond_callback).Run("Invalid requestId");
    return;
  }
  if (details.error) {
    // The proxied request yielded a DOMException.
    auto create_callback =
        std::get<CreateCallback>(std::move(callback_it->second));
    pending_callbacks_.erase(callback_it);
    std::move(create_callback)
        .Run(details.request_id,
             blink::mojom::WebAuthnDOMExceptionDetails::New(
                 details.error->name, details.error->message),
             nullptr);
    std::move(respond_callback).Run(std::nullopt);
    return;
  }
  if (!details.response_json) {
    std::move(respond_callback)
        .Run("Missing CreateResponseDetails.responseJson");
    return;
  }
  data_decoder::DataDecoder::ParseJsonIsolated(
      *details.response_json,
      base::BindOnce(&WebAuthenticationProxyService::OnParseCreateResponse,
                     weak_ptr_factory_.GetWeakPtr(),
                     std::move(respond_callback), details.request_id));
}

void WebAuthenticationProxyService::CompleteGetRequest(
    const api::web_authentication_proxy::GetResponseDetails& details,
    RespondCallback respond_callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  auto callback_it = pending_callbacks_.find(details.request_id);
  if (callback_it == pending_callbacks_.end() ||
      !std::holds_alternative<GetCallback>(callback_it->second)) {
    std::move(respond_callback).Run("Invalid requestId");
    return;
  }
  if (details.error) {
    // The proxied request yielded a DOMException.
    GetCallback callback =
        std::get<GetCallback>(std::move(callback_it->second));
    pending_callbacks_.erase(callback_it);
    std::move(callback).Run(details.request_id,
                            blink::mojom::WebAuthnDOMExceptionDetails::New(
                                details.error->name, details.error->message),
                            nullptr);
    std::move(respond_callback).Run(std::nullopt);
    return;
  }
  if (!details.response_json) {
    std::move(respond_callback).Run("Missing GetResponseDetails.responseJson");
    return;
  }
  data_decoder::DataDecoder::ParseJsonIsolated(
      *details.response_json,
      base::BindOnce(&WebAuthenticationProxyService::OnParseGetResponse,
                     weak_ptr_factory_.GetWeakPtr(),
                     std::move(respond_callback), details.request_id));
}

bool WebAuthenticationProxyService::CompleteIsUvpaaRequest(
    const api::web_authentication_proxy::IsUvpaaResponseDetails& details) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  auto callback_it = pending_callbacks_.find(details.request_id);
  if (callback_it == pending_callbacks_.end() ||
      !std::holds_alternative<IsUvpaaCallback>(callback_it->second)) {
    return false;
  }
  IsUvpaaCallback callback =
      std::get<IsUvpaaCallback>(std::move(callback_it->second));
  pending_callbacks_.erase(callback_it);
  std::move(callback).Run(details.is_uvpaa);
  return true;
}

void WebAuthenticationProxyService::CancelRequest(RequestId request_id) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  const Extension* proxy_extension = GetActiveRequestProxy();
  DCHECK(proxy_extension);

  auto callback_it = pending_callbacks_.find(request_id);
  if (callback_it == pending_callbacks_.end() ||
      std::holds_alternative<IsUvpaaCallback>(callback_it->second)) {
    // Invalid `request_id`. Note that isUvpaa requests cannot be cancelled.
    return;
  }
  pending_callbacks_.erase(request_id);
  event_router_->DispatchEventToExtension(
      proxy_extension->id(),
      std::make_unique<Event>(
          events::WEB_AUTHENTICATION_PROXY_REQUEST_CANCELLED,
          api::web_authentication_proxy::OnRequestCanceled::kEventName,
          api::web_authentication_proxy::OnRequestCanceled::Create(request_id),
          browser_context_));
}

void WebAuthenticationProxyService::SetRequestProxy(
    base::PassKey<WebAuthenticationProxyRegistrar>,
    const Extension* extension) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(extension);
  DCHECK(extension_registry_->enabled_extensions().Contains(extension->id()));
  DCHECK(!active_proxy_ || active_proxy_ == extension->id());
  active_proxy_ = extension->id();
}

void WebAuthenticationProxyService::ClearRequestProxy(
    base::PassKey<WebAuthenticationProxyRegistrar>) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(active_proxy_);
  CancelPendingCallbacks();
  active_proxy_.reset();
}

void WebAuthenticationProxyService::CancelPendingCallbacks() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // Complete all pending callbacks with a cancellation signal.
  for (auto it = pending_callbacks_.begin(); it != pending_callbacks_.end();) {
    auto& [request_id, callback] = *it;
    std::visit(
        base::Overloaded{
            [](IsUvpaaCallback& cb) { std::move(cb).Run(/*is_uvpaa=*/false); },
            // CreateCallback or GetCallback:
            [id = request_id](auto& cb) {
              auto error = blink::mojom::WebAuthnDOMExceptionDetails::New(
                  "AbortError", "The operation was aborted.");
              std::move(cb).Run(id, std::move(error), nullptr);
            }},
        callback);
    it = pending_callbacks_.erase(it);
  }
}

WebAuthenticationProxyService::RequestId
WebAuthenticationProxyService::NewRequestId() {
  int32_t request_id =
      base::RandGenerator(std::numeric_limits<uint32_t>::max()) + 1;
  // Technically, this could spin forever if there are 4 billion active
  // requests. However, there's no real risk to this happening (no security or
  // DOS concerns).
  while (base::Contains(pending_callbacks_, request_id)) {
    request_id = base::RandGenerator(std::numeric_limits<uint32_t>::max()) + 1;
  }
  return request_id;
}

void WebAuthenticationProxyService::OnParseCreateResponse(
    RespondCallback respond_callback,
    RequestId request_id,
    data_decoder::DataDecoder::ValueOrError value_or_error) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (!value_or_error.has_value()) {
    std::move(respond_callback)
        .Run("Parsing responseJson failed: " + value_or_error.error());
    return;
  }
  auto [response, error] =
      webauthn::MakeCredentialResponseFromValue(*value_or_error);
  if (!response) {
    std::move(respond_callback).Run("Invalid responseJson: " + error);
    return;
  }

  auto callback_it = pending_callbacks_.find(request_id);
  if (callback_it == pending_callbacks_.end() ||
      !std::holds_alternative<CreateCallback>(callback_it->second)) {
    // The request was canceled while waiting for JSON decoding.
    std::move(respond_callback).Run("Invalid requestId");
    return;
  }

  // Success.
  CreateCallback create_callback =
      std::get<CreateCallback>(std::move(callback_it->second));
  pending_callbacks_.erase(callback_it);
  std::move(create_callback).Run(request_id, nullptr, std::move(response));
  std::move(respond_callback).Run(std::nullopt);
}

void WebAuthenticationProxyService::OnParseGetResponse(
    RespondCallback respond_callback,
    RequestId request_id,
    data_decoder::DataDecoder::ValueOrError value_or_error) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (!value_or_error.has_value()) {
    std::move(respond_callback)
        .Run("Parsing responseJson failed: " + value_or_error.error());
    return;
  }
  auto [response, error] =
      webauthn::GetAssertionResponseFromValue(*value_or_error);
  if (!response) {
    std::move(respond_callback).Run("Invalid responseJson: " + error);
    return;
  }

  auto callback_it = pending_callbacks_.find(request_id);
  if (callback_it == pending_callbacks_.end() ||
      !std::holds_alternative<GetCallback>(callback_it->second)) {
    // The request was canceled while waiting for JSON decoding.
    std::move(respond_callback).Run("Invalid requestId");
    return;
  }

  // Success.
  GetCallback get_callback =
      std::get<GetCallback>(std::move(callback_it->second));
  pending_callbacks_.erase(callback_it);
  std::move(get_callback).Run(request_id, nullptr, std::move(response));
  std::move(respond_callback).Run(std::nullopt);
}

bool WebAuthenticationProxyService::IsActive(const url::Origin& caller_origin) {
  const Extension* proxy = GetActiveRequestProxy();
  return proxy && ProxyMayAttachToHost(*proxy, caller_origin);
}

WebAuthenticationProxyService::RequestId
WebAuthenticationProxyService::SignalCreateRequest(
    const blink::mojom::PublicKeyCredentialCreationOptionsPtr& options_ptr,
    CreateCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  const Extension* proxy_extension = GetActiveRequestProxy();
  DCHECK(proxy_extension);

  auto request_id = NewRequestId();
  pending_callbacks_.emplace(request_id, std::move(callback));

  api::web_authentication_proxy::CreateRequest request;
  request.request_id = request_id;

  base::Value options_value = webauthn::ToValue(options_ptr);
  std::optional<std::string> request_json = base::WriteJson(options_value);
  CHECK(request_json);
  request.request_details_json = *std::move(request_json);

  event_router_->DispatchEventToExtension(
      proxy_extension->id(),
      std::make_unique<Event>(
          events::WEB_AUTHENTICATION_PROXY_ON_CREATE_REQUEST,
          api::web_authentication_proxy::OnCreateRequest::kEventName,
          api::web_authentication_proxy::OnCreateRequest::Create(request),
          browser_context_));
  return request_id;
}

WebAuthenticationProxyService::RequestId
WebAuthenticationProxyService::SignalGetRequest(
    const blink::mojom::PublicKeyCredentialRequestOptionsPtr& options_ptr,
    GetCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  const Extension* proxy_extension = GetActiveRequestProxy();
  DCHECK(proxy_extension);

  auto request_id = NewRequestId();
  pending_callbacks_.emplace(request_id, std::move(callback));

  api::web_authentication_proxy::GetRequest request;
  request.request_id = request_id;

  base::Value options_value = webauthn::ToValue(options_ptr);
  std::optional<std::string> request_json = base::WriteJson(options_value);
  CHECK(request_json);
  request.request_details_json = *std::move(request_json);

  event_router_->DispatchEventToExtension(
      proxy_extension->id(),
      std::make_unique<Event>(
          events::WEB_AUTHENTICATION_PROXY_ON_GET_REQUEST,
          api::web_authentication_proxy::OnGetRequest::kEventName,
          api::web_authentication_proxy::OnGetRequest::Create(request),
          browser_context_));
  return request_id;
}

WebAuthenticationProxyService::RequestId
WebAuthenticationProxyService::SignalIsUvpaaRequest(IsUvpaaCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  const Extension* proxy_extension = GetActiveRequestProxy();
  DCHECK(proxy_extension);

  auto request_id = NewRequestId();
  pending_callbacks_.emplace(request_id, std::move(callback));
  api::web_authentication_proxy::IsUvpaaRequest request;
  request.request_id = request_id;
  event_router_->DispatchEventToExtension(
      proxy_extension->id(),
      std::make_unique<Event>(
          events::WEB_AUTHENTICATION_PROXY_ON_ISUVPAA_REQUEST,
          api::web_authentication_proxy::OnIsUvpaaRequest::kEventName,
          api::web_authentication_proxy::OnIsUvpaaRequest::Create(request),
          browser_context_));
  return request_id;
}

WebAuthenticationProxyServiceFactory*
WebAuthenticationProxyServiceFactory::GetInstance() {
  static base::NoDestructor<WebAuthenticationProxyServiceFactory> instance;
  return instance.get();
}

WebAuthenticationProxyServiceFactory::WebAuthenticationProxyServiceFactory()
    : ProfileKeyedServiceFactory(
          "WebAuthenticationProxyService",
          ProfileSelections::Builder()
              .WithRegular(ProfileSelection::kOwnInstance)
              .WithGuest(ProfileSelection::kOwnInstance)
              // TODO(crbug.com/41488885): Check if this service is needed for
              // Ash Internals.
              .WithAshInternals(ProfileSelection::kOwnInstance)
              .Build()) {
  DependsOn(EventRouterFactory::GetInstance());
  DependsOn(ExtensionRegistryFactory::GetInstance());
}

WebAuthenticationProxyServiceFactory::~WebAuthenticationProxyServiceFactory() =
    default;

WebAuthenticationProxyService*
WebAuthenticationProxyServiceFactory::GetForBrowserContext(
    content::BrowserContext* context) {
  return static_cast<WebAuthenticationProxyService*>(
      WebAuthenticationProxyServiceFactory::GetInstance()
          ->GetServiceForBrowserContext(context, true));
}

std::unique_ptr<KeyedService>
WebAuthenticationProxyServiceFactory::BuildServiceInstanceForBrowserContext(
    content::BrowserContext* context) const {
  return std::make_unique<WebAuthenticationProxyService>(context);
}

}  // namespace extensions