login_utils_browsertest.cc revision 90dce4d38c5ff5333bea97d859d4e484e27edf0c
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/chromeos/login/login_utils.h" 6 7#include "base/basictypes.h" 8#include "base/bind.h" 9#include "base/command_line.h" 10#include "base/files/scoped_temp_dir.h" 11#include "base/message_loop.h" 12#include "base/path_service.h" 13#include "base/prefs/pref_registry_simple.h" 14#include "base/run_loop.h" 15#include "base/string_util.h" 16#include "base/synchronization/waitable_event.h" 17#include "base/threading/sequenced_worker_pool.h" 18#include "base/threading/thread.h" 19#include "chrome/browser/chromeos/cros/cros_library.h" 20#include "chrome/browser/chromeos/input_method/input_method_configuration.h" 21#include "chrome/browser/chromeos/input_method/mock_input_method_manager.h" 22#include "chrome/browser/chromeos/login/authenticator.h" 23#include "chrome/browser/chromeos/login/login_status_consumer.h" 24#include "chrome/browser/chromeos/login/user_manager.h" 25#include "chrome/browser/chromeos/net/connectivity_state_helper.h" 26#include "chrome/browser/chromeos/net/mock_connectivity_state_helper.h" 27#include "chrome/browser/chromeos/policy/enterprise_install_attributes.h" 28#include "chrome/browser/chromeos/settings/cros_settings.h" 29#include "chrome/browser/chromeos/settings/device_settings_service.h" 30#include "chrome/browser/chromeos/settings/device_settings_test_helper.h" 31#include "chrome/browser/chromeos/settings/mock_owner_key_util.h" 32#include "chrome/browser/io_thread.h" 33#include "chrome/browser/net/predictor.h" 34#include "chrome/browser/policy/browser_policy_connector.h" 35#include "chrome/browser/policy/cloud/device_management_service.h" 36#include "chrome/browser/policy/policy_service.h" 37#include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h" 38#include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h" 39#include "chrome/browser/profiles/profile_manager.h" 40#include "chrome/browser/rlz/rlz.h" 41#include "chrome/common/chrome_notification_types.h" 42#include "chrome/common/chrome_paths.h" 43#include "chrome/common/chrome_switches.h" 44#include "chrome/common/pref_names.h" 45#include "chrome/test/base/scoped_testing_local_state.h" 46#include "chrome/test/base/testing_browser_process.h" 47#include "chromeos/chromeos_switches.h" 48#include "chromeos/cryptohome/mock_async_method_caller.h" 49#include "chromeos/cryptohome/mock_cryptohome_library.h" 50#include "chromeos/dbus/mock_dbus_thread_manager_without_gmock.h" 51#include "chromeos/disks/disk_mount_manager.h" 52#include "chromeos/disks/mock_disk_mount_manager.h" 53#include "chromeos/login/login_state.h" 54#include "content/public/browser/browser_thread.h" 55#include "content/public/test/test_browser_thread.h" 56#include "content/public/test/test_utils.h" 57#include "google_apis/gaia/gaia_auth_consumer.h" 58#include "google_apis/gaia/gaia_urls.h" 59#include "net/url_request/test_url_fetcher_factory.h" 60#include "net/url_request/url_fetcher_delegate.h" 61#include "net/url_request/url_request.h" 62#include "net/url_request/url_request_context_getter.h" 63#include "net/url_request/url_request_status.h" 64#include "testing/gmock/include/gmock/gmock.h" 65#include "testing/gtest/include/gtest/gtest.h" 66 67#if defined(ENABLE_RLZ) 68#include "rlz/lib/rlz_value_store.h" 69#endif 70 71using ::testing::AnyNumber; 72 73namespace chromeos { 74 75namespace { 76 77namespace em = enterprise_management; 78 79using ::testing::DoAll; 80using ::testing::Return; 81using ::testing::SaveArg; 82using ::testing::SetArgPointee; 83using ::testing::_; 84using content::BrowserThread; 85 86const char kTrue[] = "true"; 87const char kDomain[] = "domain.com"; 88const char kUsername[] = "user@domain.com"; 89const char kMode[] = "enterprise"; 90const char kDeviceId[] = "100200300"; 91const char kUsernameOtherDomain[] = "user@other.com"; 92const char kAttributeOwned[] = "enterprise.owned"; 93const char kAttributeOwner[] = "enterprise.user"; 94const char kAttrEnterpriseDomain[] = "enterprise.domain"; 95const char kAttrEnterpriseMode[] = "enterprise.mode"; 96const char kAttrEnterpriseDeviceId[] = "enterprise.device_id"; 97 98const char kOAuthTokenCookie[] = "oauth_token=1234"; 99 100const char kGaiaAccountDisabledResponse[] = "Error=AccountDeleted"; 101 102const char kOAuth2TokenPairData[] = 103 "{" 104 " \"refresh_token\": \"1234\"," 105 " \"access_token\": \"5678\"," 106 " \"expires_in\": 3600" 107 "}"; 108 109const char kOAuth2AccessTokenData[] = 110 "{" 111 " \"access_token\": \"5678\"," 112 " \"expires_in\": 3600" 113 "}"; 114 115const char kDMServer[] = "http://server/device_management"; 116const char kDMRegisterRequest[] = 117 "http://server/device_management?request=register"; 118const char kDMPolicyRequest[] = 119 "http://server/device_management?request=policy"; 120 121const char kDMToken[] = "1234"; 122 123// Used to mark |flag|, indicating that RefreshPolicies() has executed its 124// callback. 125void SetFlag(bool* flag) { 126 *flag = true; 127} 128 129// Single task of the fake IO loop used in the test, that just waits until 130// it is signaled to quit or perform some work. 131// |completion| is the event to wait for, and |work| is the task to invoke 132// when signaled. If the task returns false then this quits the IO loop. 133void BlockLoop(base::WaitableEvent* completion, base::Callback<bool()> work) { 134 do { 135 completion->Wait(); 136 } while (work.Run()); 137 base::MessageLoop::current()->QuitNow(); 138} 139 140void CopyLockResult(base::RunLoop* loop, 141 policy::EnterpriseInstallAttributes::LockResult* out, 142 policy::EnterpriseInstallAttributes::LockResult result) { 143 *out = result; 144 loop->Quit(); 145} 146 147class LoginUtilsTest : public testing::Test, 148 public LoginUtils::Delegate, 149 public LoginStatusConsumer { 150 public: 151 // Initialization here is important. The UI thread gets the test's 152 // message loop, as does the file thread (which never actually gets 153 // started - so this is a way to fake multiple threads on a single 154 // test thread). The IO thread does not get the message loop set, 155 // and is never started. This is necessary so that we skip various 156 // bits of initialization that get posted to the IO thread. We do 157 // however, at one point in the test, temporarily set the message 158 // loop for the IO thread. 159 LoginUtilsTest() 160 : fake_io_thread_completion_(false, false), 161 fake_io_thread_("fake_io_thread"), 162 loop_(base::MessageLoop::TYPE_IO), 163 browser_process_(TestingBrowserProcess::GetGlobal()), 164 local_state_(browser_process_), 165 ui_thread_(BrowserThread::UI, &loop_), 166 db_thread_(BrowserThread::DB, &loop_), 167 file_thread_(BrowserThread::FILE, &loop_), 168 mock_input_method_manager_(NULL), 169 mock_async_method_caller_(NULL), 170 connector_(NULL), 171 cryptohome_(NULL), 172 prepared_profile_(NULL) {} 173 174 virtual void SetUp() OVERRIDE { 175 // This test is not a full blown InProcessBrowserTest, and doesn't have 176 // all the usual threads running. However a lot of subsystems pulled from 177 // ProfileImpl post to IO (usually from ProfileIOData), and DCHECK that 178 // those tasks were posted. Those tasks in turn depend on a lot of other 179 // components that aren't there during this test, so this kludge is used to 180 // have a running IO loop that doesn't really execute any tasks. 181 // 182 // See InvokeOnIO() below for a way to perform specific tasks on IO, when 183 // that's necessary. 184 185 // A thread is needed to create a new MessageLoop, since there can be only 186 // one loop per thread. 187 fake_io_thread_.StartWithOptions( 188 base::Thread::Options(base::MessageLoop::TYPE_IO, 0)); 189 base::MessageLoop* fake_io_loop = fake_io_thread_.message_loop(); 190 // Make this loop enter the single task, BlockLoop(). Pass in the completion 191 // event and the work callback. 192 fake_io_thread_.StopSoon(); 193 fake_io_loop->PostTask( 194 FROM_HERE, 195 base::Bind( 196 BlockLoop, 197 &fake_io_thread_completion_, 198 base::Bind(&LoginUtilsTest::DoIOWork, base::Unretained(this)))); 199 // Map BrowserThread::IO to this loop. This allows posting to IO but nothing 200 // will be executed. 201 io_thread_.reset( 202 new content::TestBrowserThread(BrowserThread::IO, fake_io_loop)); 203 204 ASSERT_TRUE(scoped_temp_dir_.CreateUniqueTempDir()); 205 206 CommandLine* command_line = CommandLine::ForCurrentProcess(); 207 command_line->AppendSwitchASCII( 208 ::switches::kDeviceManagementUrl, kDMServer); 209 command_line->AppendSwitchASCII(switches::kLoginProfile, "user"); 210 211 // DBusThreadManager should be initialized before io_thread_state_, as 212 // DBusThreadManager is used from chromeos::ProxyConfigServiceImpl, 213 // which is part of io_thread_state_. 214 DBusThreadManager::InitializeForTesting(&mock_dbus_thread_manager_); 215 216 CryptohomeLibrary::Initialize(); 217 LoginState::Initialize(); 218 ConnectivityStateHelper::SetForTest(&mock_connectivity_state_helper_); 219 220 mock_input_method_manager_ = new input_method::MockInputMethodManager(); 221 input_method::InitializeForTesting(mock_input_method_manager_); 222 disks::DiskMountManager::InitializeForTesting(&mock_disk_mount_manager_); 223 mock_disk_mount_manager_.SetupDefaultReplies(); 224 225 mock_async_method_caller_ = new cryptohome::MockAsyncMethodCaller; 226 cryptohome::AsyncMethodCaller::InitializeForTesting( 227 mock_async_method_caller_); 228 229 cryptohome_.reset(new MockCryptohomeLibrary()); 230 EXPECT_CALL(*cryptohome_, InstallAttributesIsInvalid()) 231 .WillRepeatedly(Return(false)); 232 EXPECT_CALL(*cryptohome_, InstallAttributesIsFirstInstall()) 233 .WillRepeatedly(Return(true)); 234 EXPECT_CALL(*cryptohome_, TpmIsEnabled()) 235 .WillRepeatedly(Return(false)); 236 EXPECT_CALL(*cryptohome_, InstallAttributesSet(kAttributeOwned, kTrue)) 237 .WillRepeatedly(Return(true)); 238 EXPECT_CALL(*cryptohome_, InstallAttributesSet(kAttributeOwner, 239 kUsername)) 240 .WillRepeatedly(Return(true)); 241 EXPECT_CALL(*cryptohome_, InstallAttributesSet(kAttrEnterpriseDomain, 242 kDomain)) 243 .WillRepeatedly(Return(true)); 244 EXPECT_CALL(*cryptohome_, InstallAttributesSet(kAttrEnterpriseMode, 245 kMode)) 246 .WillRepeatedly(Return(true)); 247 EXPECT_CALL(*cryptohome_, InstallAttributesSet(kAttrEnterpriseDeviceId, 248 kDeviceId)) 249 .WillRepeatedly(Return(true)); 250 EXPECT_CALL(*cryptohome_, InstallAttributesFinalize()) 251 .WillRepeatedly(Return(true)); 252 EXPECT_CALL(*cryptohome_, InstallAttributesGet(kAttributeOwned, _)) 253 .WillRepeatedly(DoAll(SetArgPointee<1>(kTrue), 254 Return(true))); 255 EXPECT_CALL(*cryptohome_, InstallAttributesGet(kAttributeOwner, _)) 256 .WillRepeatedly(DoAll(SetArgPointee<1>(kUsername), 257 Return(true))); 258 EXPECT_CALL(*cryptohome_, InstallAttributesGet(kAttrEnterpriseDomain, _)) 259 .WillRepeatedly(DoAll(SetArgPointee<1>(kDomain), 260 Return(true))); 261 EXPECT_CALL(*cryptohome_, InstallAttributesGet(kAttrEnterpriseMode, _)) 262 .WillRepeatedly(DoAll(SetArgPointee<1>(kMode), 263 Return(true))); 264 EXPECT_CALL(*cryptohome_, InstallAttributesGet(kAttrEnterpriseDeviceId, _)) 265 .WillRepeatedly(DoAll(SetArgPointee<1>(kDeviceId), 266 Return(true))); 267 CryptohomeLibrary::SetForTest(cryptohome_.get()); 268 269 test_device_settings_service_.reset(new ScopedTestDeviceSettingsService); 270 test_cros_settings_.reset(new ScopedTestCrosSettings); 271 test_user_manager_.reset(new ScopedTestUserManager); 272 273 browser_process_->SetProfileManager( 274 new ProfileManagerWithoutInit(scoped_temp_dir_.path())); 275 connector_ = browser_process_->browser_policy_connector(); 276 connector_->Init(local_state_.Get(), 277 browser_process_->system_request_context()); 278 279 io_thread_state_.reset(new IOThread(local_state_.Get(), 280 browser_process_->policy_service(), 281 NULL, NULL)); 282 browser_process_->SetIOThread(io_thread_state_.get()); 283 284#if defined(ENABLE_RLZ) 285 rlz_initialized_cb_ = base::Bind(&base::DoNothing); 286 rlz_lib::testing::SetRlzStoreDirectory(scoped_temp_dir_.path()); 287 RLZTracker::EnableZeroDelayForTesting(); 288#endif 289 290 RunUntilIdle(); 291 } 292 293 virtual void TearDown() OVERRIDE { 294 cryptohome::AsyncMethodCaller::Shutdown(); 295 mock_async_method_caller_ = NULL; 296 297 test_user_manager_.reset(); 298 299 InvokeOnIO( 300 base::Bind(&LoginUtilsTest::TearDownOnIO, base::Unretained(this))); 301 302 // LoginUtils instance must not outlive Profile instances. 303 LoginUtils::Set(NULL); 304 305 input_method::Shutdown(); 306 ConnectivityStateHelper::SetForTest(NULL); 307 LoginState::Shutdown(); 308 CryptohomeLibrary::Shutdown(); 309 310 // These trigger some tasks that have to run while BrowserThread::UI 311 // exists. Delete all the profiles before deleting the connector. 312 browser_process_->SetProfileManager(NULL); 313 connector_ = NULL; 314 browser_process_->SetBrowserPolicyConnector(NULL); 315 QuitIOLoop(); 316 RunUntilIdle(); 317 318 CryptohomeLibrary::SetForTest(NULL); 319 } 320 321 void TearDownOnIO() { 322 // chrome_browser_net::Predictor usually skips its shutdown routines on 323 // unit_tests, but does the full thing when 324 // g_browser_process->profile_manager() is valid during initialization. 325 // That includes a WaitableEvent on UI waiting for a task on IO, so that 326 // task must execute. Do it directly from here now. 327 std::vector<Profile*> profiles = 328 browser_process_->profile_manager()->GetLoadedProfiles(); 329 for (size_t i = 0; i < profiles.size(); ++i) { 330 chrome_browser_net::Predictor* predictor = 331 profiles[i]->GetNetworkPredictor(); 332 if (predictor) { 333 predictor->EnablePredictorOnIOThread(false); 334 predictor->Shutdown(); 335 } 336 } 337 } 338 339 void RunUntilIdle() { 340 loop_.RunUntilIdle(); 341 BrowserThread::GetBlockingPool()->FlushForTesting(); 342 loop_.RunUntilIdle(); 343 } 344 345 // Invokes |task| on the IO loop and returns after it has executed. 346 void InvokeOnIO(const base::Closure& task) { 347 fake_io_thread_work_ = task; 348 fake_io_thread_completion_.Signal(); 349 content::RunMessageLoop(); 350 } 351 352 // Makes the fake IO loop return. 353 void QuitIOLoop() { 354 fake_io_thread_completion_.Signal(); 355 content::RunMessageLoop(); 356 } 357 358 // Helper for BlockLoop, InvokeOnIO and QuitIOLoop. 359 bool DoIOWork() { 360 bool has_work = !fake_io_thread_work_.is_null(); 361 if (has_work) 362 fake_io_thread_work_.Run(); 363 fake_io_thread_work_.Reset(); 364 BrowserThread::PostTask( 365 BrowserThread::UI, FROM_HERE, 366 base::MessageLoop::QuitWhenIdleClosure()); 367 // If there was work then keep waiting for more work. 368 // If there was no work then quit the fake IO loop. 369 return has_work; 370 } 371 372 virtual void OnProfilePrepared(Profile* profile) OVERRIDE { 373 EXPECT_FALSE(prepared_profile_); 374 prepared_profile_ = profile; 375 } 376 377#if defined(ENABLE_RLZ) 378 virtual void OnRlzInitialized(Profile* profile) OVERRIDE { 379 rlz_initialized_cb_.Run(); 380 } 381#endif 382 383 virtual void OnLoginFailure(const LoginFailure& error) OVERRIDE { 384 FAIL() << "OnLoginFailure not expected"; 385 } 386 387 virtual void OnLoginSuccess(const UserContext& user_context, 388 bool pending_requests, 389 bool using_oauth) OVERRIDE { 390 FAIL() << "OnLoginSuccess not expected"; 391 } 392 393 void EnrollDevice(const std::string& username) { 394 EXPECT_CALL(*cryptohome_, InstallAttributesIsFirstInstall()) 395 .WillOnce(Return(true)) 396 .WillRepeatedly(Return(false)); 397 398 base::RunLoop loop; 399 policy::EnterpriseInstallAttributes::LockResult result; 400 connector_->GetInstallAttributes()->LockDevice( 401 username, policy::DEVICE_MODE_ENTERPRISE, kDeviceId, 402 base::Bind(&CopyLockResult, &loop, &result)); 403 loop.Run(); 404 EXPECT_EQ(policy::EnterpriseInstallAttributes::LOCK_SUCCESS, result); 405 RunUntilIdle(); 406 } 407 408 void PrepareProfile(const std::string& username) { 409 // Normally this would happen during browser startup, but for tests 410 // we need to trigger creation of Profile-related services. 411 ChromeBrowserMainExtraPartsProfiles:: 412 EnsureBrowserContextKeyedServiceFactoriesBuilt(); 413 ProfileManager::AllowGetDefaultProfile(); 414 415 DeviceSettingsTestHelper device_settings_test_helper; 416 DeviceSettingsService::Get()->SetSessionManager( 417 &device_settings_test_helper, new MockOwnerKeyUtil()); 418 419 EXPECT_CALL(*cryptohome_, GetSystemSalt()) 420 .WillRepeatedly(Return(std::string("stub_system_salt"))); 421 EXPECT_CALL(*mock_async_method_caller_, AsyncMount(_, _, _, _)) 422 .WillRepeatedly(Return()); 423 EXPECT_CALL(*mock_async_method_caller_, AsyncGetSanitizedUsername(_, _)) 424 .WillRepeatedly(Return()); 425 426 scoped_refptr<Authenticator> authenticator = 427 LoginUtils::Get()->CreateAuthenticator(this); 428 authenticator->CompleteLogin(ProfileManager::GetDefaultProfile(), 429 UserContext(username, 430 "password", 431 std::string(), 432 username)); // username_hash 433 434 const bool kUsingOAuth = true; 435 // Setting |kHasCookies| to false prevents ProfileAuthData::Transfer from 436 // waiting for an IO task before proceeding. 437 const bool kHasCookies = false; 438 const bool kHasActiveSession = false; 439 LoginUtils::Get()->PrepareProfile( 440 UserContext(username, "password", std::string(), username), 441 std::string(), kUsingOAuth, kHasCookies, kHasActiveSession, this); 442 device_settings_test_helper.Flush(); 443 RunUntilIdle(); 444 445 DeviceSettingsService::Get()->UnsetSessionManager(); 446 } 447 448 net::TestURLFetcher* PrepareOAuthFetcher(const std::string& expected_url) { 449 net::TestURLFetcher* fetcher = test_url_fetcher_factory_.GetFetcherByID(0); 450 EXPECT_TRUE(fetcher); 451 if (!fetcher) 452 return NULL; 453 EXPECT_TRUE(fetcher->delegate()); 454 EXPECT_TRUE(StartsWithASCII(fetcher->GetOriginalURL().spec(), 455 expected_url, 456 true)); 457 fetcher->set_url(fetcher->GetOriginalURL()); 458 fetcher->set_response_code(200); 459 fetcher->set_status(net::URLRequestStatus()); 460 return fetcher; 461 } 462 463 net::TestURLFetcher* PrepareDMServiceFetcher( 464 const std::string& expected_url, 465 const em::DeviceManagementResponse& response) { 466 net::TestURLFetcher* fetcher = test_url_fetcher_factory_.GetFetcherByID( 467 policy::DeviceManagementService::kURLFetcherID); 468 EXPECT_TRUE(fetcher); 469 if (!fetcher) 470 return NULL; 471 EXPECT_TRUE(fetcher->delegate()); 472 EXPECT_TRUE(StartsWithASCII(fetcher->GetOriginalURL().spec(), 473 expected_url, 474 true)); 475 fetcher->set_url(fetcher->GetOriginalURL()); 476 fetcher->set_response_code(200); 477 fetcher->set_status(net::URLRequestStatus()); 478 std::string data; 479 EXPECT_TRUE(response.SerializeToString(&data)); 480 fetcher->SetResponseString(data); 481 return fetcher; 482 } 483 484 net::TestURLFetcher* PrepareDMRegisterFetcher() { 485 em::DeviceManagementResponse response; 486 em::DeviceRegisterResponse* register_response = 487 response.mutable_register_response(); 488 register_response->set_device_management_token(kDMToken); 489 register_response->set_enrollment_type( 490 em::DeviceRegisterResponse::ENTERPRISE); 491 return PrepareDMServiceFetcher(kDMRegisterRequest, response); 492 } 493 494 net::TestURLFetcher* PrepareDMPolicyFetcher() { 495 em::DeviceManagementResponse response; 496 response.mutable_policy_response()->add_response(); 497 return PrepareDMServiceFetcher(kDMPolicyRequest, response); 498 } 499 500 protected: 501 ScopedStubCrosEnabler stub_cros_enabler_; 502 503 base::Closure fake_io_thread_work_; 504 base::WaitableEvent fake_io_thread_completion_; 505 base::Thread fake_io_thread_; 506 507 base::MessageLoop loop_; 508 TestingBrowserProcess* browser_process_; 509 ScopedTestingLocalState local_state_; 510 511 content::TestBrowserThread ui_thread_; 512 content::TestBrowserThread db_thread_; 513 content::TestBrowserThread file_thread_; 514 scoped_ptr<content::TestBrowserThread> io_thread_; 515 scoped_ptr<IOThread> io_thread_state_; 516 517 MockDBusThreadManagerWithoutGMock mock_dbus_thread_manager_; 518 input_method::MockInputMethodManager* mock_input_method_manager_; 519 disks::MockDiskMountManager mock_disk_mount_manager_; 520 net::TestURLFetcherFactory test_url_fetcher_factory_; 521 MockConnectivityStateHelper mock_connectivity_state_helper_; 522 523 cryptohome::MockAsyncMethodCaller* mock_async_method_caller_; 524 525 policy::BrowserPolicyConnector* connector_; 526 scoped_ptr<MockCryptohomeLibrary> cryptohome_; 527 528 // Initialized after |mock_dbus_thread_manager_| and |cryptohome_| are set up. 529 scoped_ptr<ScopedTestDeviceSettingsService> test_device_settings_service_; 530 scoped_ptr<ScopedTestCrosSettings> test_cros_settings_; 531 scoped_ptr<ScopedTestUserManager> test_user_manager_; 532 533 Profile* prepared_profile_; 534 535 base::Closure rlz_initialized_cb_; 536 537 private: 538 base::ScopedTempDir scoped_temp_dir_; 539 540 std::string device_policy_; 541 std::string user_policy_; 542 543 DISALLOW_COPY_AND_ASSIGN(LoginUtilsTest); 544}; 545 546class LoginUtilsBlockingLoginTest 547 : public LoginUtilsTest, 548 public testing::WithParamInterface<int> {}; 549 550TEST_F(LoginUtilsTest, NormalLoginDoesntBlock) { 551 UserManager* user_manager = UserManager::Get(); 552 EXPECT_FALSE(user_manager->IsUserLoggedIn()); 553 EXPECT_FALSE(connector_->IsEnterpriseManaged()); 554 EXPECT_FALSE(prepared_profile_); 555 EXPECT_EQ(policy::USER_AFFILIATION_NONE, 556 connector_->GetUserAffiliation(kUsername)); 557 558 // The profile will be created without waiting for a policy response. 559 PrepareProfile(kUsername); 560 561 EXPECT_TRUE(prepared_profile_); 562 ASSERT_TRUE(user_manager->IsUserLoggedIn()); 563 EXPECT_EQ(kUsername, user_manager->GetLoggedInUser()->email()); 564} 565 566TEST_F(LoginUtilsTest, EnterpriseLoginDoesntBlockForNormalUser) { 567 UserManager* user_manager = UserManager::Get(); 568 EXPECT_FALSE(user_manager->IsUserLoggedIn()); 569 EXPECT_FALSE(connector_->IsEnterpriseManaged()); 570 EXPECT_FALSE(prepared_profile_); 571 572 // Enroll the device. 573 EnrollDevice(kUsername); 574 575 EXPECT_FALSE(user_manager->IsUserLoggedIn()); 576 EXPECT_TRUE(connector_->IsEnterpriseManaged()); 577 EXPECT_EQ(kDomain, connector_->GetEnterpriseDomain()); 578 EXPECT_FALSE(prepared_profile_); 579 EXPECT_EQ(policy::USER_AFFILIATION_NONE, 580 connector_->GetUserAffiliation(kUsernameOtherDomain)); 581 582 // Login with a non-enterprise user shouldn't block. 583 PrepareProfile(kUsernameOtherDomain); 584 585 EXPECT_TRUE(prepared_profile_); 586 ASSERT_TRUE(user_manager->IsUserLoggedIn()); 587 EXPECT_EQ(kUsernameOtherDomain, user_manager->GetLoggedInUser()->email()); 588} 589 590#if defined(ENABLE_RLZ) 591TEST_F(LoginUtilsTest, RlzInitialized) { 592 // No RLZ brand code set initially. 593 EXPECT_FALSE(local_state_.Get()->HasPrefPath(prefs::kRLZBrand)); 594 595 base::RunLoop wait_for_rlz_init; 596 rlz_initialized_cb_ = wait_for_rlz_init.QuitClosure(); 597 598 PrepareProfile(kUsername); 599 600 wait_for_rlz_init.Run(); 601 // Wait for blocking RLZ tasks to complete. 602 RunUntilIdle(); 603 604 // RLZ brand code has been set to empty string. 605 EXPECT_TRUE(local_state_.Get()->HasPrefPath(prefs::kRLZBrand)); 606 EXPECT_EQ(std::string(), local_state_.Get()->GetString(prefs::kRLZBrand)); 607 608 // RLZ value for homepage access point should have been initialized. 609 string16 rlz_string; 610 EXPECT_TRUE(RLZTracker::GetAccessPointRlz( 611 RLZTracker::CHROME_HOME_PAGE, &rlz_string)); 612 EXPECT_EQ(string16(), rlz_string); 613} 614#endif 615 616TEST_P(LoginUtilsBlockingLoginTest, EnterpriseLoginBlocksForEnterpriseUser) { 617 UserManager* user_manager = UserManager::Get(); 618 EXPECT_FALSE(user_manager->IsUserLoggedIn()); 619 EXPECT_FALSE(connector_->IsEnterpriseManaged()); 620 EXPECT_FALSE(prepared_profile_); 621 622 // Enroll the device. 623 EnrollDevice(kUsername); 624 625 EXPECT_FALSE(user_manager->IsUserLoggedIn()); 626 EXPECT_TRUE(connector_->IsEnterpriseManaged()); 627 EXPECT_EQ(kDomain, connector_->GetEnterpriseDomain()); 628 EXPECT_FALSE(prepared_profile_); 629 EXPECT_EQ(policy::USER_AFFILIATION_MANAGED, 630 connector_->GetUserAffiliation(kUsername)); 631 EXPECT_FALSE(user_manager->IsKnownUser(kUsername)); 632 633 // Login with a user of the enterprise domain waits for policy. 634 PrepareProfile(kUsername); 635 636 EXPECT_FALSE(prepared_profile_); 637 ASSERT_TRUE(user_manager->IsUserLoggedIn()); 638 EXPECT_TRUE(user_manager->IsCurrentUserNew()); 639 640 GaiaUrls* gaia_urls = GaiaUrls::GetInstance(); 641 net::TestURLFetcher* fetcher; 642 643 // |steps| is the test parameter, and is the number of successful fetches. 644 // The first incomplete fetch will fail. In any case, the profile creation 645 // should resume. 646 int steps = GetParam(); 647 648 // The next expected fetcher ID. This is used to make it fail. 649 int next_expected_fetcher_id = 0; 650 651 do { 652 if (steps < 1) break; 653 654 // Fake refresh token retrieval: 655 fetcher = PrepareOAuthFetcher(gaia_urls->client_login_to_oauth2_url()); 656 ASSERT_TRUE(fetcher); 657 net::ResponseCookies cookies; 658 cookies.push_back(kOAuthTokenCookie); 659 fetcher->set_cookies(cookies); 660 fetcher->delegate()->OnURLFetchComplete(fetcher); 661 if (steps < 2) break; 662 663 // Fake OAuth2 token pair retrieval: 664 fetcher = PrepareOAuthFetcher(gaia_urls->oauth2_token_url()); 665 ASSERT_TRUE(fetcher); 666 fetcher->SetResponseString(kOAuth2TokenPairData); 667 fetcher->delegate()->OnURLFetchComplete(fetcher); 668 if (steps < 3) break; 669 670 // Fake OAuth2 access token retrieval: 671 fetcher = PrepareOAuthFetcher(gaia_urls->oauth2_token_url()); 672 ASSERT_TRUE(fetcher); 673 fetcher->SetResponseString(kOAuth2AccessTokenData); 674 fetcher->delegate()->OnURLFetchComplete(fetcher); 675 676 // The cloud policy subsystem is now ready to fetch the dmtoken and the user 677 // policy. 678 next_expected_fetcher_id = policy::DeviceManagementService::kURLFetcherID; 679 RunUntilIdle(); 680 if (steps < 4) break; 681 682 fetcher = PrepareDMRegisterFetcher(); 683 ASSERT_TRUE(fetcher); 684 fetcher->delegate()->OnURLFetchComplete(fetcher); 685 // The policy fetch job has now been scheduled, run it: 686 RunUntilIdle(); 687 if (steps < 5) break; 688 689 // Verify that there is no profile prepared just before the policy fetch. 690 EXPECT_FALSE(prepared_profile_); 691 692 fetcher = PrepareDMPolicyFetcher(); 693 ASSERT_TRUE(fetcher); 694 fetcher->delegate()->OnURLFetchComplete(fetcher); 695 RunUntilIdle(); 696 } while (0); 697 698 if (steps < 5) { 699 // Verify that the profile hasn't been created yet. 700 EXPECT_FALSE(prepared_profile_); 701 702 // Make the current fetcher fail with a Gaia error. 703 net::TestURLFetcher* fetcher = test_url_fetcher_factory_.GetFetcherByID( 704 next_expected_fetcher_id); 705 ASSERT_TRUE(fetcher); 706 EXPECT_TRUE(fetcher->delegate()); 707 fetcher->set_url(fetcher->GetOriginalURL()); 708 fetcher->set_response_code(401); 709 // This response body is important to make the gaia fetcher skip its delayed 710 // retry behavior, which makes testing harder. If this is sent to the policy 711 // fetchers then it will make them fail too. 712 fetcher->SetResponseString(kGaiaAccountDisabledResponse); 713 fetcher->delegate()->OnURLFetchComplete(fetcher); 714 RunUntilIdle(); 715 } 716 717 // The profile is finally ready: 718 EXPECT_TRUE(prepared_profile_); 719} 720 721INSTANTIATE_TEST_CASE_P( 722 LoginUtilsBlockingLoginTestInstance, 723 LoginUtilsBlockingLoginTest, 724 testing::Values(0, 1, 2, 3, 4, 5)); 725 726} // namespace 727 728} 729