existing_user_controller_browsertest.cc revision 116680a4aac90f2aa7413d9095a592090648e557
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 <vector>
6
7#include "base/bind.h"
8#include "base/bind_helpers.h"
9#include "base/callback.h"
10#include "base/command_line.h"
11#include "base/location.h"
12#include "base/memory/ref_counted.h"
13#include "base/run_loop.h"
14#include "chrome/browser/chrome_notification_types.h"
15#include "chrome/browser/chromeos/login/auth/authenticator.h"
16#include "chrome/browser/chromeos/login/auth/mock_authenticator.h"
17#include "chrome/browser/chromeos/login/auth/mock_url_fetchers.h"
18#include "chrome/browser/chromeos/login/existing_user_controller.h"
19#include "chrome/browser/chromeos/login/helper.h"
20#include "chrome/browser/chromeos/login/mock_login_utils.h"
21#include "chrome/browser/chromeos/login/ui/mock_login_display.h"
22#include "chrome/browser/chromeos/login/ui/mock_login_display_host.h"
23#include "chrome/browser/chromeos/login/users/mock_user_manager.h"
24#include "chrome/browser/chromeos/login/users/user.h"
25#include "chrome/browser/chromeos/login/users/user_manager.h"
26#include "chrome/browser/chromeos/login/wizard_controller.h"
27#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
28#include "chrome/browser/chromeos/policy/device_local_account.h"
29#include "chrome/browser/chromeos/policy/device_local_account_policy_service.h"
30#include "chrome/browser/chromeos/policy/device_policy_cros_browser_test.h"
31#include "chrome/browser/chromeos/policy/proto/chrome_device_policy.pb.h"
32#include "chrome/browser/chromeos/settings/cros_settings.h"
33#include "chrome/test/base/testing_browser_process.h"
34#include "chrome/test/base/testing_profile.h"
35#include "chrome/test/base/ui_test_utils.h"
36#include "chromeos/chromeos_switches.h"
37#include "chromeos/dbus/fake_session_manager_client.h"
38#include "chromeos/login/auth/key.h"
39#include "chromeos/login/auth/user_context.h"
40#include "chromeos/settings/cros_settings_names.h"
41#include "components/policy/core/common/cloud/cloud_policy_constants.h"
42#include "components/policy/core/common/cloud/cloud_policy_core.h"
43#include "components/policy/core/common/cloud/cloud_policy_store.h"
44#include "components/policy/core/common/cloud/mock_cloud_policy_store.h"
45#include "components/policy/core/common/cloud/policy_builder.h"
46#include "content/public/test/mock_notification_observer.h"
47#include "content/public/test/test_utils.h"
48#include "google_apis/gaia/mock_url_fetcher_factory.h"
49#include "grit/generated_resources.h"
50#include "testing/gmock/include/gmock/gmock.h"
51#include "testing/gtest/include/gtest/gtest.h"
52#include "ui/base/l10n/l10n_util.h"
53
54using ::testing::AnyNumber;
55using ::testing::Invoke;
56using ::testing::InvokeWithoutArgs;
57using ::testing::Return;
58using ::testing::ReturnNull;
59using ::testing::Sequence;
60using ::testing::WithArg;
61using ::testing::_;
62
63namespace em = enterprise_management;
64
65namespace chromeos {
66
67namespace {
68
69const char kUsername[] = "test_user@gmail.com";
70const char kNewUsername[] = "test_new_user@gmail.com";
71const char kPassword[] = "test_password";
72
73const char kPublicSessionAccountId[] = "public_session_user@localhost";
74const int kAutoLoginNoDelay = 0;
75const int kAutoLoginShortDelay = 1;
76const int kAutoLoginLongDelay = 10000;
77
78ACTION_P(CreateAuthenticator, user_context) {
79  return new MockAuthenticator(arg0, user_context);
80}
81
82}  // namespace
83
84class ExistingUserControllerTest : public policy::DevicePolicyCrosBrowserTest {
85 protected:
86  ExistingUserControllerTest()
87      : mock_login_display_(NULL), mock_user_manager_(NULL) {}
88
89  ExistingUserController* existing_user_controller() {
90    return ExistingUserController::current_controller();
91  }
92
93  const ExistingUserController* existing_user_controller() const {
94    return ExistingUserController::current_controller();
95  }
96
97  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
98    SetUpSessionManager();
99
100    DevicePolicyCrosBrowserTest::SetUpInProcessBrowserTestFixture();
101
102    mock_login_utils_ = new MockLoginUtils();
103    LoginUtils::Set(mock_login_utils_);
104    EXPECT_CALL(*mock_login_utils_, DelegateDeleted(_))
105        .Times(1);
106
107    mock_login_display_host_.reset(new MockLoginDisplayHost());
108    mock_login_display_ = new MockLoginDisplay();
109    SetUpLoginDisplay();
110  }
111
112  virtual void SetUpSessionManager() {
113  }
114
115  virtual void SetUpLoginDisplay() {
116    EXPECT_CALL(*mock_login_display_host_.get(), CreateLoginDisplay(_))
117        .Times(1)
118        .WillOnce(Return(mock_login_display_));
119    EXPECT_CALL(*mock_login_display_host_.get(), GetNativeWindow())
120        .Times(1)
121        .WillOnce(ReturnNull());
122    EXPECT_CALL(*mock_login_display_host_.get(), OnPreferencesChanged())
123        .Times(1);
124    EXPECT_CALL(*mock_login_display_, Init(_, false, true, true))
125        .Times(1);
126  }
127
128  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
129    command_line->AppendSwitch(switches::kLoginManager);
130  }
131
132  virtual void SetUpUserManager() {
133    // Replace the UserManager singleton with a mock.
134    mock_user_manager_ = new MockUserManager;
135    user_manager_enabler_.reset(
136        new ScopedUserManagerEnabler(mock_user_manager_));
137    EXPECT_CALL(*mock_user_manager_, IsKnownUser(kUsername))
138        .Times(AnyNumber())
139        .WillRepeatedly(Return(true));
140    EXPECT_CALL(*mock_user_manager_, IsKnownUser(kNewUsername))
141        .Times(AnyNumber())
142        .WillRepeatedly(Return(false));
143    EXPECT_CALL(*mock_user_manager_, IsUserLoggedIn())
144        .Times(AnyNumber())
145        .WillRepeatedly(Return(false));
146    EXPECT_CALL(*mock_user_manager_, IsLoggedInAsGuest())
147        .Times(AnyNumber())
148        .WillRepeatedly(Return(false));
149    EXPECT_CALL(*mock_user_manager_, IsLoggedInAsDemoUser())
150        .Times(AnyNumber())
151        .WillRepeatedly(Return(false));
152    EXPECT_CALL(*mock_user_manager_, IsLoggedInAsPublicAccount())
153        .Times(AnyNumber())
154        .WillRepeatedly(Return(false));
155    EXPECT_CALL(*mock_user_manager_, IsSessionStarted())
156        .Times(AnyNumber())
157        .WillRepeatedly(Return(false));
158    EXPECT_CALL(*mock_user_manager_, IsCurrentUserNew())
159        .Times(AnyNumber())
160        .WillRepeatedly(Return(false));
161    EXPECT_CALL(*mock_user_manager_, Shutdown())
162        .Times(1);
163  }
164
165  virtual void SetUpOnMainThread() OVERRIDE {
166    testing_profile_.reset(new TestingProfile());
167    SetUpUserManager();
168    existing_user_controller_.reset(
169        new ExistingUserController(mock_login_display_host_.get()));
170    ASSERT_EQ(existing_user_controller(), existing_user_controller_.get());
171    existing_user_controller_->Init(UserList());
172    profile_prepared_cb_ =
173        base::Bind(&ExistingUserController::OnProfilePrepared,
174                   base::Unretained(existing_user_controller()),
175                   testing_profile_.get());
176  }
177
178  virtual void CleanUpOnMainThread() OVERRIDE {
179    // ExistingUserController must be deleted before the thread is cleaned up:
180    // If there is an outstanding login attempt when ExistingUserController is
181    // deleted, its LoginPerformer instance will be deleted, which in turn
182    // deletes its OnlineAttemptHost instance.  However, OnlineAttemptHost must
183    // be deleted on the UI thread.
184    existing_user_controller_.reset();
185    DevicePolicyCrosBrowserTest::InProcessBrowserTest::CleanUpOnMainThread();
186    testing_profile_.reset(NULL);
187    user_manager_enabler_.reset();
188  }
189
190  // ExistingUserController private member accessors.
191  base::OneShotTimer<ExistingUserController>* auto_login_timer() {
192    return existing_user_controller()->auto_login_timer_.get();
193  }
194
195  const std::string& auto_login_username() const {
196    return existing_user_controller()->public_session_auto_login_username_;
197  }
198
199  int auto_login_delay() const {
200    return existing_user_controller()->public_session_auto_login_delay_;
201  }
202
203  bool is_login_in_progress() const {
204    return existing_user_controller()->is_login_in_progress_;
205  }
206
207  scoped_ptr<ExistingUserController> existing_user_controller_;
208
209  // |mock_login_display_| is owned by the ExistingUserController, which calls
210  // CreateLoginDisplay() on the |mock_login_display_host_| to get it.
211  MockLoginDisplay* mock_login_display_;
212  scoped_ptr<MockLoginDisplayHost> mock_login_display_host_;
213
214  // Owned by LoginUtilsWrapper.
215  MockLoginUtils* mock_login_utils_;
216
217  MockUserManager* mock_user_manager_;  // Not owned.
218  scoped_ptr<ScopedUserManagerEnabler> user_manager_enabler_;
219
220  scoped_ptr<TestingProfile> testing_profile_;
221
222  // Mock URLFetcher.
223  MockURLFetcherFactory<SuccessFetcher> factory_;
224
225  base::Callback<void(void)> profile_prepared_cb_;
226
227 private:
228  DISALLOW_COPY_AND_ASSIGN(ExistingUserControllerTest);
229};
230
231IN_PROC_BROWSER_TEST_F(ExistingUserControllerTest, ExistingUserLogin) {
232  // This is disabled twice: once right after signin but before checking for
233  // auto-enrollment, and again after doing an ownership status check.
234  EXPECT_CALL(*mock_login_display_, SetUIEnabled(false))
235      .Times(2);
236  UserContext user_context(kUsername);
237  user_context.SetKey(Key(kPassword));
238  user_context.SetUserIDHash(kUsername);
239  EXPECT_CALL(*mock_login_utils_, CreateAuthenticator(_))
240      .Times(1)
241      .WillOnce(WithArg<0>(CreateAuthenticator(user_context)));
242  EXPECT_CALL(*mock_login_utils_, PrepareProfile(user_context, _, _, _))
243      .Times(1)
244      .WillOnce(InvokeWithoutArgs(&profile_prepared_cb_,
245                                  &base::Callback<void(void)>::Run));
246  EXPECT_CALL(*mock_login_utils_,
247              DoBrowserLaunch(testing_profile_.get(),
248                              mock_login_display_host_.get()))
249      .Times(1);
250  EXPECT_CALL(*mock_login_display_, SetUIEnabled(true))
251      .Times(1);
252  EXPECT_CALL(*mock_login_display_host_,
253              StartWizardPtr(WizardController::kTermsOfServiceScreenName, NULL))
254      .Times(0);
255  EXPECT_CALL(*mock_user_manager_, IsCurrentUserNew())
256      .Times(AnyNumber())
257      .WillRepeatedly(Return(false));
258  existing_user_controller()->Login(user_context, SigninSpecifics());
259  content::RunAllPendingInMessageLoop();
260}
261
262IN_PROC_BROWSER_TEST_F(ExistingUserControllerTest, AutoEnrollAfterSignIn) {
263  EXPECT_CALL(*mock_login_display_host_,
264              StartWizardPtr(WizardController::kEnrollmentScreenName,
265                             _))
266      .Times(1);
267  EXPECT_CALL(*mock_login_display_host_.get(), OnCompleteLogin())
268      .Times(1);
269  EXPECT_CALL(*mock_user_manager_, IsCurrentUserNew())
270      .Times(AnyNumber())
271      .WillRepeatedly(Return(false));
272  // The order of these expected calls matters: the UI if first disabled
273  // during the login sequence, and is enabled again for the enrollment screen.
274  Sequence uiEnabledSequence;
275  EXPECT_CALL(*mock_login_display_, SetUIEnabled(false))
276      .Times(1)
277      .InSequence(uiEnabledSequence);
278  EXPECT_CALL(*mock_login_display_, SetUIEnabled(true))
279      .Times(1)
280      .InSequence(uiEnabledSequence);
281  existing_user_controller()->DoAutoEnrollment();
282  UserContext user_context(kUsername);
283  user_context.SetKey(Key(kPassword));
284  existing_user_controller()->CompleteLogin(user_context);
285  content::RunAllPendingInMessageLoop();
286}
287
288IN_PROC_BROWSER_TEST_F(ExistingUserControllerTest,
289                       NewUserDontAutoEnrollAfterSignIn) {
290  EXPECT_CALL(*mock_login_display_host_,
291              StartWizardPtr(WizardController::kEnrollmentScreenName,
292                             _))
293      .Times(0);
294  EXPECT_CALL(*mock_login_display_host_,
295              StartWizardPtr(WizardController::kTermsOfServiceScreenName,
296                             NULL))
297      .Times(1);
298  UserContext user_context(kNewUsername);
299  user_context.SetKey(Key(kPassword));
300  user_context.SetUserIDHash(kNewUsername);
301  EXPECT_CALL(*mock_login_utils_, CreateAuthenticator(_))
302      .Times(1)
303      .WillOnce(WithArg<0>(CreateAuthenticator(user_context)));
304  base::Callback<void(void)> add_user_cb =
305      base::Bind(&MockUserManager::AddUser,
306                 base::Unretained(mock_user_manager_),
307                 kNewUsername);
308  EXPECT_CALL(*mock_login_utils_, PrepareProfile(user_context, _, _, _))
309      .Times(1)
310      .WillOnce(DoAll(
311          InvokeWithoutArgs(&add_user_cb,
312                            &base::Callback<void(void)>::Run),
313          InvokeWithoutArgs(&profile_prepared_cb_,
314                            &base::Callback<void(void)>::Run)));
315  EXPECT_CALL(*mock_login_display_host_.get(), OnCompleteLogin())
316      .Times(1);
317  EXPECT_CALL(*mock_user_manager_, IsCurrentUserNew())
318      .Times(AnyNumber())
319      .WillRepeatedly(Return(true));
320
321  // The order of these expected calls matters: the UI if first disabled
322  // during the login sequence, and is enabled again after login completion.
323  Sequence uiEnabledSequence;
324  // This is disabled twice: once right after signin but before checking for
325  // auto-enrollment, and again after doing an ownership status check.
326  EXPECT_CALL(*mock_login_display_, SetUIEnabled(false))
327      .Times(2)
328      .InSequence(uiEnabledSequence);
329  EXPECT_CALL(*mock_login_display_, SetUIEnabled(true))
330      .Times(1)
331      .InSequence(uiEnabledSequence);
332
333  existing_user_controller()->CompleteLogin(user_context);
334  content::RunAllPendingInMessageLoop();
335}
336
337MATCHER_P(HasDetails, expected, "") {
338  return expected == *content::Details<const std::string>(arg).ptr();
339}
340
341class ExistingUserControllerPublicSessionTest
342    : public ExistingUserControllerTest {
343 protected:
344  ExistingUserControllerPublicSessionTest()
345      : public_session_user_id_(policy::GenerateDeviceLocalAccountUserId(
346            kPublicSessionAccountId,
347            policy::DeviceLocalAccount::TYPE_PUBLIC_SESSION)) {
348  }
349
350  virtual void SetUpOnMainThread() OVERRIDE {
351    ExistingUserControllerTest::SetUpOnMainThread();
352
353    // Wait for the public session user to be created.
354    if (!chromeos::UserManager::Get()->IsKnownUser(public_session_user_id_)) {
355      content::WindowedNotificationObserver(
356          chrome::NOTIFICATION_USER_LIST_CHANGED,
357          base::Bind(&chromeos::UserManager::IsKnownUser,
358                     base::Unretained(chromeos::UserManager::Get()),
359                     public_session_user_id_)).Wait();
360    }
361
362    // Wait for the device local account policy to be installed.
363    policy::CloudPolicyStore* store =
364        TestingBrowserProcess::GetGlobal()
365            ->platform_part()
366            ->browser_policy_connector_chromeos()
367            ->GetDeviceLocalAccountPolicyService()
368            ->GetBrokerForUser(public_session_user_id_)
369            ->core()
370            ->store();
371    if (!store->has_policy()) {
372      policy::MockCloudPolicyStoreObserver observer;
373
374      base::RunLoop loop;
375      store->AddObserver(&observer);
376      EXPECT_CALL(observer, OnStoreLoaded(store))
377          .Times(1)
378          .WillOnce(InvokeWithoutArgs(&loop, &base::RunLoop::Quit));
379      loop.Run();
380      store->RemoveObserver(&observer);
381    }
382  }
383
384  virtual void SetUpSessionManager() OVERRIDE {
385    InstallOwnerKey();
386
387    // Setup the device policy.
388    em::ChromeDeviceSettingsProto& proto(device_policy()->payload());
389    em::DeviceLocalAccountInfoProto* account =
390        proto.mutable_device_local_accounts()->add_account();
391    account->set_account_id(kPublicSessionAccountId);
392    account->set_type(
393        em::DeviceLocalAccountInfoProto::ACCOUNT_TYPE_PUBLIC_SESSION);
394    RefreshDevicePolicy();
395
396    // Setup the device local account policy.
397    policy::UserPolicyBuilder device_local_account_policy;
398    device_local_account_policy.policy_data().set_username(
399        kPublicSessionAccountId);
400    device_local_account_policy.policy_data().set_policy_type(
401        policy::dm_protocol::kChromePublicAccountPolicyType);
402    device_local_account_policy.policy_data().set_settings_entity_id(
403        kPublicSessionAccountId);
404    device_local_account_policy.Build();
405    session_manager_client()->set_device_local_account_policy(
406        kPublicSessionAccountId,
407        device_local_account_policy.GetBlob());
408  }
409
410  virtual void SetUpLoginDisplay() OVERRIDE {
411    EXPECT_CALL(*mock_login_display_host_.get(), CreateLoginDisplay(_))
412        .Times(1)
413        .WillOnce(Return(mock_login_display_));
414    EXPECT_CALL(*mock_login_display_host_.get(), GetNativeWindow())
415      .Times(AnyNumber())
416      .WillRepeatedly(ReturnNull());
417    EXPECT_CALL(*mock_login_display_host_.get(), OnPreferencesChanged())
418      .Times(AnyNumber());
419    EXPECT_CALL(*mock_login_display_, Init(_, _, _, _))
420      .Times(AnyNumber());
421  }
422
423  virtual void SetUpUserManager() OVERRIDE {
424  }
425
426  void ExpectSuccessfulLogin(const UserContext& user_context) {
427    EXPECT_CALL(*mock_login_display_, SetUIEnabled(false))
428        .Times(AnyNumber());
429    EXPECT_CALL(*mock_login_utils_, CreateAuthenticator(_))
430        .Times(1)
431        .WillOnce(WithArg<0>(CreateAuthenticator(user_context)));
432    EXPECT_CALL(*mock_login_utils_, PrepareProfile(user_context, _, _, _))
433        .Times(1)
434        .WillOnce(InvokeWithoutArgs(&profile_prepared_cb_,
435                                    &base::Callback<void(void)>::Run));
436    EXPECT_CALL(*mock_login_utils_,
437                DoBrowserLaunch(testing_profile_.get(),
438                                mock_login_display_host_.get()))
439        .Times(1);
440    EXPECT_CALL(*mock_login_display_, SetUIEnabled(true))
441        .Times(1);
442    EXPECT_CALL(*mock_login_display_host_,
443                StartWizardPtr(WizardController::kTermsOfServiceScreenName,
444                               NULL))
445        .Times(0);
446  }
447
448  void SetAutoLoginPolicy(const std::string& username, int delay) {
449    // Wait until ExistingUserController has finished auto-login
450    // configuration by observing the same settings that trigger
451    // ConfigurePublicSessionAutoLogin.
452
453    em::ChromeDeviceSettingsProto& proto(device_policy()->payload());
454
455    // If both settings have changed we need to wait for both to
456    // propagate, so check the new values against the old ones.
457    scoped_refptr<content::MessageLoopRunner> runner1;
458    scoped_ptr<CrosSettings::ObserverSubscription> subscription1;
459    if (!proto.has_device_local_accounts() ||
460        !proto.device_local_accounts().has_auto_login_id() ||
461        proto.device_local_accounts().auto_login_id() != username) {
462      runner1 = new content::MessageLoopRunner;
463      subscription1 = chromeos::CrosSettings::Get()->AddSettingsObserver(
464          chromeos::kAccountsPrefDeviceLocalAccountAutoLoginId,
465          runner1->QuitClosure());
466    }
467    scoped_refptr<content::MessageLoopRunner> runner2;
468    scoped_ptr<CrosSettings::ObserverSubscription> subscription2;
469    if (!proto.has_device_local_accounts() ||
470        !proto.device_local_accounts().has_auto_login_delay() ||
471        proto.device_local_accounts().auto_login_delay() != delay) {
472      runner1 = new content::MessageLoopRunner;
473      subscription1 = chromeos::CrosSettings::Get()->AddSettingsObserver(
474          chromeos::kAccountsPrefDeviceLocalAccountAutoLoginDelay,
475          runner1->QuitClosure());
476    }
477
478    // Update the policy.
479    proto.mutable_device_local_accounts()->set_auto_login_id(username);
480    proto.mutable_device_local_accounts()->set_auto_login_delay(delay);
481    RefreshDevicePolicy();
482
483    // Wait for ExistingUserController to read the updated settings.
484    if (runner1.get())
485      runner1->Run();
486    if (runner2.get())
487      runner2->Run();
488  }
489
490  void ConfigureAutoLogin() {
491    existing_user_controller()->ConfigurePublicSessionAutoLogin();
492  }
493
494  void FireAutoLogin() {
495    existing_user_controller()->OnPublicSessionAutoLoginTimerFire();
496  }
497
498  const std::string public_session_user_id_;
499
500 private:
501  DISALLOW_COPY_AND_ASSIGN(ExistingUserControllerPublicSessionTest);
502};
503
504IN_PROC_BROWSER_TEST_F(ExistingUserControllerPublicSessionTest,
505                       ConfigureAutoLoginUsingPolicy) {
506  existing_user_controller()->OnSigninScreenReady();
507  EXPECT_EQ("", auto_login_username());
508  EXPECT_EQ(0, auto_login_delay());
509  EXPECT_FALSE(auto_login_timer());
510
511  // Set the policy.
512  SetAutoLoginPolicy(kPublicSessionAccountId, kAutoLoginLongDelay);
513  EXPECT_EQ(public_session_user_id_, auto_login_username());
514  EXPECT_EQ(kAutoLoginLongDelay, auto_login_delay());
515  ASSERT_TRUE(auto_login_timer());
516  EXPECT_TRUE(auto_login_timer()->IsRunning());
517
518  // Unset the policy.
519  SetAutoLoginPolicy("", 0);
520  EXPECT_EQ("", auto_login_username());
521  EXPECT_EQ(0, auto_login_delay());
522  ASSERT_TRUE(auto_login_timer());
523  EXPECT_FALSE(auto_login_timer()->IsRunning());
524}
525
526IN_PROC_BROWSER_TEST_F(ExistingUserControllerPublicSessionTest,
527                       AutoLoginNoDelay) {
528  // Set up mocks to check login success.
529  UserContext user_context(public_session_user_id_);
530  user_context.SetUserIDHash(user_context.GetUserID());
531  ExpectSuccessfulLogin(user_context);
532  existing_user_controller()->OnSigninScreenReady();
533
534  // Start auto-login and wait for login tasks to complete.
535  SetAutoLoginPolicy(kPublicSessionAccountId, kAutoLoginNoDelay);
536  content::RunAllPendingInMessageLoop();
537}
538
539IN_PROC_BROWSER_TEST_F(ExistingUserControllerPublicSessionTest,
540                       AutoLoginShortDelay) {
541  // Set up mocks to check login success.
542  UserContext user_context(public_session_user_id_);
543  user_context.SetUserIDHash(user_context.GetUserID());
544  ExpectSuccessfulLogin(user_context);
545  existing_user_controller()->OnSigninScreenReady();
546  SetAutoLoginPolicy(kPublicSessionAccountId, kAutoLoginShortDelay);
547  ASSERT_TRUE(auto_login_timer());
548  // Don't assert that timer is running: with the short delay sometimes
549  // the trigger happens before the assert.  We've already tested that
550  // the timer starts when it should.
551
552  // Wait for the timer to fire.
553  base::RunLoop runner;
554  base::OneShotTimer<base::RunLoop> timer;
555  timer.Start(FROM_HERE,
556              base::TimeDelta::FromMilliseconds(kAutoLoginShortDelay + 1),
557              runner.QuitClosure());
558  runner.Run();
559
560  // Wait for login tasks to complete.
561  content::RunAllPendingInMessageLoop();
562}
563
564IN_PROC_BROWSER_TEST_F(ExistingUserControllerPublicSessionTest,
565                       LoginStopsAutoLogin) {
566  // Set up mocks to check login success.
567  UserContext user_context(kUsername);
568  user_context.SetKey(Key(kPassword));
569  user_context.SetUserIDHash(user_context.GetUserID());
570  ExpectSuccessfulLogin(user_context);
571
572  existing_user_controller()->OnSigninScreenReady();
573  SetAutoLoginPolicy(kPublicSessionAccountId, kAutoLoginLongDelay);
574  ASSERT_TRUE(auto_login_timer());
575
576  // Log in and check that it stopped the timer.
577  existing_user_controller()->Login(user_context, SigninSpecifics());
578  EXPECT_TRUE(is_login_in_progress());
579  ASSERT_TRUE(auto_login_timer());
580  EXPECT_FALSE(auto_login_timer()->IsRunning());
581
582  // Wait for login tasks to complete.
583  content::RunAllPendingInMessageLoop();
584
585  // Timer should still be stopped after login completes.
586  ASSERT_TRUE(auto_login_timer());
587  EXPECT_FALSE(auto_login_timer()->IsRunning());
588}
589
590IN_PROC_BROWSER_TEST_F(ExistingUserControllerPublicSessionTest,
591                       GuestModeLoginStopsAutoLogin) {
592  EXPECT_CALL(*mock_login_display_, SetUIEnabled(false))
593      .Times(1);
594  UserContext user_context(kUsername);
595  user_context.SetKey(Key(kPassword));
596  EXPECT_CALL(*mock_login_utils_, CreateAuthenticator(_))
597      .Times(1)
598      .WillOnce(WithArg<0>(CreateAuthenticator(user_context)));
599  EXPECT_CALL(*mock_login_utils_, CompleteOffTheRecordLogin(_))
600      .Times(1);
601
602  existing_user_controller()->OnSigninScreenReady();
603  SetAutoLoginPolicy(kPublicSessionAccountId, kAutoLoginLongDelay);
604  ASSERT_TRUE(auto_login_timer());
605
606  // Login and check that it stopped the timer.
607  existing_user_controller()->LoginAsGuest();
608  EXPECT_TRUE(is_login_in_progress());
609  ASSERT_TRUE(auto_login_timer());
610  EXPECT_FALSE(auto_login_timer()->IsRunning());
611
612  // Wait for login tasks to complete.
613  content::RunAllPendingInMessageLoop();
614
615  // Timer should still be stopped after login completes.
616  ASSERT_TRUE(auto_login_timer());
617  EXPECT_FALSE(auto_login_timer()->IsRunning());
618}
619
620IN_PROC_BROWSER_TEST_F(ExistingUserControllerPublicSessionTest,
621                       CompleteLoginStopsAutoLogin) {
622  // Set up mocks to check login success.
623  UserContext user_context(kUsername);
624  user_context.SetKey(Key(kPassword));
625  user_context.SetUserIDHash(user_context.GetUserID());
626  ExpectSuccessfulLogin(user_context);
627  EXPECT_CALL(*mock_login_display_host_, OnCompleteLogin())
628      .Times(1);
629
630  existing_user_controller()->OnSigninScreenReady();
631  SetAutoLoginPolicy(kPublicSessionAccountId, kAutoLoginLongDelay);
632  ASSERT_TRUE(auto_login_timer());
633
634  // Check that login completes and stops the timer.
635  existing_user_controller()->CompleteLogin(user_context);
636  ASSERT_TRUE(auto_login_timer());
637  EXPECT_FALSE(auto_login_timer()->IsRunning());
638
639  // Wait for login tasks to complete.
640  content::RunAllPendingInMessageLoop();
641
642  // Timer should still be stopped after login completes.
643  ASSERT_TRUE(auto_login_timer());
644  EXPECT_FALSE(auto_login_timer()->IsRunning());
645}
646
647IN_PROC_BROWSER_TEST_F(ExistingUserControllerPublicSessionTest,
648                       PublicSessionLoginStopsAutoLogin) {
649  // Set up mocks to check login success.
650  UserContext user_context(public_session_user_id_);
651  user_context.SetUserIDHash(user_context.GetUserID());
652  ExpectSuccessfulLogin(user_context);
653  existing_user_controller()->OnSigninScreenReady();
654  SetAutoLoginPolicy(kPublicSessionAccountId, kAutoLoginLongDelay);
655  ASSERT_TRUE(auto_login_timer());
656
657  // Login and check that it stopped the timer.
658  existing_user_controller()->LoginAsPublicAccount(public_session_user_id_);
659  EXPECT_TRUE(is_login_in_progress());
660  ASSERT_TRUE(auto_login_timer());
661  EXPECT_FALSE(auto_login_timer()->IsRunning());
662
663  // Wait for login tasks to complete.
664  content::RunAllPendingInMessageLoop();
665
666  // Timer should still be stopped after login completes.
667  ASSERT_TRUE(auto_login_timer());
668  EXPECT_FALSE(auto_login_timer()->IsRunning());
669}
670
671IN_PROC_BROWSER_TEST_F(ExistingUserControllerPublicSessionTest,
672                       PRE_TestLoadingPublicUsersFromLocalState) {
673  // First run propagates public accounts and stores them in Local State.
674}
675
676// See http://crbug.com/393704; flaky.
677IN_PROC_BROWSER_TEST_F(ExistingUserControllerPublicSessionTest,
678                       DISABLED_TestLoadingPublicUsersFromLocalState) {
679  // Second run loads list of public accounts from Local State.
680}
681
682}  // namespace chromeos
683