Only grant permissions to new extensions from sync if they have the expected version
[chromium-blink-merge.git] / chrome / browser / signin / mutable_profile_oauth2_token_service_delegate_unittest.cc
blob224c51468359f80a92c5243876255b80eaa53d9c
1 // Copyright 2014 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/command_line.h"
8 #include "base/run_loop.h"
9 #include "base/prefs/pref_registry_simple.h"
10 #include "base/prefs/scoped_user_pref_update.h"
11 #include "base/prefs/testing_pref_service.h"
12 #include "components/signin/core/browser/profile_oauth2_token_service.h"
13 #include "components/signin/core/browser/signin_error_controller.h"
14 #include "components/signin/core/browser/test_signin_client.h"
15 #include "components/signin/core/browser/webdata/token_web_data.h"
16 #include "components/signin/core/common/profile_management_switches.h"
17 #include "components/signin/core/common/signin_pref_names.h"
18 #include "google_apis/gaia/gaia_constants.h"
19 #include "google_apis/gaia/gaia_urls.h"
20 #include "google_apis/gaia/google_service_auth_error.h"
21 #include "google_apis/gaia/oauth2_access_token_consumer.h"
22 #include "google_apis/gaia/oauth2_token_service_test_util.h"
23 #include "net/http/http_status_code.h"
24 #include "net/url_request/test_url_fetcher_factory.h"
25 #include "testing/gtest/include/gtest/gtest.h"
27 #if defined(OS_MACOSX)
28 #include "components/os_crypt/os_crypt.h"
29 #endif
31 // Defining constant here to handle backward compatiblity tests, but this
32 // constant is no longer used in current versions of chrome.
33 static const char kLSOService[] = "lso";
34 static const char kEmail[] = "user@gmail.com";
36 class MutableProfileOAuth2TokenServiceDelegateTest
37 : public testing::Test,
38 public OAuth2AccessTokenConsumer,
39 public OAuth2TokenService::Observer {
40 public:
41 MutableProfileOAuth2TokenServiceDelegateTest()
42 : factory_(NULL),
43 access_token_success_count_(0),
44 access_token_failure_count_(0),
45 access_token_failure_(GoogleServiceAuthError::NONE),
46 token_available_count_(0),
47 token_revoked_count_(0),
48 tokens_loaded_count_(0),
49 start_batch_changes_(0),
50 end_batch_changes_(0) {}
52 void SetUp() override {
53 #if defined(OS_MACOSX)
54 OSCrypt::UseMockKeychain(true);
55 #endif
57 factory_.SetFakeResponse(GaiaUrls::GetInstance()->oauth2_revoke_url(), "",
58 net::HTTP_OK, net::URLRequestStatus::SUCCESS);
60 pref_service_.registry()->RegisterListPref(
61 AccountTrackerService::kAccountInfoPref);
62 pref_service_.registry()->RegisterIntegerPref(
63 prefs::kAccountIdMigrationState,
64 AccountTrackerService::MIGRATION_NOT_STARTED);
65 client_.reset(new TestSigninClient(&pref_service_));
66 client_->SetURLRequestContext(new net::TestURLRequestContextGetter(
67 base::ThreadTaskRunnerHandle::Get()));
68 client_->LoadTokenDatabase();
69 account_tracker_service_.Initialize(client_.get());
70 oauth2_service_delegate_.reset(new MutableProfileOAuth2TokenServiceDelegate(
71 client_.get(), &signin_error_controller_, &account_tracker_service_));
72 // Make sure PO2TS has a chance to load itself before continuing.
73 base::RunLoop().RunUntilIdle();
74 oauth2_service_delegate_->AddObserver(this);
77 void TearDown() override {
78 oauth2_service_delegate_->RemoveObserver(this);
79 oauth2_service_delegate_->Shutdown();
82 void AddAuthTokenManually(const std::string& service,
83 const std::string& value) {
84 scoped_refptr<TokenWebData> token_web_data = client_->GetDatabase();
85 if (token_web_data.get())
86 token_web_data->SetTokenForService(service, value);
89 // OAuth2AccessTokenConusmer implementation
90 void OnGetTokenSuccess(const std::string& access_token,
91 const base::Time& expiration_time) override {
92 ++access_token_success_count_;
95 void OnGetTokenFailure(const GoogleServiceAuthError& error) override {
96 ++access_token_failure_count_;
97 access_token_failure_ = error;
100 // OAuth2TokenService::Observer implementation.
101 void OnRefreshTokenAvailable(const std::string& account_id) override {
102 ++token_available_count_;
104 void OnRefreshTokenRevoked(const std::string& account_id) override {
105 ++token_revoked_count_;
107 void OnRefreshTokensLoaded() override { ++tokens_loaded_count_; }
109 void OnStartBatchChanges() override { ++start_batch_changes_; }
111 void OnEndBatchChanges() override { ++end_batch_changes_; }
113 void ResetObserverCounts() {
114 token_available_count_ = 0;
115 token_revoked_count_ = 0;
116 tokens_loaded_count_ = 0;
117 start_batch_changes_ = 0;
118 end_batch_changes_ = 0;
121 void ExpectNoNotifications() {
122 EXPECT_EQ(0, token_available_count_);
123 EXPECT_EQ(0, token_revoked_count_);
124 EXPECT_EQ(0, tokens_loaded_count_);
125 ResetObserverCounts();
128 void ExpectOneTokenAvailableNotification() {
129 EXPECT_EQ(1, token_available_count_);
130 EXPECT_EQ(0, token_revoked_count_);
131 EXPECT_EQ(0, tokens_loaded_count_);
132 ResetObserverCounts();
135 void ExpectOneTokenRevokedNotification() {
136 EXPECT_EQ(0, token_available_count_);
137 EXPECT_EQ(1, token_revoked_count_);
138 EXPECT_EQ(0, tokens_loaded_count_);
139 ResetObserverCounts();
142 void ExpectOneTokensLoadedNotification() {
143 EXPECT_EQ(0, token_available_count_);
144 EXPECT_EQ(0, token_revoked_count_);
145 EXPECT_EQ(1, tokens_loaded_count_);
146 ResetObserverCounts();
149 protected:
150 base::MessageLoop message_loop_;
151 net::FakeURLFetcherFactory factory_;
152 scoped_ptr<TestSigninClient> client_;
153 scoped_ptr<MutableProfileOAuth2TokenServiceDelegate> oauth2_service_delegate_;
154 TestingOAuth2TokenServiceConsumer consumer_;
155 SigninErrorController signin_error_controller_;
156 TestingPrefServiceSimple pref_service_;
157 AccountTrackerService account_tracker_service_;
158 int access_token_success_count_;
159 int access_token_failure_count_;
160 GoogleServiceAuthError access_token_failure_;
161 int token_available_count_;
162 int token_revoked_count_;
163 int tokens_loaded_count_;
164 int start_batch_changes_;
165 int end_batch_changes_;
168 TEST_F(MutableProfileOAuth2TokenServiceDelegateTest, PersistenceDBUpgrade) {
169 std::string main_account_id(kEmail);
170 std::string main_refresh_token("old_refresh_token");
172 // Populate DB with legacy tokens.
173 AddAuthTokenManually(GaiaConstants::kSyncService, "syncServiceToken");
174 AddAuthTokenManually(kLSOService, "lsoToken");
175 AddAuthTokenManually(GaiaConstants::kGaiaOAuth2LoginRefreshToken,
176 main_refresh_token);
178 switches::EnableAccountConsistencyForTesting(
179 base::CommandLine::ForCurrentProcess());
181 // Force LoadCredentials.
182 oauth2_service_delegate_->LoadCredentials(main_account_id);
183 base::RunLoop().RunUntilIdle();
185 // Legacy tokens get discarded, but the old refresh token is kept.
186 EXPECT_EQ(1, tokens_loaded_count_);
187 EXPECT_EQ(1, token_available_count_);
188 EXPECT_EQ(1, start_batch_changes_);
189 EXPECT_EQ(1, end_batch_changes_);
190 EXPECT_TRUE(
191 oauth2_service_delegate_->RefreshTokenIsAvailable(main_account_id));
192 EXPECT_EQ(1U, oauth2_service_delegate_->refresh_tokens_.size());
193 EXPECT_EQ(main_refresh_token,
194 oauth2_service_delegate_->refresh_tokens_[main_account_id]
195 ->refresh_token());
197 // Add an old legacy token to the DB, to ensure it will not overwrite existing
198 // credentials for main account.
199 AddAuthTokenManually(GaiaConstants::kGaiaOAuth2LoginRefreshToken,
200 "secondOldRefreshToken");
201 // Add some other legacy token. (Expected to get discarded).
202 AddAuthTokenManually(kLSOService, "lsoToken");
203 // Also add a token using PO2TS.UpdateCredentials and make sure upgrade does
204 // not wipe it.
205 std::string other_account_id("other_account_id");
206 std::string other_refresh_token("other_refresh_token");
207 oauth2_service_delegate_->UpdateCredentials(other_account_id,
208 other_refresh_token);
209 ResetObserverCounts();
211 // Force LoadCredentials.
212 oauth2_service_delegate_->LoadCredentials(main_account_id);
213 base::RunLoop().RunUntilIdle();
215 // Again legacy tokens get discarded, but since the main porfile account
216 // token is present it is not overwritten.
217 EXPECT_EQ(2, token_available_count_);
218 EXPECT_EQ(1, tokens_loaded_count_);
219 EXPECT_EQ(1, start_batch_changes_);
220 EXPECT_EQ(1, end_batch_changes_);
221 EXPECT_EQ(main_refresh_token,
222 oauth2_service_delegate_->GetRefreshToken(main_account_id));
223 EXPECT_TRUE(
224 oauth2_service_delegate_->RefreshTokenIsAvailable(main_account_id));
225 // TODO(fgorski): cover both using RefreshTokenIsAvailable() and then get the
226 // tokens using GetRefreshToken()
227 EXPECT_EQ(2U, oauth2_service_delegate_->refresh_tokens_.size());
228 EXPECT_EQ(main_refresh_token,
229 oauth2_service_delegate_->refresh_tokens_[main_account_id]
230 ->refresh_token());
231 EXPECT_EQ(other_refresh_token,
232 oauth2_service_delegate_->refresh_tokens_[other_account_id]
233 ->refresh_token());
235 oauth2_service_delegate_->RevokeAllCredentials();
236 EXPECT_EQ(2, start_batch_changes_);
237 EXPECT_EQ(2, end_batch_changes_);
240 TEST_F(MutableProfileOAuth2TokenServiceDelegateTest,
241 PersistenceRevokeCredentials) {
242 std::string account_id_1 = "account_id_1";
243 std::string refresh_token_1 = "refresh_token_1";
244 std::string account_id_2 = "account_id_2";
245 std::string refresh_token_2 = "refresh_token_2";
247 // TODO(fgorski): Enable below when implemented:
248 // EXPECT_FALSE(oauth2_servive_->RefreshTokenIsAvailable(account_id_1));
249 // EXPECT_FALSE(oauth2_servive_->RefreshTokenIsAvailable(account_id_2));
251 oauth2_service_delegate_->UpdateCredentials(account_id_1, refresh_token_1);
252 oauth2_service_delegate_->UpdateCredentials(account_id_2, refresh_token_2);
253 EXPECT_EQ(2, start_batch_changes_);
254 EXPECT_EQ(2, end_batch_changes_);
256 // TODO(fgorski): Enable below when implemented:
257 // EXPECT_TRUE(oauth2_servive_->RefreshTokenIsAvailable(account_id_1));
258 EXPECT_TRUE(oauth2_service_delegate_->RefreshTokenIsAvailable(account_id_2));
260 ResetObserverCounts();
261 oauth2_service_delegate_->RevokeCredentials(account_id_1);
262 EXPECT_EQ(1, start_batch_changes_);
263 EXPECT_EQ(1, end_batch_changes_);
264 ExpectOneTokenRevokedNotification();
266 // TODO(fgorski): Enable below when implemented:
267 // EXPECT_FALSE(oauth2_servive_->RefreshTokenIsAvailable(account_id_1));
268 EXPECT_TRUE(oauth2_service_delegate_->RefreshTokenIsAvailable(account_id_2));
270 oauth2_service_delegate_->RevokeAllCredentials();
271 EXPECT_EQ(0, token_available_count_);
272 EXPECT_EQ(1, token_revoked_count_);
273 EXPECT_EQ(0, tokens_loaded_count_);
274 EXPECT_EQ(1, start_batch_changes_);
275 EXPECT_EQ(1, end_batch_changes_);
276 ResetObserverCounts();
279 TEST_F(MutableProfileOAuth2TokenServiceDelegateTest,
280 PersistenceLoadCredentials) {
281 switches::EnableAccountConsistencyForTesting(
282 base::CommandLine::ForCurrentProcess());
284 // Ensure DB is clean.
285 oauth2_service_delegate_->RevokeAllCredentials();
286 ResetObserverCounts();
287 // Perform a load from an empty DB.
288 oauth2_service_delegate_->LoadCredentials("account_id");
289 base::RunLoop().RunUntilIdle();
290 EXPECT_EQ(1, start_batch_changes_);
291 EXPECT_EQ(1, end_batch_changes_);
292 ExpectOneTokensLoadedNotification();
293 // LoadCredentials() guarantees that the account given to it as argument
294 // is in the refresh_token map.
295 EXPECT_EQ(1U, oauth2_service_delegate_->refresh_tokens_.size());
296 EXPECT_TRUE(oauth2_service_delegate_->refresh_tokens_["account_id"]
297 ->refresh_token()
298 .empty());
299 // Setup a DB with tokens that don't require upgrade and clear memory.
300 oauth2_service_delegate_->UpdateCredentials("account_id", "refresh_token");
301 oauth2_service_delegate_->UpdateCredentials("account_id2", "refresh_token2");
302 oauth2_service_delegate_->refresh_tokens_.clear();
303 EXPECT_EQ(2, start_batch_changes_);
304 EXPECT_EQ(2, end_batch_changes_);
305 ResetObserverCounts();
307 oauth2_service_delegate_->LoadCredentials("account_id");
308 base::RunLoop().RunUntilIdle();
309 EXPECT_EQ(2, token_available_count_);
310 EXPECT_EQ(0, token_revoked_count_);
311 EXPECT_EQ(1, tokens_loaded_count_);
312 EXPECT_EQ(1, start_batch_changes_);
313 EXPECT_EQ(1, end_batch_changes_);
314 ResetObserverCounts();
316 // TODO(fgorski): Enable below when implemented:
317 // EXPECT_TRUE(oauth2_servive_->RefreshTokenIsAvailable("account_id"));
318 EXPECT_TRUE(oauth2_service_delegate_->RefreshTokenIsAvailable("account_id2"));
320 oauth2_service_delegate_->RevokeAllCredentials();
321 EXPECT_EQ(0, token_available_count_);
322 EXPECT_EQ(2, token_revoked_count_);
323 EXPECT_EQ(0, tokens_loaded_count_);
324 EXPECT_EQ(1, start_batch_changes_);
325 EXPECT_EQ(1, end_batch_changes_);
326 ResetObserverCounts();
329 TEST_F(MutableProfileOAuth2TokenServiceDelegateTest, PersistanceNotifications) {
330 oauth2_service_delegate_->UpdateCredentials("account_id", "refresh_token");
331 ExpectOneTokenAvailableNotification();
333 oauth2_service_delegate_->UpdateCredentials("account_id", "refresh_token");
334 ExpectNoNotifications();
336 oauth2_service_delegate_->UpdateCredentials("account_id", "refresh_token2");
337 ExpectOneTokenAvailableNotification();
339 oauth2_service_delegate_->RevokeCredentials("account_id");
340 ExpectOneTokenRevokedNotification();
342 oauth2_service_delegate_->UpdateCredentials("account_id", "refresh_token2");
343 ExpectOneTokenAvailableNotification();
345 oauth2_service_delegate_->RevokeAllCredentials();
346 ResetObserverCounts();
349 TEST_F(MutableProfileOAuth2TokenServiceDelegateTest, GetAccounts) {
350 EXPECT_TRUE(oauth2_service_delegate_->GetAccounts().empty());
351 oauth2_service_delegate_->UpdateCredentials("account_id1", "refresh_token1");
352 oauth2_service_delegate_->UpdateCredentials("account_id2", "refresh_token2");
353 std::vector<std::string> accounts = oauth2_service_delegate_->GetAccounts();
354 EXPECT_EQ(2u, accounts.size());
355 EXPECT_EQ(1, count(accounts.begin(), accounts.end(), "account_id1"));
356 EXPECT_EQ(1, count(accounts.begin(), accounts.end(), "account_id2"));
357 oauth2_service_delegate_->RevokeCredentials("account_id2");
358 accounts = oauth2_service_delegate_->GetAccounts();
359 EXPECT_EQ(1u, oauth2_service_delegate_->GetAccounts().size());
360 EXPECT_EQ(1, count(accounts.begin(), accounts.end(), "account_id1"));
363 TEST_F(MutableProfileOAuth2TokenServiceDelegateTest, FetchPersistentError) {
364 oauth2_service_delegate_->UpdateCredentials(kEmail, "refreshToken");
365 EXPECT_EQ(GoogleServiceAuthError::AuthErrorNone(),
366 signin_error_controller_.auth_error());
368 GoogleServiceAuthError authfail(GoogleServiceAuthError::ACCOUNT_DELETED);
369 oauth2_service_delegate_->UpdateAuthError(kEmail, authfail);
370 EXPECT_NE(GoogleServiceAuthError::AuthErrorNone(),
371 signin_error_controller_.auth_error());
373 // Create a "success" fetch we don't expect to get called.
374 factory_.SetFakeResponse(GaiaUrls::GetInstance()->oauth2_token_url(),
375 GetValidTokenResponse("token", 3600), net::HTTP_OK,
376 net::URLRequestStatus::SUCCESS);
378 EXPECT_EQ(0, access_token_success_count_);
379 EXPECT_EQ(0, access_token_failure_count_);
380 std::vector<std::string> scope_list;
381 scope_list.push_back("scope");
382 scoped_ptr<OAuth2AccessTokenFetcher> fetcher(
383 oauth2_service_delegate_->CreateAccessTokenFetcher(
384 kEmail, oauth2_service_delegate_->GetRequestContext(), this));
385 fetcher->Start("foo", "bar", scope_list);
386 base::RunLoop().RunUntilIdle();
387 EXPECT_EQ(0, access_token_success_count_);
388 EXPECT_EQ(1, access_token_failure_count_);
391 TEST_F(MutableProfileOAuth2TokenServiceDelegateTest, RetryBackoff) {
392 oauth2_service_delegate_->UpdateCredentials(kEmail, "refreshToken");
393 EXPECT_EQ(GoogleServiceAuthError::AuthErrorNone(),
394 signin_error_controller_.auth_error());
396 GoogleServiceAuthError authfail(GoogleServiceAuthError::SERVICE_UNAVAILABLE);
397 oauth2_service_delegate_->UpdateAuthError(kEmail, authfail);
398 EXPECT_EQ(GoogleServiceAuthError::AuthErrorNone(),
399 signin_error_controller_.auth_error());
401 // Create a "success" fetch we don't expect to get called just yet.
402 factory_.SetFakeResponse(GaiaUrls::GetInstance()->oauth2_token_url(),
403 GetValidTokenResponse("token", 3600), net::HTTP_OK,
404 net::URLRequestStatus::SUCCESS);
406 // Transient error will repeat until backoff period expires.
407 EXPECT_EQ(0, access_token_success_count_);
408 EXPECT_EQ(0, access_token_failure_count_);
409 std::vector<std::string> scope_list;
410 scope_list.push_back("scope");
411 scoped_ptr<OAuth2AccessTokenFetcher> fetcher1(
412 oauth2_service_delegate_->CreateAccessTokenFetcher(
413 kEmail, oauth2_service_delegate_->GetRequestContext(), this));
414 fetcher1->Start("foo", "bar", scope_list);
415 base::RunLoop().RunUntilIdle();
416 EXPECT_EQ(0, access_token_success_count_);
417 EXPECT_EQ(1, access_token_failure_count_);
419 // Pretend that backoff has expired and try again.
420 oauth2_service_delegate_->backoff_entry_.SetCustomReleaseTime(
421 base::TimeTicks());
422 scoped_ptr<OAuth2AccessTokenFetcher> fetcher2(
423 oauth2_service_delegate_->CreateAccessTokenFetcher(
424 kEmail, oauth2_service_delegate_->GetRequestContext(), this));
425 fetcher2->Start("foo", "bar", scope_list);
426 base::RunLoop().RunUntilIdle();
427 EXPECT_EQ(1, access_token_success_count_);
428 EXPECT_EQ(1, access_token_failure_count_);
431 TEST_F(MutableProfileOAuth2TokenServiceDelegateTest, CanonicalizeAccountId) {
432 std::map<std::string, std::string> tokens;
433 tokens["AccountId-user@gmail.com"] = "refresh_token";
434 tokens["AccountId-Foo.Bar@gmail.com"] = "refresh_token";
435 tokens["AccountId-12345"] = "refresh_token";
437 switches::EnableAccountConsistencyForTesting(
438 base::CommandLine::ForCurrentProcess());
439 oauth2_service_delegate_->LoadAllCredentialsIntoMemory(tokens);
441 EXPECT_TRUE(
442 oauth2_service_delegate_->RefreshTokenIsAvailable("user@gmail.com"));
443 EXPECT_TRUE(
444 oauth2_service_delegate_->RefreshTokenIsAvailable("foobar@gmail.com"));
445 EXPECT_TRUE(oauth2_service_delegate_->RefreshTokenIsAvailable("12345"));
448 TEST_F(MutableProfileOAuth2TokenServiceDelegateTest,
449 CanonAndNonCanonAccountId) {
450 std::map<std::string, std::string> tokens;
451 tokens["AccountId-Foo.Bar@gmail.com"] = "bad_token";
452 tokens["AccountId-foobar@gmail.com"] = "good_token";
454 switches::EnableAccountConsistencyForTesting(
455 base::CommandLine::ForCurrentProcess());
456 oauth2_service_delegate_->LoadAllCredentialsIntoMemory(tokens);
458 EXPECT_EQ(1u, oauth2_service_delegate_->GetAccounts().size());
459 EXPECT_TRUE(
460 oauth2_service_delegate_->RefreshTokenIsAvailable("foobar@gmail.com"));
461 EXPECT_STREQ(
462 "good_token",
463 oauth2_service_delegate_->GetRefreshToken("foobar@gmail.com").c_str());
466 TEST_F(MutableProfileOAuth2TokenServiceDelegateTest, ShutdownService) {
467 switches::EnableAccountConsistencyForTesting(
468 base::CommandLine::ForCurrentProcess());
469 EXPECT_TRUE(oauth2_service_delegate_->GetAccounts().empty());
470 oauth2_service_delegate_->UpdateCredentials("account_id1", "refresh_token1");
471 oauth2_service_delegate_->UpdateCredentials("account_id2", "refresh_token2");
472 std::vector<std::string> accounts = oauth2_service_delegate_->GetAccounts();
473 EXPECT_EQ(2u, accounts.size());
474 EXPECT_EQ(1, count(accounts.begin(), accounts.end(), "account_id1"));
475 EXPECT_EQ(1, count(accounts.begin(), accounts.end(), "account_id2"));
476 oauth2_service_delegate_->LoadCredentials("account_id1");
477 oauth2_service_delegate_->UpdateCredentials("account_id1", "refresh_token3");
478 oauth2_service_delegate_->Shutdown();
479 EXPECT_TRUE(oauth2_service_delegate_->server_revokes_.empty());
480 EXPECT_TRUE(oauth2_service_delegate_->refresh_tokens_.empty());
481 EXPECT_EQ(0, oauth2_service_delegate_->web_data_service_request_);
484 TEST_F(MutableProfileOAuth2TokenServiceDelegateTest, GaiaIdMigration) {
485 if (account_tracker_service_.GetMigrationState() !=
486 AccountTrackerService::MIGRATION_NOT_STARTED) {
487 std::string email = "foo@gmail.com";
488 std::string gaia_id = "foo's gaia id";
490 switches::EnableAccountConsistencyForTesting(
491 base::CommandLine::ForCurrentProcess());
492 pref_service_.SetInteger(prefs::kAccountIdMigrationState,
493 AccountTrackerService::MIGRATION_NOT_STARTED);
495 ListPrefUpdate update(&pref_service_,
496 AccountTrackerService::kAccountInfoPref);
497 update->Clear();
498 base::DictionaryValue* dict = new base::DictionaryValue();
499 update->Append(dict);
500 dict->SetString("account_id", base::UTF8ToUTF16(email));
501 dict->SetString("email", base::UTF8ToUTF16(email));
502 dict->SetString("gaia", base::UTF8ToUTF16(gaia_id));
503 account_tracker_service_.Shutdown();
504 account_tracker_service_.Initialize(client_.get());
506 AddAuthTokenManually("AccountId-" + email, "refresh_token");
507 oauth2_service_delegate_->LoadCredentials(gaia_id);
508 base::RunLoop().RunUntilIdle();
510 EXPECT_EQ(1, tokens_loaded_count_);
511 EXPECT_EQ(1, token_available_count_);
512 EXPECT_EQ(1, start_batch_changes_);
513 EXPECT_EQ(1, end_batch_changes_);
515 std::vector<std::string> accounts = oauth2_service_delegate_->GetAccounts();
516 EXPECT_EQ(1u, accounts.size());
518 EXPECT_FALSE(oauth2_service_delegate_->RefreshTokenIsAvailable(email));
519 EXPECT_TRUE(oauth2_service_delegate_->RefreshTokenIsAvailable(gaia_id));
521 account_tracker_service_.SetMigrationDone();
522 oauth2_service_delegate_->Shutdown();
523 ResetObserverCounts();
525 oauth2_service_delegate_->LoadCredentials(gaia_id);
526 base::RunLoop().RunUntilIdle();
528 EXPECT_EQ(1, tokens_loaded_count_);
529 EXPECT_EQ(1, token_available_count_);
530 EXPECT_EQ(1, start_batch_changes_);
531 EXPECT_EQ(1, end_batch_changes_);
533 EXPECT_FALSE(oauth2_service_delegate_->RefreshTokenIsAvailable(email));
534 EXPECT_TRUE(oauth2_service_delegate_->RefreshTokenIsAvailable(gaia_id));
535 accounts = oauth2_service_delegate_->GetAccounts();
536 EXPECT_EQ(1u, accounts.size());
540 TEST_F(MutableProfileOAuth2TokenServiceDelegateTest,
541 GaiaIdMigrationCrashInTheMiddle) {
542 if (account_tracker_service_.GetMigrationState() !=
543 AccountTrackerService::MIGRATION_NOT_STARTED) {
544 std::string email1 = "foo@gmail.com";
545 std::string gaia_id1 = "foo's gaia id";
546 std::string email2 = "bar@gmail.com";
547 std::string gaia_id2 = "bar's gaia id";
549 switches::EnableAccountConsistencyForTesting(
550 base::CommandLine::ForCurrentProcess());
551 pref_service_.SetInteger(prefs::kAccountIdMigrationState,
552 AccountTrackerService::MIGRATION_NOT_STARTED);
554 ListPrefUpdate update(&pref_service_,
555 AccountTrackerService::kAccountInfoPref);
556 update->Clear();
557 base::DictionaryValue* dict = new base::DictionaryValue();
558 update->Append(dict);
559 dict->SetString("account_id", base::UTF8ToUTF16(email1));
560 dict->SetString("email", base::UTF8ToUTF16(email1));
561 dict->SetString("gaia", base::UTF8ToUTF16(gaia_id1));
562 dict = new base::DictionaryValue();
563 update->Append(dict);
564 dict->SetString("account_id", base::UTF8ToUTF16(email2));
565 dict->SetString("email", base::UTF8ToUTF16(email2));
566 dict->SetString("gaia", base::UTF8ToUTF16(gaia_id2));
567 account_tracker_service_.Shutdown();
568 account_tracker_service_.Initialize(client_.get());
570 AddAuthTokenManually("AccountId-" + email1, "refresh_token");
571 AddAuthTokenManually("AccountId-" + email2, "refresh_token");
572 AddAuthTokenManually("AccountId-" + gaia_id1, "refresh_token");
573 oauth2_service_delegate_->LoadCredentials(gaia_id1);
574 base::RunLoop().RunUntilIdle();
576 EXPECT_EQ(1, tokens_loaded_count_);
577 EXPECT_EQ(2, token_available_count_);
578 EXPECT_EQ(1, start_batch_changes_);
579 EXPECT_EQ(1, end_batch_changes_);
581 std::vector<std::string> accounts = oauth2_service_delegate_->GetAccounts();
582 EXPECT_EQ(2u, accounts.size());
584 EXPECT_FALSE(oauth2_service_delegate_->RefreshTokenIsAvailable(email1));
585 EXPECT_TRUE(oauth2_service_delegate_->RefreshTokenIsAvailable(gaia_id1));
586 EXPECT_FALSE(oauth2_service_delegate_->RefreshTokenIsAvailable(email2));
587 EXPECT_TRUE(oauth2_service_delegate_->RefreshTokenIsAvailable(gaia_id2));
589 account_tracker_service_.SetMigrationDone();
590 oauth2_service_delegate_->Shutdown();
591 ResetObserverCounts();
593 oauth2_service_delegate_->LoadCredentials(gaia_id1);
594 base::RunLoop().RunUntilIdle();
596 EXPECT_EQ(1, tokens_loaded_count_);
597 EXPECT_EQ(2, token_available_count_);
598 EXPECT_EQ(1, start_batch_changes_);
599 EXPECT_EQ(1, end_batch_changes_);
601 EXPECT_FALSE(oauth2_service_delegate_->RefreshTokenIsAvailable(email1));
602 EXPECT_TRUE(oauth2_service_delegate_->RefreshTokenIsAvailable(gaia_id1));
603 EXPECT_FALSE(oauth2_service_delegate_->RefreshTokenIsAvailable(email2));
604 EXPECT_TRUE(oauth2_service_delegate_->RefreshTokenIsAvailable(gaia_id2));
605 accounts = oauth2_service_delegate_->GetAccounts();
606 EXPECT_EQ(2u, accounts.size());
610 TEST_F(MutableProfileOAuth2TokenServiceDelegateTest,
611 LoadPrimaryAccountOnlyWhenAccountConsistencyDisabled) {
612 std::string primary_account = "primaryaccount";
613 std::string secondary_account = "secondaryaccount";
615 oauth2_service_delegate_->RevokeAllCredentials();
616 ResetObserverCounts();
617 AddAuthTokenManually("AccountId-" + primary_account, "refresh_token");
618 AddAuthTokenManually("AccountId-" + secondary_account, "refresh_token");
619 oauth2_service_delegate_->LoadCredentials(primary_account);
620 base::RunLoop().RunUntilIdle();
622 EXPECT_EQ(1, tokens_loaded_count_);
623 EXPECT_EQ(1, token_available_count_);
624 EXPECT_EQ(1, token_revoked_count_);
625 EXPECT_EQ(1, start_batch_changes_);
626 EXPECT_EQ(1, end_batch_changes_);
627 EXPECT_TRUE(
628 oauth2_service_delegate_->RefreshTokenIsAvailable(primary_account));
629 EXPECT_FALSE(
630 oauth2_service_delegate_->RefreshTokenIsAvailable(secondary_account));
632 oauth2_service_delegate_->RevokeAllCredentials();
633 ResetObserverCounts();
634 AddAuthTokenManually("AccountId-" + primary_account, "refresh_token");
635 AddAuthTokenManually("AccountId-" + secondary_account, "refresh_token");
636 switches::EnableAccountConsistencyForTesting(
637 base::CommandLine::ForCurrentProcess());
638 oauth2_service_delegate_->LoadCredentials(primary_account);
639 base::RunLoop().RunUntilIdle();
641 EXPECT_EQ(1, tokens_loaded_count_);
642 EXPECT_EQ(2, token_available_count_);
643 EXPECT_EQ(0, token_revoked_count_);
644 EXPECT_EQ(1, start_batch_changes_);
645 EXPECT_EQ(1, end_batch_changes_);
646 EXPECT_TRUE(
647 oauth2_service_delegate_->RefreshTokenIsAvailable(primary_account));
648 EXPECT_TRUE(
649 oauth2_service_delegate_->RefreshTokenIsAvailable(secondary_account));