File: profile_picker_dice_reauth_provider.cc

package info (click to toggle)
chromium 139.0.7258.138-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,120,676 kB
  • sloc: cpp: 35,100,869; 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 (267 lines) | stat: -rw-r--r-- 11,588 bytes parent folder | download | duplicates (5)
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
// Copyright 2023 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/ui/views/profiles/profile_picker_dice_reauth_provider.h"

#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/metrics/histogram_functions.h"
#include "base/time/time.h"
#include "chrome/browser/profiles/keep_alive/profile_keep_alive_types.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/dice_response_handler.h"
#include "chrome/browser/signin/dice_tab_helper.h"
#include "chrome/browser/signin/force_signin_verifier.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/browser/signin/signin_promo.h"
#include "chrome/browser/ui/views/profiles/profile_management_types.h"
#include "chrome/browser/ui/views/profiles/profile_picker_view.h"
#include "chrome/browser/ui/views/profiles/profile_picker_web_contents_host.h"
#include "chrome/browser/ui/webui/signin/signin_ui_error.h"
#include "chrome/common/webui_url_constants.h"
#include "components/signin/public/identity_manager/accounts_mutator.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/web_contents.h"
#include "google_apis/gaia/gaia_id.h"
#include "google_apis/gaia/gaia_urls.h"

namespace {

void RecordReauthResult(ProfilePickerReauthResult result) {
  base::UmaHistogramEnumeration("ProfilePicker.ReauthResult", result);
}

GURL GetLoadingScreenURL() {
  GURL url = GURL(chrome::kChromeUISyncConfirmationURL);
  return url.Resolve(chrome::kChromeUISyncConfirmationLoadingPath);
}

ForceSigninUIError ComputeReauthUIError(ProfilePickerReauthResult result,
                                        const std::string& reauth_email) {
  switch (result) {
    case ProfilePickerReauthResult::kSuccess:
    case ProfilePickerReauthResult::kSuccessTokenAlreadyValid:
      return ForceSigninUIError::ErrorNone();
    case ProfilePickerReauthResult::kErrorUsedNewEmail:
    case ProfilePickerReauthResult::kErrorUsedOtherSignedInEmail:
      return ForceSigninUIError::ReauthWrongAccount(reauth_email);
    case ProfilePickerReauthResult::kTimeoutForceSigninVerifierCheck:
    case ProfilePickerReauthResult::kTimeoutSigninError:
      return ForceSigninUIError::ReauthTimeout();
  }
}

}  // namespace

ProfilePickerDiceReauthProvider::ProfilePickerDiceReauthProvider(
    ProfilePickerWebContentsHost* host,
    Profile* profile,
    const GaiaId& gaia_id_to_reauth,
    const std::string& email_to_reauth,
    base::OnceCallback<void(bool, const ForceSigninUIError&)>
        on_reauth_completed)
    : host_(*host),
      profile_(*profile),
      identity_manager_(*IdentityManagerFactory::GetForProfile(profile)),
      gaia_id_to_reauth_(gaia_id_to_reauth),
      email_to_reauth_(email_to_reauth),
      on_reauth_completed_(std::move(on_reauth_completed)) {
  DCHECK(!gaia_id_to_reauth_.empty());
  DCHECK(!email_to_reauth_.empty());
}

ProfilePickerDiceReauthProvider::~ProfilePickerDiceReauthProvider() = default;

