Fix infinite recursion on hiding panel when created during fullscreen mode.
[chromium-blink-merge.git] / chrome / browser / chromeos / login / kiosk_browsertest.cc
blobf81a2dda50b6a610e5c016157a206ee7721420ec
1 // Copyright (c) 2013 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.
5 #include "apps/app_window.h"
6 #include "apps/app_window_registry.h"
7 #include "apps/ui/native_app_window.h"
8 #include "ash/desktop_background/desktop_background_controller.h"
9 #include "ash/desktop_background/desktop_background_controller_observer.h"
10 #include "ash/shell.h"
11 #include "base/file_util.h"
12 #include "base/path_service.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/strings/string_util.h"
15 #include "chrome/browser/browser_process.h"
16 #include "chrome/browser/chrome_notification_types.h"
17 #include "chrome/browser/chromeos/app_mode/kiosk_app_launch_error.h"
18 #include "chrome/browser/chromeos/app_mode/kiosk_app_manager.h"
19 #include "chrome/browser/chromeos/login/app_launch_controller.h"
20 #include "chrome/browser/chromeos/login/fake_user_manager.h"
21 #include "chrome/browser/chromeos/login/mock_user_manager.h"
22 #include "chrome/browser/chromeos/login/oobe_base_test.h"
23 #include "chrome/browser/chromeos/login/startup_utils.h"
24 #include "chrome/browser/chromeos/login/test/oobe_screen_waiter.h"
25 #include "chrome/browser/chromeos/login/wizard_controller.h"
26 #include "chrome/browser/chromeos/policy/device_policy_cros_browser_test.h"
27 #include "chrome/browser/chromeos/policy/proto/chrome_device_policy.pb.h"
28 #include "chrome/browser/chromeos/profiles/profile_helper.h"
29 #include "chrome/browser/chromeos/settings/device_oauth2_token_service.h"
30 #include "chrome/browser/chromeos/settings/device_oauth2_token_service_factory.h"
31 #include "chrome/browser/extensions/extension_service.h"
32 #include "chrome/browser/extensions/extension_test_message_listener.h"
33 #include "chrome/common/chrome_constants.h"
34 #include "chrome/common/chrome_paths.h"
35 #include "chrome/common/chrome_switches.h"
36 #include "chrome/common/pref_names.h"
37 #include "chromeos/chromeos_switches.h"
38 #include "chromeos/dbus/cryptohome_client.h"
39 #include "content/public/browser/notification_observer.h"
40 #include "content/public/browser/notification_registrar.h"
41 #include "content/public/browser/notification_service.h"
42 #include "content/public/test/browser_test_utils.h"
43 #include "crypto/sha2.h"
44 #include "extensions/browser/extension_system.h"
45 #include "google_apis/gaia/gaia_constants.h"
46 #include "google_apis/gaia/gaia_switches.h"
47 #include "google_apis/gaia/gaia_urls.h"
48 #include "net/test/embedded_test_server/embedded_test_server.h"
49 #include "net/test/embedded_test_server/http_request.h"
50 #include "net/test/embedded_test_server/http_response.h"
52 using net::test_server::BasicHttpResponse;
53 using net::test_server::HttpRequest;
54 using net::test_server::HttpResponse;
56 namespace em = enterprise_management;
58 namespace chromeos {
60 namespace {
62 // This is a simple test app that creates an app window and immediately closes
63 // it again. Webstore data json is in
64 // chrome/test/data/chromeos/app_mode/webstore/inlineinstall/
65 // detail/ggbflgnkafappblpkiflbgpmkfdpnhhe
66 const char kTestKioskApp[] = "ggbflgnkafappblpkiflbgpmkfdpnhhe";
68 // This app creates a window and declares usage of the identity API in its
69 // manifest, so we can test device robot token minting via the identity API.
70 // Webstore data json is in
71 // chrome/test/data/chromeos/app_mode/webstore/inlineinstall/
72 // detail/ibjkkfdnfcaoapcpheeijckmpcfkifob
73 const char kTestEnterpriseKioskApp[] = "ibjkkfdnfcaoapcpheeijckmpcfkifob";
75 // An offline enable test app. Webstore data json is in
76 // chrome/test/data/chromeos/app_mode/webstore/inlineinstall/
77 // detail/ajoggoflpgplnnjkjamcmbepjdjdnpdp
78 // An app profile with version 1.0.0 installed is in
79 // chrome/test/data/chromeos/app_mode/offline_enabled_app_profile
80 // The version 2.0.0 crx is in
81 // chrome/test/data/chromeos/app_mode/webstore/downloads/
82 const char kTestOfflineEnabledKioskApp[] = "ajoggoflpgplnnjkjamcmbepjdjdnpdp";
84 // An app to test local fs data persistence across app update. V1 app writes
85 // data into local fs. V2 app reads and verifies the data.
86 // Webstore data json is in
87 // chrome/test/data/chromeos/app_mode/webstore/inlineinstall/
88 // detail/bmbpicmpniaclbbpdkfglgipkkebnbjf
89 const char kTestLocalFsKioskApp[] = "bmbpicmpniaclbbpdkfglgipkkebnbjf";
91 // Timeout while waiting for network connectivity during tests.
92 const int kTestNetworkTimeoutSeconds = 1;
94 // Email of owner account for test.
95 const char kTestOwnerEmail[] = "owner@example.com";
97 const char kTestEnterpriseAccountId[] = "enterprise-kiosk-app@localhost";
98 const char kTestEnterpriseServiceAccountId[] = "service_account@example.com";
99 const char kTestRefreshToken[] = "fake-refresh-token";
100 const char kTestUserinfoToken[] = "fake-userinfo-token";
101 const char kTestLoginToken[] = "fake-login-token";
102 const char kTestAccessToken[] = "fake-access-token";
103 const char kTestClientId[] = "fake-client-id";
104 const char kTestAppScope[] =
105 "https://www.googleapis.com/auth/userinfo.profile";
107 // Test JS API.
108 const char kLaunchAppForTestNewAPI[] =
109 "login.AccountPickerScreen.runAppForTesting";
110 const char kLaunchAppForTestOldAPI[] =
111 "login.AppsMenuButton.runAppForTesting";
112 const char kCheckDiagnosticModeNewAPI[] =
113 "$('oobe').confirmDiagnosticMode_";
114 const char kCheckDiagnosticModeOldAPI[] =
115 "$('show-apps-button').confirmDiagnosticMode_";
117 // Helper function for GetConsumerKioskAutoLaunchStatusCallback.
118 void ConsumerKioskAutoLaunchStatusCheck(
119 KioskAppManager::ConsumerKioskAutoLaunchStatus* out_status,
120 const base::Closure& runner_quit_task,
121 KioskAppManager::ConsumerKioskAutoLaunchStatus in_status) {
122 LOG(INFO) << "KioskAppManager::ConsumerKioskModeStatus = " << in_status;
123 *out_status = in_status;
124 runner_quit_task.Run();
127 // Helper KioskAppManager::EnableKioskModeCallback implementation.
128 void ConsumerKioskModeAutoStartLockCheck(
129 bool* out_locked,
130 const base::Closure& runner_quit_task,
131 bool in_locked) {
132 LOG(INFO) << "kiosk locked = " << in_locked;
133 *out_locked = in_locked;
134 runner_quit_task.Run();
137 // Helper function for WaitForNetworkTimeOut.
138 void OnNetworkWaitTimedOut(const base::Closure& runner_quit_task) {
139 runner_quit_task.Run();
142 // Helper functions for CanConfigureNetwork mock.
143 class ScopedCanConfigureNetwork {
144 public:
145 ScopedCanConfigureNetwork(bool can_configure, bool needs_owner_auth)
146 : can_configure_(can_configure),
147 needs_owner_auth_(needs_owner_auth),
148 can_configure_network_callback_(
149 base::Bind(&ScopedCanConfigureNetwork::CanConfigureNetwork,
150 base::Unretained(this))),
151 needs_owner_auth_callback_(base::Bind(
152 &ScopedCanConfigureNetwork::NeedsOwnerAuthToConfigureNetwork,
153 base::Unretained(this))) {
154 AppLaunchController::SetCanConfigureNetworkCallbackForTesting(
155 &can_configure_network_callback_);
156 AppLaunchController::SetNeedOwnerAuthToConfigureNetworkCallbackForTesting(
157 &needs_owner_auth_callback_);
159 ~ScopedCanConfigureNetwork() {
160 AppLaunchController::SetCanConfigureNetworkCallbackForTesting(NULL);
161 AppLaunchController::SetNeedOwnerAuthToConfigureNetworkCallbackForTesting(
162 NULL);
165 bool CanConfigureNetwork() {
166 return can_configure_;
169 bool NeedsOwnerAuthToConfigureNetwork() {
170 return needs_owner_auth_;
173 private:
174 bool can_configure_;
175 bool needs_owner_auth_;
176 AppLaunchController::ReturnBoolCallback can_configure_network_callback_;
177 AppLaunchController::ReturnBoolCallback needs_owner_auth_callback_;
178 DISALLOW_COPY_AND_ASSIGN(ScopedCanConfigureNetwork);
181 // Helper class to wait until a js condition becomes true.
182 class JsConditionWaiter {
183 public:
184 JsConditionWaiter(content::WebContents* web_contents,
185 const std::string& js)
186 : web_contents_(web_contents),
187 js_(js) {
190 void Wait() {
191 if (CheckJs())
192 return;
194 base::RepeatingTimer<JsConditionWaiter> check_timer;
195 check_timer.Start(
196 FROM_HERE,
197 base::TimeDelta::FromMilliseconds(10),
198 this,
199 &JsConditionWaiter::OnTimer);
201 runner_ = new content::MessageLoopRunner;
202 runner_->Run();
205 private:
206 bool CheckJs() {
207 bool result;
208 CHECK(content::ExecuteScriptAndExtractBool(
209 web_contents_,
210 "window.domAutomationController.send(!!(" + js_ + "));",
211 &result));
212 return result;
215 void OnTimer() {
216 DCHECK(runner_);
217 if (CheckJs())
218 runner_->Quit();
221 content::WebContents* web_contents_;
222 const std::string js_;
223 scoped_refptr<content::MessageLoopRunner> runner_;
225 DISALLOW_COPY_AND_ASSIGN(JsConditionWaiter);
228 } // namespace
230 // Helper class that monitors app windows to wait for a window to appear.
231 class AppWindowObserver : public apps::AppWindowRegistry::Observer {
232 public:
233 AppWindowObserver(apps::AppWindowRegistry* registry,
234 const std::string& app_id)
235 : registry_(registry), app_id_(app_id), window_(NULL), running_(false) {
236 registry_->AddObserver(this);
238 virtual ~AppWindowObserver() { registry_->RemoveObserver(this); }
240 apps::AppWindow* Wait() {
241 running_ = true;
242 message_loop_runner_ = new content::MessageLoopRunner;
243 message_loop_runner_->Run();
244 EXPECT_TRUE(window_);
245 return window_;
248 // AppWindowRegistry::Observer
249 virtual void OnAppWindowAdded(apps::AppWindow* app_window) OVERRIDE {
250 if (!running_)
251 return;
253 if (app_window->extension_id() == app_id_) {
254 window_ = app_window;
255 message_loop_runner_->Quit();
256 running_ = false;
259 virtual void OnAppWindowIconChanged(apps::AppWindow* app_window) OVERRIDE {}
260 virtual void OnAppWindowRemoved(apps::AppWindow* app_window) OVERRIDE {}
262 private:
263 apps::AppWindowRegistry* registry_;
264 std::string app_id_;
265 scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
266 apps::AppWindow* window_;
267 bool running_;
269 DISALLOW_COPY_AND_ASSIGN(AppWindowObserver);
272 class KioskTest : public OobeBaseTest {
273 public:
274 KioskTest() {
275 set_exit_when_last_browser_closes(false);
278 virtual ~KioskTest() {}
280 protected:
281 virtual void SetUp() OVERRIDE {
282 test_app_id_ = kTestKioskApp;
283 mock_user_manager_.reset(new MockUserManager);
284 AppLaunchController::SkipSplashWaitForTesting();
285 AppLaunchController::SetNetworkWaitForTesting(kTestNetworkTimeoutSeconds);
287 OobeBaseTest::SetUp();
290 virtual void CleanUpOnMainThread() OVERRIDE {
291 AppLaunchController::SetNetworkTimeoutCallbackForTesting(NULL);
292 AppLaunchSigninScreen::SetUserManagerForTesting(NULL);
294 OobeBaseTest::CleanUpOnMainThread();
296 // Clean up while main thread still runs.
297 // See http://crbug.com/176659.
298 KioskAppManager::Get()->CleanUp();
301 virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
302 OobeBaseTest::SetUpCommandLine(command_line);
304 // Create gaia and webstore URL from test server url but using different
305 // host names. This is to avoid gaia response being tagged as from
306 // webstore in chrome_resource_dispatcher_host_delegate.cc.
307 GURL webstore_url = GetTestWebstoreUrl();
308 command_line->AppendSwitchASCII(
309 ::switches::kAppsGalleryURL,
310 webstore_url.Resolve("/chromeos/app_mode/webstore").spec());
311 command_line->AppendSwitchASCII(
312 ::switches::kAppsGalleryDownloadURL,
313 webstore_url.Resolve(
314 "/chromeos/app_mode/webstore/downloads/%s.crx").spec());
317 GURL GetTestWebstoreUrl() {
318 const GURL& server_url = embedded_test_server()->base_url();
319 std::string webstore_host("webstore");
320 GURL::Replacements replace_webstore_host;
321 replace_webstore_host.SetHostStr(webstore_host);
322 return server_url.ReplaceComponents(replace_webstore_host);
325 void LaunchApp(const std::string& app_id, bool diagnostic_mode) {
326 bool new_kiosk_ui = !CommandLine::ForCurrentProcess()->
327 HasSwitch(switches::kDisableNewKioskUI);
328 GetLoginUI()->CallJavascriptFunction(new_kiosk_ui ?
329 kLaunchAppForTestNewAPI : kLaunchAppForTestOldAPI,
330 base::StringValue(app_id),
331 base::FundamentalValue(diagnostic_mode));
334 void ReloadKioskApps() {
335 // Remove then add to ensure NOTIFICATION_KIOSK_APPS_LOADED fires.
336 KioskAppManager::Get()->RemoveApp(test_app_id_);
337 KioskAppManager::Get()->AddApp(test_app_id_);
340 void ReloadAutolaunchKioskApps() {
341 KioskAppManager::Get()->AddApp(test_app_id_);
342 KioskAppManager::Get()->SetAutoLaunchApp(test_app_id_);
345 void PrepareAppLaunch() {
346 EnableConsumerKioskMode();
348 // Start UI
349 content::WindowedNotificationObserver login_signal(
350 chrome::NOTIFICATION_LOGIN_OR_LOCK_WEBUI_VISIBLE,
351 content::NotificationService::AllSources());
352 chromeos::WizardController::SkipPostLoginScreensForTesting();
353 chromeos::WizardController* wizard_controller =
354 chromeos::WizardController::default_controller();
355 if (wizard_controller) {
356 wizard_controller->SkipToLoginForTesting(LoginScreenContext());
357 login_signal.Wait();
358 } else {
359 // No wizard and running with an existing profile and it should land
360 // on account picker.
361 OobeScreenWaiter(OobeDisplay::SCREEN_ACCOUNT_PICKER).Wait();
364 // Wait for the Kiosk App configuration to reload.
365 content::WindowedNotificationObserver apps_loaded_signal(
366 chrome::NOTIFICATION_KIOSK_APPS_LOADED,
367 content::NotificationService::AllSources());
368 ReloadKioskApps();
369 apps_loaded_signal.Wait();
372 void StartAppLaunchFromLoginScreen(const base::Closure& network_setup_cb) {
373 PrepareAppLaunch();
375 if (!network_setup_cb.is_null())
376 network_setup_cb.Run();
378 LaunchApp(test_app_id(), false);
381 const extensions::Extension* GetInstalledApp() {
382 Profile* app_profile = ProfileManager::GetPrimaryUserProfile();
383 return extensions::ExtensionSystem::Get(app_profile)->
384 extension_service()->GetInstalledExtension(test_app_id_);
387 const Version& GetInstalledAppVersion() {
388 return *GetInstalledApp()->version();
391 void WaitForAppLaunchSuccess() {
392 ExtensionTestMessageListener
393 launch_data_check_listener("launchData.isKioskSession = true", false);
395 // Wait for the Kiosk App to launch.
396 content::WindowedNotificationObserver(
397 chrome::NOTIFICATION_KIOSK_APP_LAUNCHED,
398 content::NotificationService::AllSources()).Wait();
400 // Default profile switches to app profile after app is launched.
401 Profile* app_profile = ProfileManager::GetPrimaryUserProfile();
402 ASSERT_TRUE(app_profile);
404 // Check installer status.
405 EXPECT_EQ(chromeos::KioskAppLaunchError::NONE,
406 chromeos::KioskAppLaunchError::Get());
408 // Check if the kiosk webapp is really installed for the default profile.
409 const extensions::Extension* app =
410 extensions::ExtensionSystem::Get(app_profile)->
411 extension_service()->GetInstalledExtension(test_app_id_);
412 EXPECT_TRUE(app);
414 // App should appear with its window.
415 apps::AppWindowRegistry* app_window_registry =
416 apps::AppWindowRegistry::Get(app_profile);
417 apps::AppWindow* window =
418 AppWindowObserver(app_window_registry, test_app_id_).Wait();
419 EXPECT_TRUE(window);
421 // Login screen should be gone or fading out.
422 chromeos::LoginDisplayHost* login_display_host =
423 chromeos::LoginDisplayHostImpl::default_host();
424 EXPECT_TRUE(
425 login_display_host == NULL ||
426 login_display_host->GetNativeWindow()->layer()->GetTargetOpacity() ==
427 0.0f);
429 // Wait until the app terminates if it is still running.
430 if (!app_window_registry->GetAppWindowsForApp(test_app_id_).empty())
431 content::RunMessageLoop();
433 // Check that the app had been informed that it is running in a kiosk
434 // session.
435 EXPECT_TRUE(launch_data_check_listener.was_satisfied());
438 void WaitForAppLaunchNetworkTimeout() {
439 if (GetAppLaunchController()->network_wait_timedout())
440 return;
442 scoped_refptr<content::MessageLoopRunner> runner =
443 new content::MessageLoopRunner;
445 base::Closure callback = base::Bind(
446 &OnNetworkWaitTimedOut, runner->QuitClosure());
447 AppLaunchController::SetNetworkTimeoutCallbackForTesting(&callback);
449 runner->Run();
451 CHECK(GetAppLaunchController()->network_wait_timedout());
452 AppLaunchController::SetNetworkTimeoutCallbackForTesting(NULL);
455 void EnableConsumerKioskMode() {
456 scoped_ptr<bool> locked(new bool(false));
457 scoped_refptr<content::MessageLoopRunner> runner =
458 new content::MessageLoopRunner;
459 KioskAppManager::Get()->EnableConsumerKioskAutoLaunch(
460 base::Bind(&ConsumerKioskModeAutoStartLockCheck,
461 locked.get(),
462 runner->QuitClosure()));
463 runner->Run();
464 EXPECT_TRUE(*locked.get());
467 KioskAppManager::ConsumerKioskAutoLaunchStatus
468 GetConsumerKioskModeStatus() {
469 KioskAppManager::ConsumerKioskAutoLaunchStatus status =
470 static_cast<KioskAppManager::ConsumerKioskAutoLaunchStatus>(-1);
471 scoped_refptr<content::MessageLoopRunner> runner =
472 new content::MessageLoopRunner;
473 KioskAppManager::Get()->GetConsumerKioskAutoLaunchStatus(
474 base::Bind(&ConsumerKioskAutoLaunchStatusCheck,
475 &status,
476 runner->QuitClosure()));
477 runner->Run();
478 CHECK_NE(status,
479 static_cast<KioskAppManager::ConsumerKioskAutoLaunchStatus>(-1));
480 return status;
483 // Copies the app profile from |relative_app_profile_dir| from test directory
484 // to the app profile directory (assuming "user") under testing profile. This
485 // is for that needs to have a kiosk app already installed from a previous
486 // run. Note this must be called before app profile is loaded.
487 void SetupAppProfile(const std::string& relative_app_profile_dir) {
488 base::FilePath app_profile_dir;
489 if (CommandLine::ForCurrentProcess()->HasSwitch(
490 ::switches::kMultiProfiles)) {
491 KioskAppManager::App app_data;
492 CHECK(KioskAppManager::Get()->GetApp(test_app_id(), &app_data));
493 std::string app_user_id_hash =
494 CryptohomeClient::GetStubSanitizedUsername(app_data.user_id);
495 app_profile_dir =
496 ProfileHelper::GetProfilePathByUserIdHash(app_user_id_hash);
497 } else {
498 ASSERT_TRUE(PathService::Get(chrome::DIR_USER_DATA, &app_profile_dir));
499 app_profile_dir = app_profile_dir.Append(
500 ProfileHelper::GetProfileDirByLegacyLoginProfileSwitch());
502 ASSERT_TRUE(base::CreateDirectory(app_profile_dir));
504 base::FilePath test_data_dir;
505 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir));
506 test_data_dir = test_data_dir.AppendASCII(relative_app_profile_dir);
507 ASSERT_TRUE(
508 base::CopyFile(test_data_dir.Append(chrome::kPreferencesFilename),
509 app_profile_dir.Append(chrome::kPreferencesFilename)));
510 ASSERT_TRUE(
511 base::CopyDirectory(test_data_dir.AppendASCII("Extensions"),
512 app_profile_dir,
513 true));
516 void RunAppLaunchNetworkDownTest() {
517 // Mock network could be configured with owner's password.
518 ScopedCanConfigureNetwork can_configure_network(true, true);
520 // Start app launch and wait for network connectivity timeout.
521 StartAppLaunchFromLoginScreen(SimulateNetworkOfflineClosure());
522 OobeScreenWaiter splash_waiter(OobeDisplay::SCREEN_APP_LAUNCH_SPLASH);
523 splash_waiter.Wait();
524 WaitForAppLaunchNetworkTimeout();
526 // Configure network link should be visible.
527 JsExpect("$('splash-config-network').hidden == false");
529 // Set up fake user manager with an owner for the test.
530 mock_user_manager()->SetActiveUser(kTestOwnerEmail);
531 AppLaunchSigninScreen::SetUserManagerForTesting(mock_user_manager());
532 static_cast<LoginDisplayHostImpl*>(LoginDisplayHostImpl::default_host())
533 ->GetOobeUI()->ShowOobeUI(false);
535 // Configure network should bring up lock screen for owner.
536 OobeScreenWaiter lock_screen_waiter(OobeDisplay::SCREEN_ACCOUNT_PICKER);
537 static_cast<AppLaunchSplashScreenActor::Delegate*>(GetAppLaunchController())
538 ->OnConfigureNetwork();
539 lock_screen_waiter.Wait();
541 // There should be only one owner pod on this screen.
542 JsExpect("$('pod-row').isSinglePod");
544 // A network error screen should be shown after authenticating.
545 OobeScreenWaiter error_screen_waiter(OobeDisplay::SCREEN_ERROR_MESSAGE);
546 static_cast<AppLaunchSigninScreen::Delegate*>(GetAppLaunchController())
547 ->OnOwnerSigninSuccess();
548 error_screen_waiter.Wait();
550 ASSERT_TRUE(GetAppLaunchController()->showing_network_dialog());
552 SimulateNetworkOnline();
553 WaitForAppLaunchSuccess();
556 AppLaunchController* GetAppLaunchController() {
557 return chromeos::LoginDisplayHostImpl::default_host()
558 ->GetAppLaunchController();
561 MockUserManager* mock_user_manager() { return mock_user_manager_.get(); }
563 void set_test_app_id(const std::string& test_app_id) {
564 test_app_id_ = test_app_id;
566 const std::string& test_app_id() const { return test_app_id_; }
568 private:
569 std::string test_app_id_;
570 scoped_ptr<MockUserManager> mock_user_manager_;
572 DISALLOW_COPY_AND_ASSIGN(KioskTest);
575 IN_PROC_BROWSER_TEST_F(KioskTest, InstallAndLaunchApp) {
576 StartAppLaunchFromLoginScreen(SimulateNetworkOnlineClosure());
577 WaitForAppLaunchSuccess();
580 IN_PROC_BROWSER_TEST_F(KioskTest, PRE_LaunchAppNetworkDown) {
581 // Tests the network down case for the initial app download and launch.
582 RunAppLaunchNetworkDownTest();
585 IN_PROC_BROWSER_TEST_F(KioskTest, LaunchAppNetworkDown) {
586 // Tests the network down case for launching an existing app that is
587 // installed in PRE_LaunchAppNetworkDown.
588 RunAppLaunchNetworkDownTest();
591 IN_PROC_BROWSER_TEST_F(KioskTest, LaunchAppNetworkDownConfigureNotAllowed) {
592 // Mock network could not be configured.
593 ScopedCanConfigureNetwork can_configure_network(false, true);
595 // Start app launch and wait for network connectivity timeout.
596 StartAppLaunchFromLoginScreen(SimulateNetworkOfflineClosure());
597 OobeScreenWaiter splash_waiter(OobeDisplay::SCREEN_APP_LAUNCH_SPLASH);
598 splash_waiter.Wait();
599 WaitForAppLaunchNetworkTimeout();
601 // Configure network link should not be visible.
602 JsExpect("$('splash-config-network').hidden == true");
604 // Network becomes online and app launch is resumed.
605 SimulateNetworkOnline();
606 WaitForAppLaunchSuccess();
609 IN_PROC_BROWSER_TEST_F(KioskTest, LaunchAppNetworkPortal) {
610 // Mock network could be configured without the owner password.
611 ScopedCanConfigureNetwork can_configure_network(true, false);
613 // Start app launch with network portal state.
614 StartAppLaunchFromLoginScreen(SimulateNetworkPortalClosure());
615 OobeScreenWaiter(OobeDisplay::SCREEN_APP_LAUNCH_SPLASH)
616 .WaitNoAssertCurrentScreen();
617 WaitForAppLaunchNetworkTimeout();
619 // Network error should show up automatically since this test does not
620 // require owner auth to configure network.
621 OobeScreenWaiter(OobeDisplay::SCREEN_ERROR_MESSAGE).Wait();
623 ASSERT_TRUE(GetAppLaunchController()->showing_network_dialog());
624 SimulateNetworkOnline();
625 WaitForAppLaunchSuccess();
628 IN_PROC_BROWSER_TEST_F(KioskTest, LaunchAppUserCancel) {
629 StartAppLaunchFromLoginScreen(SimulateNetworkOfflineClosure());
630 OobeScreenWaiter splash_waiter(OobeDisplay::SCREEN_APP_LAUNCH_SPLASH);
631 splash_waiter.Wait();
633 CrosSettings::Get()->SetBoolean(
634 kAccountsPrefDeviceLocalAccountAutoLoginBailoutEnabled, true);
635 content::WindowedNotificationObserver signal(
636 chrome::NOTIFICATION_APP_TERMINATING,
637 content::NotificationService::AllSources());
638 GetLoginUI()->CallJavascriptFunction("cr.ui.Oobe.handleAccelerator",
639 base::StringValue("app_launch_bailout"));
640 signal.Wait();
641 EXPECT_EQ(chromeos::KioskAppLaunchError::USER_CANCEL,
642 chromeos::KioskAppLaunchError::Get());
645 IN_PROC_BROWSER_TEST_F(KioskTest, LaunchInDiagnosticMode) {
646 PrepareAppLaunch();
647 SimulateNetworkOnline();
649 LaunchApp(kTestKioskApp, true);
651 content::WebContents* login_contents = GetLoginUI()->GetWebContents();
653 bool new_kiosk_ui = !CommandLine::ForCurrentProcess()->
654 HasSwitch(switches::kDisableNewKioskUI);
655 JsConditionWaiter(login_contents, new_kiosk_ui ?
656 kCheckDiagnosticModeNewAPI : kCheckDiagnosticModeOldAPI).Wait();
658 std::string diagnosticMode(new_kiosk_ui ?
659 kCheckDiagnosticModeNewAPI : kCheckDiagnosticModeOldAPI);
660 ASSERT_TRUE(content::ExecuteScript(
661 login_contents,
662 "(function() {"
663 "var e = new Event('click');" +
664 diagnosticMode + "."
665 "okButton_.dispatchEvent(e);"
666 "})();"));
668 WaitForAppLaunchSuccess();
671 IN_PROC_BROWSER_TEST_F(KioskTest, AutolaunchWarningCancel) {
672 EnableConsumerKioskMode();
673 // Start UI, find menu entry for this app and launch it.
674 chromeos::WizardController::SkipPostLoginScreensForTesting();
675 chromeos::WizardController* wizard_controller =
676 chromeos::WizardController::default_controller();
677 CHECK(wizard_controller);
678 ReloadAutolaunchKioskApps();
679 wizard_controller->SkipToLoginForTesting(LoginScreenContext());
681 EXPECT_FALSE(KioskAppManager::Get()->GetAutoLaunchApp().empty());
682 EXPECT_FALSE(KioskAppManager::Get()->IsAutoLaunchEnabled());
684 // Wait for the auto launch warning come up.
685 content::WindowedNotificationObserver(
686 chrome::NOTIFICATION_KIOSK_AUTOLAUNCH_WARNING_VISIBLE,
687 content::NotificationService::AllSources()).Wait();
688 GetLoginUI()->CallJavascriptFunction(
689 "login.AutolaunchScreen.confirmAutoLaunchForTesting",
690 base::FundamentalValue(false));
692 // Wait for the auto launch warning to go away.
693 content::WindowedNotificationObserver(
694 chrome::NOTIFICATION_KIOSK_AUTOLAUNCH_WARNING_COMPLETED,
695 content::NotificationService::AllSources()).Wait();
697 EXPECT_FALSE(KioskAppManager::Get()->IsAutoLaunchEnabled());
700 IN_PROC_BROWSER_TEST_F(KioskTest, AutolaunchWarningConfirm) {
701 EnableConsumerKioskMode();
702 // Start UI, find menu entry for this app and launch it.
703 chromeos::WizardController::SkipPostLoginScreensForTesting();
704 chromeos::WizardController* wizard_controller =
705 chromeos::WizardController::default_controller();
706 CHECK(wizard_controller);
707 wizard_controller->SkipToLoginForTesting(LoginScreenContext());
709 ReloadAutolaunchKioskApps();
710 EXPECT_FALSE(KioskAppManager::Get()->GetAutoLaunchApp().empty());
711 EXPECT_FALSE(KioskAppManager::Get()->IsAutoLaunchEnabled());
713 // Wait for the auto launch warning come up.
714 content::WindowedNotificationObserver(
715 chrome::NOTIFICATION_KIOSK_AUTOLAUNCH_WARNING_VISIBLE,
716 content::NotificationService::AllSources()).Wait();
717 GetLoginUI()->CallJavascriptFunction(
718 "login.AutolaunchScreen.confirmAutoLaunchForTesting",
719 base::FundamentalValue(true));
721 // Wait for the auto launch warning to go away.
722 content::WindowedNotificationObserver(
723 chrome::NOTIFICATION_KIOSK_AUTOLAUNCH_WARNING_COMPLETED,
724 content::NotificationService::AllSources()).Wait();
726 EXPECT_FALSE(KioskAppManager::Get()->GetAutoLaunchApp().empty());
727 EXPECT_TRUE(KioskAppManager::Get()->IsAutoLaunchEnabled());
729 WaitForAppLaunchSuccess();
732 IN_PROC_BROWSER_TEST_F(KioskTest, KioskEnableCancel) {
733 chromeos::WizardController::SkipPostLoginScreensForTesting();
734 chromeos::WizardController* wizard_controller =
735 chromeos::WizardController::default_controller();
736 CHECK(wizard_controller);
738 // Check Kiosk mode status.
739 EXPECT_EQ(KioskAppManager::CONSUMER_KIOSK_AUTO_LAUNCH_CONFIGURABLE,
740 GetConsumerKioskModeStatus());
742 // Wait for the login UI to come up and switch to the kiosk_enable screen.
743 wizard_controller->SkipToLoginForTesting(LoginScreenContext());
744 content::WindowedNotificationObserver(
745 chrome::NOTIFICATION_LOGIN_OR_LOCK_WEBUI_VISIBLE,
746 content::NotificationService::AllSources()).Wait();
747 GetLoginUI()->CallJavascriptFunction("cr.ui.Oobe.handleAccelerator",
748 base::StringValue("kiosk_enable"));
750 // Wait for the kiosk_enable screen to show and cancel the screen.
751 content::WindowedNotificationObserver(
752 chrome::NOTIFICATION_KIOSK_ENABLE_WARNING_VISIBLE,
753 content::NotificationService::AllSources()).Wait();
754 GetLoginUI()->CallJavascriptFunction(
755 "login.KioskEnableScreen.enableKioskForTesting",
756 base::FundamentalValue(false));
758 // Wait for the kiosk_enable screen to disappear.
759 content::WindowedNotificationObserver(
760 chrome::NOTIFICATION_KIOSK_ENABLE_WARNING_COMPLETED,
761 content::NotificationService::AllSources()).Wait();
763 // Check that the status still says configurable.
764 EXPECT_EQ(KioskAppManager::CONSUMER_KIOSK_AUTO_LAUNCH_CONFIGURABLE,
765 GetConsumerKioskModeStatus());
768 IN_PROC_BROWSER_TEST_F(KioskTest, KioskEnableConfirmed) {
769 // Start UI, find menu entry for this app and launch it.
770 chromeos::WizardController::SkipPostLoginScreensForTesting();
771 chromeos::WizardController* wizard_controller =
772 chromeos::WizardController::default_controller();
773 CHECK(wizard_controller);
775 // Check Kiosk mode status.
776 EXPECT_EQ(KioskAppManager::CONSUMER_KIOSK_AUTO_LAUNCH_CONFIGURABLE,
777 GetConsumerKioskModeStatus());
778 wizard_controller->SkipToLoginForTesting(LoginScreenContext());
780 // Wait for the login UI to come up and switch to the kiosk_enable screen.
781 wizard_controller->SkipToLoginForTesting(LoginScreenContext());
782 content::WindowedNotificationObserver(
783 chrome::NOTIFICATION_LOGIN_OR_LOCK_WEBUI_VISIBLE,
784 content::NotificationService::AllSources()).Wait();
785 GetLoginUI()->CallJavascriptFunction("cr.ui.Oobe.handleAccelerator",
786 base::StringValue("kiosk_enable"));
788 // Wait for the kiosk_enable screen to show and cancel the screen.
789 content::WindowedNotificationObserver(
790 chrome::NOTIFICATION_KIOSK_ENABLE_WARNING_VISIBLE,
791 content::NotificationService::AllSources()).Wait();
792 GetLoginUI()->CallJavascriptFunction(
793 "login.KioskEnableScreen.enableKioskForTesting",
794 base::FundamentalValue(true));
796 // Wait for the signal that indicates Kiosk Mode is enabled.
797 content::WindowedNotificationObserver(
798 chrome::NOTIFICATION_KIOSK_ENABLED,
799 content::NotificationService::AllSources()).Wait();
800 EXPECT_EQ(KioskAppManager::CONSUMER_KIOSK_AUTO_LAUNCH_ENABLED,
801 GetConsumerKioskModeStatus());
804 IN_PROC_BROWSER_TEST_F(KioskTest, KioskEnableAbortedWithAutoEnrollment) {
805 // Fake an auto enrollment is going to be enforced.
806 CommandLine::ForCurrentProcess()->AppendSwitchASCII(
807 switches::kEnterpriseEnrollmentInitialModulus, "1");
808 CommandLine::ForCurrentProcess()->AppendSwitchASCII(
809 switches::kEnterpriseEnrollmentModulusLimit, "2");
810 g_browser_process->local_state()->SetBoolean(prefs::kShouldAutoEnroll, true);
811 g_browser_process->local_state()->SetInteger(
812 prefs::kAutoEnrollmentPowerLimit, 3);
814 // Start UI, find menu entry for this app and launch it.
815 chromeos::WizardController::SkipPostLoginScreensForTesting();
816 chromeos::WizardController* wizard_controller =
817 chromeos::WizardController::default_controller();
818 CHECK(wizard_controller);
820 // Check Kiosk mode status.
821 EXPECT_EQ(KioskAppManager::CONSUMER_KIOSK_AUTO_LAUNCH_CONFIGURABLE,
822 GetConsumerKioskModeStatus());
823 wizard_controller->SkipToLoginForTesting(LoginScreenContext());
825 // Wait for the login UI to come up and switch to the kiosk_enable screen.
826 wizard_controller->SkipToLoginForTesting(LoginScreenContext());
827 content::WindowedNotificationObserver(
828 chrome::NOTIFICATION_LOGIN_OR_LOCK_WEBUI_VISIBLE,
829 content::NotificationService::AllSources()).Wait();
830 GetLoginUI()->CallJavascriptFunction("cr.ui.Oobe.handleAccelerator",
831 base::StringValue("kiosk_enable"));
833 // The flow should be aborted due to auto enrollment enforcement.
834 scoped_refptr<content::MessageLoopRunner> runner =
835 new content::MessageLoopRunner;
836 GetSigninScreenHandler()->set_kiosk_enable_flow_aborted_callback_for_test(
837 runner->QuitClosure());
838 runner->Run();
841 IN_PROC_BROWSER_TEST_F(KioskTest, KioskEnableAfter2ndSigninScreen) {
842 // Fake an auto enrollment is not going to be enforced.
843 CommandLine::ForCurrentProcess()->AppendSwitchASCII(
844 switches::kEnterpriseEnrollmentInitialModulus, "1");
845 CommandLine::ForCurrentProcess()->AppendSwitchASCII(
846 switches::kEnterpriseEnrollmentModulusLimit, "2");
847 g_browser_process->local_state()->SetBoolean(prefs::kShouldAutoEnroll, false);
848 g_browser_process->local_state()->SetInteger(
849 prefs::kAutoEnrollmentPowerLimit, -1);
851 chromeos::WizardController::SkipPostLoginScreensForTesting();
852 chromeos::WizardController* wizard_controller =
853 chromeos::WizardController::default_controller();
854 CHECK(wizard_controller);
856 // Check Kiosk mode status.
857 EXPECT_EQ(KioskAppManager::CONSUMER_KIOSK_AUTO_LAUNCH_CONFIGURABLE,
858 GetConsumerKioskModeStatus());
860 // Wait for the login UI to come up and switch to the kiosk_enable screen.
861 wizard_controller->SkipToLoginForTesting(LoginScreenContext());
862 content::WindowedNotificationObserver(
863 chrome::NOTIFICATION_LOGIN_OR_LOCK_WEBUI_VISIBLE,
864 content::NotificationService::AllSources()).Wait();
865 GetLoginUI()->CallJavascriptFunction("cr.ui.Oobe.handleAccelerator",
866 base::StringValue("kiosk_enable"));
868 // Wait for the kiosk_enable screen to show and cancel the screen.
869 content::WindowedNotificationObserver(
870 chrome::NOTIFICATION_KIOSK_ENABLE_WARNING_VISIBLE,
871 content::NotificationService::AllSources()).Wait();
872 GetLoginUI()->CallJavascriptFunction(
873 "login.KioskEnableScreen.enableKioskForTesting",
874 base::FundamentalValue(false));
876 // Wait for the kiosk_enable screen to disappear.
877 content::WindowedNotificationObserver(
878 chrome::NOTIFICATION_KIOSK_ENABLE_WARNING_COMPLETED,
879 content::NotificationService::AllSources()).Wait();
881 // Show signin screen again.
882 chromeos::LoginDisplayHostImpl::default_host()->StartSignInScreen(
883 LoginScreenContext());
884 OobeScreenWaiter(OobeDisplay::SCREEN_GAIA_SIGNIN).Wait();
886 // Show kiosk enable screen again.
887 GetLoginUI()->CallJavascriptFunction("cr.ui.Oobe.handleAccelerator",
888 base::StringValue("kiosk_enable"));
890 // And it should show up.
891 content::WindowedNotificationObserver(
892 chrome::NOTIFICATION_KIOSK_ENABLE_WARNING_VISIBLE,
893 content::NotificationService::AllSources()).Wait();
896 class KioskUpdateTest : public KioskTest,
897 public testing::WithParamInterface<bool> {
898 public:
899 KioskUpdateTest() {}
900 virtual ~KioskUpdateTest() {}
902 protected:
903 virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
904 // Needs background networking so that ExtensionDownloader works.
905 needs_background_networking_ = true;
907 KioskTest::SetUpCommandLine(command_line);
908 if (GetParam())
909 command_line->AppendSwitch(::switches::kMultiProfiles);
912 virtual void SetUpOnMainThread() OVERRIDE {
913 KioskTest::SetUpOnMainThread();
915 GURL webstore_url = GetTestWebstoreUrl();
916 CommandLine::ForCurrentProcess()->AppendSwitchASCII(
917 ::switches::kAppsGalleryUpdateURL,
918 webstore_url.Resolve("/update_check.xml").spec());
920 embedded_test_server()->RegisterRequestHandler(
921 base::Bind(&KioskUpdateTest::HandleRequest,
922 base::Unretained(this)));
925 void SetNoUpdate() {
926 SetUpdateCheckContent(
927 "chromeos/app_mode/webstore/update_check/no_update.xml",
928 GURL(),
931 "");
934 void SetUpdateCrx(const std::string& crx_file, const std::string& version) {
935 GURL webstore_url = GetTestWebstoreUrl();
936 GURL crx_download_url = webstore_url.Resolve(
937 "/chromeos/app_mode/webstore/downloads/" + crx_file);
938 base::FilePath test_data_dir;
939 PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir);
940 base::FilePath crx_file_path =
941 test_data_dir.AppendASCII("chromeos/app_mode/webstore/downloads")
942 .AppendASCII(crx_file);
944 std::string crx_content;
945 ASSERT_TRUE(base::ReadFileToString(crx_file_path, &crx_content));
947 const std::string sha256 = crypto::SHA256HashString(crx_content);
948 const std::string sha256_hex =
949 base::HexEncode(sha256.c_str(), sha256.size());
951 SetUpdateCheckContent(
952 "chromeos/app_mode/webstore/update_check/has_update.xml",
953 crx_download_url,
954 sha256_hex,
955 base::UintToString(crx_content.size()),
956 version);
959 private:
960 void SetUpdateCheckContent(const std::string& update_check_file,
961 const GURL& crx_download_url,
962 const std::string& crx_fp,
963 const std::string& crx_size,
964 const std::string& version) {
965 base::FilePath test_data_dir;
966 PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir);
967 base::FilePath update_file =
968 test_data_dir.AppendASCII(update_check_file.c_str());
969 ASSERT_TRUE(base::ReadFileToString(update_file, &update_check_content_));
971 ReplaceSubstringsAfterOffset(
972 &update_check_content_, 0, "$AppId", test_app_id());
973 ReplaceSubstringsAfterOffset(
974 &update_check_content_, 0, "$CrxDownloadUrl", crx_download_url.spec());
975 ReplaceSubstringsAfterOffset(&update_check_content_, 0, "$FP", crx_fp);
976 ReplaceSubstringsAfterOffset(&update_check_content_, 0, "$Size", crx_size);
977 ReplaceSubstringsAfterOffset(
978 &update_check_content_, 0, "$Version", version);
981 scoped_ptr<HttpResponse> HandleRequest(const HttpRequest& request) {
982 GURL request_url = GURL("http://localhost").Resolve(request.relative_url);
983 std::string request_path = request_url.path();
984 if (!update_check_content_.empty() &&
985 request_path == "/update_check.xml") {
986 scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse());
987 http_response->set_code(net::HTTP_OK);
988 http_response->set_content_type("text/xml");
989 http_response->set_content(update_check_content_);
990 return http_response.PassAs<HttpResponse>();
993 return scoped_ptr<HttpResponse>();
996 std::string update_check_content_;
998 DISALLOW_COPY_AND_ASSIGN(KioskUpdateTest);
1001 IN_PROC_BROWSER_TEST_P(KioskUpdateTest, LaunchOfflineEnabledAppNoNetwork) {
1002 set_test_app_id(kTestOfflineEnabledKioskApp);
1004 PrepareAppLaunch();
1005 SimulateNetworkOffline();
1006 SetupAppProfile("chromeos/app_mode/offline_enabled_app_profile");
1008 LaunchApp(test_app_id(), false);
1009 WaitForAppLaunchSuccess();
1012 IN_PROC_BROWSER_TEST_P(KioskUpdateTest, LaunchOfflineEnabledAppNoUpdate) {
1013 set_test_app_id(kTestOfflineEnabledKioskApp);
1015 SetNoUpdate();
1017 PrepareAppLaunch();
1018 SimulateNetworkOnline();
1019 SetupAppProfile("chromeos/app_mode/offline_enabled_app_profile");
1021 LaunchApp(test_app_id(), false);
1022 WaitForAppLaunchSuccess();
1024 EXPECT_EQ("1.0.0", GetInstalledAppVersion().GetString());
1027 IN_PROC_BROWSER_TEST_P(KioskUpdateTest, LaunchOfflineEnabledAppHasUpdate) {
1028 set_test_app_id(kTestOfflineEnabledKioskApp);
1030 SetUpdateCrx("ajoggoflpgplnnjkjamcmbepjdjdnpdp.crx", "2.0.0");
1032 PrepareAppLaunch();
1033 SimulateNetworkOnline();
1034 SetupAppProfile("chromeos/app_mode/offline_enabled_app_profile");
1036 LaunchApp(test_app_id(), false);
1037 WaitForAppLaunchSuccess();
1039 EXPECT_EQ("2.0.0", GetInstalledAppVersion().GetString());
1042 IN_PROC_BROWSER_TEST_P(KioskUpdateTest, PermissionChange) {
1043 set_test_app_id(kTestOfflineEnabledKioskApp);
1045 SetUpdateCrx("ajoggoflpgplnnjkjamcmbepjdjdnpdp_v2_permission_change.crx",
1046 "2.0.0");
1048 PrepareAppLaunch();
1049 SimulateNetworkOnline();
1050 SetupAppProfile("chromeos/app_mode/offline_enabled_app_profile");
1052 LaunchApp(test_app_id(), false);
1053 WaitForAppLaunchSuccess();
1055 EXPECT_EQ("2.0.0", GetInstalledAppVersion().GetString());
1058 IN_PROC_BROWSER_TEST_P(KioskUpdateTest, PRE_PreserveLocalData) {
1059 // Installs v1 app and writes some local data.
1060 set_test_app_id(kTestLocalFsKioskApp);
1062 ResultCatcher catcher;
1063 StartAppLaunchFromLoginScreen(SimulateNetworkOnlineClosure());
1064 WaitForAppLaunchSuccess();
1065 ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();
1068 IN_PROC_BROWSER_TEST_P(KioskUpdateTest, PreserveLocalData) {
1069 // Update existing v1 app installed in PRE_PreserveLocalData to v2
1070 // that reads and verifies the local data.
1071 set_test_app_id(kTestLocalFsKioskApp);
1073 SetUpdateCrx("bmbpicmpniaclbbpdkfglgipkkebnbjf_v2_read_and_verify_data.crx",
1074 "2.0.0");
1076 ResultCatcher catcher;
1077 StartAppLaunchFromLoginScreen(SimulateNetworkOnlineClosure());
1078 WaitForAppLaunchSuccess();
1080 EXPECT_EQ("2.0.0", GetInstalledAppVersion().GetString());
1081 ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();
1084 // TODO(xiyuan): Remove this after multi profile is turned on by default.
1085 INSTANTIATE_TEST_CASE_P(KioskUpdateTestInstantiation,
1086 KioskUpdateTest,
1087 testing::Bool());
1089 class KioskEnterpriseTest : public KioskTest {
1090 protected:
1091 KioskEnterpriseTest() {}
1093 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
1094 device_policy_test_helper_.MarkAsEnterpriseOwned();
1095 device_policy_test_helper_.InstallOwnerKey();
1097 KioskTest::SetUpInProcessBrowserTestFixture();
1100 virtual void SetUpOnMainThread() OVERRIDE {
1101 KioskTest::SetUpOnMainThread();
1102 // Configure kTestEnterpriseKioskApp in device policy.
1103 em::DeviceLocalAccountsProto* accounts =
1104 device_policy_test_helper_.device_policy()->payload()
1105 .mutable_device_local_accounts();
1106 em::DeviceLocalAccountInfoProto* account = accounts->add_account();
1107 account->set_account_id(kTestEnterpriseAccountId);
1108 account->set_type(
1109 em::DeviceLocalAccountInfoProto::ACCOUNT_TYPE_KIOSK_APP);
1110 account->mutable_kiosk_app()->set_app_id(kTestEnterpriseKioskApp);
1111 accounts->set_auto_login_id(kTestEnterpriseAccountId);
1112 em::PolicyData& policy_data =
1113 device_policy_test_helper_.device_policy()->policy_data();
1114 policy_data.set_service_account_identity(kTestEnterpriseServiceAccountId);
1115 device_policy_test_helper_.device_policy()->Build();
1116 DBusThreadManager::Get()->GetSessionManagerClient()->StoreDevicePolicy(
1117 device_policy_test_helper_.device_policy()->GetBlob(),
1118 base::Bind(&KioskEnterpriseTest::StorePolicyCallback));
1120 DeviceSettingsService::Get()->Load();
1122 // Configure OAuth authentication.
1123 GaiaUrls* gaia_urls = GaiaUrls::GetInstance();
1125 // This token satisfies the userinfo.email request from
1126 // DeviceOAuth2TokenService used in token validation.
1127 FakeGaia::AccessTokenInfo userinfo_token_info;
1128 userinfo_token_info.token = kTestUserinfoToken;
1129 userinfo_token_info.scopes.insert(
1130 "https://www.googleapis.com/auth/userinfo.email");
1131 userinfo_token_info.audience = gaia_urls->oauth2_chrome_client_id();
1132 userinfo_token_info.email = kTestEnterpriseServiceAccountId;
1133 fake_gaia_->IssueOAuthToken(kTestRefreshToken, userinfo_token_info);
1135 // The any-api access token for accessing the token minting endpoint.
1136 FakeGaia::AccessTokenInfo login_token_info;
1137 login_token_info.token = kTestLoginToken;
1138 login_token_info.scopes.insert(GaiaConstants::kAnyApiOAuth2Scope);
1139 login_token_info.audience = gaia_urls->oauth2_chrome_client_id();
1140 fake_gaia_->IssueOAuthToken(kTestRefreshToken, login_token_info);
1142 // This is the access token requested by the app via the identity API.
1143 FakeGaia::AccessTokenInfo access_token_info;
1144 access_token_info.token = kTestAccessToken;
1145 access_token_info.scopes.insert(kTestAppScope);
1146 access_token_info.audience = kTestClientId;
1147 access_token_info.email = kTestEnterpriseServiceAccountId;
1148 fake_gaia_->IssueOAuthToken(kTestLoginToken, access_token_info);
1150 DeviceOAuth2TokenService* token_service =
1151 DeviceOAuth2TokenServiceFactory::Get();
1152 token_service->SetAndSaveRefreshToken(
1153 kTestRefreshToken, DeviceOAuth2TokenService::StatusCallback());
1154 base::RunLoop().RunUntilIdle();
1157 static void StorePolicyCallback(bool result) {
1158 ASSERT_TRUE(result);
1161 policy::DevicePolicyCrosTestHelper device_policy_test_helper_;
1163 private:
1164 DISALLOW_COPY_AND_ASSIGN(KioskEnterpriseTest);
1167 IN_PROC_BROWSER_TEST_F(KioskEnterpriseTest, EnterpriseKioskApp) {
1168 chromeos::WizardController::SkipPostLoginScreensForTesting();
1169 chromeos::WizardController* wizard_controller =
1170 chromeos::WizardController::default_controller();
1171 wizard_controller->SkipToLoginForTesting(LoginScreenContext());
1173 // Wait for the Kiosk App configuration to reload, then launch the app.
1174 KioskAppManager::App app;
1175 content::WindowedNotificationObserver(
1176 chrome::NOTIFICATION_KIOSK_APPS_LOADED,
1177 base::Bind(&KioskAppManager::GetApp,
1178 base::Unretained(KioskAppManager::Get()),
1179 kTestEnterpriseKioskApp, &app)).Wait();
1181 LaunchApp(kTestEnterpriseKioskApp, false);
1183 // Wait for the Kiosk App to launch.
1184 content::WindowedNotificationObserver(
1185 chrome::NOTIFICATION_KIOSK_APP_LAUNCHED,
1186 content::NotificationService::AllSources()).Wait();
1188 // Check installer status.
1189 EXPECT_EQ(chromeos::KioskAppLaunchError::NONE,
1190 chromeos::KioskAppLaunchError::Get());
1192 // Wait for the window to appear.
1193 apps::AppWindow* window =
1194 AppWindowObserver(
1195 apps::AppWindowRegistry::Get(ProfileManager::GetPrimaryUserProfile()),
1196 kTestEnterpriseKioskApp).Wait();
1197 ASSERT_TRUE(window);
1199 // Check whether the app can retrieve an OAuth2 access token.
1200 std::string result;
1201 EXPECT_TRUE(content::ExecuteScriptAndExtractString(
1202 window->web_contents(),
1203 "chrome.identity.getAuthToken({ 'interactive': false }, function(token) {"
1204 " window.domAutomationController.setAutomationId(0);"
1205 " window.domAutomationController.send(token);"
1206 "});",
1207 &result));
1208 EXPECT_EQ(kTestAccessToken, result);
1210 // Terminate the app.
1211 window->GetBaseWindow()->Close();
1212 content::RunAllPendingInMessageLoop();
1215 // Specialized test fixture for testing kiosk mode on the
1216 // hidden WebUI initialization flow for slow hardware.
1217 class KioskHiddenWebUITest : public KioskTest,
1218 public ash::DesktopBackgroundControllerObserver {
1219 public:
1220 KioskHiddenWebUITest() : wallpaper_loaded_(false) {}
1222 // KioskTest overrides:
1223 virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
1224 KioskTest::SetUpCommandLine(command_line);
1225 command_line->AppendSwitch(switches::kDisableBootAnimation);
1228 virtual void SetUpOnMainThread() OVERRIDE {
1229 KioskTest::SetUpOnMainThread();
1230 ash::Shell::GetInstance()->desktop_background_controller()
1231 ->AddObserver(this);
1232 StartupUtils::MarkDeviceRegistered();
1235 virtual void TearDownOnMainThread() OVERRIDE {
1236 ash::Shell::GetInstance()->desktop_background_controller()
1237 ->RemoveObserver(this);
1238 KioskTest::TearDownOnMainThread();
1241 void WaitForWallpaper() {
1242 if (!wallpaper_loaded_) {
1243 runner_ = new content::MessageLoopRunner;
1244 runner_->Run();
1248 bool wallpaper_loaded() const { return wallpaper_loaded_; }
1250 // ash::DesktopBackgroundControllerObserver overrides:
1251 virtual void OnWallpaperDataChanged() OVERRIDE {
1252 wallpaper_loaded_ = true;
1253 if (runner_.get())
1254 runner_->Quit();
1257 bool wallpaper_loaded_;
1258 scoped_refptr<content::MessageLoopRunner> runner_;
1260 DISALLOW_COPY_AND_ASSIGN(KioskHiddenWebUITest);
1263 IN_PROC_BROWSER_TEST_F(KioskHiddenWebUITest, AutolaunchWarning) {
1264 // Add a device owner.
1265 FakeUserManager* user_manager = new FakeUserManager();
1266 user_manager->AddUser(kTestOwnerEmail);
1267 ScopedUserManagerEnabler enabler(user_manager);
1269 // Set kiosk app to autolaunch.
1270 EnableConsumerKioskMode();
1271 chromeos::WizardController::SkipPostLoginScreensForTesting();
1272 chromeos::WizardController* wizard_controller =
1273 chromeos::WizardController::default_controller();
1274 CHECK(wizard_controller);
1275 ReloadAutolaunchKioskApps();
1276 wizard_controller->SkipToLoginForTesting(LoginScreenContext());
1278 EXPECT_FALSE(KioskAppManager::Get()->GetAutoLaunchApp().empty());
1279 EXPECT_FALSE(KioskAppManager::Get()->IsAutoLaunchEnabled());
1281 // Wait for the auto launch warning come up.
1282 content::WindowedNotificationObserver(
1283 chrome::NOTIFICATION_KIOSK_AUTOLAUNCH_WARNING_VISIBLE,
1284 content::NotificationService::AllSources()).Wait();
1286 // Wait for the wallpaper to load.
1287 WaitForWallpaper();
1288 EXPECT_TRUE(wallpaper_loaded());
1291 } // namespace chromeos