File: recovery_key_store_connection_impl.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 (377 lines) | stat: -rw-r--r-- 15,683 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
// 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.

#include "components/trusted_vault/recovery_key_store_connection_impl.h"

#include <memory>

#include "base/barrier_closure.h"
#include "base/functional/bind.h"
#include "base/notreached.h"
#include "base/strings/string_number_conversions.h"
#include "base/time/clock.h"
#include "base/time/time.h"
#include "base/types/expected.h"
#include "components/signin/public/identity_manager/account_info.h"
#include "components/trusted_vault/proto/recovery_key_store.pb.h"
#include "components/trusted_vault/proto_string_bytes_conversion.h"
#include "components/trusted_vault/recovery_key_store_certificate.h"
#include "components/trusted_vault/recovery_key_store_connection.h"
#include "components/trusted_vault/trusted_vault_access_token_fetcher.h"
#include "components/trusted_vault/trusted_vault_connection.h"
#include "components/trusted_vault/trusted_vault_histograms.h"
#include "components/trusted_vault/trusted_vault_request.h"
#include "net/base/url_util.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
#include "services/network/public/cpp/simple_url_loader.h"
#include "url/gurl.h"

namespace trusted_vault {

namespace {

// The "/0" suffix is required but ignored.
constexpr char kUpdateVaultUrl[] =
    "https://cryptauthvault.googleapis.com/v1/vaults/0";

constexpr char kListVaultsUrl[] =
    "https://cryptauthvault.googleapis.com/v1/"
    "vaults?use_case=13&challenge_not_required=1";

constexpr char kRecoveryKeyStoreCertFileUrl[] =
    "https://www.gstatic.com/cryptauthvault/v0/cert.xml";

constexpr char kRecoveryKeyStoreSigFileUrl[] =
    "https://www.gstatic.com/cryptauthvault/v0/cert.sig.xml";

// The maximum number of bytes that will be downloaded from the above two URLs.
constexpr size_t kMaxRecoveryKeyStoreCertFetchBodyBytes = 128 * 1024;

static constexpr net::NetworkTrafficAnnotationTag kCertXmlTrafficAnnotation =
    net::DefineNetworkTrafficAnnotation("trusted_vault_cert_request",
                                        R"(
      semantics {
        sender: "Trusted Vault Service"
        description:
          "Request to the vault service in order to retrieve the public list "
          "of certificates to perform encryption key operations for Chrome, "
          "such as Google Password Manager passkey operations"
        trigger:
          "Periodically/upon certain non-user controlled events after user "
          "signs in Chrome profile."
        data: "None"
        destination: GOOGLE_OWNED_SERVICE
        last_reviewed: "2025-06-05"
        user_data {
          type: NONE
        }
        internal {
          contacts {
            email: "nsatragno@chromium.org"
          }
          contacts {
            email: "chrome-webauthn@google.com"
          }
        }
      }
      policy {
        cookies_allowed: NO
        setting:
          "This feature cannot be disabled in settings, but if user signs "
          "out of Chrome, this request would not be made."
        chrome_policy {
          SigninAllowed {
            policy_options {mode: MANDATORY}
            SigninAllowed: false
          }
        }
      })");

RecoveryKeyStoreStatus HttpStatusToRecoveryKeyStoreStatus(
    TrustedVaultRequest::HttpStatus http_status) {
  switch (http_status) {
    case TrustedVaultRequest::HttpStatus::kSuccess:
      return RecoveryKeyStoreStatus::kSuccess;
    case TrustedVaultRequest::HttpStatus::kBadRequest:
    case TrustedVaultRequest::HttpStatus::kNotFound:
    case TrustedVaultRequest::HttpStatus::kConflict:
    case TrustedVaultRequest::HttpStatus::kOtherError:
      return RecoveryKeyStoreStatus::kOtherError;
    case TrustedVaultRequest::HttpStatus::kNetworkError:
      return RecoveryKeyStoreStatus::kNetworkError;
    case TrustedVaultRequest::HttpStatus::kTransientAccessTokenFetchError:
      return RecoveryKeyStoreStatus::kTransientAccessTokenFetchError;
    case TrustedVaultRequest::HttpStatus::kPersistentAccessTokenFetchError:
      return RecoveryKeyStoreStatus::kPersistentAccessTokenFetchError;
    case TrustedVaultRequest::HttpStatus::
        kPrimaryAccountChangeAccessTokenFetchError:
      return RecoveryKeyStoreStatus::kPrimaryAccountChangeAccessTokenFetchError;
  }
}

void ProcessUpdateVaultResponseResponse(
    RecoveryKeyStoreConnection::UpdateRecoveryKeyStoreCallback callback,
    TrustedVaultRequest::HttpStatus http_status,
    const std::string& response_body) {
  std::move(callback).Run(HttpStatusToRecoveryKeyStoreStatus(http_status));
}

// Represents a request to the listVaults RPC endpoint.
class ListRecoveryKeyStoresRequest : public TrustedVaultConnection::Request {
 public:
  ListRecoveryKeyStoresRequest(
      const CoreAccountInfo& account_info,
      scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
      std::unique_ptr<TrustedVaultAccessTokenFetcher> access_token_fetcher,
      RecoveryKeyStoreConnection::ListRecoveryKeyStoresCallback callback)
      : account_id_(account_info.account_id),
        url_loader_factory_(std::move(url_loader_factory)),
        access_token_fetcher_(std::move(access_token_fetcher)),
        callback_(std::move(callback)) {
    StartOrContinueRequest();
  }

