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