void ProfilePickerDiceReauthProvider::SwitchToReauth(
    StepSwitchFinishedCallback step_switch_callback) {
  CHECK(!contents_);
  CHECK(!step_switch_callback->is_null());
  CHECK(step_switch_callback_->is_null());
  step_switch_callback_ = std::move(step_switch_callback);

  profile_keep_alive_ = std::make_unique<ScopedProfileKeepAlive>(
      &*profile_, ProfileKeepAliveOrigin::kProfileCreationFlow);
  scoped_identity_manager_observation_.Observe(&*identity_manager_);

  contents_ = content::WebContents::Create(
      content::WebContents::CreateParams(&*profile_));
  host_->ShowScreen(contents_.get(), GetLoadingScreenURL(),
                    /*navigation_finished_closure=*/base::OnceClosure());
  timer_.Start(
      FROM_HERE, base::Seconds(kDiceTokenFetchTimeoutSeconds),
      base::BindOnce(
          &ProfilePickerDiceReauthProvider::OnForceSigninVerifierTimeOut,
          base::Unretained(this)));

  // Attempt to create the `force_signin_verifier_` here, otherwise it will be
  // done after the refresh tokens are loaded in `OnRefreshTokensLoaded()`.
  // This is the first step to the reauth flow.
  TryCreateForceSigninVerifier();
}

void ProfilePickerDiceReauthProvider::OnRefreshTokensLoaded() {
  // If the verifier was not created before, we should create it now after the
  // refresh tokens were properly loaded.
  TryCreateForceSigninVerifier();
}

void ProfilePickerDiceReauthProvider::OnForceSigninVerifierTimeOut() {
  // TODO(crbug.com/40280498): Improve the error message if this timeout
  // occurs. Currently the error that will be displayed is the one that is shown
  // if the wrong account is being reauth-ed.
  Finish(false, ProfilePickerReauthResult::kTimeoutForceSigninVerifierCheck);
  std::move(step_switch_callback_.value()).Run(false);
}

void ProfilePickerDiceReauthProvider::TryCreateForceSigninVerifier() {
  if (!force_signin_verifier_ && identity_manager_->AreRefreshTokensLoaded()) {
    force_signin_verifier_ = std::make_unique<ForceSigninVerifier>(
        &*profile_, &*identity_manager_,
        base::BindOnce(&ProfilePickerDiceReauthProvider::OnTokenFetchComplete,
                       base::Unretained(this)));
  }
}

void ProfilePickerDiceReauthProvider::OnTokenFetchComplete(
    bool token_is_valid) {
  // Stop the timeout check for the ForceSigninVerifier. The response happened.
  timer_.Stop();

  // If the token is valid, we do not need to reauth and proceed to finish
  // with success directly.
  if (token_is_valid) {
    Finish(true, ProfilePickerReauthResult::kSuccessTokenAlreadyValid);
    std::move(step_switch_callback_.value()).Run(false);
    return;
  }

  ShowReauth();
}

void ProfilePickerDiceReauthProvider::ShowReauth() {
  // Recreating the web contents so that the loading screen is not part of the
  // history when pressing the back button.
  contents_ = content::WebContents::Create(
      content::WebContents::CreateParams(&*profile_));
  // Show the back button, the reactions are handled by the host itself.
  // Use the continue_url to know that the user finalized the reauth flow, in
  // case no refresh token were generated.
  GURL reauth_url = signin::GetChromeReauthURL(
      {.email = email_to_reauth_,
       .continue_url = GaiaUrls::GetInstance()->blank_page_url()});
  host_->ShowScreen(
      contents_.get(), reauth_url,
      base::BindOnce(&ProfilePickerWebContentsHost::SetNativeToolbarVisible,
                     // Unretained is enough as the callback is called by the
                     // host itself.
                     base::Unretained(host_), /*visible=*/true)
          .Then(
              base::BindOnce(std::move(step_switch_callback_.value()), true)));
  // Listen to the changes of the web contents to know if we got to the
  // `continue_url`.
  content::WebContentsObserver::Observe(contents());

  // Creating the DiceTabHelper to detect the new sign in events.
  // This will be used to make sure that the expected account is signed in, and
  // not using a potentially already existing signed in account.
  // On signout error, we proceed with a failure.
  DiceTabHelper::CreateForWebContents(contents());
  DiceTabHelper* tab_helper = DiceTabHelper::FromWebContents(contents());
  tab_helper->InitializeSigninFlow(
      reauth_url, signin_metrics::AccessPoint::kForcedSignin,
      signin_metrics::Reason::kReauthentication,
      signin_metrics::PromoAction::PROMO_ACTION_NO_SIGNIN_PROMO, GURL(), false,
      DiceTabHelper::EnableSyncCallback(),
      DiceTabHelper::EnableHistorySyncOptinCallback(),
      base::BindRepeating(
          &ProfilePickerDiceReauthProvider::OnDiceSigninHeaderReceived,
          base::Unretained(this)),
      base::BindRepeating(&ProfilePickerDiceReauthProvider::OnSigninError,
                          base::Unretained(this)));
}

