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