 private:
  void StartOrContinueRequest(const std::string* next_page_token = nullptr) {
    TrustedVaultRequest::RecordFetchStatusCallback record_fetch_status_to_uma =
        base::BindRepeating(
            &RecordRecoveryKeyStoreURLFetchResponse,
            RecoveryKeyStoreURLFetchReasonForUMA::kListRecoveryKeyStores);
    GURL request_url(kListVaultsUrl);
    request_ = std::make_unique<TrustedVaultRequest>(
        SecurityDomainId::kPasskeys, account_id_,
        TrustedVaultRequest::HttpMethod::kGet,
        next_page_token ? net::AppendQueryParameter(request_url, "page_token",
                                                    *next_page_token)
                        : request_url,
        /*serialized_request_proto=*/std::nullopt,
        /*max_retry_duration=*/base::Seconds(0), url_loader_factory_,
        access_token_fetcher_->Clone(), std::move(record_fetch_status_to_uma));

    // Unretained: this object owns `request_`. When `request_` is deleted, so
    // is the `SimpleURLLoader` and thus any callback is canceled.
    request_->FetchAccessTokenAndSendRequest(
        base::BindOnce(&ListRecoveryKeyStoresRequest::ProcessResponse,
                       base::Unretained(this)));
  }

  void ProcessResponse(TrustedVaultRequest::HttpStatus http_status,
                       const std::string& response_body) {
    if (http_status != TrustedVaultRequest::HttpStatus::kSuccess) {
      FinishWithResultAndMaybeDestroySelf(
          base::unexpected(HttpStatusToRecoveryKeyStoreStatus(http_status)));
      return;
    }
    trusted_vault_pb::ListVaultsResponse response;
    if (!response.ParseFromString(response_body)) {
      FinishWithResultAndMaybeDestroySelf(
          base::unexpected(RecoveryKeyStoreStatus::kOtherError));
      return;
    }
    for (const auto& vault : response.vaults()) {
      RecoveryKeyStoreEntry entry;
      entry.backend_public_key =
          ProtoStringToBytes(vault.vault_parameters().backend_public_key());
      entry.vault_handle =
          ProtoStringToBytes(vault.vault_parameters().vault_handle());
      result_.push_back(std::move(entry));
    }
    if (!response.next_page_token().empty()) {
      StartOrContinueRequest(&response.next_page_token());
      return;
    }
    FinishWithResultAndMaybeDestroySelf(std::move(result_));
  }

  void FinishWithResultAndMaybeDestroySelf(
      base::expected<std::vector<RecoveryKeyStoreEntry>, RecoveryKeyStoreStatus>
          result) {
    std::move(callback_).Run(std::move(result));
  }

