File: gpm_enclave_controller.h

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 (430 lines) | stat: -rw-r--r-- 16,287 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
// 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.

#ifndef CHROME_BROWSER_WEBAUTHN_GPM_ENCLAVE_CONTROLLER_H_
#define CHROME_BROWSER_WEBAUTHN_GPM_ENCLAVE_CONTROLLER_H_

#include <cstdint>
#include <memory>
#include <optional>
#include <string>
#include <vector>

#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
#include "base/memory/weak_ptr.h"
#include "base/scoped_observation.h"
#include "base/time/tick_clock.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "build/build_config.h"
#include "chrome/browser/webauthn/authenticator_request_dialog_model.h"
#include "chrome/browser/webauthn/enclave_manager.h"
#include "chrome/browser/webauthn/gpm_enclave_transaction.h"
#include "components/trusted_vault/trusted_vault_connection.h"
#include "content/public/browser/document_user_data.h"
#include "content/public/browser/global_routing_id.h"
#include "google_apis/gaia/gaia_id.h"

namespace base {
class TickClock;
class SequencedTaskRunner;
}  // namespace base

namespace content {
class RenderFrameHost;
class WebContents;
}  // namespace content

namespace device {
class FidoDiscoveryFactory;
enum class FidoRequestType : uint8_t;
enum class UserVerificationRequirement;
namespace enclave {
struct CredentialRequest;
}  // namespace enclave
}  // namespace device

namespace sync_pb {
class WebauthnCredentialSpecifics;
}  // namespace sync_pb

namespace trusted_vault {
class ICloudRecoveryKey;
}  // namespace trusted_vault

enum class EnclaveEnabledStatus;
class Profile;

// Provides a TrustedVaultConnection for a given RenderFrameHost.
// This allows tests to override the connection used by GPMEnclaveController.
class GpmTrustedVaultConnectionProvider
    : public content::DocumentUserData<GpmTrustedVaultConnectionProvider> {
 public:
  ~GpmTrustedVaultConnectionProvider() override;

  // Sets a TrustedVaultConnection override for the document associated with
  // `rfh`. The next call to GetConnectionForFrame for this document will
  // return this override.
  static void SetOverrideForFrame(
      content::RenderFrameHost* rfh,
      std::unique_ptr<trusted_vault::TrustedVaultConnection>
          connection_override);

  // Returns a TrustedVaultConnection for the document associated with `rfh`.
  // If an override has been set via SetOverrideForFrame, that override is
  // returned (and ownership is transferred). Otherwise, a new default
  // TrustedVaultConnection is created. That connection is not associated with
  // any particular document.
  static std::unique_ptr<trusted_vault::TrustedVaultConnection> GetConnection(
      content::RenderFrameHost* rfh,
      signin::IdentityManager* identity_manager,
      scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory);

 private:
  explicit GpmTrustedVaultConnectionProvider(content::RenderFrameHost* rfh);

  friend class content::DocumentUserData<GpmTrustedVaultConnectionProvider>;
  DOCUMENT_USER_DATA_KEY_DECL();

  std::unique_ptr<trusted_vault::TrustedVaultConnection> connection_override_;
};

class GpmTickAndTaskRunnerProvider
    : public content::DocumentUserData<GpmTickAndTaskRunnerProvider> {
 public:
  ~GpmTickAndTaskRunnerProvider() override;

  // Sets a TickClock and SequencedTaskRunner override for the document
  // associated with |rfh|. The next call to GetConnectionForFrame for this
  // document will return this override.
  static void SetOverrideForFrame(
      content::RenderFrameHost* rfh,
      base::TickClock const* tick_clock,
      scoped_refptr<base::SequencedTaskRunner> task_runner);

  // Returns the TickClock for the document associated with `rfh` if an override
  // has been set via SetOverrideForFrame. Otherwise, the default TickClock is
  // returned.
  static base::TickClock const* GetTickClock(content::RenderFrameHost* rfh);

  // Returns the SequencedTaskRunner for the document associated with `rfh` if
  // an override has been set via SetOverrideForFrame. Otherwise, nullptr` is
  // returned.
  static scoped_refptr<base::SequencedTaskRunner> GetTaskRunner(
      content::RenderFrameHost* rfh);

 private:
  explicit GpmTickAndTaskRunnerProvider(content::RenderFrameHost* rfh);
  friend class content::DocumentUserData<GpmTickAndTaskRunnerProvider>;
  DOCUMENT_USER_DATA_KEY_DECL();

  raw_ptr<base::TickClock const> tick_clock_;
  scoped_refptr<base::SequencedTaskRunner> task_runner_;
};