void ProfilePickerDiceReauthProvider::OnDiceSigninHeaderReceived() {
  signin_event_received_ = true;
}

void ProfilePickerDiceReauthProvider::OnSigninError(
    Profile* profile,
    content::WebContents* web_contents,
    const SigninUIError& error) {
  Finish(false, ProfilePickerReauthResult::kTimeoutSigninError);
}

void ProfilePickerDiceReauthProvider::DidFinishNavigation(
    content::NavigationHandle* navigation_handle) {
  // If we get to the continue URL without exiting previously, then we wait for
  // potential valid refresh token. If by the delay set, we obtain no token we
  // consider it as a failure.
  // This case can happen when a user uses a previously signed in account
  // through the reauth Gaia page, no token will be emitted.
  GURL::Replacements replacements;
  replacements.ClearQuery();
  replacements.ClearRef();
  if (navigation_handle->GetURL().ReplaceComponents(replacements) ==
      GaiaUrls::GetInstance()->blank_page_url()) {
    content::WebContentsObserver::Observe(nullptr);
    host_->SetNativeToolbarVisible(false);

    // If no sign in event was received but we reached the continue URL, then
    // the user used an already signed in account to reauth. The reauth did not
    // happen with the right address. Proceed with a failure (keeping the
    // account signed in).
    if (!signin_event_received_) {
      Finish(false, ProfilePickerReauthResult::kErrorUsedOtherSignedInEmail);
      return;
    }

    // Otherwise we just wait for the refersh token to be valid with a timeout
    // check through the `DiceTabHelper` and the `ProcessDiceHeaderDelegateImpl`
    // after fetching the tokens.
    // Show a loading screen while waiting.
    host_->ShowScreen(contents_.get(), GetLoadingScreenURL(),
                      /*navigation_finished_closure=*/base::OnceClosure());
  }
}

void ProfilePickerDiceReauthProvider::OnRefreshTokenUpdatedForAccount(
    const CoreAccountInfo& account_info) {
  if (!identity_manager_->AreRefreshTokensLoaded() || !force_signin_verifier_) {
    return;
  }

  // Compare the account name that is being reauthed (since the account name can
  // be changed) with the one for which we received a refresh token to know if
  // the reauth was as expected or not.
  // The case where a user uses a previously signed in account which does not
  // generate a token is handled in `DidFinishNavigation()` with the help of the
  // `continue_url` and the `DiceTabHelper`.
  bool success = gaia_id_to_reauth_ == account_info.gaia;

  // If the email reauth-ed is not the same as the intended email, we do not
  // want the user to proceed with success. Since at this point this would be a
  // new sign in, the account should be signed out.
  if (!success) {
    identity_manager_->GetAccountsMutator()->RemoveAccount(
        account_info.account_id,
        signin_metrics::SourceForRefreshTokenOperation::
            kForceSigninReauthWithDifferentAccount);
  }

  Finish(success, success ? ProfilePickerReauthResult::kSuccess
                          : ProfilePickerReauthResult::kErrorUsedNewEmail);
}

void ProfilePickerDiceReauthProvider::Finish(bool success,
                                             ProfilePickerReauthResult result) {
  RecordReauthResult(result);
  scoped_identity_manager_observation_.Reset();
  content::WebContentsObserver::Observe(nullptr);
  // Hide the toolbar in case it was visible after showing the reauth page.
  host_->SetNativeToolbarVisible(false);

  ForceSigninUIError error = ComputeReauthUIError(result, email_to_reauth_);
  std::move(on_reauth_completed_).Run(success, error);
}