  std::unique_ptr<TrustedVaultRequest> request_;
  const CoreAccountId account_id_;
  scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
  std::unique_ptr<TrustedVaultAccessTokenFetcher> access_token_fetcher_;
  RecoveryKeyStoreConnection::ListRecoveryKeyStoresCallback callback_;
  std::vector<RecoveryKeyStoreEntry> result_;
};

// Represents a request to fetch the recovery key store certificates.
class FetchRecoveryKeyStoreCertificatesRequest
    : public TrustedVaultConnection::Request {
 public:
  // `clock` must outlive this.
  FetchRecoveryKeyStoreCertificatesRequest(
      base::Clock* clock,
      scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
      RecoveryKeyStoreConnection::FetchRecoveryKeyStoreCertificatesCallback
          callback)
      : clock_(clock),
        url_loader_factory_(std::move(url_loader_factory)),
        callback_(std::move(callback)) {
    // Destroying `this` will also destroy the URL loader, which means these
    // callbacks will never complete. Thus, unretained is fine.
    file_download_closure_ = base::BarrierClosure(
        2, base::BindOnce(
               &FetchRecoveryKeyStoreCertificatesRequest::OnDownloadComplete,
               base::Unretained(this)));
    cert_xml_loader_ =
        Fetch(kRecoveryKeyStoreCertFileUrl,
              base::BindOnce(
                  &FetchRecoveryKeyStoreCertificatesRequest::OnFileReceived,
                  base::Unretained(this), &cert_xml_));
    sig_xml_loader_ =
        Fetch(kRecoveryKeyStoreSigFileUrl,
              base::BindOnce(
                  &FetchRecoveryKeyStoreCertificatesRequest::OnFileReceived,
                  base::Unretained(this), &sig_xml_));
  }

 private:
  // Fetches `url` and runs `callback` when done.
  std::unique_ptr<network::SimpleURLLoader> Fetch(
      const std::string_view url,
      base::OnceCallback<void(std::optional<std::string>)> callback) {
    auto network_request = std::make_unique<network::ResourceRequest>();
    GURL request_url(url);
    CHECK(request_url.is_valid());
    network_request->url = std::move(request_url);

    auto loader = network::SimpleURLLoader::Create(std::move(network_request),
                                                   kCertXmlTrafficAnnotation);
    loader->SetTimeoutDuration(base::Seconds(10));
    loader->SetURLLoaderFactoryOptions(
        network::mojom::kURLLoadOptionBlockAllCookies);
    loader->DownloadToString(url_loader_factory_.get(), std::move(callback),
                             kMaxRecoveryKeyStoreCertFetchBodyBytes);
    return loader;
  }

  // Called after a fetch request finishes.
  void OnFileReceived(std::string* destination,
                      std::optional<std::string> file) {
    if (!file) {
      FinishRequestAndMaybeDestroySelf(base::unexpected(
          RecoveryKeyStoreCertificateFetchStatus::kNetworkError));
      return;
    }
    *destination = std::move(*file);
    file_download_closure_.Run();
  }

  // Called after both `sig_xml_` and `cert_xml_` have been downloaded.
  void OnDownloadComplete() {
    std::optional<RecoveryKeyStoreCertificate> certificate =
        RecoveryKeyStoreCertificate::Parse(cert_xml_, sig_xml_, clock_->Now());
    if (certificate) {
      FinishRequestAndMaybeDestroySelf(std::move(*certificate));
      return;
    }
    FinishRequestAndMaybeDestroySelf(
        base::unexpected(RecoveryKeyStoreCertificateFetchStatus::kParseError));
  }

  void FinishRequestAndMaybeDestroySelf(
      base::expected<RecoveryKeyStoreCertificate,
                     RecoveryKeyStoreCertificateFetchStatus> result) {
    RecoveryKeyStoreCertificatesFetchStatusForUMA status =
        RecoveryKeyStoreCertificatesFetchStatusForUMA::kSuccess;
    if (!result.has_value()) {
      switch (result.error()) {
        case RecoveryKeyStoreCertificateFetchStatus::kNetworkError:
          status = RecoveryKeyStoreCertificatesFetchStatusForUMA::kNetworkError;
          break;
        case RecoveryKeyStoreCertificateFetchStatus::kParseError:
          status = RecoveryKeyStoreCertificatesFetchStatusForUMA::kParseError;
          break;
        case RecoveryKeyStoreCertificateFetchStatus::kSuccess:
          NOTREACHED();
      }
    }
    RecordRecoveryKeyStoreFetchCertificatesStatus(status);
    std::move(callback_).Run(std::move(result));
  }

  raw_ptr<base::Clock> clock_;
  scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory_;
  RecoveryKeyStoreConnection::FetchRecoveryKeyStoreCertificatesCallback
      callback_;
  base::RepeatingClosure file_download_closure_;
  std::unique_ptr<network::SimpleURLLoader> cert_xml_loader_;
  std::unique_ptr<network::SimpleURLLoader> sig_xml_loader_;
  std::string cert_xml_;
  std::string sig_xml_;
};

}  // namespace

RecoveryKeyStoreEntry::RecoveryKeyStoreEntry() = default;
RecoveryKeyStoreEntry::RecoveryKeyStoreEntry(RecoveryKeyStoreEntry&&) = default;
RecoveryKeyStoreEntry& RecoveryKeyStoreEntry::operator=(
    RecoveryKeyStoreEntry&&) = default;
RecoveryKeyStoreEntry::~RecoveryKeyStoreEntry() = default;
bool RecoveryKeyStoreEntry::operator==(const RecoveryKeyStoreEntry&) const =
    default;

RecoveryKeyStoreConnectionImpl::RecoveryKeyStoreConnectionImpl(
    std::unique_ptr<network::PendingSharedURLLoaderFactory>
        pending_url_loader_factory,
    std::unique_ptr<TrustedVaultAccessTokenFetcher> access_token_fetcher)
    : pending_url_loader_factory_(std::move(pending_url_loader_factory)),
      access_token_fetcher_(std::move(access_token_fetcher)) {}

RecoveryKeyStoreConnectionImpl::~RecoveryKeyStoreConnectionImpl() = default;

std::unique_ptr<RecoveryKeyStoreConnectionImpl::Request>
RecoveryKeyStoreConnectionImpl::UpdateRecoveryKeyStore(
    const CoreAccountInfo& account_info,
    const trusted_vault_pb::Vault& vault,
    UpdateRecoveryKeyStoreCallback callback) {
  TrustedVaultRequest::RecordFetchStatusCallback record_fetch_status_to_uma =
      base::BindRepeating(
          &RecordRecoveryKeyStoreURLFetchResponse,
          RecoveryKeyStoreURLFetchReasonForUMA::kUpdateRecoveryKeyStore);
  auto request = std::make_unique<TrustedVaultRequest>(
      SecurityDomainId::kPasskeys, account_info.account_id,
      TrustedVaultRequest::HttpMethod::kPatch, GURL(kUpdateVaultUrl),
      vault.SerializeAsString(),
      /*max_retry_duration=*/base::Seconds(0), URLLoaderFactory(),
      access_token_fetcher_->Clone(), std::move(record_fetch_status_to_uma));
  request->FetchAccessTokenAndSendRequest(
      base::BindOnce(&ProcessUpdateVaultResponseResponse, std::move(callback)));
  return request;
}

std::unique_ptr<RecoveryKeyStoreConnectionImpl::Request>
RecoveryKeyStoreConnectionImpl::ListRecoveryKeyStores(
    const CoreAccountInfo& account_info,
    ListRecoveryKeyStoresCallback callback) {
  return std::make_unique<ListRecoveryKeyStoresRequest>(
      account_info, URLLoaderFactory(), access_token_fetcher_->Clone(),
      std::move(callback));
}

std::unique_ptr<RecoveryKeyStoreConnectionImpl::Request>
RecoveryKeyStoreConnectionImpl::FetchRecoveryKeyStoreCertificates(
    base::Clock* clock,
    FetchRecoveryKeyStoreCertificatesCallback callback) {
  return std::make_unique<FetchRecoveryKeyStoreCertificatesRequest>(
      clock, URLLoaderFactory(), std::move(callback));
}

scoped_refptr<network::SharedURLLoaderFactory>
RecoveryKeyStoreConnectionImpl::URLLoaderFactory() {
  // `url_loader_factory_` is created lazily, because it needs to be done on
  // the backend sequence, while this class ctor is called on UI thread.
  if (!url_loader_factory_) {
    CHECK(pending_url_loader_factory_);
    url_loader_factory_ = network::SharedURLLoaderFactory::Create(
        std::move(pending_url_loader_factory_));
  }
  return url_loader_factory_;
}

}  // namespace trusted_vault