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