class GPMEnclaveController : public AuthenticatorRequestDialogModel::Observer,
                             public EnclaveManager::Observer,
                             public GPMEnclaveTransaction::Delegate {
 public:
  static constexpr base::TimeDelta kDownloadAccountStateTimeout =
      base::Seconds(1);
  static constexpr base::TimeDelta kLoadingTimeout = base::Milliseconds(500);

  enum class AccountState {
    // There isn't a primary account, or enclave support is disabled.
    kNone,
    // The enclave state is still being loaded from disk.
    kLoading,
    // The state of the account is unknown pending network requests.
    kChecking,
    // The account can be recovered via user action.
    kRecoverable,
    // The account cannot be recovered, but could be reset.
    kIrrecoverable,
    // The security domain is empty.
    kEmpty,
    // The enclave is ready to use.
    kReady,
  };

  enum class AccountReadyState {
    kNotReady,
    kLoading,
    kReady,
  };

  explicit GPMEnclaveController(
      content::RenderFrameHost* render_frame_host,
      AuthenticatorRequestDialogModel* model,
      const std::string& rp_id,
      device::FidoRequestType request_type,
      device::UserVerificationRequirement user_verification_requirement);
  GPMEnclaveController(const GPMEnclaveController&) = delete;
  GPMEnclaveController& operator=(const GPMEnclaveController&) = delete;
  GPMEnclaveController(GPMEnclaveController&&) = delete;
  GPMEnclaveController& operator=(GPMEnclaveController&&) = delete;
  ~GPMEnclaveController() override;

  // Determines the enclave user verification early depending on the enclave
  // state and UV requirements. Can return `std::nullopt` if the enclave is not
  // ready. This is used for immediate mode requests.
  std::optional<EnclaveUserVerificationMethod>
  GetEnclaveUserVerificationMethod();

  // Returns true if the enclave is active for this request. Crashes the address
  // space if this hasn't yet been resolved.
  bool is_active() const;

  // Returns true if the enclave state is loaded to the point where the UI
  // can be shown. If false, then the `OnReadyForUI` event will be triggered
  // on the model when ready.
  bool ready_for_ui() const;

  // Configures an WebAuthn enclave authenticator discovery and provides it with
  // synced passkeys.
  void ConfigureDiscoveries(device::FidoDiscoveryFactory* discovery_factory);

  // Fetch the set of GPM passkeys for this request.
  const std::vector<sync_pb::WebauthnCredentialSpecifics>& creds() const;

  AccountState account_state_for_testing() const;

  // Returns the ready state of the account.
  AccountReadyState account_ready_state() const;
  // Runs `callback` once the account state is no longer `kLoading` or
  // `kChecking`. If it's already in such a state, runs it immediately.
  void RunWhenAccountReady(base::OnceClosure callback);

  base::RepeatingCallback<
      void(std::unique_ptr<device::enclave::CredentialRequest>)>&
  enclave_request_callback_for_testing() {
    return enclave_request_callback_;
  }

 private:
  // GPMEnclaveTransaction::Delegate:
  void HandleEnclaveTransactionError() override;
  void BuildUVKeyOptions(EnclaveManager::UVKeyOptions& options) override;
  void HandlePINValidationResult(
      device::enclave::PINValidationResult result) override;
  void OnPasskeyCreated(
      const sync_pb::WebauthnCredentialSpecifics& passkey) override;
  EnclaveUserVerificationMethod GetUvMethod() override;

  Profile* GetProfile() const;

  void OnUVCapabilityKnown(bool can_create_uv_keys);

  // Called when the EnclaveManager has finished loading its state from the
  // disk.
  void OnEnclaveLoaded();

  // Starts downloading the state of the account from the security domain
  // service.
  void DownloadAccountState();

  // Called when fetching the account state took too long.
  void OnAccountStateTimeOut();

  // Called when fetching the account state received partial data from the
  // server.
  void OnAccountStateKeepAlive();

  // Called when the account state has finished downloading.
  void OnAccountStateDownloaded(
      GaiaId gaia_id,
      std::unique_ptr<trusted_vault::TrustedVaultConnection> unused,
      trusted_vault::DownloadAuthenticationFactorsRegistrationStateResult
          result);

  // Called when enough state has been loaded that the initial UI can be shown.
  // If `kEnabled` then the enclave will be a valid mechanism.
  void SetActive(EnclaveEnabledStatus enclave_enabled_status);

  // EnclaveManager::Observer:
  void OnKeysStored() override;

  // Called when the local device has been added to the security domain.
  void OnDeviceAdded(bool success);

  // Initiates recovery from an iCloud keychain recovery key or MagicArch
  // depending on availability.
  void RecoverSecurityDomain();

#if BUILDFLAG(IS_MAC)
  // Enrolls an iCloud keychain recovery factor if available and needed.
  void MaybeAddICloudRecoveryKey();

  // Called when Chrome has retrieved the iCloud recovery keys present in the
  // current device.
  void OnICloudKeysRetrievedForEnrollment(
      std::vector<std::unique_ptr<trusted_vault::ICloudRecoveryKey>>
          local_icloud_keys);

  // Enrolls a specific iCloud keychain recovery key. |key| may be null, in
  // which case we skip to the next step.
  void EnrollICloudRecoveryKey(
      std::unique_ptr<trusted_vault::ICloudRecoveryKey> key);

  // Called when Chrome has retrieved the iCloud recovery keys present in the
  // current device.
  void OnICloudKeysRetrievedForRecovery(
      std::vector<std::unique_ptr<trusted_vault::ICloudRecoveryKey>>
          local_icloud_keys);
#endif  // BUILDFLAG(IS_MAC)

  // Called when the enclave enrollment is complete.
  void OnEnclaveAccountSetUpComplete();

  // Called when the EnclaveManager has finished loading. Sets `account_state_`
  // and progresses the flow if waiting.
  void SetAccountState(AccountState account_state);

  // Called when the user selects Google Password Manager from the list of
  // mechanisms. (Or when it's the priority mechanism.)
  void OnGPMSelected() override;

  // Called when a GPM passkey is selected from a list of credentials.
  void OnGPMPasskeySelected(std::vector<uint8_t> credential_id) override;

  // Sets the UI to the correct PIN prompt for the type of PIN configured.
  void PromptForPin();

  // Called when the user completes forgot pin flow.
  void OnGpmPinChanged(bool success);

  // Called when the user selects a GPM option, but the enclave is still loading
  // or the account data hasn't finished downloading yet.
  void OnGpmSelectedWhileLoading();

  // Called when the enclave is still loading and |loading_timeout_| is
  // triggered.
  void OnLoadingTimeout();

  // AuthenticatorRequestDialogModel::Observer:
  void OnTrustThisComputer() override;
  void OnGPMPinOptionChanged(bool is_arbitrary) override;
  void OnGPMCreatePasskey() override;
  void OnGPMConfirmOffTheRecordCreate() override;
  void OnGPMPinEntered(const std::u16string& pin) override;
  void OnTouchIDComplete(bool success) override;
  void OnForgotGPMPinPressed() override;
  void OnReauthComplete(std::string rapt) override;
  void OnGpmPasskeysReset(bool success) override;

  // Starts a create() or get() action with the enclave.
  void StartTransaction();

  // Accessors for the profile pref that counts the number of consecutive failed
  // PIN attempts to know when a lockout will happen.
  int GetFailedPINAttemptCount();
  void SetFailedPINAttemptCount(int count);

  // BrowserIsApp returns true if the current `Browser` is `TYPE_APP`. (I.e. a
  // PWA.)
  bool BrowserIsApp() const;

  content::WebContents* web_contents() const;

  const content::GlobalRenderFrameHostId render_frame_host_id_;
  const std::string rp_id_;
  const device::FidoRequestType request_type_;
  const device::UserVerificationRequirement user_verification_requirement_;

  // The `EnclaveManager` is a `KeyedService` for the current profile and so
  // outlives this object.
  const raw_ptr<EnclaveManager> enclave_manager_;

  // This is owned by the ChromeAuthenticatorRequestDelegate, which also owns
  // this object.
  const raw_ptr<AuthenticatorRequestDialogModel> model_;

  base::ScopedObservation<AuthenticatorRequestDialogModel,
                          AuthenticatorRequestDialogModel::Observer>
      model_observer_{this};
  base::ScopedObservation<EnclaveManager, EnclaveManager::Observer>
      enclave_manager_observer_{this};

  AccountState account_state_ = AccountState::kNone;
  bool pin_is_arbitrary_ = false;
  std::optional<std::string> pin_;
  std::vector<sync_pb::WebauthnCredentialSpecifics> creds_;

  // The user verification that will be performed for this request.
  std::optional<EnclaveUserVerificationMethod> uv_method_;

  std::optional<bool> is_active_;

  // Whether the system can make UV keys.
  std::optional<bool> can_make_uv_keys_;

  // have_added_device_ is set to true if the local device was added to the
  // security domain during this transaction. In this case, the security domain
  // secret is available and can be used to satisfy user verification.
  bool have_added_device_ = false;

  // The ID of the selected credential when doing a get().
  std::optional<std::vector<uint8_t>> selected_cred_id_;

  // Contains the bytes of a WrappedPIN structure, downloaded from the security
  // domain service. This is only set if the PIN is usable for recovery.
  std::optional<trusted_vault::GpmPinMetadata> pin_metadata_;

  // The list of iCloud recovery key members known to the security domain
  // service.
  std::vector<trusted_vault::VaultMember> security_domain_icloud_recovery_keys_;

  // |recovered_with_icloud_keychain_| is true if this controller performed a
  // successful recovery from iCloud keychain. This is reset on OnKeysStored().
  bool recovered_with_icloud_keychain_ = false;

  // The pending request to fetch the state of the trusted vault.
  std::unique_ptr<trusted_vault::TrustedVaultConnection::Request>
      download_account_state_request_;

  std::unique_ptr<GPMEnclaveTransaction> pending_enclave_transaction_;

  // The callback used to trigger a request to the enclave.
  base::RepeatingCallback<void(
      std::unique_ptr<device::enclave::CredentialRequest>)>
      enclave_request_callback_;

  // Whether the initial UI is being blocked while enclave state is loaded.
  bool ready_for_ui_ = false;

  // Whether showing the UI was delayed because the result from the security
  // domain service is needed.
  base::OnceClosure waiting_for_account_state_;

  // If changing a GPM PIN, this holds a ReAuthentication Proof Token (RAPT), if
  // the user is authenticating the request via doing a GAIA reauth.
  std::optional<std::string> rapt_ = std::nullopt;

  // A timeout to prevent waiting for the security domain service forever.
  std::unique_ptr<base::OneShotTimer> account_state_timeout_;

  // A timeout to prevent waiting for the enclave to load forever. If triggered
  // while still loading, the user is sent to the mechanism selection screen.
  // Loading the enclave and downloading account data are not interrupted.
  base::OneShotTimer loading_timeout_;

  // Set to true when the user initiates reset GPM pin flow during UV.
  bool changing_gpm_pin_ = false;

  // Records when the user has confirmed credential creation in an Incognito
  // context.
  bool off_the_record_confirmed_ = false;

  // Whether the user confirmed GPM PIN creation in the flow.
  bool gpm_pin_creation_confirmed_ = false;

  // The gaia id of the user at the time the account state was downloaded.
  GaiaId user_gaia_id_;

  base::WeakPtrFactory<GPMEnclaveController> weak_ptr_factory_{this};
};

#endif  // CHROME_BROWSER_WEBAUTHN_GPM_ENCLAVE_CONTROLLER_H_