1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/signin/mutable_profile_oauth2_token_service_delegate.h"
7 #include "base/profiler/scoped_tracker.h"
8 #include "components/signin/core/browser/signin_client.h"
9 #include "components/signin/core/browser/signin_metrics.h"
10 #include "components/signin/core/browser/webdata/token_web_data.h"
11 #include "components/webdata/common/web_data_service_base.h"
12 #include "google_apis/gaia/gaia_auth_fetcher.h"
13 #include "google_apis/gaia/gaia_auth_util.h"
14 #include "google_apis/gaia/gaia_constants.h"
15 #include "google_apis/gaia/oauth2_access_token_fetcher_immediate_error.h"
16 #include "google_apis/gaia/oauth2_access_token_fetcher_impl.h"
17 #include "net/url_request/url_request_context_getter.h"
21 const char kAccountIdPrefix
[] = "AccountId-";
22 const size_t kAccountIdPrefixLength
= 10;
24 std::string
ApplyAccountIdPrefix(const std::string
& account_id
) {
25 return kAccountIdPrefix
+ account_id
;
28 bool IsLegacyRefreshTokenId(const std::string
& service_id
) {
29 return service_id
== GaiaConstants::kGaiaOAuth2LoginRefreshToken
;
32 bool IsLegacyServiceId(const std::string
& account_id
) {
33 return account_id
.compare(0u, kAccountIdPrefixLength
, kAccountIdPrefix
) != 0;
36 std::string
RemoveAccountIdPrefix(const std::string
& prefixed_account_id
) {
37 return prefixed_account_id
.substr(kAccountIdPrefixLength
);
42 // This class sends a request to GAIA to revoke the given refresh token from
43 // the server. This is a best effort attempt only. This class deletes itself
44 // when done sucessfully or otherwise.
45 class MutableProfileOAuth2TokenServiceDelegate::RevokeServerRefreshToken
46 : public GaiaAuthConsumer
{
48 RevokeServerRefreshToken(
49 MutableProfileOAuth2TokenServiceDelegate
* token_service_delegate
,
50 const std::string
& account_id
);
51 ~RevokeServerRefreshToken() override
;
54 // GaiaAuthConsumer overrides:
55 void OnOAuth2RevokeTokenCompleted() override
;
57 MutableProfileOAuth2TokenServiceDelegate
* token_service_delegate_
;
58 GaiaAuthFetcher fetcher_
;
60 DISALLOW_COPY_AND_ASSIGN(RevokeServerRefreshToken
);
63 MutableProfileOAuth2TokenServiceDelegate::RevokeServerRefreshToken::
64 RevokeServerRefreshToken(
65 MutableProfileOAuth2TokenServiceDelegate
* token_service_delegate
,
66 const std::string
& refresh_token
)
67 : token_service_delegate_(token_service_delegate
),
69 GaiaConstants::kChromeSource
,
70 token_service_delegate_
->GetRequestContext()) {
71 fetcher_
.StartRevokeOAuth2Token(refresh_token
);
74 MutableProfileOAuth2TokenServiceDelegate::RevokeServerRefreshToken::
75 ~RevokeServerRefreshToken() {
78 void MutableProfileOAuth2TokenServiceDelegate::RevokeServerRefreshToken::
79 OnOAuth2RevokeTokenCompleted() {
80 // |this| pointer will be deleted when removed from the vector, so don't
81 // access any members after call to erase().
82 token_service_delegate_
->server_revokes_
.erase(
83 std::find(token_service_delegate_
->server_revokes_
.begin(),
84 token_service_delegate_
->server_revokes_
.end(), this));
87 MutableProfileOAuth2TokenServiceDelegate::AccountInfo::AccountInfo(
88 SigninErrorController
* signin_error_controller
,
89 const std::string
& account_id
,
90 const std::string
& refresh_token
)
91 : signin_error_controller_(signin_error_controller
),
92 account_id_(account_id
),
93 refresh_token_(refresh_token
),
94 last_auth_error_(GoogleServiceAuthError::NONE
) {
95 DCHECK(signin_error_controller_
);
96 DCHECK(!account_id_
.empty());
97 signin_error_controller_
->AddProvider(this);
100 MutableProfileOAuth2TokenServiceDelegate::AccountInfo::~AccountInfo() {
101 signin_error_controller_
->RemoveProvider(this);
104 void MutableProfileOAuth2TokenServiceDelegate::AccountInfo::SetLastAuthError(
105 const GoogleServiceAuthError
& error
) {
106 if (error
.state() != last_auth_error_
.state()) {
107 last_auth_error_
= error
;
108 signin_error_controller_
->AuthStatusChanged();
113 MutableProfileOAuth2TokenServiceDelegate::AccountInfo::GetAccountId() const {
117 GoogleServiceAuthError
118 MutableProfileOAuth2TokenServiceDelegate::AccountInfo::GetAuthStatus() const {
119 return last_auth_error_
;
122 MutableProfileOAuth2TokenServiceDelegate::
123 MutableProfileOAuth2TokenServiceDelegate(
124 SigninClient
* client
,
125 SigninErrorController
* signin_error_controller
,
126 AccountTrackerService
* account_tracker_service
)
127 : web_data_service_request_(0),
128 backoff_entry_(&backoff_policy_
),
129 backoff_error_(GoogleServiceAuthError::NONE
),
131 signin_error_controller_(signin_error_controller
),
132 account_tracker_service_(account_tracker_service
) {
133 VLOG(1) << "MutablePO2TS::MutablePO2TS";
135 DCHECK(signin_error_controller
);
136 // It's okay to fill the backoff policy after being used in construction.
137 backoff_policy_
.num_errors_to_ignore
= 0;
138 backoff_policy_
.initial_delay_ms
= 1000;
139 backoff_policy_
.multiply_factor
= 2.0;
140 backoff_policy_
.jitter_factor
= 0.2;
141 backoff_policy_
.maximum_backoff_ms
= 15 * 60 * 1000;
142 backoff_policy_
.entry_lifetime_ms
= -1;
143 backoff_policy_
.always_use_initial_delay
= false;
146 MutableProfileOAuth2TokenServiceDelegate::
147 ~MutableProfileOAuth2TokenServiceDelegate() {
148 VLOG(1) << "MutablePO2TS::~MutablePO2TS";
149 DCHECK(server_revokes_
.empty());
152 OAuth2AccessTokenFetcher
*
153 MutableProfileOAuth2TokenServiceDelegate::CreateAccessTokenFetcher(
154 const std::string
& account_id
,
155 net::URLRequestContextGetter
* getter
,
156 OAuth2AccessTokenConsumer
* consumer
) {
157 ValidateAccountId(account_id
);
158 // check whether the account has persistent error.
159 if (refresh_tokens_
[account_id
]->GetAuthStatus().IsPersistentError()) {
160 VLOG(1) << "Request for token has been rejected due to persistent error #"
161 << refresh_tokens_
[account_id
]->GetAuthStatus().state();
162 return new OAuth2AccessTokenFetcherImmediateError(
163 consumer
, refresh_tokens_
[account_id
]->GetAuthStatus());
165 if (backoff_entry_
.ShouldRejectRequest()) {
166 VLOG(1) << "Request for token has been rejected due to backoff rules from"
167 << " previous error #" << backoff_error_
.state();
168 return new OAuth2AccessTokenFetcherImmediateError(consumer
, backoff_error_
);
170 std::string refresh_token
= GetRefreshToken(account_id
);
171 DCHECK(!refresh_token
.empty());
172 return new OAuth2AccessTokenFetcherImpl(consumer
, getter
, refresh_token
);
175 void MutableProfileOAuth2TokenServiceDelegate::UpdateAuthError(
176 const std::string
& account_id
,
177 const GoogleServiceAuthError
& error
) {
178 VLOG(1) << "MutablePO2TS::UpdateAuthError. Error: " << error
.state();
179 backoff_entry_
.InformOfRequest(!error
.IsTransientError());
180 ValidateAccountId(account_id
);
182 // Do not report connection errors as these are not actually auth errors.
183 // We also want to avoid masking a "real" auth error just because we
184 // subsequently get a transient network error. We do keep it around though
185 // to report for future requests being denied for "backoff" reasons.
186 if (error
.IsTransientError()) {
187 backoff_error_
= error
;
191 if (refresh_tokens_
.count(account_id
) == 0) {
192 // This could happen if the preferences have been corrupted (see
193 // http://crbug.com/321370). In a Debug build that would be a bug, but in a
194 // Release build we want to deal with it gracefully.
198 refresh_tokens_
[account_id
]->SetLastAuthError(error
);
201 bool MutableProfileOAuth2TokenServiceDelegate::RefreshTokenIsAvailable(
202 const std::string
& account_id
) const {
203 VLOG(1) << "MutablePO2TS::RefreshTokenIsAvailable";
204 return !GetRefreshToken(account_id
).empty();
207 std::string
MutableProfileOAuth2TokenServiceDelegate::GetRefreshToken(
208 const std::string
& account_id
) const {
209 AccountInfoMap::const_iterator iter
= refresh_tokens_
.find(account_id
);
210 if (iter
!= refresh_tokens_
.end())
211 return iter
->second
->refresh_token();
212 return std::string();
215 std::vector
<std::string
>
216 MutableProfileOAuth2TokenServiceDelegate::GetAccounts() {
217 std::vector
<std::string
> account_ids
;
218 for (AccountInfoMap::const_iterator iter
= refresh_tokens_
.begin();
219 iter
!= refresh_tokens_
.end(); ++iter
) {
220 account_ids
.push_back(iter
->first
);
225 net::URLRequestContextGetter
*
226 MutableProfileOAuth2TokenServiceDelegate::GetRequestContext() const {
227 return client_
->GetURLRequestContext();
230 void MutableProfileOAuth2TokenServiceDelegate::LoadCredentials(
231 const std::string
& primary_account_id
) {
232 DCHECK(!primary_account_id
.empty());
233 ValidateAccountId(primary_account_id
);
234 DCHECK(loading_primary_account_id_
.empty());
235 DCHECK_EQ(0, web_data_service_request_
);
237 refresh_tokens_
.clear();
239 // If the account_id is an email address, then canonicalize it. This
240 // is to support legacy account_ids, and will not be needed after
241 // switching to gaia-ids.
242 if (primary_account_id
.find('@') != std::string::npos
) {
243 loading_primary_account_id_
= gaia::CanonicalizeEmail(primary_account_id
);
245 loading_primary_account_id_
= primary_account_id
;
248 scoped_refptr
<TokenWebData
> token_web_data
= client_
->GetDatabase();
249 if (token_web_data
.get())
250 web_data_service_request_
= token_web_data
->GetAllTokens(this);
253 void MutableProfileOAuth2TokenServiceDelegate::OnWebDataServiceRequestDone(
254 WebDataServiceBase::Handle handle
,
255 const WDTypedResult
* result
) {
256 VLOG(1) << "MutablePO2TS::OnWebDataServiceRequestDone. Result type: "
257 << (result
== nullptr ? -1 : (int)result
->GetType());
259 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460 is
261 tracked_objects::ScopedTracker
tracking_profile(
262 FROM_HERE_WITH_EXPLICIT_FUNCTION(
263 "422460 MutableProfileOAuth2Token...::OnWebDataServiceRequestDone"));
265 DCHECK_EQ(web_data_service_request_
, handle
);
266 web_data_service_request_
= 0;
269 DCHECK(result
->GetType() == TOKEN_RESULT
);
270 const WDResult
<std::map
<std::string
, std::string
>>* token_result
=
271 static_cast<const WDResult
<std::map
<std::string
, std::string
>>*>(
273 LoadAllCredentialsIntoMemory(token_result
->GetValue());
276 // Make sure that we have an entry for |loading_primary_account_id_| in the
277 // map. The entry could be missing if there is a corruption in the token DB
278 // while this profile is connected to an account.
279 DCHECK(!loading_primary_account_id_
.empty());
280 if (refresh_tokens_
.count(loading_primary_account_id_
) == 0) {
281 refresh_tokens_
[loading_primary_account_id_
].reset(new AccountInfo(
282 signin_error_controller_
, loading_primary_account_id_
, std::string()));
285 // If we don't have a refresh token for a known account, signal an error.
286 for (AccountInfoMap::const_iterator i
= refresh_tokens_
.begin();
287 i
!= refresh_tokens_
.end(); ++i
) {
288 if (!RefreshTokenIsAvailable(i
->first
)) {
289 UpdateAuthError(i
->first
,
290 GoogleServiceAuthError(
291 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS
));
296 loading_primary_account_id_
.clear();
299 void MutableProfileOAuth2TokenServiceDelegate::LoadAllCredentialsIntoMemory(
300 const std::map
<std::string
, std::string
>& db_tokens
) {
301 std::string old_login_token
;
304 ScopedBatchChange
batch(this);
306 VLOG(1) << "MutablePO2TS::LoadAllCredentialsIntoMemory; "
307 << db_tokens
.size() << " Credential(s).";
308 AccountTrackerService::AccountIdMigrationState migration_state
=
309 account_tracker_service_
->GetMigrationState();
310 for (std::map
<std::string
, std::string
>::const_iterator iter
=
312 iter
!= db_tokens
.end(); ++iter
) {
313 std::string prefixed_account_id
= iter
->first
;
314 std::string refresh_token
= iter
->second
;
316 if (IsLegacyRefreshTokenId(prefixed_account_id
) && !refresh_token
.empty())
317 old_login_token
= refresh_token
;
319 if (IsLegacyServiceId(prefixed_account_id
)) {
320 scoped_refptr
<TokenWebData
> token_web_data
= client_
->GetDatabase();
321 if (token_web_data
.get())
322 token_web_data
->RemoveTokenForService(prefixed_account_id
);
324 DCHECK(!refresh_token
.empty());
325 std::string account_id
= RemoveAccountIdPrefix(prefixed_account_id
);
327 if (migration_state
== AccountTrackerService::MIGRATION_IN_PROGRESS
) {
328 // Migrate to gaia-ids.
329 AccountTrackerService::AccountInfo account_info
=
330 account_tracker_service_
->FindAccountInfoByEmail(account_id
);
331 // |account_info.gaia| could be empty if |account_id| is already gaia
332 // id. This could happen if the chrome was closed in the middle of
334 if (!account_info
.gaia
.empty()) {
335 PersistCredentials(account_info
.gaia
, refresh_token
);
336 ClearPersistedCredentials(account_id
);
337 account_id
= account_info
.gaia
;
340 // Skip duplicate accounts, this could happen if migration was
341 // crashed in the middle.
342 if (refresh_tokens_
.count(account_id
) != 0)
346 // If the account_id is an email address, then canonicalize it. This
347 // is to support legacy account_ids, and will not be needed after
348 // switching to gaia-ids.
349 if (account_id
.find('@') != std::string::npos
) {
350 // If the canonical account id is not the same as the loaded
351 // account id, make sure not to overwrite a refresh token from
352 // a canonical version. If no canonical version was loaded, then
353 // re-persist this refresh token with the canonical account id.
354 std::string canon_account_id
= gaia::CanonicalizeEmail(account_id
);
355 if (canon_account_id
!= account_id
) {
356 ClearPersistedCredentials(account_id
);
357 if (db_tokens
.count(ApplyAccountIdPrefix(canon_account_id
)) == 0)
358 PersistCredentials(canon_account_id
, refresh_token
);
361 account_id
= canon_account_id
;
364 refresh_tokens_
[account_id
].reset(new AccountInfo(
365 signin_error_controller_
, account_id
, refresh_token
));
366 FireRefreshTokenAvailable(account_id
);
370 if (!old_login_token
.empty()) {
371 DCHECK(!loading_primary_account_id_
.empty());
372 if (refresh_tokens_
.count(loading_primary_account_id_
) == 0)
373 UpdateCredentials(loading_primary_account_id_
, old_login_token
);
377 FireRefreshTokensLoaded();
380 void MutableProfileOAuth2TokenServiceDelegate::UpdateCredentials(
381 const std::string
& account_id
,
382 const std::string
& refresh_token
) {
383 DCHECK(thread_checker_
.CalledOnValidThread());
384 DCHECK(!account_id
.empty());
385 DCHECK(!refresh_token
.empty());
386 ValidateAccountId(account_id
);
388 signin_metrics::LogSigninAddAccount();
390 bool refresh_token_present
= refresh_tokens_
.count(account_id
) > 0;
391 if (!refresh_token_present
||
392 refresh_tokens_
[account_id
]->refresh_token() != refresh_token
) {
393 ScopedBatchChange
batch(this);
395 // If token present, and different from the new one, cancel its requests,
396 // and clear the entries in cache related to that account.
397 if (refresh_token_present
) {
398 VLOG(1) << "MutablePO2TS::UpdateCredentials; Refresh Token was present. "
399 << "account_id=" << account_id
;
401 refresh_tokens_
[account_id
]->set_refresh_token(refresh_token
);
403 VLOG(1) << "MutablePO2TS::UpdateCredentials; Refresh Token was absent. "
404 << "account_id=" << account_id
;
405 refresh_tokens_
[account_id
].reset(
406 new AccountInfo(signin_error_controller_
, account_id
, refresh_token
));
409 // Save the token in memory and in persistent store.
410 PersistCredentials(account_id
, refresh_token
);
412 UpdateAuthError(account_id
, GoogleServiceAuthError::AuthErrorNone());
413 FireRefreshTokenAvailable(account_id
);
417 void MutableProfileOAuth2TokenServiceDelegate::PersistCredentials(
418 const std::string
& account_id
,
419 const std::string
& refresh_token
) {
420 scoped_refptr
<TokenWebData
> token_web_data
= client_
->GetDatabase();
421 if (token_web_data
.get()) {
422 VLOG(1) << "MutablePO2TS::PersistCredentials for account_id=" << account_id
;
423 token_web_data
->SetTokenForService(ApplyAccountIdPrefix(account_id
),
428 void MutableProfileOAuth2TokenServiceDelegate::RevokeAllCredentials() {
429 if (!client_
->CanRevokeCredentials())
431 DCHECK(thread_checker_
.CalledOnValidThread());
433 ScopedBatchChange
batch(this);
435 VLOG(1) << "MutablePO2TS::RevokeAllCredentials";
436 CancelWebTokenFetch();
437 AccountInfoMap tokens
= refresh_tokens_
;
438 for (AccountInfoMap::iterator i
= tokens
.begin(); i
!= tokens
.end(); ++i
)
439 RevokeCredentials(i
->first
);
441 DCHECK_EQ(0u, refresh_tokens_
.size());
443 // Make sure all tokens are removed.
444 scoped_refptr
<TokenWebData
> token_web_data
= client_
->GetDatabase();
445 if (token_web_data
.get())
446 token_web_data
->RemoveAllTokens();
449 void MutableProfileOAuth2TokenServiceDelegate::RevokeCredentials(
450 const std::string
& account_id
) {
451 ValidateAccountId(account_id
);
452 DCHECK(thread_checker_
.CalledOnValidThread());
454 if (refresh_tokens_
.count(account_id
) > 0) {
455 VLOG(1) << "MutablePO2TS::RevokeCredentials for account_id=" << account_id
;
456 ScopedBatchChange
batch(this);
457 RevokeCredentialsOnServer(refresh_tokens_
[account_id
]->refresh_token());
458 refresh_tokens_
.erase(account_id
);
459 ClearPersistedCredentials(account_id
);
460 FireRefreshTokenRevoked(account_id
);
464 void MutableProfileOAuth2TokenServiceDelegate::ClearPersistedCredentials(
465 const std::string
& account_id
) {
466 scoped_refptr
<TokenWebData
> token_web_data
= client_
->GetDatabase();
467 if (token_web_data
.get()) {
468 VLOG(1) << "MutablePO2TS::ClearPersistedCredentials for account_id="
470 token_web_data
->RemoveTokenForService(ApplyAccountIdPrefix(account_id
));
474 void MutableProfileOAuth2TokenServiceDelegate::RevokeCredentialsOnServer(
475 const std::string
& refresh_token
) {
476 // Keep track or all server revoke requests. This way they can be deleted
477 // before the token service is shutdown and won't outlive the profile.
478 server_revokes_
.push_back(new RevokeServerRefreshToken(this, refresh_token
));
481 void MutableProfileOAuth2TokenServiceDelegate::CancelWebTokenFetch() {
482 if (web_data_service_request_
!= 0) {
483 scoped_refptr
<TokenWebData
> token_web_data
= client_
->GetDatabase();
484 DCHECK(token_web_data
.get());
485 token_web_data
->CancelRequest(web_data_service_request_
);
486 web_data_service_request_
= 0;
490 void MutableProfileOAuth2TokenServiceDelegate::Shutdown() {
491 VLOG(1) << "MutablePO2TS::Shutdown";
492 server_revokes_
.clear();
493 CancelWebTokenFetch();
494 refresh_tokens_
.clear();