Home | History | Annotate | Download | only in signin
      1 // Copyright (c) 2012 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.
      4 
      5 #include "chrome/browser/signin/signin_manager.h"
      6 
      7 #include "base/bind.h"
      8 #include "base/bind_helpers.h"
      9 #include "base/compiler_specific.h"
     10 #include "base/prefs/pref_service.h"
     11 #include "base/prefs/testing_pref_service.h"
     12 #include "base/run_loop.h"
     13 #include "base/strings/stringprintf.h"
     14 #include "chrome/browser/browser_process.h"
     15 #include "chrome/browser/chrome_notification_types.h"
     16 #include "chrome/browser/prefs/browser_prefs.h"
     17 #include "chrome/browser/signin/chrome_signin_manager_delegate.h"
     18 #include "chrome/browser/signin/token_service.h"
     19 #include "chrome/browser/signin/token_service_unittest.h"
     20 #include "chrome/common/pref_names.h"
     21 #include "chrome/common/url_constants.h"
     22 #include "chrome/test/base/testing_browser_process.h"
     23 #include "chrome/test/base/testing_profile.h"
     24 #include "components/webdata/encryptor/encryptor.h"
     25 #include "content/public/browser/child_process_security_policy.h"
     26 #include "content/public/test/test_browser_thread_bundle.h"
     27 #include "google_apis/gaia/gaia_constants.h"
     28 #include "google_apis/gaia/gaia_urls.h"
     29 #include "net/cookies/cookie_monster.h"
     30 #include "net/url_request/test_url_fetcher_factory.h"
     31 #include "net/url_request/url_request.h"
     32 #include "net/url_request/url_request_context_getter.h"
     33 #include "net/url_request/url_request_status.h"
     34 
     35 #include "testing/gmock/include/gmock/gmock.h"
     36 #include "testing/gtest/include/gtest/gtest.h"
     37 
     38 namespace {
     39 
     40 const char kGetTokenPairValidResponse[] =
     41     "{"
     42     "  \"refresh_token\": \"rt1\","
     43     "  \"access_token\": \"at1\","
     44     "  \"expires_in\": 3600,"
     45     "  \"token_type\": \"Bearer\""
     46     "}";
     47 
     48 const char kUberAuthTokenURLFormat[] = "%s?source=%s&issueuberauth=1";
     49 
     50 }  // namespace
     51 
     52 
     53 class SigninManagerTest : public TokenServiceTestHarness {
     54  public:
     55   virtual void SetUp() OVERRIDE {
     56     prefs_.reset(new TestingPrefServiceSimple);
     57     chrome::RegisterLocalState(prefs_->registry());
     58     TestingBrowserProcess::GetGlobal()->SetLocalState(
     59         prefs_.get());
     60     TokenServiceTestHarness::SetUp();
     61     manager_.reset(new SigninManager(
     62         scoped_ptr<SigninManagerDelegate>(
     63             new ChromeSigninManagerDelegate(profile()))));
     64     google_login_success_.ListenFor(
     65         chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL,
     66         content::Source<Profile>(profile()));
     67     google_login_failure_.ListenFor(chrome::NOTIFICATION_GOOGLE_SIGNIN_FAILED,
     68                                     content::Source<Profile>(profile()));
     69   }
     70 
     71   virtual void TearDown() OVERRIDE {
     72     // Destroy the SigninManager here, because it relies on profile() which is
     73     // freed in the base class.
     74     manager_->Shutdown();
     75     manager_.reset(NULL);
     76     TestingBrowserProcess::GetGlobal()->SetLocalState(NULL);
     77     prefs_.reset(NULL);
     78     TokenServiceTestHarness::TearDown();
     79   }
     80 
     81   void SetupFetcherAndComplete(const std::string& url,
     82                                int response_code,
     83                                const net::ResponseCookies& cookies,
     84                                const std::string& response_string) {
     85     net::TestURLFetcher* fetcher = factory_.GetFetcherByID(0);
     86     DCHECK(fetcher);
     87     DCHECK(fetcher->delegate());
     88 
     89     cookies_.insert(cookies_.end(), cookies.begin(), cookies.end());
     90     fetcher->set_url(GURL(url));
     91     fetcher->set_status(net::URLRequestStatus());
     92     fetcher->set_response_code(response_code);
     93     fetcher->SetResponseString(response_string);
     94     fetcher->set_cookies(cookies);
     95     fetcher->delegate()->OnURLFetchComplete(fetcher);
     96   }
     97 
     98   void SimulateValidResponseSignInWithCredentials() {
     99     // Simulate the correct StartOAuthLoginTokenFetch response.  This involves
    100     // two separate fetches.
    101     SetupFetcherAndComplete(
    102         GaiaUrls::GetInstance()->client_login_to_oauth2_url(), 200,
    103         net::ResponseCookies(), kGetTokenPairValidResponse);
    104 
    105     SetupFetcherAndComplete(GaiaUrls::GetInstance()->oauth2_token_url(), 200,
    106                             net::ResponseCookies(), kGetTokenPairValidResponse);
    107 
    108     // Simulate the correct StartOAuthLogin response.
    109     SetupFetcherAndComplete(GaiaUrls::GetInstance()->oauth1_login_url(), 200,
    110                             net::ResponseCookies(),
    111                             "SID=sid\nLSID=lsid\nAuth=auth_token");
    112 
    113     SimulateValidResponseGetClientInfo(false);
    114   }
    115 
    116   void SimulateValidResponseClientLogin(bool isGPlusUser) {
    117     SetupFetcherAndComplete(GaiaUrls::GetInstance()->client_login_url(), 200,
    118                             net::ResponseCookies(),
    119                             "SID=sid\nLSID=lsid\nAuth=auth");
    120     SimulateValidResponseGetClientInfo(isGPlusUser);
    121   }
    122 
    123   void SimulateValidResponseGetClientInfo(bool isGPlusUser) {
    124     // Simulate the correct ClientLogin response.
    125     std::string response_string = isGPlusUser ?
    126         "email=user (at) gmail.com\ndisplayEmail=USER (at) gmail.com\n"
    127         "allServices=googleme" :
    128         "email=user (at) gmail.com\ndisplayEmail=USER (at) gmail.com\n"
    129         "allServices=";
    130     SetupFetcherAndComplete(GaiaUrls::GetInstance()->get_user_info_url(), 200,
    131                             net::ResponseCookies(), response_string);
    132   }
    133 
    134   void SimulateValidUberToken() {
    135     SetupFetcherAndComplete(GaiaUrls::GetInstance()->oauth2_token_url(), 200,
    136                             net::ResponseCookies(), kGetTokenPairValidResponse);
    137     std::string  uberauth_token_gurl = base::StringPrintf(
    138         kUberAuthTokenURLFormat,
    139         GaiaUrls::GetInstance()->oauth1_login_url().c_str(),
    140         "source");
    141     SetupFetcherAndComplete(uberauth_token_gurl, 200,
    142                             net::ResponseCookies(), "ut1");
    143 
    144     net::ResponseCookies cookies;
    145     cookies.push_back("checkCookie = true");
    146     SetupFetcherAndComplete(GaiaUrls::GetInstance()->merge_session_url(), 200,
    147                             cookies, "<html></html>");
    148   }
    149 
    150   void ExpectSignInWithCredentialsSuccess() {
    151     EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    152 
    153     SimulateValidResponseSignInWithCredentials();
    154 
    155     EXPECT_FALSE(manager_->GetAuthenticatedUsername().empty());
    156 
    157     // This is flow, the oauth2 credentials should already be available in
    158     // the token service.
    159     EXPECT_TRUE(service()->HasOAuthLoginToken());
    160 
    161     // Should go into token service and stop.
    162     EXPECT_EQ(1U, google_login_success_.size());
    163     EXPECT_EQ(0U, google_login_failure_.size());
    164 
    165     // Should persist across resets.
    166     manager_->Shutdown();
    167     manager_.reset(new SigninManager(
    168         scoped_ptr<SigninManagerDelegate>(
    169             new ChromeSigninManagerDelegate(profile()))));
    170     manager_->Initialize(profile(), NULL);
    171     EXPECT_EQ("user (at) gmail.com", manager_->GetAuthenticatedUsername());
    172   }
    173 
    174   // Helper method that wraps the logic when signin with credentials
    175   // should fail. If |requestSent| is true, then simulate valid resopnse.
    176   // Otherwise the sign-in is aborted before any request is sent, thus no need
    177   // to simulatate response.
    178   void ExpectSignInWithCredentialsFail(bool requestSent) {
    179     EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    180 
    181     if (requestSent)
    182       SimulateValidResponseSignInWithCredentials();
    183 
    184     // The oauth2 credentials should not be available in the token service
    185     // because the email was incorrect.
    186     EXPECT_FALSE(service()->HasOAuthLoginToken());
    187 
    188     // Should go into token service and stop.
    189     EXPECT_EQ(0U, google_login_success_.size());
    190     EXPECT_EQ(1U, google_login_failure_.size());
    191   }
    192 
    193   void CompleteSigninCallback(const std::string& oauth_token) {
    194     oauth_tokens_fetched_.push_back(oauth_token);
    195     manager_->CompletePendingSignin();
    196   }
    197 
    198   void CancelSigninCallback(const std::string& oauth_token) {
    199     oauth_tokens_fetched_.push_back(oauth_token);
    200     manager_->SignOut();
    201   }
    202 
    203   net::TestURLFetcherFactory factory_;
    204   scoped_ptr<SigninManager> manager_;
    205   content::TestNotificationTracker google_login_success_;
    206   content::TestNotificationTracker google_login_failure_;
    207   std::vector<std::string> oauth_tokens_fetched_;
    208   scoped_ptr<TestingPrefServiceSimple> prefs_;
    209   std::vector<std::string> cookies_;
    210 };
    211 
    212 // NOTE: ClientLogin's "StartSignin" is called after collecting credentials
    213 //       from the user.
    214 TEST_F(SigninManagerTest, SignInClientLogin) {
    215   manager_->Initialize(profile(), NULL);
    216   EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    217 
    218   manager_->StartSignIn(
    219       "user (at) gmail.com", "password", std::string(), std::string());
    220   EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    221 
    222   SimulateValidResponseClientLogin(true);
    223   EXPECT_FALSE(manager_->GetAuthenticatedUsername().empty());
    224 
    225   // Should go into token service and stop.
    226   EXPECT_EQ(1U, google_login_success_.size());
    227   EXPECT_EQ(0U, google_login_failure_.size());
    228 
    229   service()->OnIssueAuthTokenSuccess(
    230       GaiaConstants::kGaiaOAuth2LoginRefreshToken,
    231       "oauth2Token");
    232   SimulateValidUberToken();
    233   // Check that the login cookie has been sent.
    234   ASSERT_NE(std::find(cookies_.begin(), cookies_.end(), "checkCookie = true"),
    235             cookies_.end());
    236 
    237   // Should persist across resets.
    238   manager_->Shutdown();
    239   manager_.reset(new SigninManager(
    240       scoped_ptr<SigninManagerDelegate>(
    241           new ChromeSigninManagerDelegate(profile()))));
    242   manager_->Initialize(profile(), NULL);
    243   EXPECT_EQ("user (at) gmail.com", manager_->GetAuthenticatedUsername());
    244 }
    245 
    246 TEST_F(SigninManagerTest, SignInWithCredentials) {
    247   manager_->Initialize(profile(), NULL);
    248   EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    249 
    250   manager_->StartSignInWithCredentials(
    251       "0",
    252       "user (at) gmail.com",
    253       "password",
    254       SigninManager::OAuthTokenFetchedCallback());
    255 
    256   ExpectSignInWithCredentialsSuccess();
    257 }
    258 
    259 TEST_F(SigninManagerTest, SignInWithCredentialsNonCanonicalEmail) {
    260   manager_->Initialize(profile(), NULL);
    261   EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    262 
    263   manager_->StartSignInWithCredentials(
    264       "0",
    265       "user",
    266       "password",
    267       SigninManager::OAuthTokenFetchedCallback());
    268 
    269   ExpectSignInWithCredentialsSuccess();
    270 }
    271 
    272 TEST_F(SigninManagerTest, SignInWithCredentialsWrongEmail) {
    273   manager_->Initialize(profile(), NULL);
    274   EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    275 
    276   // If the email address used to start the sign in does not match the
    277   // email address returned by /GetUserInfo, the sign in should fail.
    278   manager_->StartSignInWithCredentials(
    279       "0",
    280       "user2 (at) gmail.com",
    281       "password",
    282       SigninManager::OAuthTokenFetchedCallback());
    283 
    284   ExpectSignInWithCredentialsFail(true /* requestSent */);
    285 }
    286 
    287 TEST_F(SigninManagerTest, SignInWithCredentialsEmptyPasswordValidCookie) {
    288   manager_->Initialize(profile(), NULL);
    289   EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    290 
    291   // Set a valid LSID cookie in the test cookie store.
    292   scoped_refptr<net::CookieMonster> cookie_monster =
    293       profile()->GetCookieMonster();
    294   net::CookieOptions options;
    295   options.set_include_httponly();
    296   cookie_monster->SetCookieWithOptionsAsync(
    297         GURL("https://accounts.google.com"),
    298         "LSID=1234; secure; httponly", options,
    299         net::CookieMonster::SetCookiesCallback());
    300 
    301   // Since the password is empty, will verify the gaia cookies first.
    302   manager_->StartSignInWithCredentials(
    303       "0",
    304       "user (at) gmail.com",
    305       std::string(),
    306       SigninManager::OAuthTokenFetchedCallback());
    307 
    308   base::RunLoop().RunUntilIdle();
    309 
    310   // Verification should succeed and continue with auto signin.
    311   ExpectSignInWithCredentialsSuccess();
    312 }
    313 
    314 TEST_F(SigninManagerTest, SignInWithCredentialsEmptyPasswordNoValidCookie) {
    315   manager_->Initialize(profile(), NULL);
    316   EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    317 
    318   // Since the password is empty, will verify the gaia cookies first.
    319   manager_->StartSignInWithCredentials(
    320       "0",
    321       "user (at) gmail.com",
    322       std::string(),
    323       SigninManager::OAuthTokenFetchedCallback());
    324 
    325   base::RunLoop().RunUntilIdle();
    326 
    327   // Since the test cookie store is empty, verification should fail and throws
    328   // a login error.
    329   ExpectSignInWithCredentialsFail(false /* requestSent */);
    330 }
    331 
    332 TEST_F(SigninManagerTest, SignInWithCredentialsEmptyPasswordInValidCookie) {
    333   manager_->Initialize(profile(), NULL);
    334   EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    335 
    336   // Set an invalid LSID cookie in the test cookie store.
    337   scoped_refptr<net::CookieMonster> cookie_monster =
    338       profile()->GetCookieMonster();
    339   net::CookieOptions options;
    340   options.set_include_httponly();
    341   cookie_monster->SetCookieWithOptionsAsync(
    342         GURL("https://accounts.google.com"),
    343         "LSID=1234; domain=google.com; secure; httponly", options,
    344         net::CookieMonster::SetCookiesCallback());
    345 
    346   // Since the password is empty, must verify the gaia cookies first.
    347   manager_->StartSignInWithCredentials(
    348       "0",
    349       "user (at) gmail.com",
    350       std::string(),
    351       SigninManager::OAuthTokenFetchedCallback());
    352 
    353   base::RunLoop().RunUntilIdle();
    354 
    355   // Since the LSID cookie is invalid, verification should fail and throws
    356   // a login error.
    357   ExpectSignInWithCredentialsFail(false /* requestSent */);
    358 }
    359 
    360 TEST_F(SigninManagerTest, SignInWithCredentialsCallbackComplete) {
    361   manager_->Initialize(profile(), NULL);
    362   EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    363 
    364   // Since the password is empty, must verify the gaia cookies first.
    365   SigninManager::OAuthTokenFetchedCallback callback =
    366       base::Bind(&SigninManagerTest::CompleteSigninCallback,
    367                  base::Unretained(this));
    368   manager_->StartSignInWithCredentials(
    369       "0",
    370       "user (at) gmail.com",
    371       "password",
    372       callback);
    373 
    374   ExpectSignInWithCredentialsSuccess();
    375   ASSERT_EQ(1U, oauth_tokens_fetched_.size());
    376   EXPECT_EQ(oauth_tokens_fetched_[0], "rt1");
    377 }
    378 
    379 TEST_F(SigninManagerTest, SignInWithCredentialsCallbackCancel) {
    380   manager_->Initialize(profile(), NULL);
    381   EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    382 
    383   // Since the password is empty, must verify the gaia cookies first.
    384   SigninManager::OAuthTokenFetchedCallback callback =
    385       base::Bind(&SigninManagerTest::CancelSigninCallback,
    386                  base::Unretained(this));
    387   manager_->StartSignInWithCredentials(
    388       "0",
    389       "user (at) gmail.com",
    390       "password",
    391       callback);
    392 
    393   // Signin should fail since it would be cancelled by the callback.
    394   ExpectSignInWithCredentialsFail(true);
    395   ASSERT_EQ(1U, oauth_tokens_fetched_.size());
    396   EXPECT_EQ(oauth_tokens_fetched_[0], "rt1");
    397 }
    398 
    399 TEST_F(SigninManagerTest, SignInClientLoginNoGPlus) {
    400   manager_->Initialize(profile(), NULL);
    401   EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    402 
    403   manager_->StartSignIn("username", "password", std::string(), std::string());
    404   EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    405 
    406   SimulateValidResponseClientLogin(false);
    407   EXPECT_FALSE(manager_->GetAuthenticatedUsername().empty());
    408 }
    409 
    410 TEST_F(SigninManagerTest, ClearTransientSigninData) {
    411   manager_->Initialize(profile(), NULL);
    412   EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    413 
    414   manager_->StartSignIn("username", "password", std::string(), std::string());
    415   EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    416 
    417   SimulateValidResponseClientLogin(false);
    418 
    419   // Should go into token service and stop.
    420   EXPECT_EQ(1U, google_login_success_.size());
    421   EXPECT_EQ(0U, google_login_failure_.size());
    422 
    423   EXPECT_EQ("user (at) gmail.com", manager_->GetAuthenticatedUsername());
    424 
    425   // Now clear the in memory data.
    426   manager_->ClearTransientSigninData();
    427   EXPECT_TRUE(manager_->last_result_.data.empty());
    428   EXPECT_FALSE(manager_->GetAuthenticatedUsername().empty());
    429 
    430   // Ensure preferences are not modified.
    431   EXPECT_FALSE(
    432      profile()->GetPrefs()->GetString(prefs::kGoogleServicesUsername).empty());
    433 
    434   // On reset it should be regenerated.
    435   manager_->Shutdown();
    436   manager_.reset(new SigninManager(
    437       scoped_ptr<SigninManagerDelegate>(
    438           new ChromeSigninManagerDelegate(profile()))));
    439   manager_->Initialize(profile(), NULL);
    440 
    441   // Now make sure we have the right user name.
    442   EXPECT_EQ("user (at) gmail.com", manager_->GetAuthenticatedUsername());
    443 }
    444 
    445 TEST_F(SigninManagerTest, SignOutClientLogin) {
    446   manager_->Initialize(profile(), NULL);
    447   manager_->StartSignIn("username", "password", std::string(), std::string());
    448   SimulateValidResponseClientLogin(false);
    449   manager_->OnClientLoginSuccess(credentials());
    450 
    451   EXPECT_EQ("user (at) gmail.com", manager_->GetAuthenticatedUsername());
    452   manager_->SignOut();
    453   EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    454   // Should not be persisted anymore
    455   manager_->Shutdown();
    456   manager_.reset(new SigninManager(
    457       scoped_ptr<SigninManagerDelegate>(
    458           new ChromeSigninManagerDelegate(profile()))));
    459   manager_->Initialize(profile(), NULL);
    460   EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    461 }
    462 
    463 TEST_F(SigninManagerTest, SignInFailureClientLogin) {
    464   manager_->Initialize(profile(), NULL);
    465   manager_->StartSignIn("username", "password", std::string(), std::string());
    466   GoogleServiceAuthError error(GoogleServiceAuthError::REQUEST_CANCELED);
    467   manager_->OnClientLoginFailure(error);
    468 
    469   EXPECT_EQ(0U, google_login_success_.size());
    470   EXPECT_EQ(1U, google_login_failure_.size());
    471 
    472   EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    473 
    474   // Should not be persisted
    475   manager_->Shutdown();
    476   manager_.reset(new SigninManager(
    477       scoped_ptr<SigninManagerDelegate>(
    478           new ChromeSigninManagerDelegate(profile()))));
    479   manager_->Initialize(profile(), NULL);
    480   EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    481 }
    482 
    483 TEST_F(SigninManagerTest, ProvideSecondFactorSuccess) {
    484   manager_->Initialize(profile(), NULL);
    485   manager_->StartSignIn("username", "password", std::string(), std::string());
    486   GoogleServiceAuthError error(GoogleServiceAuthError::TWO_FACTOR);
    487   manager_->OnClientLoginFailure(error);
    488 
    489   EXPECT_EQ(0U, google_login_success_.size());
    490   EXPECT_EQ(1U, google_login_failure_.size());
    491 
    492   EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    493   EXPECT_FALSE(manager_->possibly_invalid_username_.empty());
    494 
    495   manager_->ProvideSecondFactorAccessCode("access");
    496   SimulateValidResponseClientLogin(false);
    497 
    498   EXPECT_EQ(1U, google_login_success_.size());
    499   EXPECT_EQ(1U, google_login_failure_.size());
    500 }
    501 
    502 TEST_F(SigninManagerTest, ProvideSecondFactorFailure) {
    503   manager_->Initialize(profile(), NULL);
    504   manager_->StartSignIn("username", "password", std::string(), std::string());
    505   GoogleServiceAuthError error1(GoogleServiceAuthError::TWO_FACTOR);
    506   manager_->OnClientLoginFailure(error1);
    507 
    508   EXPECT_EQ(0U, google_login_success_.size());
    509   EXPECT_EQ(1U, google_login_failure_.size());
    510 
    511   EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    512   EXPECT_FALSE(manager_->possibly_invalid_username_.empty());
    513 
    514   manager_->ProvideSecondFactorAccessCode("badaccess");
    515   GoogleServiceAuthError error2(
    516       GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
    517   manager_->OnClientLoginFailure(error2);
    518 
    519   EXPECT_EQ(0U, google_login_success_.size());
    520   EXPECT_EQ(2U, google_login_failure_.size());
    521   EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    522 
    523   manager_->ProvideSecondFactorAccessCode("badaccess");
    524   GoogleServiceAuthError error3(GoogleServiceAuthError::CONNECTION_FAILED);
    525   manager_->OnClientLoginFailure(error3);
    526 
    527   EXPECT_EQ(0U, google_login_success_.size());
    528   EXPECT_EQ(3U, google_login_failure_.size());
    529   EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    530 }
    531 
    532 TEST_F(SigninManagerTest, SignOutMidConnect) {
    533   manager_->Initialize(profile(), NULL);
    534   manager_->StartSignIn("username", "password", std::string(), std::string());
    535   EXPECT_EQ("username", manager_->GetUsernameForAuthInProgress());
    536   manager_->SignOut();
    537   EXPECT_EQ(0U, google_login_success_.size());
    538   EXPECT_EQ(1U, google_login_failure_.size());
    539 
    540   EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    541   EXPECT_TRUE(manager_->GetUsernameForAuthInProgress().empty());
    542 }
    543 
    544 TEST_F(SigninManagerTest, SignOutWhileProhibited) {
    545   manager_->Initialize(profile(), NULL);
    546   EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    547 
    548   manager_->SetAuthenticatedUsername("user (at) gmail.com");
    549   manager_->ProhibitSignout(true);
    550   manager_->SignOut();
    551   EXPECT_FALSE(manager_->GetAuthenticatedUsername().empty());
    552   manager_->ProhibitSignout(false);
    553   manager_->SignOut();
    554   EXPECT_TRUE(manager_->GetAuthenticatedUsername().empty());
    555 }
    556 
    557 TEST_F(SigninManagerTest, TestIsWebBasedSigninFlowURL) {
    558   EXPECT_FALSE(SigninManager::IsWebBasedSigninFlowURL(
    559       GURL("http://www.google.com")));
    560   EXPECT_TRUE(SigninManager::IsWebBasedSigninFlowURL(
    561       GURL("https://accounts.google.com/ServiceLogin?service=chromiumsync")));
    562   EXPECT_FALSE(SigninManager::IsWebBasedSigninFlowURL(
    563       GURL("http://accounts.google.com/ServiceLogin?service=chromiumsync")));
    564   // http, not https, should not be treated as web based signin.
    565   EXPECT_FALSE(SigninManager::IsWebBasedSigninFlowURL(
    566       GURL("http://accounts.google.com/ServiceLogin?service=googlemail")));
    567   // chromiumsync is double-embedded in a continue query param.
    568   EXPECT_TRUE(SigninManager::IsWebBasedSigninFlowURL(
    569       GURL("https://accounts.google.com/CheckCookie?"
    570            "continue=https%3A%2F%2Fwww.google.com%2Fintl%2Fen-US%2Fchrome"
    571            "%2Fblank.html%3Fsource%3D3%26nonadv%3D1&service=chromiumsync")));
    572 }
    573 
    574 TEST_F(SigninManagerTest, Prohibited) {
    575   g_browser_process->local_state()->SetString(
    576       prefs::kGoogleServicesUsernamePattern, ".*@google.com");
    577   manager_->Initialize(profile(), g_browser_process->local_state());
    578   EXPECT_TRUE(manager_->IsAllowedUsername("test (at) google.com"));
    579   EXPECT_TRUE(manager_->IsAllowedUsername("happy (at) google.com"));
    580   EXPECT_FALSE(manager_->IsAllowedUsername("test (at) invalid.com"));
    581   EXPECT_FALSE(manager_->IsAllowedUsername("test (at) notgoogle.com"));
    582   EXPECT_FALSE(manager_->IsAllowedUsername(std::string()));
    583 }
    584 
    585 TEST_F(SigninManagerTest, TestAlternateWildcard) {
    586   // Test to make sure we accept "*@google.com" as a pattern (treat it as if
    587   // the admin entered ".*@google.com").
    588   g_browser_process->local_state()->SetString(
    589       prefs::kGoogleServicesUsernamePattern, "*@google.com");
    590   manager_->Initialize(profile(), g_browser_process->local_state());
    591   EXPECT_TRUE(manager_->IsAllowedUsername("test (at) google.com"));
    592   EXPECT_TRUE(manager_->IsAllowedUsername("happy (at) google.com"));
    593   EXPECT_FALSE(manager_->IsAllowedUsername("test (at) invalid.com"));
    594   EXPECT_FALSE(manager_->IsAllowedUsername("test (at) notgoogle.com"));
    595   EXPECT_FALSE(manager_->IsAllowedUsername(std::string()));
    596 }
    597 
    598 TEST_F(SigninManagerTest, ProhibitedAtStartup) {
    599   profile()->GetPrefs()->SetString(prefs::kGoogleServicesUsername,
    600                                    "monkey (at) invalid.com");
    601   g_browser_process->local_state()->SetString(
    602       prefs::kGoogleServicesUsernamePattern, ".*@google.com");
    603   manager_->Initialize(profile(), g_browser_process->local_state());
    604   // Currently signed in user is prohibited by policy, so should be signed out.
    605   EXPECT_EQ("", manager_->GetAuthenticatedUsername());
    606 }
    607 
    608 TEST_F(SigninManagerTest, ProhibitedAfterStartup) {
    609   std::string user("monkey (at) invalid.com");
    610   profile()->GetPrefs()->SetString(prefs::kGoogleServicesUsername, user);
    611   manager_->Initialize(profile(), g_browser_process->local_state());
    612   EXPECT_EQ(user, manager_->GetAuthenticatedUsername());
    613   // Update the profile - user should be signed out.
    614   g_browser_process->local_state()->SetString(
    615       prefs::kGoogleServicesUsernamePattern, ".*@google.com");
    616   EXPECT_EQ("", manager_->GetAuthenticatedUsername());
    617 }
    618 
    619 TEST_F(SigninManagerTest, ExternalSignIn) {
    620   manager_->Initialize(profile(), g_browser_process->local_state());
    621   EXPECT_EQ("",
    622             profile()->GetPrefs()->GetString(prefs::kGoogleServicesUsername));
    623   EXPECT_EQ("", manager_->GetAuthenticatedUsername());
    624   EXPECT_EQ(0u, google_login_success_.size());
    625 
    626   manager_->OnExternalSigninCompleted("external (at) example.com");
    627   EXPECT_EQ(1u, google_login_success_.size());
    628   EXPECT_EQ(0u, google_login_failure_.size());
    629   EXPECT_EQ("external (at) example.com",
    630             profile()->GetPrefs()->GetString(prefs::kGoogleServicesUsername));
    631   EXPECT_EQ("external (at) example.com", manager_->GetAuthenticatedUsername());
    632 }
    633