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.
4 
5 #include <stddef.h>
6 
7 #include <map>
8 #include <memory>
9 #include <set>
10 #include <string>
11 #include <utility>
12 #include <vector>
13 
14 #include "ash/public/cpp/login_screen_test_api.h"
15 #include "ash/shell.h"
16 #include "ash/system/session/logout_confirmation_controller.h"
17 #include "ash/system/session/logout_confirmation_dialog.h"
18 #include "base/bind.h"
19 #include "base/callback.h"
20 #include "base/callback_helpers.h"
21 #include "base/command_line.h"
22 #include "base/files/file_path.h"
23 #include "base/files/file_util.h"
24 #include "base/json/json_reader.h"
25 #include "base/json/json_writer.h"
26 #include "base/location.h"
27 #include "base/memory/ref_counted.h"
28 #include "base/path_service.h"
29 #include "base/run_loop.h"
30 #include "base/sequenced_task_runner.h"
31 #include "base/single_thread_task_runner.h"
32 #include "base/stl_util.h"
33 #include "base/strings/string_number_conversions.h"
34 #include "base/strings/string_util.h"
35 #include "base/strings/stringprintf.h"
36 #include "base/strings/utf_string_conversions.h"
37 #include "base/synchronization/lock.h"
38 #include "base/threading/thread_restrictions.h"
39 #include "base/threading/thread_task_runner_handle.h"
40 #include "base/values.h"
41 #include "chrome/browser/apps/app_service/app_launch_params.h"
42 #include "chrome/browser/apps/app_service/app_service_proxy.h"
43 #include "chrome/browser/apps/app_service/app_service_proxy_factory.h"
44 #include "chrome/browser/apps/app_service/launch_utils.h"
45 #include "chrome/browser/browser_process.h"
46 #include "chrome/browser/browser_process_platform_part.h"
47 #include "chrome/browser/chrome_notification_types.h"
48 #include "chrome/browser/chromeos/extensions/device_local_account_external_policy_loader.h"
49 #include "chrome/browser/chromeos/extensions/external_cache.h"
50 #include "chrome/browser/chromeos/login/existing_user_controller.h"
51 #include "chrome/browser/chromeos/login/screens/base_screen.h"
52 #include "chrome/browser/chromeos/login/screens/terms_of_service_screen.h"
53 #include "chrome/browser/chromeos/login/session/user_session_manager.h"
54 #include "chrome/browser/chromeos/login/session/user_session_manager_test_api.h"
55 #include "chrome/browser/chromeos/login/signin_specifics.h"
56 #include "chrome/browser/chromeos/login/test/js_checker.h"
57 #include "chrome/browser/chromeos/login/test/local_policy_test_server_mixin.h"
58 #include "chrome/browser/chromeos/login/test/oobe_base_test.h"
59 #include "chrome/browser/chromeos/login/test/oobe_screen_waiter.h"
60 #include "chrome/browser/chromeos/login/test/session_manager_state_waiter.h"
61 #include "chrome/browser/chromeos/login/test/test_predicate_waiter.h"
62 #include "chrome/browser/chromeos/login/test/webview_content_extractor.h"
63 #include "chrome/browser/chromeos/login/ui/login_display_host.h"
64 #include "chrome/browser/chromeos/login/ui/webui_login_view.h"
65 #include "chrome/browser/chromeos/login/users/avatar/user_image_manager.h"
66 #include "chrome/browser/chromeos/login/users/avatar/user_image_manager_impl.h"
67 #include "chrome/browser/chromeos/login/users/avatar/user_image_manager_test_util.h"
68 #include "chrome/browser/chromeos/login/users/chrome_user_manager.h"
69 #include "chrome/browser/chromeos/login/users/chrome_user_manager_impl.h"
70 #include "chrome/browser/chromeos/login/wizard_controller.h"
71 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
72 #include "chrome/browser/chromeos/policy/cloud_external_data_manager_base_test_util.h"
73 #include "chrome/browser/chromeos/policy/device_local_account.h"
74 #include "chrome/browser/chromeos/policy/device_local_account_policy_service.h"
75 #include "chrome/browser/chromeos/policy/device_network_configuration_updater.h"
76 #include "chrome/browser/chromeos/policy/device_policy_builder.h"
77 #include "chrome/browser/chromeos/policy/device_policy_cros_browser_test.h"
78 #include "chrome/browser/chromeos/profiles/profile_helper.h"
79 #include "chrome/browser/chromeos/system/timezone_util.h"
80 #include "chrome/browser/extensions/crx_installer.h"
81 #include "chrome/browser/extensions/extension_service.h"
82 #include "chrome/browser/extensions/updater/chromeos_extension_cache_delegate.h"
83 #include "chrome/browser/extensions/updater/extension_cache_impl.h"
84 #include "chrome/browser/extensions/updater/local_extension_cache.h"
85 #include "chrome/browser/lifetime/application_lifetime.h"
86 #include "chrome/browser/net/profile_network_context_service.h"
87 #include "chrome/browser/net/profile_network_context_service_test_utils.h"
88 #include "chrome/browser/policy/profile_policy_connector.h"
89 #include "chrome/browser/prefs/session_startup_pref.h"
90 #include "chrome/browser/profiles/profile.h"
91 #include "chrome/browser/profiles/profile_manager.h"
92 #include "chrome/browser/signin/identity_manager_factory.h"
93 #include "chrome/browser/ui/browser.h"
94 #include "chrome/browser/ui/browser_commands.h"
95 #include "chrome/browser/ui/browser_finder.h"
96 #include "chrome/browser/ui/browser_list.h"
97 #include "chrome/browser/ui/browser_list_observer.h"
98 #include "chrome/browser/ui/browser_window.h"
99 #include "chrome/browser/ui/tabs/tab_strip_model.h"
100 #include "chrome/browser/ui/webui/chromeos/login/gaia_screen_handler.h"
101 #include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h"
102 #include "chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h"
103 #include "chrome/browser/ui/webui/chromeos/login/terms_of_service_screen_handler.h"
104 #include "chrome/browser/web_applications/web_app_provider.h"
105 #include "chrome/common/chrome_paths.h"
106 #include "chrome/common/extensions/extension_constants.h"
107 #include "chrome/common/pref_names.h"
108 #include "chrome/grit/chromium_strings.h"
109 #include "chrome/grit/generated_resources.h"
110 #include "chromeos/constants/chromeos_paths.h"
111 #include "chromeos/constants/chromeos_switches.h"
112 #include "chromeos/dbus/session_manager/fake_session_manager_client.h"
113 #include "chromeos/login/auth/mock_auth_status_consumer.h"
114 #include "chromeos/login/auth/user_context.h"
115 #include "chromeos/network/policy_certificate_provider.h"
116 #include "chromeos/settings/timezone_settings.h"
117 #include "components/crx_file/crx_verifier.h"
118 #include "components/policy/core/common/cloud/cloud_policy_constants.h"
119 #include "components/policy/core/common/cloud/cloud_policy_core.h"
120 #include "components/policy/core/common/cloud/cloud_policy_store.h"
121 #include "components/policy/core/common/cloud/policy_builder.h"
122 #include "components/policy/core/common/external_data_fetcher.h"
123 #include "components/policy/core/common/policy_map.h"
124 #include "components/policy/core/common/policy_namespace.h"
125 #include "components/policy/core/common/policy_service.h"
126 #include "components/policy/core/common/policy_switches.h"
127 #include "components/policy/policy_constants.h"
128 #include "components/policy/proto/chrome_device_policy.pb.h"
129 #include "components/prefs/pref_change_registrar.h"
130 #include "components/prefs/pref_service.h"
131 #include "components/session_manager/core/session_manager.h"
132 #include "components/signin/public/identity_manager/identity_manager.h"
133 #include "components/user_manager/user.h"
134 #include "components/user_manager/user_manager.h"
135 #include "components/user_manager/user_type.h"
136 #include "content/public/browser/notification_details.h"
137 #include "content/public/browser/notification_service.h"
138 #include "content/public/browser/notification_source.h"
139 #include "content/public/browser/web_contents.h"
140 #include "content/public/browser/web_ui.h"
141 #include "content/public/test/browser_test.h"
142 #include "content/public/test/browser_test_utils.h"
143 #include "content/public/test/test_utils.h"
144 #include "crypto/rsa_private_key.h"
145 #include "extensions/browser/app_window/app_window.h"
146 #include "extensions/browser/app_window/app_window_registry.h"
147 #include "extensions/browser/app_window/native_app_window.h"
148 #include "extensions/browser/extension_registry.h"
149 #include "extensions/browser/extension_system.h"
150 #include "extensions/browser/install/crx_install_error.h"
151 #include "extensions/browser/management_policy.h"
152 #include "extensions/browser/notification_types.h"
153 #include "extensions/browser/sandboxed_unpacker.h"
154 #include "extensions/browser/test_extension_registry_observer.h"
155 #include "extensions/common/constants.h"
156 #include "extensions/common/extension.h"
157 #include "extensions/common/extension_builder.h"
158 #include "net/base/url_util.h"
159 #include "net/http/http_status_code.h"
160 #include "net/test/embedded_test_server/embedded_test_server.h"
161 #include "net/test/embedded_test_server/http_request.h"
162 #include "net/test/embedded_test_server/http_response.h"
163 #include "testing/gmock/include/gmock/gmock.h"
164 #include "third_party/icu/source/common/unicode/locid.h"
165 #include "ui/base/ime/chromeos/extension_ime_util.h"
166 #include "ui/base/ime/chromeos/input_method_descriptor.h"
167 #include "ui/base/ime/chromeos/input_method_manager.h"
168 #include "ui/base/ime/chromeos/input_method_util.h"
169 #include "ui/base/l10n/l10n_util.h"
170 #include "ui/base/window_open_disposition.h"
171 #include "ui/display/display.h"
172 #include "ui/display/screen.h"
173 #include "ui/gfx/image/image_skia.h"
174 #include "ui/views/widget/widget.h"
175 #include "url/gurl.h"
176 
177 namespace em = enterprise_management;
178 
179 using chromeos::test::GetOobeElementPath;
180 using testing::_;
181 using testing::InvokeWithoutArgs;
182 using testing::Return;
183 
184 namespace policy {
185 
186 namespace {
187 
188 const char kDomain[] = "example.com";
189 const char kAccountId1[] = "dla1@example.com";
190 const char kAccountId2[] = "dla2@example.com";
191 const char kDisplayName1[] = "display name 1";
192 const char kDisplayName2[] = "display name 2";
193 const char* const kStartupURLs[] = {
194   "chrome://policy",
195   "chrome://about",
196 };
197 const char kExistentTermsOfServicePath[] = "chromeos/enterprise/tos.txt";
198 const char kNonexistentTermsOfServicePath[] = "chromeos/enterprise/tos404.txt";
199 const char kRelativeUpdateURL[] = "/service/update2/crx";
200 const char kUpdateManifestHeader[] =
201     "<?xml version='1.0' encoding='UTF-8'?>\n"
202     "<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>\n";
203 const char kUpdateManifestTemplate[] =
204     "  <app appid='%s'>\n"
205     "    <updatecheck codebase='%s' version='%s' />\n"
206     "  </app>\n";
207 const char kUpdateManifestFooter[] =
208     "</gupdate>\n";
209 const char kHostedAppID[] = "kbmnembihfiondgfjekmnmcbddelicoi";
210 const char kHostedAppCRXPath[] = "extensions/hosted_app.crx";
211 const char kHostedAppVersion[] = "1.0.0.0";
212 const char kGoodExtensionID[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
213 const char kGoodExtensionCRXPath[] = "extensions/good.crx";
214 const char kGoodExtensionVersion[] = "1.0";
215 const char kPackagedAppCRXPath[] = "extensions/platform_apps/app_window_2.crx";
216 const char kShowManagedStorageID[] = "ongnjlefhnoajpbodoldndkbkdgfomlp";
217 const char kShowManagedStorageCRXPath[] = "extensions/show_managed_storage.crx";
218 const char kShowManagedStorageVersion[] = "1.0";
219 
220 const char kExternalData[] = "External data";
221 const char kExternalDataPath[] = "/external";
222 
223 const char* const kSingleRecommendedLocale[] = {
224   "el",
225 };
226 const char* const kRecommendedLocales1[] = {
227   "pl",
228   "et",
229   "en-US",
230 };
231 const char* const kRecommendedLocales2[] = {
232   "fr",
233   "nl",
234 };
235 const char* const kInvalidRecommendedLocale[] = {
236   "xx",
237 };
238 const char kPublicSessionLocale[] = "de";
239 const char kPublicSessionInputMethodIDTemplate[] = "_comp_ime_%sxkb:de:neo:ger";
240 
241 const char kFakeOncWithCertificate[] =
242     "{\"Certificates\":["
243     "{\"Type\":\"Authority\","
244     "\"TrustBits\":[\"Web\"],"
245     "\"X509\":\"-----BEGIN CERTIFICATE-----\n"
246     "MIICVTCCAb6gAwIBAgIJAK8kOY/OQDsKMA0GCSqGSIb3DQEBCwUAMEIxCzAJBgNV\n"
247     "BAYTAkRFMRAwDgYDVQQIDAdCYXZhcmlhMSEwHwYDVQQKDBhJbnRlcm5ldCBXaWRn\n"
248     "aXRzIFB0eSBMdGQwHhcNMTgxMjI3MTIyNjI0WhcNMTkxMjI3MTIyNjI0WjBCMQsw\n"
249     "CQYDVQQGEwJERTEQMA4GA1UECAwHQmF2YXJpYTEhMB8GA1UECgwYSW50ZXJuZXQg\n"
250     "V2lkZ2l0cyBQdHkgTHRkMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDbFncT\n"
251     "Q8slhRgLg7sK9DhkYZaNiD1jVbdGvuXahex3uQl+2bACyQ7Peq/MkpFLy4M75nj3\n"
252     "WrydAycw1KCDPENPz2jmdHwGl5+6P7bob0Rqe+4i/9XwGdl8EPH5GFZbaz8aSYiL\n"
253     "/aaVvOm+8IYrhbp44s3cOLriPaQDbWtZMZKCiwIDAQABo1MwUTAdBgNVHQ4EFgQU\n"
254     "26bvyiqj3uQynNcZru72m3Uv3eswHwYDVR0jBBgwFoAU26bvyiqj3uQynNcZru72\n"
255     "m3Uv3eswDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOBgQCHKz8NJg6f\n"
256     "qwkFmG+tOsfyn3JHj3NfkMGJugSV6Yf7LYJXHpc4kWmfGuseTtHt57PG/BzCjLs1\n"
257     "qTF8svVecDj5Qku/SbGQCf2Vg/tLnq8XidbMmp26nUXrLzNQnTm0MJYEk6PJRiod\n"
258     "BIrpuq5z+9r//9f27iXidR94qFbbvServw==\n"
259     "-----END CERTIFICATE-----\","
260     "\"GUID\":\"{00f79111-51e0-e6e0-76b3b55450d80a1b}\"}"
261     "]}";
262 
IsLogoutConfirmationDialogShowing()263 bool IsLogoutConfirmationDialogShowing() {
264   return !!ash::Shell::Get()
265                ->logout_confirmation_controller()
266                ->dialog_for_testing();
267 }
268 
CloseLogoutConfirmationDialog()269 void CloseLogoutConfirmationDialog() {
270   // TODO(mash): Add mojo test API for this.
271   ash::LogoutConfirmationDialog* dialog =
272       ash::Shell::Get()->logout_confirmation_controller()->dialog_for_testing();
273   ASSERT_TRUE(dialog);
274   dialog->GetWidget()->Close();
275   base::RunLoop().RunUntilIdle();
276 }
277 
278 // Helper that serves extension update manifests to Chrome.
279 class TestingUpdateManifestProvider
280     : public base::RefCountedThreadSafe<TestingUpdateManifestProvider> {
281  public:
282   // Update manifests will be served at |relative_update_url|.
283   explicit TestingUpdateManifestProvider(
284       const std::string& relative_update_url);
285 
286   // When an update manifest is requested for the given extension |id|, indicate
287   // that |version| of the extension can be downloaded at |crx_url|.
288   void AddUpdate(const std::string& id,
289                  const std::string& version,
290                  const GURL& crx_url);
291 
292   // This method must be registered with the test's EmbeddedTestServer to start
293   // serving update manifests.
294   std::unique_ptr<net::test_server::HttpResponse> HandleRequest(
295       const net::test_server::HttpRequest& request);
296 
297  private:
298   struct Update {
299    public:
300     Update(const std::string& version, const GURL& crx_url);
301     Update();
302 
303     std::string version;
304     GURL crx_url;
305   };
306   typedef std::map<std::string, Update> UpdateMap;
307 
308   ~TestingUpdateManifestProvider();
309   friend class RefCountedThreadSafe<TestingUpdateManifestProvider>;
310 
311   // Protects other members against concurrent access from main thread and
312   // test server io thread.
313   base::Lock lock_;
314 
315   std::string relative_update_url_;
316   UpdateMap updates_;
317 
318   DISALLOW_COPY_AND_ASSIGN(TestingUpdateManifestProvider);
319 };
320 
Update(const std::string & version,const GURL & crx_url)321 TestingUpdateManifestProvider::Update::Update(const std::string& version,
322                                               const GURL& crx_url)
323     : version(version),
324       crx_url(crx_url) {
325 }
326 
Update()327 TestingUpdateManifestProvider::Update::Update() {
328 }
329 
TestingUpdateManifestProvider(const std::string & relative_update_url)330 TestingUpdateManifestProvider::TestingUpdateManifestProvider(
331     const std::string& relative_update_url)
332     : relative_update_url_(relative_update_url) {
333 }
334 
AddUpdate(const std::string & id,const std::string & version,const GURL & crx_url)335 void TestingUpdateManifestProvider::AddUpdate(const std::string& id,
336                                               const std::string& version,
337                                               const GURL& crx_url) {
338   base::AutoLock auto_lock(lock_);
339   updates_[id] = Update(version, crx_url);
340 }
341 
342 std::unique_ptr<net::test_server::HttpResponse>
HandleRequest(const net::test_server::HttpRequest & request)343 TestingUpdateManifestProvider::HandleRequest(
344     const net::test_server::HttpRequest& request) {
345   base::AutoLock auto_lock(lock_);
346   const GURL url("http://localhost" + request.relative_url);
347   if (url.path() != relative_update_url_)
348     return std::unique_ptr<net::test_server::HttpResponse>();
349 
350   std::string content = kUpdateManifestHeader;
351   for (net::QueryIterator it(url); !it.IsAtEnd(); it.Advance()) {
352     if (it.GetKey() != "x")
353       continue;
354     // Extract the extension id from the subquery. Since GetValueForKeyInQuery()
355     // expects a complete URL, dummy scheme and host must be prepended.
356     std::string id;
357     net::GetValueForKeyInQuery(GURL("http://dummy?" + it.GetUnescapedValue()),
358                                "id", &id);
359     UpdateMap::const_iterator entry = updates_.find(id);
360     if (entry != updates_.end()) {
361       content += base::StringPrintf(kUpdateManifestTemplate,
362                                     id.c_str(),
363                                     entry->second.crx_url.spec().c_str(),
364                                     entry->second.version.c_str());
365     }
366   }
367   content += kUpdateManifestFooter;
368   std::unique_ptr<net::test_server::BasicHttpResponse> http_response(
369       new net::test_server::BasicHttpResponse);
370   http_response->set_code(net::HTTP_OK);
371   http_response->set_content(content);
372   http_response->set_content_type("text/xml");
373   return std::move(http_response);
374 }
375 
~TestingUpdateManifestProvider()376 TestingUpdateManifestProvider::~TestingUpdateManifestProvider() {
377 }
378 
379 
DoesInstallFailureReferToId(const std::string & id,const content::NotificationSource & source,const content::NotificationDetails & details)380 bool DoesInstallFailureReferToId(const std::string& id,
381                                  const content::NotificationSource& source,
382                                  const content::NotificationDetails& details) {
383   return content::Details<const extensions::CrxInstallError>(details)
384              ->message()
385              .find(base::UTF8ToUTF16(id)) != base::string16::npos;
386 }
387 
IsSessionStarted()388 bool IsSessionStarted() {
389   return session_manager::SessionManager::Get()->IsSessionStarted();
390 }
391 
PolicyChangedCallback(const base::Closure & callback,const base::Value * old_value,const base::Value * new_value)392 void PolicyChangedCallback(const base::Closure& callback,
393                            const base::Value* old_value,
394                            const base::Value* new_value) {
395   callback.Run();
396 }
397 
398 }  // namespace
399 
400 class DeviceLocalAccountTest : public DevicePolicyCrosBrowserTest,
401                                public user_manager::UserManager::Observer,
402                                public BrowserListObserver,
403                                public extensions::AppWindowRegistry::Observer {
404  protected:
DeviceLocalAccountTest()405   DeviceLocalAccountTest()
406       : public_session_input_method_id_(
407             base::StringPrintf(kPublicSessionInputMethodIDTemplate,
408                                chromeos::extension_ime_util::kXkbExtensionId)),
409         contents_(NULL),
410         verifier_format_override_(crx_file::VerifierFormat::CRX3) {
411     set_exit_when_last_browser_closes(false);
412   }
413 
~DeviceLocalAccountTest()414   ~DeviceLocalAccountTest() override {}
415 
SetUp()416   void SetUp() override {
417     BrowserList::AddObserver(this);
418 
419     DevicePolicyCrosBrowserTest::SetUp();
420   }
421 
SetUpCommandLine(base::CommandLine * command_line)422   void SetUpCommandLine(base::CommandLine* command_line) override {
423     DevicePolicyCrosBrowserTest::SetUpCommandLine(command_line);
424     command_line->AppendSwitch(chromeos::switches::kLoginManager);
425     command_line->AppendSwitch(chromeos::switches::kForceLoginManagerInTests);
426     command_line->AppendSwitchASCII(chromeos::switches::kLoginProfile, "user");
427   }
428 
SetUpInProcessBrowserTestFixture()429   void SetUpInProcessBrowserTestFixture() override {
430     DevicePolicyCrosBrowserTest::SetUpInProcessBrowserTestFixture();
431 
432     // Clear command-line arguments (but keep command-line switches) so the
433     // startup pages policy takes effect.
434     base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
435     base::CommandLine::StringVector argv(command_line->argv());
436     argv.erase(argv.begin() + argv.size() - command_line->GetArgs().size(),
437                argv.end());
438     command_line->InitFromArgv(argv);
439 
440     InitializePolicy();
441   }
442 
SetUpOnMainThread()443   void SetUpOnMainThread() override {
444     DevicePolicyCrosBrowserTest::SetUpOnMainThread();
445 
446     initial_locale_ = g_browser_process->GetApplicationLocale();
447     initial_language_ = l10n_util::GetLanguage(initial_locale_);
448 
449     content::WindowedNotificationObserver(
450         chrome::NOTIFICATION_LOGIN_OR_LOCK_WEBUI_VISIBLE,
451         content::NotificationService::AllSources()).Wait();
452 
453     chromeos::LoginDisplayHost* host =
454         chromeos::LoginDisplayHost::default_host();
455     contents_ = host->GetOobeWebContents();
456     ASSERT_TRUE(contents_);
457 
458     // Wait for the login UI to be ready.
459     chromeos::OobeUI* oobe_ui = host->GetOobeUI();
460     ASSERT_TRUE(oobe_ui);
461     base::RunLoop run_loop;
462     const bool oobe_ui_ready = oobe_ui->IsJSReady(run_loop.QuitClosure());
463     if (!oobe_ui_ready)
464       run_loop.Run();
465 
466     // Skip to the login screen.
467     chromeos::OobeScreenWaiter(chromeos::OobeBaseTest::GetFirstSigninScreen())
468         .Wait();
469 
470     chromeos::test::UserSessionManagerTestApi session_manager_test_api(
471         chromeos::UserSessionManager::GetInstance());
472     session_manager_test_api.SetShouldObtainTokenHandleInTests(false);
473   }
474 
TearDownOnMainThread()475   void TearDownOnMainThread() override {
476     BrowserList::RemoveObserver(this);
477     DevicePolicyCrosBrowserTest::TearDownOnMainThread();
478   }
479 
480   // user_manager::UserManager::Observer:
LocalStateChanged(user_manager::UserManager * user_manager)481   void LocalStateChanged(user_manager::UserManager* user_manager) override {
482     if (local_state_changed_run_loop_)
483       local_state_changed_run_loop_->Quit();
484   }
485 
486   // BrowserListObserver:
OnBrowserRemoved(Browser * browser)487   void OnBrowserRemoved(Browser* browser) override {
488     if (run_loop_)
489       run_loop_->Quit();
490   }
491 
492   // extensions::AppWindowRegistry::Observer:
OnAppWindowAdded(extensions::AppWindow * app_window)493   void OnAppWindowAdded(extensions::AppWindow* app_window) override {
494     if (run_loop_)
495       run_loop_->Quit();
496   }
497 
OnAppWindowRemoved(extensions::AppWindow * app_window)498   void OnAppWindowRemoved(extensions::AppWindow* app_window) override {
499     if (run_loop_)
500       run_loop_->Quit();
501   }
502 
InitializePolicy()503   void InitializePolicy() {
504     device_policy()->policy_data().set_public_key_version(1);
505     DeviceLocalAccountTestHelper::SetupDeviceLocalAccount(
506         &device_local_account_policy_, kAccountId1, kDisplayName1);
507     // Don't enable new managed sessions, use old public sessions.
508     SetManagedSessionsEnabled(/* managed_sessions_enabled */ false);
509   }
510 
BuildDeviceLocalAccountPolicy()511   void BuildDeviceLocalAccountPolicy() {
512     device_local_account_policy_.SetDefaultSigningKey();
513     device_local_account_policy_.Build();
514   }
515 
UploadDeviceLocalAccountPolicy()516   void UploadDeviceLocalAccountPolicy() {
517     BuildDeviceLocalAccountPolicy();
518     ASSERT_TRUE(local_policy_mixin_.server()->UpdatePolicy(
519         dm_protocol::kChromePublicAccountPolicyType, kAccountId1,
520         device_local_account_policy_.payload().SerializeAsString()));
521   }
522 
UploadAndInstallDeviceLocalAccountPolicy()523   void UploadAndInstallDeviceLocalAccountPolicy() {
524     UploadDeviceLocalAccountPolicy();
525     session_manager_client()->set_device_local_account_policy(
526         kAccountId1, device_local_account_policy_.GetBlob());
527   }
528 
SetRecommendedLocales(const char * const recommended_locales[],size_t array_size)529   void SetRecommendedLocales(const char* const recommended_locales[],
530                              size_t array_size) {
531     em::StringListPolicyProto* session_locales_proto =
532         device_local_account_policy_.payload().mutable_sessionlocales();
533      session_locales_proto->mutable_policy_options()->set_mode(
534         em::PolicyOptions_PolicyMode_RECOMMENDED);
535     session_locales_proto->mutable_value()->Clear();
536     for (size_t i = 0; i < array_size; ++i) {
537       session_locales_proto->mutable_value()->add_entries(
538           recommended_locales[i]);
539     }
540   }
541 
WaitForPublicSessionLocalesChange(const AccountId & account_id)542   void WaitForPublicSessionLocalesChange(const AccountId& account_id) {
543     std::vector<ash::LocaleItem> locales =
544         ash::LoginScreenTestApi::GetPublicSessionLocales(account_id);
545     chromeos::test::TestPredicateWaiter(
546         base::BindRepeating(
547             [](const std::vector<ash::LocaleItem>& locales,
548                const AccountId& account_id) {
549               return locales !=
550                      ash::LoginScreenTestApi::GetPublicSessionLocales(
551                          account_id);
552             },
553             locales, account_id))
554         .Wait();
555   }
556 
AddPublicSessionToDevicePolicy(const std::string & username)557   void AddPublicSessionToDevicePolicy(const std::string& username) {
558     em::ChromeDeviceSettingsProto& proto(device_policy()->payload());
559     DeviceLocalAccountTestHelper::AddPublicSession(&proto, username);
560     RefreshDevicePolicy();
561     ASSERT_TRUE(local_policy_mixin_.UpdateDevicePolicy(proto));
562   }
563 
SetManagedSessionsEnabled(bool managed_sessions_enabled)564   void SetManagedSessionsEnabled(bool managed_sessions_enabled) {
565     device_local_account_policy_.payload()
566         .mutable_devicelocalaccountmanagedsessionenabled()
567         ->set_value(managed_sessions_enabled);
568     UploadDeviceLocalAccountPolicy();
569   }
570 
EnableAutoLogin()571   void EnableAutoLogin() {
572     em::ChromeDeviceSettingsProto& proto(device_policy()->payload());
573     em::DeviceLocalAccountsProto* device_local_accounts =
574         proto.mutable_device_local_accounts();
575     device_local_accounts->set_auto_login_id(kAccountId1);
576     device_local_accounts->set_auto_login_delay(0);
577     RefreshDevicePolicy();
578     ASSERT_TRUE(local_policy_mixin_.UpdateDevicePolicy(proto));
579   }
580 
CheckPublicSessionPresent(const AccountId & account_id)581   void CheckPublicSessionPresent(const AccountId& account_id) {
582     const user_manager::User* user =
583         user_manager::UserManager::Get()->FindUser(account_id);
584     ASSERT_TRUE(user) << " account " << account_id.GetUserEmail()
585                       << " not found";
586     EXPECT_EQ(account_id, user->GetAccountId());
587     EXPECT_EQ(user_manager::USER_TYPE_PUBLIC_ACCOUNT, user->GetType());
588   }
589 
SetSystemTimezoneAutomaticDetectionPolicy(em::SystemTimezoneProto_AutomaticTimezoneDetectionType policy)590   void SetSystemTimezoneAutomaticDetectionPolicy(
591       em::SystemTimezoneProto_AutomaticTimezoneDetectionType policy) {
592     em::ChromeDeviceSettingsProto& proto(device_policy()->payload());
593     proto.mutable_system_timezone()->set_timezone_detection_type(policy);
594     RefreshDevicePolicy();
595 
596     LocalStateValueWaiter(prefs::kSystemTimezoneAutomaticDetectionPolicy,
597                           base::Value(policy))
598         .Wait();
599     ASSERT_TRUE(local_policy_mixin_.UpdateDevicePolicy(proto));
600   }
601 
GetExtensionCacheDirectoryForAccountID(const std::string & account_id)602   base::FilePath GetExtensionCacheDirectoryForAccountID(
603       const std::string& account_id) {
604     base::FilePath extension_cache_root_dir;
605     if (!base::PathService::Get(chromeos::DIR_DEVICE_LOCAL_ACCOUNT_EXTENSIONS,
606                                 &extension_cache_root_dir)) {
607       ADD_FAILURE();
608     }
609     return extension_cache_root_dir.Append(
610         base::HexEncode(account_id.c_str(), account_id.size()));
611   }
612 
GetCacheCRXFilePath(const std::string & id,const std::string & version,const base::FilePath & path)613   base::FilePath GetCacheCRXFilePath(const std::string& id,
614                                      const std::string& version,
615                                      const base::FilePath& path) {
616     return path.Append(
617         extensions::LocalExtensionCache::ExtensionFileName(id, version, ""));
618   }
619 
GetCacheCRXFile(const std::string & account_id,const std::string & id,const std::string & version)620   base::FilePath GetCacheCRXFile(const std::string& account_id,
621                                  const std::string& id,
622                                  const std::string& version) {
623     return GetCacheCRXFilePath(
624         id, version, GetExtensionCacheDirectoryForAccountID(account_id));
625   }
626 
627   // Returns a profile which can be used for testing.
GetProfileForTest()628   Profile* GetProfileForTest() {
629     // Any profile can be used here since this test does not test multi profile.
630     return ProfileManager::GetActiveUserProfile();
631   }
632 
WaitForDisplayName(const std::string & user_id,const std::string & expected_display_name)633   void WaitForDisplayName(const std::string& user_id,
634                           const std::string& expected_display_name) {
635     DictionaryLocalStateValueWaiter("UserDisplayName", expected_display_name,
636                                     user_id)
637         .Wait();
638   }
639 
WaitForPolicy()640   void WaitForPolicy() {
641     // Wait for the display name becoming available as that indicates
642     // device-local account policy is fully loaded, which is a prerequisite for
643     // successful login.
644     WaitForDisplayName(account_id_1_.GetUserEmail(), kDisplayName1);
645   }
646 
ExpandPublicSessionPod(bool expect_advanced)647   void ExpandPublicSessionPod(bool expect_advanced) {
648     ASSERT_TRUE(ash::LoginScreenTestApi::ExpandPublicSessionPod(account_id_1_));
649     ASSERT_EQ(ash::LoginScreenTestApi::IsExpandedPublicSessionAdvanced(),
650               expect_advanced);
651     // Verify that the construction of the pod's language list did not affect
652     // the current ICU locale.
653     EXPECT_EQ(initial_language_, icu::Locale::getDefault().getLanguage());
654   }
655 
656   // GetKeyboardLayoutsForLocale() posts a task to a background task runner and
657   // handles the response on the main thread. This method flushes both the
658   // thread pool backing the background task runner and the main thread.
WaitForGetKeyboardLayoutsForLocaleToFinish()659   void WaitForGetKeyboardLayoutsForLocaleToFinish() {
660     content::RunAllTasksUntilIdle();
661 
662     // Verify that the construction of the keyboard layout list did not affect
663     // the current ICU locale.
664     EXPECT_EQ(initial_language_, icu::Locale::getDefault().getLanguage());
665   }
666 
StartLogin(const std::string & locale,const std::string & input_method)667   void StartLogin(const std::string& locale,
668                   const std::string& input_method) {
669     // Start login into the device-local account.
670     chromeos::LoginDisplayHost* host =
671         chromeos::LoginDisplayHost::default_host();
672     ASSERT_TRUE(host);
673     host->StartSignInScreen();
674     chromeos::ExistingUserController* controller =
675         chromeos::ExistingUserController::current_controller();
676     ASSERT_TRUE(controller);
677 
678     chromeos::UserContext user_context(user_manager::USER_TYPE_PUBLIC_ACCOUNT,
679                                        account_id_1_);
680     user_context.SetPublicSessionLocale(locale);
681     user_context.SetPublicSessionInputMethod(input_method);
682     controller->Login(user_context, chromeos::SigninSpecifics());
683   }
684 
WaitForSessionStart()685   void WaitForSessionStart() {
686     if (IsSessionStarted())
687       return;
688     chromeos::WizardController::SkipPostLoginScreensForTesting();
689     chromeos::test::WaitForPrimaryUserSessionStart();
690   }
691 
WaitUntilLocalStateChanged()692   void WaitUntilLocalStateChanged() {
693     local_state_changed_run_loop_ = std::make_unique<base::RunLoop>();
694     user_manager::UserManager::Get()->AddObserver(this);
695     local_state_changed_run_loop_->Run();
696     user_manager::UserManager::Get()->RemoveObserver(this);
697   }
698 
GetDefaultKeyboardIdFromLanguageCode(const std::string & language_code)699   static std::string GetDefaultKeyboardIdFromLanguageCode(
700       const std::string& language_code) {
701     chromeos::input_method::InputMethodManager* input_method_manager =
702         chromeos::input_method::InputMethodManager::Get();
703     std::vector<std::string> layouts_from_locale;
704     input_method_manager->GetInputMethodUtil()
705         ->GetInputMethodIdsFromLanguageCode(
706             language_code, chromeos::input_method::kKeyboardLayoutsOnly,
707             &layouts_from_locale);
708     EXPECT_FALSE(layouts_from_locale.empty());
709     if (layouts_from_locale.empty())
710       return std::string();
711     return layouts_from_locale.front();
712   }
VerifyKeyboardLayoutMatchesLocale()713   void VerifyKeyboardLayoutMatchesLocale() {
714     chromeos::input_method::InputMethodManager* input_method_manager =
715         chromeos::input_method::InputMethodManager::Get();
716     EXPECT_EQ(GetDefaultKeyboardIdFromLanguageCode(
717                   g_browser_process->GetApplicationLocale()),
718               input_method_manager->GetActiveIMEState()
719                   ->GetCurrentInputMethod()
720                   .id());
721   }
722 
RunWithRecommendedLocale(const char * const locales[],size_t locales_size)723   void RunWithRecommendedLocale(const char* const locales[],
724                                 size_t locales_size) {
725     SetRecommendedLocales(locales, locales_size);
726     UploadAndInstallDeviceLocalAccountPolicy();
727     AddPublicSessionToDevicePolicy(kAccountId1);
728     EnableAutoLogin();
729 
730     WaitForPolicy();
731 
732     WaitForSessionStart();
733 
734     EXPECT_EQ(locales[0], g_browser_process->GetApplicationLocale());
735     EXPECT_EQ(l10n_util::GetLanguage(locales[0]),
736               icu::Locale::getDefault().getLanguage());
737     VerifyKeyboardLayoutMatchesLocale();
738   }
739 
740   const AccountId account_id_1_ =
741       AccountId::FromUserEmail(GenerateDeviceLocalAccountUserId(
742           kAccountId1,
743           DeviceLocalAccount::TYPE_PUBLIC_SESSION));
744   const AccountId account_id_2_ =
745       AccountId::FromUserEmail(GenerateDeviceLocalAccountUserId(
746           kAccountId2,
747           DeviceLocalAccount::TYPE_PUBLIC_SESSION));
748   const std::string public_session_input_method_id_;
749 
750   std::string initial_locale_;
751   std::string initial_language_;
752 
753   std::unique_ptr<base::RunLoop> run_loop_;
754 
755   // Specifically exists to assist with waiting for a LocalStateChanged()
756   // invocation.
757   std::unique_ptr<base::RunLoop> local_state_changed_run_loop_;
758 
759   UserPolicyBuilder device_local_account_policy_;
760   chromeos::LocalPolicyTestServerMixin local_policy_mixin_{&mixin_host_};
761 
762   content::WebContents* contents_;
763 
764   // These are member variables so they're guaranteed that the destructors
765   // (which may delete a directory) run in a scope where file IO is allowed.
766   base::ScopedTempDir temp_dir_;
767   base::ScopedTempDir cache_dir_;
768 
769  private:
770   extensions::SandboxedUnpacker::ScopedVerifierFormatOverrideForTest
771       verifier_format_override_;
772   DISALLOW_COPY_AND_ASSIGN(DeviceLocalAccountTest);
773 };
774 
IsKnownUser(const AccountId & account_id)775 static bool IsKnownUser(const AccountId& account_id) {
776   return user_manager::UserManager::Get()->IsKnownUser(account_id);
777 }
778 
779 // Helper that listen extension installation when new profile is created.
780 class ExtensionInstallObserver : public content::NotificationObserver,
781                                  public extensions::ExtensionRegistryObserver {
782  public:
ExtensionInstallObserver(const std::string & extension_id)783   explicit ExtensionInstallObserver(const std::string& extension_id)
784       : registry_(nullptr),
785         waiting_extension_id_(extension_id),
786         observed_(false) {
787     registrar_.Add(this, chrome::NOTIFICATION_PROFILE_CREATED,
788                    content::NotificationService::AllSources());
789   }
790 
~ExtensionInstallObserver()791   ~ExtensionInstallObserver() override {
792     if (registry_ != nullptr)
793       registry_->RemoveObserver(this);
794   }
795 
796   // Wait until an extension with |extension_id| is installed.
Wait()797   void Wait() {
798     if (!observed_)
799       run_loop_.Run();
800   }
801 
802  private:
803   // extensions::ExtensionRegistryObserver:
OnExtensionWillBeInstalled(content::BrowserContext * browser_context,const extensions::Extension * extension,bool is_update,const std::string & old_name)804   void OnExtensionWillBeInstalled(content::BrowserContext* browser_context,
805                                   const extensions::Extension* extension,
806                                   bool is_update,
807                                   const std::string& old_name) override {
808     if (waiting_extension_id_ == extension->id()) {
809       observed_ = true;
810       run_loop_.Quit();
811     }
812   }
813 
814   // content::NotificationObserver:
Observe(int type,const content::NotificationSource & source,const content::NotificationDetails & details)815   void Observe(int type,
816                const content::NotificationSource& source,
817                const content::NotificationDetails& details) override {
818     DCHECK_EQ(chrome::NOTIFICATION_PROFILE_CREATED, type);
819 
820     Profile* profile = content::Source<Profile>(source).ptr();
821     // Ignore lock screen apps profile.
822     if (chromeos::ProfileHelper::IsLockScreenAppProfile(profile))
823       return;
824     registry_ = extensions::ExtensionRegistry::Get(profile);
825 
826     // Check if extension is already installed with newly created profile.
827     if (registry_->GetInstalledExtension(waiting_extension_id_)) {
828       observed_ = true;
829       run_loop_.Quit();
830       return;
831     }
832 
833     // Start listening for extension installation.
834     registry_->AddObserver(this);
835   }
836 
837   extensions::ExtensionRegistry* registry_;
838   base::RunLoop run_loop_;
839   content::NotificationRegistrar registrar_;
840   std::string waiting_extension_id_;
841   bool observed_;
842 
843   DISALLOW_COPY_AND_ASSIGN(ExtensionInstallObserver);
844 };
845 
846 // Tests that the data associated with a device local account is removed when
847 // that local account is no longer part of policy.
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,PRE_DataIsRemoved)848 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, PRE_DataIsRemoved) {
849   AddPublicSessionToDevicePolicy(kAccountId1);
850   WaitUntilLocalStateChanged();
851 
852   EXPECT_TRUE(IsKnownUser(account_id_1_));
853   CheckPublicSessionPresent(account_id_1_);
854 
855   // Data for the account is normally added after successful authentication.
856   // Shortcut that here.
857   DictionaryPrefUpdate given_name_update(g_browser_process->local_state(),
858                                          "UserGivenName");
859   given_name_update->SetKey(account_id_1_.GetUserEmail(),
860                             base::Value("Elaine"));
861 
862   // Add some arbitrary data to make sure the "UserGivenName" dictionary isn't
863   // cleaning up itself.
864   given_name_update->SetKey("sanity.check@example.com", base::Value("Anne"));
865 }
866 
867 // Disabled on ASan and LSAn builds due to a consistent failure. See
868 // crbug.com/1004228
869 #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER)
870 #define MAYBE_DataIsRemoved DISABLED_DataIsRemoved
871 #else
872 #define MAYBE_DataIsRemoved DataIsRemoved
873 #endif
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,MAYBE_DataIsRemoved)874 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, MAYBE_DataIsRemoved) {
875   // The device local account should have been removed.
876   EXPECT_FALSE(g_browser_process->local_state()
877                    ->GetDictionary("UserGivenName")
878                    ->FindKey(account_id_1_.GetUserEmail()));
879 
880   // The arbitrary data remains.
881   const std::string* value = g_browser_process->local_state()
882                                  ->GetDictionary("UserGivenName")
883                                  ->FindStringKey("sanity.check@example.com");
884   ASSERT_TRUE(value);
885   EXPECT_EQ("Anne", *value);
886 }
887 
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,LoginScreen)888 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, LoginScreen) {
889   AddPublicSessionToDevicePolicy(kAccountId1);
890   AddPublicSessionToDevicePolicy(kAccountId2);
891 
892   WaitUntilLocalStateChanged();
893   EXPECT_TRUE(IsKnownUser(account_id_1_));
894   EXPECT_TRUE(IsKnownUser(account_id_2_));
895 
896   CheckPublicSessionPresent(account_id_1_);
897   CheckPublicSessionPresent(account_id_2_);
898 
899   ASSERT_TRUE(user_manager::UserManager::Get()->FindUser(account_id_1_));
900   EXPECT_TRUE(user_manager::UserManager::Get()
901                   ->FindUser(account_id_1_)
902                   ->IsAffiliated());
903 
904   ASSERT_TRUE(user_manager::UserManager::Get()->FindUser(account_id_2_));
905   EXPECT_TRUE(user_manager::UserManager::Get()
906                   ->FindUser(account_id_2_)
907                   ->IsAffiliated());
908 }
909 
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,DisplayName)910 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, DisplayName) {
911   UploadAndInstallDeviceLocalAccountPolicy();
912   AddPublicSessionToDevicePolicy(kAccountId1);
913 
914   WaitForPolicy();
915 
916   // Verify that the display name is shown in the UI.
917   std::string display_name =
918       ash::LoginScreenTestApi::GetDisplayedName(account_id_1_);
919   EXPECT_EQ(kDisplayName1, display_name);
920   // Click on the pod to expand it.
921   ASSERT_TRUE(ash::LoginScreenTestApi::ExpandPublicSessionPod(account_id_1_));
922   // Change the display name.
923   device_local_account_policy_.payload().mutable_userdisplayname()->set_value(
924       kDisplayName2);
925   UploadAndInstallDeviceLocalAccountPolicy();
926   policy::BrowserPolicyConnectorChromeOS* connector =
927       g_browser_process->platform_part()->browser_policy_connector_chromeos();
928   DeviceLocalAccountPolicyBroker* broker =
929       connector->GetDeviceLocalAccountPolicyService()->GetBrokerForUser(
930           account_id_1_.GetUserEmail());
931   ASSERT_TRUE(broker);
932   broker->core()->client()->FetchPolicy();
933   WaitForDisplayName(account_id_1_.GetUserEmail(), kDisplayName2);
934 
935   // Verify that the new display name is shown in the UI.
936   display_name = ash::LoginScreenTestApi::GetDisplayedName(account_id_1_);
937   EXPECT_EQ(kDisplayName2, display_name);
938   // Verify that the pod is still expanded. This indicates that the UI updated
939   // without reloading and losing state.
940   EXPECT_TRUE(ash::LoginScreenTestApi::IsPublicSessionExpanded());
941 }
942 
943 // Tests that display name is saved in kUserDisplayName pref in local state.
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,CachedDisplayName)944 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, CachedDisplayName) {
945   UploadAndInstallDeviceLocalAccountPolicy();
946   AddPublicSessionToDevicePolicy(kAccountId1);
947 
948   WaitForDisplayName(account_id_1_.GetUserEmail(), kDisplayName1);
949   auto* dict = g_browser_process->local_state()->GetDictionary(
950       policy::key::kUserDisplayName);
951   ASSERT_TRUE(dict);
952   ASSERT_TRUE(dict->HasKey(account_id_1_.GetUserEmail()));
953   EXPECT_EQ(kDisplayName1, *dict->FindStringKey(account_id_1_.GetUserEmail()));
954 }
955 
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,PolicyDownload)956 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, PolicyDownload) {
957   UploadDeviceLocalAccountPolicy();
958   AddPublicSessionToDevicePolicy(kAccountId1);
959 
960   WaitForPolicy();
961 
962   // Sanity check: The policy should be present now.
963   ASSERT_FALSE(session_manager_client()->device_local_account_policy(
964       kAccountId1).empty());
965 }
966 
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,AccountListChange)967 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, AccountListChange) {
968   AddPublicSessionToDevicePolicy(kAccountId1);
969   AddPublicSessionToDevicePolicy(kAccountId2);
970 
971   WaitUntilLocalStateChanged();
972   EXPECT_TRUE(IsKnownUser(account_id_1_));
973   EXPECT_TRUE(IsKnownUser(account_id_2_));
974 
975   // Update policy to remove kAccountId2.
976   em::ChromeDeviceSettingsProto& proto(device_policy()->payload());
977   proto.mutable_device_local_accounts()->clear_account();
978   AddPublicSessionToDevicePolicy(kAccountId1);
979 
980   em::ChromeDeviceSettingsProto policy;
981   policy.mutable_show_user_names()->set_show_user_names(true);
982   em::DeviceLocalAccountInfoProto* account1 =
983       policy.mutable_device_local_accounts()->add_account();
984   account1->set_account_id(kAccountId1);
985   account1->set_type(
986       em::DeviceLocalAccountInfoProto::ACCOUNT_TYPE_PUBLIC_SESSION);
987 
988   local_policy_mixin_.UpdateDevicePolicy(policy);
989   g_browser_process->policy_service()->RefreshPolicies(base::Closure());
990 
991   // Make sure the second device-local account disappears.
992   WaitUntilLocalStateChanged();
993   EXPECT_FALSE(IsKnownUser(account_id_2_));
994 }
995 
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,StartSession)996 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, StartSession) {
997   // Specify startup pages.
998   device_local_account_policy_.payload().mutable_restoreonstartup()->set_value(
999       SessionStartupPref::kPrefValueURLs);
1000   em::StringListPolicyProto* startup_urls_proto =
1001       device_local_account_policy_.payload().mutable_restoreonstartupurls();
1002   for (size_t i = 0; i < base::size(kStartupURLs); ++i)
1003     startup_urls_proto->mutable_value()->add_entries(kStartupURLs[i]);
1004   UploadAndInstallDeviceLocalAccountPolicy();
1005   AddPublicSessionToDevicePolicy(kAccountId1);
1006 
1007   WaitForPolicy();
1008 
1009   ASSERT_NO_FATAL_FAILURE(StartLogin(std::string(), std::string()));
1010   WaitForSessionStart();
1011 
1012   // Check that the startup pages specified in policy were opened.
1013   BrowserList* browser_list = BrowserList::GetInstance();
1014   EXPECT_EQ(1U, browser_list->size());
1015   Browser* browser = browser_list->get(0);
1016   ASSERT_TRUE(browser);
1017 
1018   TabStripModel* tabs = browser->tab_strip_model();
1019   ASSERT_TRUE(tabs);
1020   int expected_tab_count = static_cast<int>(base::size(kStartupURLs));
1021   EXPECT_EQ(expected_tab_count, tabs->count());
1022   for (int i = 0; i < expected_tab_count && i < tabs->count(); ++i) {
1023     EXPECT_EQ(GURL(kStartupURLs[i]),
1024               tabs->GetWebContentsAt(i)->GetVisibleURL());
1025   }
1026 
1027   // Verify that the session is not considered to be logged in with a GAIA
1028   // account.
1029   Profile* profile = GetProfileForTest();
1030   ASSERT_TRUE(profile);
1031   EXPECT_FALSE(
1032       IdentityManagerFactory::GetForProfile(profile)->HasPrimaryAccount(
1033           signin::ConsentLevel::kNotRequired));
1034 }
1035 
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,FullscreenAllowed)1036 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, FullscreenAllowed) {
1037   UploadAndInstallDeviceLocalAccountPolicy();
1038   AddPublicSessionToDevicePolicy(kAccountId1);
1039 
1040   WaitForPolicy();
1041 
1042   ASSERT_NO_FATAL_FAILURE(StartLogin(std::string(), std::string()));
1043   WaitForSessionStart();
1044 
1045   BrowserList* browser_list = BrowserList::GetInstance();
1046   EXPECT_EQ(1U, browser_list->size());
1047   Browser* browser = browser_list->get(0);
1048   ASSERT_TRUE(browser);
1049   BrowserWindow* browser_window = browser->window();
1050   ASSERT_TRUE(browser_window);
1051 
1052   // Verify that an attempt to enter fullscreen mode is allowed.
1053   EXPECT_FALSE(browser_window->IsFullscreen());
1054   chrome::ToggleFullscreenMode(browser);
1055   EXPECT_TRUE(browser_window->IsFullscreen());
1056 }
1057 
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,ExtensionsUncached)1058 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, ExtensionsUncached) {
1059   // Make it possible to force-install a hosted app and an extension.
1060   ASSERT_TRUE(embedded_test_server()->InitializeAndListen());
1061   scoped_refptr<TestingUpdateManifestProvider> testing_update_manifest_provider(
1062       new TestingUpdateManifestProvider(kRelativeUpdateURL));
1063   testing_update_manifest_provider->AddUpdate(
1064       kHostedAppID, kHostedAppVersion,
1065       embedded_test_server()->GetURL(std::string("/") + kHostedAppCRXPath));
1066   testing_update_manifest_provider->AddUpdate(
1067       kGoodExtensionID, kGoodExtensionVersion,
1068       embedded_test_server()->GetURL(std::string("/") + kGoodExtensionCRXPath));
1069   embedded_test_server()->RegisterRequestHandler(
1070       base::Bind(&TestingUpdateManifestProvider::HandleRequest,
1071                  testing_update_manifest_provider));
1072   embedded_test_server()->StartAcceptingConnections();
1073 
1074   // Specify policy to force-install the hosted app and the extension.
1075   em::StringList* forcelist = device_local_account_policy_.payload()
1076       .mutable_extensioninstallforcelist()->mutable_value();
1077   forcelist->add_entries(base::StringPrintf(
1078       "%s;%s",
1079       kHostedAppID,
1080       embedded_test_server()->GetURL(kRelativeUpdateURL).spec().c_str()));
1081   forcelist->add_entries(base::StringPrintf(
1082       "%s;%s",
1083       kGoodExtensionID,
1084       embedded_test_server()->GetURL(kRelativeUpdateURL).spec().c_str()));
1085 
1086   UploadAndInstallDeviceLocalAccountPolicy();
1087   AddPublicSessionToDevicePolicy(kAccountId1);
1088 
1089   WaitForPolicy();
1090 
1091   // Start listening for app/extension installation results.
1092   ExtensionInstallObserver install_observer(kHostedAppID);
1093   content::WindowedNotificationObserver extension_observer(
1094       extensions::NOTIFICATION_EXTENSION_INSTALL_ERROR,
1095       base::Bind(DoesInstallFailureReferToId, kGoodExtensionID));
1096   ASSERT_NO_FATAL_FAILURE(StartLogin(std::string(), std::string()));
1097 
1098   // Wait for the hosted app installation to succeed and the extension
1099   // installation to fail (because hosted apps are whitelisted for use in
1100   // device-local accounts and extensions are not).
1101   install_observer.Wait();
1102   extension_observer.Wait();
1103 
1104   // Verify that the hosted app was installed.
1105   Profile* profile = GetProfileForTest();
1106   ASSERT_TRUE(profile);
1107   extensions::ExtensionRegistry* extension_registry =
1108       extensions::ExtensionRegistry::Get(profile);
1109   EXPECT_TRUE(extension_registry->enabled_extensions().GetByID(kHostedAppID));
1110 
1111   // Verify that the extension was not installed.
1112   EXPECT_FALSE(extension_registry->GetExtensionById(
1113       kGoodExtensionID, extensions::ExtensionRegistry::EVERYTHING));
1114 
1115   // Verify that the app was downloaded to the account's extension cache.
1116   base::FilePath test_dir;
1117   ASSERT_TRUE(base::PathService::Get(chrome::DIR_TEST_DATA, &test_dir));
1118   EXPECT_TRUE(ContentsEqual(
1119           GetCacheCRXFile(kAccountId1, kHostedAppID, kHostedAppVersion),
1120           test_dir.Append(kHostedAppCRXPath)));
1121 
1122   // Verify that the extension was removed from the account's extension cache
1123   // after the installation failure.
1124   DeviceLocalAccountPolicyBroker* broker =
1125       g_browser_process->platform_part()
1126           ->browser_policy_connector_chromeos()
1127           ->GetDeviceLocalAccountPolicyService()
1128           ->GetBrokerForUser(account_id_1_.GetUserEmail());
1129   ASSERT_TRUE(broker);
1130   chromeos::ExternalCache* cache =
1131       broker->extension_loader()->GetExternalCacheForTesting();
1132   ASSERT_TRUE(cache);
1133   EXPECT_FALSE(cache->GetExtension(kGoodExtensionID, NULL, NULL));
1134 }
1135 
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,ExtensionsCached)1136 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, ExtensionsCached) {
1137   ASSERT_TRUE(embedded_test_server()->Start());
1138 
1139   // Pre-populate the device local account's extension cache with a hosted app
1140   // and an extension.
1141   {
1142     base::ScopedAllowBlockingForTesting allow_blocking;
1143     EXPECT_TRUE(base::CreateDirectory(
1144         GetExtensionCacheDirectoryForAccountID(kAccountId1)));
1145   }
1146   base::FilePath test_dir;
1147   ASSERT_TRUE(base::PathService::Get(chrome::DIR_TEST_DATA, &test_dir));
1148   const base::FilePath cached_hosted_app =
1149       GetCacheCRXFile(kAccountId1, kHostedAppID, kHostedAppVersion);
1150   {
1151     base::ScopedAllowBlockingForTesting allow_blocking;
1152     EXPECT_TRUE(
1153         CopyFile(test_dir.Append(kHostedAppCRXPath), cached_hosted_app));
1154     EXPECT_TRUE(CopyFile(
1155         test_dir.Append(kGoodExtensionCRXPath),
1156         GetCacheCRXFile(kAccountId1, kGoodExtensionID, kGoodExtensionVersion)));
1157   }
1158 
1159   // Specify policy to force-install the hosted app.
1160   em::StringList* forcelist = device_local_account_policy_.payload()
1161       .mutable_extensioninstallforcelist()->mutable_value();
1162   forcelist->add_entries(base::StringPrintf(
1163       "%s;%s",
1164       kHostedAppID,
1165       embedded_test_server()->GetURL(kRelativeUpdateURL).spec().c_str()));
1166   forcelist->add_entries(base::StringPrintf(
1167       "%s;%s",
1168       kGoodExtensionID,
1169       embedded_test_server()->GetURL(kRelativeUpdateURL).spec().c_str()));
1170 
1171   UploadAndInstallDeviceLocalAccountPolicy();
1172   AddPublicSessionToDevicePolicy(kAccountId1);
1173 
1174   WaitForPolicy();
1175 
1176   // Start listening for app/extension installation results.
1177   ExtensionInstallObserver install_observer(kHostedAppID);
1178   content::WindowedNotificationObserver extension_observer(
1179       extensions::NOTIFICATION_EXTENSION_INSTALL_ERROR,
1180       base::Bind(DoesInstallFailureReferToId, kGoodExtensionID));
1181 
1182   ASSERT_NO_FATAL_FAILURE(StartLogin(std::string(), std::string()));
1183 
1184   // Wait for the hosted app installation to succeed and the extension
1185   // installation to fail.
1186   install_observer.Wait();
1187   extension_observer.Wait();
1188 
1189   // Verify that the hosted app was installed.
1190   Profile* profile = GetProfileForTest();
1191   ASSERT_TRUE(profile);
1192   extensions::ExtensionRegistry* extension_registry =
1193       extensions::ExtensionRegistry::Get(profile);
1194   EXPECT_TRUE(extension_registry->enabled_extensions().GetByID(kHostedAppID));
1195 
1196   // Verify that the extension was not installed.
1197   EXPECT_FALSE(extension_registry->GetExtensionById(
1198       kGoodExtensionID, extensions::ExtensionRegistry::EVERYTHING));
1199 
1200   // Verify that the app is still in the account's extension cache.
1201   {
1202     base::ScopedAllowBlockingForTesting allow_blocking;
1203     EXPECT_TRUE(PathExists(cached_hosted_app));
1204   }
1205 
1206   // Verify that the extension was removed from the account's extension cache.
1207   DeviceLocalAccountPolicyBroker* broker =
1208       g_browser_process->platform_part()
1209           ->browser_policy_connector_chromeos()
1210           ->GetDeviceLocalAccountPolicyService()
1211           ->GetBrokerForUser(account_id_1_.GetUserEmail());
1212   ASSERT_TRUE(broker);
1213   chromeos::ExternalCache* cache =
1214       broker->extension_loader()->GetExternalCacheForTesting();
1215   ASSERT_TRUE(cache);
1216   EXPECT_FALSE(cache->GetExtension(kGoodExtensionID, NULL, NULL));
1217 }
1218 
OnPutExtension(std::unique_ptr<base::RunLoop> * run_loop,const base::FilePath & file_path,bool file_ownership_passed)1219 static void OnPutExtension(std::unique_ptr<base::RunLoop>* run_loop,
1220                            const base::FilePath& file_path,
1221                            bool file_ownership_passed) {
1222   ASSERT_TRUE(*run_loop);
1223   (*run_loop)->Quit();
1224 }
1225 
OnExtensionCacheImplInitialized(std::unique_ptr<base::RunLoop> * run_loop)1226 static void OnExtensionCacheImplInitialized(
1227     std::unique_ptr<base::RunLoop>* run_loop) {
1228   ASSERT_TRUE(*run_loop);
1229   (*run_loop)->Quit();
1230 }
1231 
CreateFile(const base::FilePath & file,size_t size,const base::Time & timestamp)1232 static void CreateFile(const base::FilePath& file,
1233                 size_t size,
1234                 const base::Time& timestamp) {
1235   base::ScopedAllowBlockingForTesting allow_blocking;
1236   std::string data(size, 0);
1237   EXPECT_TRUE(base::WriteFile(file, data));
1238   EXPECT_TRUE(base::TouchFile(file, timestamp, timestamp));
1239 }
1240 
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,ExtensionCacheImplTest)1241 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, ExtensionCacheImplTest) {
1242   // Make it possible to force-install a hosted app and an extension.
1243   ASSERT_TRUE(embedded_test_server()->InitializeAndListen());
1244   scoped_refptr<TestingUpdateManifestProvider> testing_update_manifest_provider(
1245       new TestingUpdateManifestProvider(kRelativeUpdateURL));
1246   testing_update_manifest_provider->AddUpdate(
1247       kHostedAppID, kHostedAppVersion,
1248       embedded_test_server()->GetURL(std::string("/") + kHostedAppCRXPath));
1249   testing_update_manifest_provider->AddUpdate(
1250       kGoodExtensionID, kGoodExtensionVersion,
1251       embedded_test_server()->GetURL(std::string("/") + kGoodExtensionCRXPath));
1252   embedded_test_server()->RegisterRequestHandler(
1253       base::Bind(&TestingUpdateManifestProvider::HandleRequest,
1254                  testing_update_manifest_provider));
1255   embedded_test_server()->StartAcceptingConnections();
1256   // Create and initialize local cache.
1257   base::FilePath impl_path;
1258   {
1259     base::ScopedAllowBlockingForTesting allow_blocking;
1260     EXPECT_TRUE(cache_dir_.CreateUniqueTempDir());
1261     impl_path = cache_dir_.GetPath();
1262     EXPECT_TRUE(base::CreateDirectory(impl_path));
1263   }
1264   CreateFile(impl_path.Append(
1265                  extensions::LocalExtensionCache::kCacheReadyFlagFileName),
1266              0, base::Time::Now());
1267   extensions::ExtensionCacheImpl cache_impl(
1268       std::make_unique<extensions::ChromeOSExtensionCacheDelegate>(impl_path));
1269   std::unique_ptr<base::RunLoop> run_loop;
1270   run_loop.reset(new base::RunLoop);
1271   cache_impl.Start(base::Bind(&OnExtensionCacheImplInitialized, &run_loop));
1272   run_loop->Run();
1273 
1274   // Put extension in the local cache.
1275   base::FilePath temp_path;
1276   {
1277     base::ScopedAllowBlockingForTesting allow_blocking;
1278     EXPECT_TRUE(temp_dir_.CreateUniqueTempDir());
1279     temp_path = temp_dir_.GetPath();
1280     EXPECT_TRUE(base::CreateDirectory(temp_path));
1281   }
1282   const base::FilePath temp_file =
1283       GetCacheCRXFilePath(kGoodExtensionID, kGoodExtensionVersion, temp_path);
1284   base::FilePath test_dir;
1285   std::string hash;
1286   ASSERT_TRUE(base::PathService::Get(chrome::DIR_TEST_DATA, &test_dir));
1287   {
1288     base::ScopedAllowBlockingForTesting allow_blocking;
1289     EXPECT_TRUE(CopyFile(test_dir.Append(kGoodExtensionCRXPath), temp_file));
1290   }
1291   cache_impl.AllowCaching(kGoodExtensionID);
1292   run_loop.reset(new base::RunLoop);
1293   cache_impl.PutExtension(kGoodExtensionID, hash, temp_file,
1294                           kGoodExtensionVersion,
1295                           base::Bind(&OnPutExtension, &run_loop));
1296   run_loop->Run();
1297 
1298   // Verify that the extension file was added to the local cache.
1299   const base::FilePath local_file =
1300       GetCacheCRXFilePath(kGoodExtensionID, kGoodExtensionVersion, impl_path);
1301   {
1302     base::ScopedAllowBlockingForTesting allow_blocking;
1303     EXPECT_TRUE(PathExists(local_file));
1304   }
1305 
1306   // Specify policy to force-install the hosted app and the extension.
1307   em::StringList* forcelist = device_local_account_policy_.payload()
1308       .mutable_extensioninstallforcelist()->mutable_value();
1309   forcelist->add_entries(base::StringPrintf(
1310       "%s;%s",
1311       kHostedAppID,
1312       embedded_test_server()->GetURL(kRelativeUpdateURL).spec().c_str()));
1313   forcelist->add_entries(base::StringPrintf(
1314       "%s;%s",
1315       kGoodExtensionID,
1316       embedded_test_server()->GetURL(kRelativeUpdateURL).spec().c_str()));
1317 
1318   UploadAndInstallDeviceLocalAccountPolicy();
1319   AddPublicSessionToDevicePolicy(kAccountId1);
1320 
1321   WaitForPolicy();
1322 
1323   // Start listening for app/extension installation results.
1324   ExtensionInstallObserver install_observer(kHostedAppID);
1325   content::WindowedNotificationObserver extension_observer(
1326       extensions::NOTIFICATION_EXTENSION_INSTALL_ERROR,
1327       base::Bind(DoesInstallFailureReferToId, kGoodExtensionID));
1328 
1329   ASSERT_NO_FATAL_FAILURE(StartLogin(std::string(), std::string()));
1330 
1331   // Wait for the hosted app installation to succeed and the extension
1332   // installation to fail (because hosted apps are whitelisted for use in
1333   // device-local accounts and extensions are not).
1334   install_observer.Wait();
1335   extension_observer.Wait();
1336 
1337   // Verify that the extension was kept in the local cache.
1338   EXPECT_TRUE(cache_impl.GetExtension(kGoodExtensionID, hash, NULL, NULL));
1339 
1340   {
1341     base::ScopedAllowBlockingForTesting allow_blocking;
1342     // Verify that the extension file was kept in the local cache.
1343     EXPECT_TRUE(PathExists(local_file));
1344   }
1345 }
1346 
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,ExternalData)1347 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, ExternalData) {
1348   // user_manager::UserManager requests an external data fetch whenever
1349   // the key::kUserAvatarImage policy is set. Since this test wants to
1350   // verify that the underlying policy subsystem will start a fetch
1351   // without this request as well, the user_manager::UserManager must be
1352   // prevented from seeing the policy change.
1353   static_cast<chromeos::ChromeUserManagerImpl*>(
1354       user_manager::UserManager::Get())
1355       ->StopPolicyObserverForTesting();
1356 
1357   UploadDeviceLocalAccountPolicy();
1358   AddPublicSessionToDevicePolicy(kAccountId1);
1359 
1360   WaitForPolicy();
1361 
1362   // Start serving external data.
1363   std::unique_ptr<base::RunLoop> run_loop(new base::RunLoop);
1364   EXPECT_TRUE(embedded_test_server()->InitializeAndListen());
1365   embedded_test_server()->RegisterRequestHandler(base::BindRepeating(
1366       [](const base::RepeatingClosure& quit_closure,
1367          const net::test_server::HttpRequest& request)
1368           -> std::unique_ptr<net::test_server::HttpResponse> {
1369         if (request.relative_url != kExternalDataPath)
1370           return nullptr;
1371 
1372         auto response = std::make_unique<net::test_server::BasicHttpResponse>();
1373         response->set_content(kExternalData);
1374 
1375         quit_closure.Run();
1376         return response;
1377       },
1378       run_loop->QuitClosure()));
1379   embedded_test_server()->StartAcceptingConnections();
1380 
1381   // Specify an external data reference for the key::kUserAvatarImage policy.
1382   std::unique_ptr<base::DictionaryValue> metadata =
1383       test::ConstructExternalDataReference(
1384           embedded_test_server()->GetURL(kExternalDataPath).spec(),
1385           kExternalData);
1386   std::string policy;
1387   base::JSONWriter::Write(*metadata, &policy);
1388   device_local_account_policy_.payload().mutable_useravatarimage()->set_value(
1389       policy);
1390   UploadAndInstallDeviceLocalAccountPolicy();
1391   policy::BrowserPolicyConnectorChromeOS* connector =
1392       g_browser_process->platform_part()->browser_policy_connector_chromeos();
1393   DeviceLocalAccountPolicyBroker* broker =
1394       connector->GetDeviceLocalAccountPolicyService()->GetBrokerForUser(
1395           account_id_1_.GetUserEmail());
1396   ASSERT_TRUE(broker);
1397   broker->core()->store()->Load();
1398 
1399   // The external data should be fetched and cached automatically. Wait for this
1400   // fetch.
1401   run_loop->Run();
1402 
1403   // Stop serving external data.
1404   EXPECT_TRUE(embedded_test_server()->ShutdownAndWaitUntilComplete());
1405 
1406   const PolicyMap::Entry* policy_entry =
1407       broker->core()->store()->policy_map().Get(key::kUserAvatarImage);
1408   ASSERT_TRUE(policy_entry);
1409   ASSERT_TRUE(policy_entry->external_data_fetcher);
1410 
1411   // Retrieve the external data. Although the data is no longer being served,
1412   // the retrieval should succeed because the data has been cached.
1413   run_loop.reset(new base::RunLoop);
1414   std::unique_ptr<std::string> fetched_external_data;
1415   base::FilePath file_path;
1416   policy_entry->external_data_fetcher->Fetch(
1417       base::BindOnce(&test::ExternalDataFetchCallback, &fetched_external_data,
1418                      &file_path, run_loop->QuitClosure()));
1419   run_loop->Run();
1420 
1421   ASSERT_TRUE(fetched_external_data);
1422   EXPECT_EQ(kExternalData, *fetched_external_data);
1423 
1424   ASSERT_NO_FATAL_FAILURE(StartLogin(std::string(), std::string()));
1425   WaitForSessionStart();
1426 
1427   // Verify that the external data reference has propagated to the device-local
1428   // account's ProfilePolicyConnector.
1429   ProfilePolicyConnector* policy_connector =
1430       GetProfileForTest()->GetProfilePolicyConnector();
1431   ASSERT_TRUE(policy_connector);
1432   const PolicyMap& policies = policy_connector->policy_service()->GetPolicies(
1433       PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()));
1434   policy_entry = policies.Get(key::kUserAvatarImage);
1435   ASSERT_TRUE(policy_entry);
1436   EXPECT_EQ(*metadata, *policy_entry->value());
1437   ASSERT_TRUE(policy_entry->external_data_fetcher);
1438 
1439   // Retrieve the external data via the ProfilePolicyConnector. The retrieval
1440   // should succeed because the data has been cached.
1441   run_loop.reset(new base::RunLoop);
1442   fetched_external_data.reset();
1443   policy_entry->external_data_fetcher->Fetch(
1444       base::BindOnce(&test::ExternalDataFetchCallback, &fetched_external_data,
1445                      &file_path, run_loop->QuitClosure()));
1446   run_loop->Run();
1447 
1448   ASSERT_TRUE(fetched_external_data);
1449   EXPECT_EQ(kExternalData, *fetched_external_data);
1450 }
1451 
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,UserAvatarImage)1452 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, UserAvatarImage) {
1453   ASSERT_TRUE(embedded_test_server()->Start());
1454 
1455   UploadDeviceLocalAccountPolicy();
1456   AddPublicSessionToDevicePolicy(kAccountId1);
1457 
1458   WaitForPolicy();
1459 
1460   base::FilePath test_dir;
1461   ASSERT_TRUE(base::PathService::Get(chrome::DIR_TEST_DATA, &test_dir));
1462   std::string image_data;
1463   {
1464     base::ScopedAllowBlockingForTesting allow_blocking;
1465     ASSERT_TRUE(base::ReadFileToString(
1466         test_dir.Append(chromeos::test::kUserAvatarImage1RelativePath),
1467         &image_data));
1468   }
1469 
1470   std::string policy;
1471   base::JSONWriter::Write(
1472       *test::ConstructExternalDataReference(
1473           embedded_test_server()
1474               ->GetURL(std::string("/") +
1475                        chromeos::test::kUserAvatarImage1RelativePath)
1476               .spec(),
1477           image_data),
1478       &policy);
1479   device_local_account_policy_.payload().mutable_useravatarimage()->set_value(
1480       policy);
1481   UploadAndInstallDeviceLocalAccountPolicy();
1482   policy::BrowserPolicyConnectorChromeOS* connector =
1483       g_browser_process->platform_part()->browser_policy_connector_chromeos();
1484   DeviceLocalAccountPolicyBroker* broker =
1485       connector->GetDeviceLocalAccountPolicyService()->GetBrokerForUser(
1486           account_id_1_.GetUserEmail());
1487   ASSERT_TRUE(broker);
1488 
1489   broker->core()->store()->Load();
1490   WaitUntilLocalStateChanged();
1491 
1492   gfx::ImageSkia policy_image =
1493       chromeos::test::ImageLoader(
1494           test_dir.Append(chromeos::test::kUserAvatarImage1RelativePath))
1495           .Load();
1496   ASSERT_FALSE(policy_image.isNull());
1497 
1498   const user_manager::User* user =
1499       user_manager::UserManager::Get()->FindUser(account_id_1_);
1500   ASSERT_TRUE(user);
1501 
1502   base::FilePath user_data_dir;
1503   ASSERT_TRUE(base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir));
1504   const base::FilePath saved_image_path =
1505       user_data_dir.Append(account_id_1_.GetUserEmail()).AddExtension("jpg");
1506 
1507   EXPECT_FALSE(user->HasDefaultImage());
1508   EXPECT_EQ(user_manager::User::USER_IMAGE_EXTERNAL, user->image_index());
1509   EXPECT_TRUE(chromeos::test::AreImagesEqual(policy_image, user->GetImage()));
1510   const base::DictionaryValue* images_pref =
1511       g_browser_process->local_state()->GetDictionary("user_image_info");
1512   ASSERT_TRUE(images_pref);
1513   const base::DictionaryValue* image_properties;
1514   ASSERT_TRUE(images_pref->GetDictionaryWithoutPathExpansion(
1515       account_id_1_.GetUserEmail(), &image_properties));
1516   int image_index;
1517   std::string image_path;
1518   ASSERT_TRUE(image_properties->GetInteger("index", &image_index));
1519   ASSERT_TRUE(image_properties->GetString("path", &image_path));
1520   EXPECT_EQ(user_manager::User::USER_IMAGE_EXTERNAL, image_index);
1521   EXPECT_EQ(saved_image_path.value(), image_path);
1522 
1523   gfx::ImageSkia saved_image =
1524       chromeos::test::ImageLoader(saved_image_path).Load();
1525   ASSERT_FALSE(saved_image.isNull());
1526 
1527   // Check image dimensions. Images can't be compared since JPEG is lossy.
1528   EXPECT_EQ(policy_image.width(), saved_image.width());
1529   EXPECT_EQ(policy_image.height(), saved_image.height());
1530 }
1531 
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,LastWindowClosedLogoutReminder)1532 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, LastWindowClosedLogoutReminder) {
1533   UploadAndInstallDeviceLocalAccountPolicy();
1534   AddPublicSessionToDevicePolicy(kAccountId1);
1535 
1536   WaitForPolicy();
1537 
1538   ASSERT_NO_FATAL_FAILURE(StartLogin(std::string(), std::string()));
1539   WaitForSessionStart();
1540 
1541   Profile* profile = GetProfileForTest();
1542   ASSERT_TRUE(profile);
1543   extensions::AppWindowRegistry* app_window_registry =
1544       extensions::AppWindowRegistry::Get(profile);
1545   app_window_registry->AddObserver(this);
1546 
1547   // Verify that the logout confirmation dialog is not showing.
1548   EXPECT_FALSE(IsLogoutConfirmationDialogShowing());
1549 
1550   // Remove policy that allows only explicitly whitelisted apps to be installed
1551   // in a public session.
1552   extensions::ExtensionSystem* extension_system =
1553       extensions::ExtensionSystem::Get(profile);
1554   ASSERT_TRUE(extension_system);
1555   extension_system->management_policy()->UnregisterAllProviders();
1556 
1557   // Install and a platform app.
1558   scoped_refptr<extensions::CrxInstaller> installer =
1559       extensions::CrxInstaller::CreateSilent(
1560           extension_system->extension_service());
1561   installer->set_allow_silent_install(true);
1562   installer->set_install_cause(extension_misc::INSTALL_CAUSE_USER_DOWNLOAD);
1563   installer->set_creation_flags(extensions::Extension::FROM_WEBSTORE);
1564   content::WindowedNotificationObserver app_install_observer(
1565       extensions::NOTIFICATION_CRX_INSTALLER_DONE,
1566       content::NotificationService::AllSources());
1567   base::FilePath test_dir;
1568   ASSERT_TRUE(base::PathService::Get(chrome::DIR_TEST_DATA, &test_dir));
1569   installer->InstallCrx(test_dir.Append(kPackagedAppCRXPath));
1570   app_install_observer.Wait();
1571   const extensions::Extension* app =
1572       content::Details<const extensions::Extension>(
1573           app_install_observer.details()).ptr();
1574 
1575   // Start the platform app, causing it to open a window.
1576   run_loop_.reset(new base::RunLoop);
1577   apps::AppServiceProxy* proxy =
1578       apps::AppServiceProxyFactory::GetForProfile(profile);
1579   proxy->FlushMojoCallsForTesting();
1580   proxy->Launch(
1581       app->id(),
1582       apps::GetEventFlags(apps::mojom::LaunchContainer::kLaunchContainerWindow,
1583                           WindowOpenDisposition::NEW_WINDOW,
1584                           false /* preferred_containner */),
1585       apps::mojom::LaunchSource::kFromChromeInternal,
1586       display::Screen::GetScreen()->GetPrimaryDisplay().id());
1587   proxy->FlushMojoCallsForTesting();
1588   run_loop_->Run();
1589   EXPECT_EQ(1U, app_window_registry->app_windows().size());
1590 
1591   // Close the only open browser window.
1592   BrowserList* browser_list = BrowserList::GetInstance();
1593   EXPECT_EQ(1U, browser_list->size());
1594   Browser* browser = browser_list->get(0);
1595   ASSERT_TRUE(browser);
1596   BrowserWindow* browser_window = browser->window();
1597   ASSERT_TRUE(browser_window);
1598   run_loop_.reset(new base::RunLoop);
1599   browser_window->Close();
1600   browser_window = NULL;
1601   run_loop_->Run();
1602   browser = NULL;
1603   EXPECT_TRUE(browser_list->empty());
1604 
1605   // Verify that the logout confirmation dialog is not showing because an app
1606   // window is still open.
1607   EXPECT_FALSE(IsLogoutConfirmationDialogShowing());
1608 
1609   // Open a browser window.
1610   Browser* first_browser = CreateBrowser(profile);
1611   EXPECT_EQ(1U, browser_list->size());
1612 
1613   // Close the app window.
1614   run_loop_.reset(new base::RunLoop);
1615   ASSERT_EQ(1U, app_window_registry->app_windows().size());
1616   app_window_registry->app_windows().front()->GetBaseWindow()->Close();
1617   run_loop_->Run();
1618   EXPECT_TRUE(app_window_registry->app_windows().empty());
1619 
1620   // Verify that the logout confirmation dialog is not showing because a browser
1621   // window is still open.
1622   EXPECT_FALSE(IsLogoutConfirmationDialogShowing());
1623 
1624   // Open a second browser window.
1625   Browser* second_browser = CreateBrowser(profile);
1626   EXPECT_EQ(2U, browser_list->size());
1627 
1628   // Close the first browser window.
1629   browser_window = first_browser->window();
1630   ASSERT_TRUE(browser_window);
1631   run_loop_.reset(new base::RunLoop);
1632   browser_window->Close();
1633   browser_window = NULL;
1634   run_loop_->Run();
1635   first_browser = NULL;
1636   EXPECT_EQ(1U, browser_list->size());
1637 
1638   // Verify that the logout confirmation dialog is not showing because a browser
1639   // window is still open.
1640   EXPECT_FALSE(IsLogoutConfirmationDialogShowing());
1641 
1642   // Close the second browser window.
1643   browser_window = second_browser->window();
1644   ASSERT_TRUE(browser_window);
1645   run_loop_.reset(new base::RunLoop);
1646   browser_window->Close();
1647   browser_window = NULL;
1648   run_loop_->Run();
1649   second_browser = NULL;
1650   EXPECT_TRUE(browser_list->empty());
1651 
1652   // Verify that the logout confirmation dialog is showing.
1653   EXPECT_TRUE(IsLogoutConfirmationDialogShowing());
1654 
1655   // Deny the logout.
1656   ASSERT_NO_FATAL_FAILURE(CloseLogoutConfirmationDialog());
1657 
1658   // Verify that the logout confirmation dialog is no longer showing.
1659   EXPECT_FALSE(IsLogoutConfirmationDialogShowing());
1660 
1661   // Open a browser window.
1662   browser = CreateBrowser(profile);
1663   EXPECT_EQ(1U, browser_list->size());
1664 
1665   // Close the browser window.
1666   browser_window = browser->window();
1667   ASSERT_TRUE(browser_window);
1668   run_loop_.reset(new base::RunLoop);
1669   browser_window->Close();
1670   browser_window = NULL;
1671   run_loop_->Run();
1672   browser = NULL;
1673   EXPECT_TRUE(browser_list->empty());
1674 
1675   // Verify that the logout confirmation dialog is showing again.
1676   EXPECT_TRUE(IsLogoutConfirmationDialogShowing());
1677 
1678   // Deny the logout.
1679   ASSERT_NO_FATAL_FAILURE(CloseLogoutConfirmationDialog());
1680 
1681   app_window_registry->RemoveObserver(this);
1682 }
1683 
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,NoRecommendedLocaleNoSwitch)1684 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, NoRecommendedLocaleNoSwitch) {
1685   UploadAndInstallDeviceLocalAccountPolicy();
1686   AddPublicSessionToDevicePolicy(kAccountId1);
1687 
1688   WaitForPolicy();
1689 
1690   ExpandPublicSessionPod(false);
1691 
1692   // Click the enter button to start the session.
1693   ash::LoginScreenTestApi::ClickPublicExpandedSubmitButton();
1694 
1695   WaitForSessionStart();
1696 
1697   // Verify that the locale has not changed and the first keyboard layout
1698   // applicable to the locale was chosen.
1699   EXPECT_EQ(initial_locale_, g_browser_process->GetApplicationLocale());
1700   EXPECT_EQ(initial_language_, icu::Locale::getDefault().getLanguage());
1701   VerifyKeyboardLayoutMatchesLocale();
1702 }
1703 
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,NoRecommendedLocaleSwitch)1704 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, NoRecommendedLocaleSwitch) {
1705   UploadAndInstallDeviceLocalAccountPolicy();
1706   AddPublicSessionToDevicePolicy(kAccountId1);
1707 
1708   WaitForPolicy();
1709 
1710   ExpandPublicSessionPod(false);
1711 
1712   // Click the link that switches the pod to its advanced form. Verify that the
1713   // pod switches from basic to advanced.
1714   ash::LoginScreenTestApi::ClickPublicExpandedAdvancedViewButton();
1715   ASSERT_TRUE(ash::LoginScreenTestApi::IsExpandedPublicSessionAdvanced());
1716   ash::LoginScreenTestApi::SetPublicSessionLocale(kPublicSessionLocale);
1717   // The UI will have requested an updated list of keyboard layouts at this
1718   // point. Wait for the constructions of this list to finish.
1719   WaitForGetKeyboardLayoutsForLocaleToFinish();
1720 
1721   // Manually select a different keyboard layout.
1722   ash::LoginScreenTestApi::SetPublicSessionKeyboard(
1723       public_session_input_method_id_);
1724 
1725   ash::LoginScreenTestApi::ClickPublicExpandedSubmitButton();
1726 
1727   WaitForSessionStart();
1728 
1729   // Verify that the locale and keyboard layout have been applied.
1730   EXPECT_EQ(kPublicSessionLocale, g_browser_process->GetApplicationLocale());
1731   EXPECT_EQ(l10n_util::GetLanguage(kPublicSessionLocale),
1732             icu::Locale::getDefault().getLanguage());
1733   EXPECT_EQ(public_session_input_method_id_,
1734             chromeos::input_method::InputMethodManager::Get()
1735                 ->GetActiveIMEState()
1736                 ->GetCurrentInputMethod()
1737                 .id());
1738 }
1739 
1740 // Tests whether or not managed guest session users can change the system
1741 // timezone, which should be possible iff the timezone automatic detection
1742 // policy is set to either DISABLED or USERS_DECIDE.
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,ManagedSessionTimezoneChange)1743 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, ManagedSessionTimezoneChange) {
1744   SetManagedSessionsEnabled(true);
1745   UploadAndInstallDeviceLocalAccountPolicy();
1746   AddPublicSessionToDevicePolicy(kAccountId1);
1747   EnableAutoLogin();
1748 
1749   WaitForPolicy();
1750 
1751   WaitForSessionStart();
1752 
1753   CheckPublicSessionPresent(account_id_1_);
1754 
1755   const user_manager::User* user =
1756       user_manager::UserManager::Get()->FindUser(account_id_1_);
1757   ASSERT_TRUE(user);
1758   ASSERT_EQ(user->GetType(), user_manager::USER_TYPE_PUBLIC_ACCOUNT);
1759 
1760   std::string timezone_id1("America/Los_Angeles");
1761   std::string timezone_id2("Europe/Berlin");
1762   base::string16 timezone_id1_utf16(base::UTF8ToUTF16(timezone_id1));
1763   base::string16 timezone_id2_utf16(base::UTF8ToUTF16(timezone_id2));
1764 
1765   chromeos::system::TimezoneSettings* timezone_settings =
1766       chromeos::system::TimezoneSettings::GetInstance();
1767 
1768   timezone_settings->SetTimezoneFromID(timezone_id1_utf16);
1769   SetSystemTimezoneAutomaticDetectionPolicy(em::SystemTimezoneProto::DISABLED);
1770   chromeos::system::SetSystemTimezone(user, timezone_id2);
1771   EXPECT_EQ(timezone_settings->GetCurrentTimezoneID(), timezone_id2_utf16);
1772 
1773   timezone_settings->SetTimezoneFromID(timezone_id1_utf16);
1774   SetSystemTimezoneAutomaticDetectionPolicy(
1775       em::SystemTimezoneProto::USERS_DECIDE);
1776   chromeos::system::SetSystemTimezone(user, timezone_id2);
1777   EXPECT_EQ(timezone_settings->GetCurrentTimezoneID(), timezone_id2_utf16);
1778 
1779   timezone_settings->SetTimezoneFromID(timezone_id1_utf16);
1780   SetSystemTimezoneAutomaticDetectionPolicy(em::SystemTimezoneProto::IP_ONLY);
1781   chromeos::system::SetSystemTimezone(user, timezone_id2);
1782   EXPECT_NE(timezone_settings->GetCurrentTimezoneID(), timezone_id2_utf16);
1783 
1784   timezone_settings->SetTimezoneFromID(timezone_id1_utf16);
1785   SetSystemTimezoneAutomaticDetectionPolicy(
1786       em::SystemTimezoneProto::SEND_WIFI_ACCESS_POINTS);
1787   chromeos::system::SetSystemTimezone(user, timezone_id2);
1788   EXPECT_NE(timezone_settings->GetCurrentTimezoneID(), timezone_id2_utf16);
1789 
1790   timezone_settings->SetTimezoneFromID(timezone_id1_utf16);
1791   SetSystemTimezoneAutomaticDetectionPolicy(
1792       em::SystemTimezoneProto::SEND_ALL_LOCATION_INFO);
1793   chromeos::system::SetSystemTimezone(user, timezone_id2);
1794   EXPECT_NE(timezone_settings->GetCurrentTimezoneID(), timezone_id2_utf16);
1795 }
1796 
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,OneRecommendedLocale)1797 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, OneRecommendedLocale) {
1798   // Specify a recommended locale.
1799   SetRecommendedLocales(kSingleRecommendedLocale,
1800                         base::size(kSingleRecommendedLocale));
1801   UploadAndInstallDeviceLocalAccountPolicy();
1802   AddPublicSessionToDevicePolicy(kAccountId1);
1803 
1804   WaitForPolicy();
1805 
1806   ExpandPublicSessionPod(false);
1807 
1808   WaitForGetKeyboardLayoutsForLocaleToFinish();
1809 
1810   // Click the enter button to start the session.
1811   ash::LoginScreenTestApi::ClickPublicExpandedSubmitButton();
1812 
1813   WaitForSessionStart();
1814 
1815   // Verify that the recommended locale has been applied and the first keyboard
1816   // layout applicable to the locale was chosen.
1817   EXPECT_EQ(kSingleRecommendedLocale[0],
1818             g_browser_process->GetApplicationLocale());
1819   EXPECT_EQ(l10n_util::GetLanguage(kSingleRecommendedLocale[0]),
1820             icu::Locale::getDefault().getLanguage());
1821   VerifyKeyboardLayoutMatchesLocale();
1822 }
1823 
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,MultipleRecommendedLocales)1824 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, MultipleRecommendedLocales) {
1825   // Specify recommended locales.
1826   SetRecommendedLocales(kRecommendedLocales1, base::size(kRecommendedLocales1));
1827   UploadAndInstallDeviceLocalAccountPolicy();
1828   AddPublicSessionToDevicePolicy(kAccountId1);
1829   AddPublicSessionToDevicePolicy(kAccountId2);
1830 
1831   WaitForPolicy();
1832 
1833   ExpandPublicSessionPod(true);
1834 
1835   // Verify that the pod shows a list of locales beginning with the recommended
1836   // ones, followed by others.
1837   std::vector<ash::LocaleItem> locales =
1838       ash::LoginScreenTestApi::GetExpandedPublicSessionLocales();
1839   EXPECT_LT(base::size(kRecommendedLocales1), locales.size());
1840 
1841   // Verify that the list starts with the recommended locales, in correct order.
1842   for (size_t i = 0; i < base::size(kRecommendedLocales1); ++i) {
1843     EXPECT_EQ(kRecommendedLocales1[i], locales[i].language_code);
1844   }
1845 
1846   // Verify that the recommended locales do not appear again in the remainder of
1847   // the list.
1848   std::set<std::string> recommended_locales;
1849   for (size_t i = 0; i < base::size(kRecommendedLocales1); ++i)
1850     recommended_locales.insert(kRecommendedLocales1[i]);
1851   for (size_t i = base::size(kRecommendedLocales1); i < locales.size(); ++i) {
1852     const std::string& locale = locales[i].language_code;
1853     EXPECT_EQ(recommended_locales.end(), recommended_locales.find(locale));
1854   }
1855 
1856   // Verify that the first recommended locale is selected.
1857   std::string selected_locale =
1858       ash::LoginScreenTestApi::GetExpandedPublicSessionSelectedLocale();
1859 
1860   EXPECT_EQ(kRecommendedLocales1[0], selected_locale);
1861 
1862   // Change the list of recommended locales.
1863   SetRecommendedLocales(kRecommendedLocales2, base::size(kRecommendedLocales2));
1864 
1865   UploadAndInstallDeviceLocalAccountPolicy();
1866   policy::BrowserPolicyConnectorChromeOS* connector =
1867       g_browser_process->platform_part()->browser_policy_connector_chromeos();
1868   DeviceLocalAccountPolicyBroker* broker =
1869       connector->GetDeviceLocalAccountPolicyService()->GetBrokerForUser(
1870           account_id_1_.GetUserEmail());
1871   ASSERT_TRUE(broker);
1872   broker->core()->client()->FetchPolicy();
1873   WaitForPublicSessionLocalesChange(account_id_1_);
1874 
1875   // Verify that the new list of locales is shown in the UI.
1876   locales = ash::LoginScreenTestApi::GetExpandedPublicSessionLocales();
1877   EXPECT_LT(base::size(kRecommendedLocales2), locales.size());
1878   for (size_t i = 0; i < base::size(kRecommendedLocales2); ++i) {
1879     const std::string& locale = locales[i].language_code;
1880     EXPECT_EQ(kRecommendedLocales2[i], locale);
1881   }
1882 
1883   // Verify that the first new recommended locale is selected.
1884   selected_locale =
1885       ash::LoginScreenTestApi::GetExpandedPublicSessionSelectedLocale();
1886   EXPECT_EQ(kRecommendedLocales2[0], selected_locale);
1887 
1888   // Manually select a different locale.
1889   ash::LoginScreenTestApi::SetPublicSessionLocale(kPublicSessionLocale);
1890 
1891   // Change the list of recommended locales.
1892   SetRecommendedLocales(kRecommendedLocales1, base::size(kRecommendedLocales1));
1893 
1894   UploadAndInstallDeviceLocalAccountPolicy();
1895   broker->core()->client()->FetchPolicy();
1896   WaitForPublicSessionLocalesChange(account_id_1_);
1897 
1898   // Verify that the manually selected locale is still selected.
1899   selected_locale =
1900       ash::LoginScreenTestApi::GetExpandedPublicSessionSelectedLocale();
1901   EXPECT_EQ(kPublicSessionLocale, selected_locale);
1902 
1903   // The UI will request an updated list of keyboard layouts at this point. Wait
1904   // for the constructions of this list to finish.
1905   WaitForGetKeyboardLayoutsForLocaleToFinish();
1906 
1907   // Manually select a different keyboard layout.
1908   ash::LoginScreenTestApi::SetPublicSessionKeyboard(
1909       public_session_input_method_id_);
1910 
1911   ASSERT_TRUE(ash::LoginScreenTestApi::HidePublicSessionExpandedPod());
1912 
1913   // Click on a different pod, causing focus to shift away and the pod to
1914   // contract.
1915   ASSERT_TRUE(ash::LoginScreenTestApi::FocusUser(account_id_2_));
1916 
1917   // Click on the pod again, causing it to expand again. Verify that the pod has
1918   // reset all its state (the advanced form is being shown, the manually
1919   // selected locale and keyboard layout are selected).
1920   ASSERT_TRUE(ash::LoginScreenTestApi::FocusUser(account_id_1_));
1921   ExpandPublicSessionPod(true);
1922   EXPECT_EQ(kRecommendedLocales1[0],
1923             ash::LoginScreenTestApi::GetExpandedPublicSessionSelectedLocale());
1924 
1925   std::string selected_keyboard_layout =
1926       ash::LoginScreenTestApi::GetExpandedPublicSessionSelectedKeyboard();
1927 
1928   std::string default_keyboard_id =
1929       GetDefaultKeyboardIdFromLanguageCode(kRecommendedLocales1[0]);
1930   EXPECT_EQ(default_keyboard_id, selected_keyboard_layout);
1931 
1932   ash::LoginScreenTestApi::SetPublicSessionLocale(kPublicSessionLocale);
1933   WaitForGetKeyboardLayoutsForLocaleToFinish();
1934   ash::LoginScreenTestApi::SetPublicSessionKeyboard(
1935       public_session_input_method_id_);
1936 
1937   // Click the enter button to start the session.
1938   ash::LoginScreenTestApi::ClickPublicExpandedSubmitButton();
1939 
1940   WaitForSessionStart();
1941 
1942   // Verify that the locale and keyboard layout have been applied.
1943   EXPECT_EQ(kPublicSessionLocale, g_browser_process->GetApplicationLocale());
1944   EXPECT_EQ(l10n_util::GetLanguage(kPublicSessionLocale),
1945             icu::Locale::getDefault().getLanguage());
1946   EXPECT_EQ(public_session_input_method_id_,
1947             chromeos::input_method::InputMethodManager::Get()
1948                 ->GetActiveIMEState()
1949                 ->GetCurrentInputMethod()
1950                 .id());
1951 }
1952 
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,InvalidRecommendedLocale)1953 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, InvalidRecommendedLocale) {
1954   // Specify an invalid recommended locale.
1955   SetRecommendedLocales(kInvalidRecommendedLocale,
1956                         base::size(kInvalidRecommendedLocale));
1957   UploadAndInstallDeviceLocalAccountPolicy();
1958   AddPublicSessionToDevicePolicy(kAccountId1);
1959 
1960   WaitForPolicy();
1961 
1962   // Click on the pod to expand it. Verify that the pod expands to its basic
1963   // form as there is only one recommended locale.
1964   ExpandPublicSessionPod(false);
1965   ash::LoginScreenTestApi::ClickPublicExpandedSubmitButton();
1966 
1967   WaitForSessionStart();
1968 
1969   // Verify that since the recommended locale was invalid, the locale has not
1970   // changed and the first keyboard layout applicable to the locale was chosen.
1971   EXPECT_EQ(initial_locale_, g_browser_process->GetApplicationLocale());
1972   EXPECT_EQ(l10n_util::GetLanguage(initial_locale_),
1973             icu::Locale::getDefault().getLanguage());
1974   VerifyKeyboardLayoutMatchesLocale();
1975 }
1976 
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,LocaleWithIME)1977 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, LocaleWithIME) {
1978   // Specify a locale that has real IMEs in addition to a keyboard layout one.
1979   const char* const kSingleLocaleWithIME[] = {"ja"};
1980   RunWithRecommendedLocale(kSingleLocaleWithIME,
1981                            base::size(kSingleLocaleWithIME));
1982 
1983   EXPECT_GT(chromeos::input_method::InputMethodManager::Get()
1984                 ->GetActiveIMEState()
1985                 ->GetNumActiveInputMethods(),
1986             1u);
1987 }
1988 
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,LocaleWithNoIME)1989 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, LocaleWithNoIME) {
1990   // Specify a locale that has only keyboard layout.
1991   const char* const kSingleLocaleWithNoIME[] = {"de"};
1992   RunWithRecommendedLocale(kSingleLocaleWithNoIME,
1993                            base::size(kSingleLocaleWithNoIME));
1994 
1995   EXPECT_EQ(1u, chromeos::input_method::InputMethodManager::Get()
1996                     ->GetActiveIMEState()
1997                     ->GetNumActiveInputMethods());
1998 }
1999 
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,AutoLoginWithoutRecommendedLocales)2000 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,
2001                        AutoLoginWithoutRecommendedLocales) {
2002   UploadAndInstallDeviceLocalAccountPolicy();
2003   AddPublicSessionToDevicePolicy(kAccountId1);
2004   EnableAutoLogin();
2005 
2006   WaitForPolicy();
2007 
2008   WaitForSessionStart();
2009 
2010   // Verify that the locale has not changed and the first keyboard layout
2011   // applicable to the locale was chosen.
2012   EXPECT_EQ(initial_locale_, g_browser_process->GetApplicationLocale());
2013   EXPECT_EQ(initial_language_, icu::Locale::getDefault().getLanguage());
2014   VerifyKeyboardLayoutMatchesLocale();
2015 }
2016 
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,AutoLoginWithRecommendedLocales)2017 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,
2018                        AutoLoginWithRecommendedLocales) {
2019   // Specify recommended locales.
2020   SetRecommendedLocales(kRecommendedLocales1, base::size(kRecommendedLocales1));
2021   UploadAndInstallDeviceLocalAccountPolicy();
2022   AddPublicSessionToDevicePolicy(kAccountId1);
2023   EnableAutoLogin();
2024 
2025   WaitForPolicy();
2026 
2027   WaitForSessionStart();
2028 
2029   // Verify that the first recommended locale has been applied and the first
2030   // keyboard layout applicable to the locale was chosen.
2031   EXPECT_EQ(kRecommendedLocales1[0], g_browser_process->GetApplicationLocale());
2032   EXPECT_EQ(l10n_util::GetLanguage(kRecommendedLocales1[0]),
2033             icu::Locale::getDefault().getLanguage());
2034   VerifyKeyboardLayoutMatchesLocale();
2035 }
2036 
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,TermsOfServiceWithLocaleSwitch)2037 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, TermsOfServiceWithLocaleSwitch) {
2038   // Specify Terms of Service URL.
2039   ASSERT_TRUE(embedded_test_server()->Start());
2040   device_local_account_policy_.payload().mutable_termsofserviceurl()->set_value(
2041       embedded_test_server()->GetURL(
2042           std::string("/") + kExistentTermsOfServicePath).spec());
2043   UploadAndInstallDeviceLocalAccountPolicy();
2044   AddPublicSessionToDevicePolicy(kAccountId1);
2045 
2046   WaitForPolicy();
2047   ExpandPublicSessionPod(false);
2048 
2049   // Select a different locale.
2050   ash::LoginScreenTestApi::SetPublicSessionLocale(kPublicSessionLocale);
2051 
2052   // The UI will have requested an updated list of keyboard layouts at this
2053   // point. Wait for the constructions of this list to finish.
2054   WaitForGetKeyboardLayoutsForLocaleToFinish();
2055 
2056   // Set up an observer that will quit the message loop when login has succeeded
2057   // and the first wizard screen, if any, is being shown.
2058   base::RunLoop login_wait_run_loop;
2059   chromeos::MockAuthStatusConsumer login_status_consumer(
2060       login_wait_run_loop.QuitClosure());
2061   EXPECT_CALL(login_status_consumer, OnAuthSuccess(_)).Times(1).WillOnce(
2062       InvokeWithoutArgs(&login_wait_run_loop, &base::RunLoop::Quit));
2063   chromeos::ExistingUserController* controller =
2064       chromeos::ExistingUserController::current_controller();
2065   ASSERT_TRUE(controller);
2066   controller->AddLoginStatusConsumer(&login_status_consumer);
2067 
2068   // Manually select a different keyboard layout and click the enter button to
2069   // start the session.
2070   ash::LoginScreenTestApi::SetPublicSessionKeyboard(
2071       public_session_input_method_id_);
2072   ash::LoginScreenTestApi::ClickPublicExpandedSubmitButton();
2073 
2074   // Spin the loop until the login observer fires. Then, unregister the
2075   // observer.
2076   login_wait_run_loop.Run();
2077   controller->RemoveLoginStatusConsumer(&login_status_consumer);
2078 
2079   // Verify that the Terms of Service screen is being shown.
2080   chromeos::WizardController* wizard_controller =
2081         chromeos::WizardController::default_controller();
2082   ASSERT_TRUE(wizard_controller);
2083   ASSERT_TRUE(wizard_controller->current_screen());
2084   EXPECT_EQ(chromeos::TermsOfServiceScreenView::kScreenId.AsId(),
2085             wizard_controller->current_screen()->screen_id());
2086 
2087   // Wait for the Terms of Service to finish downloading.
2088   chromeos::test::OobeJS()
2089       .CreateWaiter(GetOobeElementPath({"terms-of-service"}) + ".uiState == " +
2090                     base::NumberToString(static_cast<int>(
2091                         chromeos::TermsOfServiceScreen::ScreenState::LOADED)))
2092       ->Wait();
2093 
2094   // Verify that the locale and keyboard layout have been applied.
2095   EXPECT_EQ(kPublicSessionLocale, g_browser_process->GetApplicationLocale());
2096   EXPECT_EQ(l10n_util::GetLanguage(kPublicSessionLocale),
2097             icu::Locale::getDefault().getLanguage());
2098   EXPECT_EQ(public_session_input_method_id_,
2099             chromeos::input_method::InputMethodManager::Get()
2100                 ->GetActiveIMEState()
2101                 ->GetCurrentInputMethod()
2102                 .id());
2103 
2104   // Wait for 'tos-accept-button' to become enabled.
2105   chromeos::test::OobeJS()
2106       .CreateEnabledWaiter(true, {"terms-of-service", "acceptButton"})
2107       ->Wait();
2108 
2109   // Click the accept button.
2110   chromeos::test::OobeJS().ClickOnPath({"terms-of-service", "acceptButton"});
2111 
2112   WaitForSessionStart();
2113 
2114   // Verify that the locale and keyboard layout are still in force.
2115   EXPECT_EQ(kPublicSessionLocale, g_browser_process->GetApplicationLocale());
2116   EXPECT_EQ(l10n_util::GetLanguage(kPublicSessionLocale),
2117             icu::Locale::getDefault().getLanguage());
2118   EXPECT_EQ(public_session_input_method_id_,
2119             chromeos::input_method::InputMethodManager::Get()
2120                 ->GetActiveIMEState()
2121                 ->GetCurrentInputMethod()
2122                 .id());
2123 }
2124 
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,PolicyForExtensions)2125 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, PolicyForExtensions) {
2126   // Set up a test update server for the Show Managed Storage app.
2127   ASSERT_TRUE(embedded_test_server()->InitializeAndListen());
2128   scoped_refptr<TestingUpdateManifestProvider> testing_update_manifest_provider(
2129       new TestingUpdateManifestProvider(kRelativeUpdateURL));
2130   testing_update_manifest_provider->AddUpdate(
2131       kShowManagedStorageID, kShowManagedStorageVersion,
2132       embedded_test_server()->GetURL(std::string("/") +
2133                                      kShowManagedStorageCRXPath));
2134   embedded_test_server()->RegisterRequestHandler(
2135       base::Bind(&TestingUpdateManifestProvider::HandleRequest,
2136                  testing_update_manifest_provider));
2137   embedded_test_server()->StartAcceptingConnections();
2138 
2139   // Force-install the Show Managed Storage app. This app can be installed in
2140   // public sessions because it's whitelisted for testing purposes.
2141   em::StringList* forcelist = device_local_account_policy_.payload()
2142       .mutable_extensioninstallforcelist()->mutable_value();
2143   forcelist->add_entries(base::StringPrintf(
2144       "%s;%s",
2145       kShowManagedStorageID,
2146       embedded_test_server()->GetURL(kRelativeUpdateURL).spec().c_str()));
2147 
2148   // Set a policy for the app at the policy testserver.
2149   // Note that the policy for the device-local account will be fetched before
2150   // the session is started, so the policy for the app must be installed before
2151   // the first device policy fetch.
2152   ASSERT_TRUE(local_policy_mixin_.server()->UpdatePolicyData(
2153       dm_protocol::kChromeExtensionPolicyType, kShowManagedStorageID,
2154       "{"
2155       "  \"string\": {"
2156       "    \"Value\": \"policy test value one\""
2157       "  }"
2158       "}"));
2159 
2160   // Install and refresh the device policy now. This will also fetch the initial
2161   // user policy for the device-local account now.
2162   UploadAndInstallDeviceLocalAccountPolicy();
2163   AddPublicSessionToDevicePolicy(kAccountId1);
2164   WaitForPolicy();
2165 
2166   // Observe the app installation after login.
2167   ExtensionInstallObserver install_observer(kShowManagedStorageID);
2168   ASSERT_NO_FATAL_FAILURE(StartLogin(std::string(), std::string()));
2169   WaitForSessionStart();
2170   install_observer.Wait();
2171 
2172   // Verify that the app was installed.
2173   Profile* profile = GetProfileForTest();
2174   ASSERT_TRUE(profile);
2175   extensions::ExtensionRegistry* extension_registry =
2176       extensions::ExtensionRegistry::Get(profile);
2177   EXPECT_TRUE(
2178       extension_registry->enabled_extensions().GetByID(kShowManagedStorageID));
2179 
2180   // Wait for the app policy if it hasn't been fetched yet.
2181   ProfilePolicyConnector* connector = profile->GetProfilePolicyConnector();
2182   ASSERT_TRUE(connector);
2183   PolicyService* policy_service = connector->policy_service();
2184   ASSERT_TRUE(policy_service);
2185   const PolicyNamespace ns(POLICY_DOMAIN_EXTENSIONS, kShowManagedStorageID);
2186   if (policy_service->GetPolicies(ns).Get("string") == nullptr) {
2187     PolicyChangeRegistrar policy_registrar(policy_service, ns);
2188     base::RunLoop run_loop;
2189     policy_registrar.Observe(
2190         "string", base::Bind(&PolicyChangedCallback, run_loop.QuitClosure()));
2191     run_loop.Run();
2192   }
2193 
2194   // Verify that the app policy was set.
2195   base::Value expected_value("policy test value one");
2196   EXPECT_EQ(expected_value,
2197             *policy_service->GetPolicies(ns).GetValue("string"));
2198 
2199   // Now update the policy at the server.
2200   ASSERT_TRUE(local_policy_mixin_.server()->UpdatePolicyData(
2201       dm_protocol::kChromeExtensionPolicyType, kShowManagedStorageID,
2202       "{"
2203       "  \"string\": {"
2204       "    \"Value\": \"policy test value two\""
2205       "  }"
2206       "}"));
2207 
2208   // And issue a policy refresh.
2209   {
2210     PolicyChangeRegistrar policy_registrar(policy_service, ns);
2211     base::RunLoop run_loop;
2212     policy_registrar.Observe(
2213         "string", base::Bind(&PolicyChangedCallback, run_loop.QuitClosure()));
2214     policy_service->RefreshPolicies(base::Closure());
2215     run_loop.Run();
2216   }
2217 
2218   // Verify that the app policy was updated.
2219   base::Value expected_new_value("policy test value two");
2220   EXPECT_EQ(expected_new_value,
2221             *policy_service->GetPolicies(ns).GetValue("string"));
2222 }
2223 
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,LoginWarningShown)2224 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, LoginWarningShown) {
2225   UploadAndInstallDeviceLocalAccountPolicy();
2226   AddPublicSessionToDevicePolicy(kAccountId1);
2227 
2228   WaitForPolicy();
2229 
2230   ExpandPublicSessionPod(false);
2231 
2232   // Click the link that switches the pod to its advanced form. Verify that the
2233   // pod switches from basic to advanced.
2234   ash::LoginScreenTestApi::ClickPublicExpandedAdvancedViewButton();
2235   ASSERT_TRUE(ash::LoginScreenTestApi::IsExpandedPublicSessionAdvanced());
2236   ASSERT_TRUE(ash::LoginScreenTestApi::IsPublicSessionWarningShown());
2237 }
2238 
2239 class DeviceLocalAccountWarnings : public DeviceLocalAccountTest {
SetUpInProcessBrowserTestFixture()2240   void SetUpInProcessBrowserTestFixture() override {
2241     DeviceLocalAccountTest::SetUpInProcessBrowserTestFixture();
2242     SetManagedSessionsWarningDisabled();
2243   }
2244 
SetManagedSessionsWarningDisabled()2245   void SetManagedSessionsWarningDisabled() {
2246     em::ChromeDeviceSettingsProto& proto(device_policy()->payload());
2247     em::ManagedGuestSessionPrivacyWarningsProto* managed_sessions_warnings =
2248         proto.mutable_managed_guest_session_privacy_warnings();
2249     managed_sessions_warnings->set_enabled(false);
2250     RefreshDevicePolicy();
2251     ASSERT_TRUE(local_policy_mixin_.UpdateDevicePolicy(proto));
2252   }
2253 };
2254 
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountWarnings,NoLoginWarningShown)2255 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountWarnings, NoLoginWarningShown) {
2256   UploadAndInstallDeviceLocalAccountPolicy();
2257   AddPublicSessionToDevicePolicy(kAccountId1);
2258 
2259   WaitForPolicy();
2260 
2261   ExpandPublicSessionPod(false);
2262 
2263   // Click the link that switches the pod to its advanced form. Verify that the
2264   // pod switches from basic to advanced.
2265   ash::LoginScreenTestApi::ClickPublicExpandedAdvancedViewButton();
2266   ASSERT_TRUE(ash::LoginScreenTestApi::IsExpandedPublicSessionAdvanced());
2267   ASSERT_FALSE(ash::LoginScreenTestApi::IsPublicSessionWarningShown());
2268 }
2269 
2270 class ManagedSessionsTest : public DeviceLocalAccountTest {
2271  protected:
2272   class CertsObserver : public chromeos::PolicyCertificateProvider::Observer {
2273    public:
CertsObserver(base::OnceClosure on_change)2274     explicit CertsObserver(base::OnceClosure on_change)
2275         : on_change_(std::move(on_change)) {}
2276 
OnPolicyProvidedCertsChanged()2277     void OnPolicyProvidedCertsChanged() override {
2278       std::move(on_change_).Run();
2279     }
2280 
2281    private:
2282     base::OnceClosure on_change_;
2283   };
2284 
StartTestExtensionsServer()2285   void StartTestExtensionsServer() {
2286     ASSERT_TRUE(embedded_test_server()->InitializeAndListen());
2287     scoped_refptr<TestingUpdateManifestProvider>
2288         testing_update_manifest_provider(
2289             new TestingUpdateManifestProvider(kRelativeUpdateURL));
2290     testing_update_manifest_provider->AddUpdate(
2291         kGoodExtensionID, kGoodExtensionVersion,
2292         embedded_test_server()->GetURL(std::string("/") +
2293                                        kGoodExtensionCRXPath));
2294     testing_update_manifest_provider->AddUpdate(
2295         kHostedAppID, kHostedAppVersion,
2296         embedded_test_server()->GetURL(std::string("/") + kHostedAppCRXPath));
2297     testing_update_manifest_provider->AddUpdate(
2298         kShowManagedStorageID, kShowManagedStorageVersion,
2299         embedded_test_server()->GetURL(std::string("/") +
2300                                        kShowManagedStorageCRXPath));
2301     embedded_test_server()->RegisterRequestHandler(
2302         base::BindRepeating(&TestingUpdateManifestProvider::HandleRequest,
2303                             testing_update_manifest_provider));
2304     embedded_test_server()->StartAcceptingConnections();
2305   }
2306 
GetDeviceLocalAccountPolicyBroker()2307   DeviceLocalAccountPolicyBroker* GetDeviceLocalAccountPolicyBroker() {
2308     return g_browser_process->platform_part()
2309         ->browser_policy_connector_chromeos()
2310         ->GetDeviceLocalAccountPolicyService()
2311         ->GetBrokerForUser(account_id_1_.GetUserEmail());
2312   }
2313 
AddExtension(const char * extension_id)2314   void AddExtension(const char* extension_id) {
2315     // Specify policy to install an extension.
2316     em::StringList* forcelist = device_local_account_policy_.payload()
2317                                     .mutable_extensioninstallforcelist()
2318                                     ->mutable_value();
2319     forcelist->add_entries(base::StringPrintf(
2320         "%s;%s", extension_id,
2321         embedded_test_server()->GetURL(kRelativeUpdateURL).spec().c_str()));
2322   }
2323 
AddForceInstalledSafeExtension()2324   void AddForceInstalledSafeExtension() { AddExtension(kHostedAppID); }
2325 
AddForceInstalledUnsafeExtension()2326   void AddForceInstalledUnsafeExtension() {
2327     // has effective hosts:
2328     // http://*.example.com/*
2329     // http://*.google.com/*
2330     // https://*.google.com/*
2331     AddExtension(kGoodExtensionID);
2332   }
2333 
AddForceInstalledWhitelistedExtension()2334   void AddForceInstalledWhitelistedExtension() {
2335     AddExtension(kShowManagedStorageID);
2336   }
2337 
WaitForCertificateUpdate()2338   void WaitForCertificateUpdate() {
2339     policy::DeviceNetworkConfigurationUpdater* updater =
2340         g_browser_process->platform_part()
2341             ->browser_policy_connector_chromeos()
2342             ->GetDeviceNetworkConfigurationUpdater();
2343     base::RunLoop run_loop;
2344     auto observer = std::make_unique<CertsObserver>(run_loop.QuitClosure());
2345     updater->AddPolicyProvidedCertsObserver(observer.get());
2346     run_loop.Run();
2347     updater->RemovePolicyProvidedCertsObserver(observer.get());
2348   }
2349 
AddNetworkCertificateToDevicePolicy()2350   void AddNetworkCertificateToDevicePolicy() {
2351     em::ChromeDeviceSettingsProto& proto(device_policy()->payload());
2352     proto.mutable_open_network_configuration()->set_open_network_configuration(
2353         kFakeOncWithCertificate);
2354     RefreshDevicePolicy();
2355     WaitForCertificateUpdate();
2356   }
2357 };
2358 
IN_PROC_BROWSER_TEST_F(ManagedSessionsTest,ManagedSessionsDisabled)2359 IN_PROC_BROWSER_TEST_F(ManagedSessionsTest, ManagedSessionsDisabled) {
2360   SetManagedSessionsEnabled(/* managed_sessions_enabled */ false);
2361 
2362   // Install and refresh the device policy now. This will also fetch the initial
2363   // user policy for the device-local account now.
2364   UploadAndInstallDeviceLocalAccountPolicy();
2365   AddPublicSessionToDevicePolicy(kAccountId1);
2366   WaitForPolicy();
2367 
2368   const user_manager::User* user =
2369       user_manager::UserManager::Get()->FindUser(account_id_1_);
2370   ASSERT_TRUE(user);
2371   auto* broker = GetDeviceLocalAccountPolicyBroker();
2372   ASSERT_TRUE(broker);
2373 
2374   // Check that managed sessions mode is disabled.
2375   EXPECT_FALSE(
2376       chromeos::ChromeUserManager::Get()->IsManagedSessionEnabledForUser(
2377           *user));
2378 
2379   // Check that disabled managed sessions mode hides full management disclosure
2380   // warning.
2381   EXPECT_FALSE(
2382       chromeos::ChromeUserManager::Get()->IsFullManagementDisclosureNeeded(
2383           broker));
2384 }
2385 
IN_PROC_BROWSER_TEST_F(ManagedSessionsTest,ManagedSessionsEnabledNonRisky)2386 IN_PROC_BROWSER_TEST_F(ManagedSessionsTest, ManagedSessionsEnabledNonRisky) {
2387   SetManagedSessionsEnabled(/* managed_sessions_enabled */ true);
2388 
2389   // Install and refresh the device policy now. This will also fetch the initial
2390   // user policy for the device-local account now.
2391   UploadAndInstallDeviceLocalAccountPolicy();
2392   AddPublicSessionToDevicePolicy(kAccountId1);
2393   WaitForPolicy();
2394 
2395   const user_manager::User* user =
2396       user_manager::UserManager::Get()->FindUser(account_id_1_);
2397   ASSERT_TRUE(user);
2398   auto* broker = GetDeviceLocalAccountPolicyBroker();
2399   ASSERT_TRUE(broker);
2400 
2401   // Check that managed sessions mode is enabled.
2402   ASSERT_TRUE(
2403       chromeos::ChromeUserManager::Get()->IsManagedSessionEnabledForUser(
2404           *user));
2405 
2406   // Management disclosure warning is shown in the beginning, because
2407   // kManagedSessionUseFullLoginWarning pref is set to true in the beginning.
2408   ASSERT_TRUE(
2409       chromeos::ChromeUserManager::Get()->IsFullManagementDisclosureNeeded(
2410           broker));
2411 
2412   ASSERT_NO_FATAL_FAILURE(StartLogin(std::string(), std::string()));
2413   WaitForSessionStart();
2414 
2415   // After the login, kManagedSessionUseFullLoginWarning pref is updated.
2416   // Check that management disclosure warning is not shown when managed sessions
2417   // are enabled, but policy settings are not risky.
2418   ASSERT_FALSE(
2419       chromeos::ChromeUserManager::Get()->IsFullManagementDisclosureNeeded(
2420           broker));
2421 }
2422 
IN_PROC_BROWSER_TEST_F(ManagedSessionsTest,ForceInstalledSafeExtension)2423 IN_PROC_BROWSER_TEST_F(ManagedSessionsTest, ForceInstalledSafeExtension) {
2424   SetManagedSessionsEnabled(/* managed_sessions_enabled */ true);
2425   StartTestExtensionsServer();
2426   AddForceInstalledSafeExtension();
2427 
2428   // Install and refresh the device policy now. This will also fetch the initial
2429   // user policy for the device-local account now.
2430   UploadAndInstallDeviceLocalAccountPolicy();
2431   AddPublicSessionToDevicePolicy(kAccountId1);
2432   WaitForPolicy();
2433 
2434   const user_manager::User* user =
2435       user_manager::UserManager::Get()->FindUser(account_id_1_);
2436   ASSERT_TRUE(user);
2437   auto* broker = GetDeviceLocalAccountPolicyBroker();
2438   ASSERT_TRUE(broker);
2439 
2440   // Check that 'DeviceLocalAccountManagedSessionEnabled' policy was applied
2441   // correctly.
2442   EXPECT_TRUE(
2443       chromeos::ChromeUserManager::Get()->IsManagedSessionEnabledForUser(
2444           *user));
2445 
2446   // Management disclosure warning is shown in the beginning, because
2447   // kManagedSessionUseFullLoginWarning pref is set to true in the beginning.
2448   ASSERT_TRUE(
2449       chromeos::ChromeUserManager::Get()->IsFullManagementDisclosureNeeded(
2450           broker));
2451 
2452   ExtensionInstallObserver install_observer(kHostedAppID);
2453 
2454   ASSERT_NO_FATAL_FAILURE(StartLogin(std::string(), std::string()));
2455   WaitForSessionStart();
2456 
2457   install_observer.Wait();
2458 
2459   // After the login, kManagedSessionUseFullLoginWarning pref is updated.
2460   // Check that force-installed extension activates managed session mode for
2461   // device-local users.
2462   EXPECT_FALSE(
2463       chromeos::ChromeUserManager::Get()->IsFullManagementDisclosureNeeded(
2464           broker));
2465 }
2466 
IN_PROC_BROWSER_TEST_F(ManagedSessionsTest,ForceInstalledUnsafeExtension)2467 IN_PROC_BROWSER_TEST_F(ManagedSessionsTest, ForceInstalledUnsafeExtension) {
2468   SetManagedSessionsEnabled(/* managed_sessions_enabled */ true);
2469   StartTestExtensionsServer();
2470   AddForceInstalledUnsafeExtension();
2471 
2472   // Install and refresh the device policy now. This will also fetch the initial
2473   // user policy for the device-local account now.
2474   UploadAndInstallDeviceLocalAccountPolicy();
2475   AddPublicSessionToDevicePolicy(kAccountId1);
2476   WaitForPolicy();
2477 
2478   const user_manager::User* user =
2479       user_manager::UserManager::Get()->FindUser(account_id_1_);
2480   ASSERT_TRUE(user);
2481   auto* broker = GetDeviceLocalAccountPolicyBroker();
2482   ASSERT_TRUE(broker);
2483 
2484   // Check that 'DeviceLocalAccountManagedSessionEnabled' policy was applied
2485   // correctly.
2486   EXPECT_TRUE(
2487       chromeos::ChromeUserManager::Get()->IsManagedSessionEnabledForUser(
2488           *user));
2489 
2490   // Management disclosure warning is shown in the beginning, because
2491   // kManagedSessionUseFullLoginWarning pref is set to true in the beginning.
2492   ASSERT_TRUE(
2493       chromeos::ChromeUserManager::Get()->IsFullManagementDisclosureNeeded(
2494           broker));
2495 
2496   ExtensionInstallObserver install_observer(kGoodExtensionID);
2497 
2498   ASSERT_NO_FATAL_FAILURE(StartLogin(std::string(), std::string()));
2499   WaitForSessionStart();
2500 
2501   install_observer.Wait();
2502 
2503   // After the login, kManagedSessionUseFullLoginWarning pref is updated.
2504   // Check that force-installed extension activates managed session mode for
2505   // device-local users.
2506   EXPECT_TRUE(
2507       chromeos::ChromeUserManager::Get()->IsFullManagementDisclosureNeeded(
2508           broker));
2509 }
2510 
IN_PROC_BROWSER_TEST_F(ManagedSessionsTest,WhitelistedExtension)2511 IN_PROC_BROWSER_TEST_F(ManagedSessionsTest, WhitelistedExtension) {
2512   SetManagedSessionsEnabled(/* managed_sessions_enabled */ true);
2513   StartTestExtensionsServer();
2514   AddForceInstalledWhitelistedExtension();
2515 
2516   // Install and refresh the device policy now. This will also fetch the initial
2517   // user policy for the device-local account now.
2518   UploadAndInstallDeviceLocalAccountPolicy();
2519   AddPublicSessionToDevicePolicy(kAccountId1);
2520   WaitForPolicy();
2521 
2522   const user_manager::User* user =
2523       user_manager::UserManager::Get()->FindUser(account_id_1_);
2524   ASSERT_TRUE(user);
2525   auto* broker = GetDeviceLocalAccountPolicyBroker();
2526   ASSERT_TRUE(broker);
2527 
2528   // Check that 'DeviceLocalAccountManagedSessionEnabled' policy was applied
2529   // correctly.
2530   EXPECT_TRUE(
2531       chromeos::ChromeUserManager::Get()->IsManagedSessionEnabledForUser(
2532           *user));
2533 
2534   // Management disclosure warning is shown in the beginning, because
2535   // kManagedSessionUseFullLoginWarning pref is set to true in the beginning.
2536   ASSERT_TRUE(
2537       chromeos::ChromeUserManager::Get()->IsFullManagementDisclosureNeeded(
2538           broker));
2539 
2540   ExtensionInstallObserver install_observer(kShowManagedStorageID);
2541 
2542   ASSERT_NO_FATAL_FAILURE(StartLogin(std::string(), std::string()));
2543   WaitForSessionStart();
2544 
2545   install_observer.Wait();
2546 
2547   // After the login, kManagedSessionUseFullLoginWarning pref is updated.
2548   // Check that white-listed extension is not considered risky and doesn't
2549   // activate managed session mode.
2550   EXPECT_FALSE(
2551       chromeos::ChromeUserManager::Get()->IsFullManagementDisclosureNeeded(
2552           broker));
2553 }
2554 
IN_PROC_BROWSER_TEST_F(ManagedSessionsTest,NetworkCertificate)2555 IN_PROC_BROWSER_TEST_F(ManagedSessionsTest, NetworkCertificate) {
2556   SetManagedSessionsEnabled(/* managed_sessions_enabled */ true);
2557 
2558   device_local_account_policy_.payload()
2559       .mutable_opennetworkconfiguration()
2560       ->set_value(kFakeOncWithCertificate);
2561 
2562   UploadAndInstallDeviceLocalAccountPolicy();
2563   AddPublicSessionToDevicePolicy(kAccountId1);
2564 
2565   WaitForPolicy();
2566 
2567   const user_manager::User* user =
2568       user_manager::UserManager::Get()->FindUser(account_id_1_);
2569   ASSERT_TRUE(user);
2570   auto* broker = GetDeviceLocalAccountPolicyBroker();
2571   ASSERT_TRUE(broker);
2572 
2573   // Check that 'DeviceLocalAccountManagedSessionEnabled' policy was applied
2574   // correctly.
2575   EXPECT_TRUE(
2576       chromeos::ChromeUserManager::Get()->IsManagedSessionEnabledForUser(
2577           *user));
2578 
2579   // Check that network certificate pushed via policy activates managed sessions
2580   // mode.
2581   EXPECT_TRUE(
2582       chromeos::ChromeUserManager::Get()->IsFullManagementDisclosureNeeded(
2583           broker));
2584 }
2585 
IN_PROC_BROWSER_TEST_F(ManagedSessionsTest,AllowCrossOriginAuthPrompt)2586 IN_PROC_BROWSER_TEST_F(ManagedSessionsTest, AllowCrossOriginAuthPrompt) {
2587   SetManagedSessionsEnabled(/* managed_sessions_enabled */ true);
2588 
2589   device_local_account_policy_.payload()
2590       .mutable_allowcrossoriginauthprompt()
2591       ->set_value(true);
2592 
2593   // Install and refresh the device policy now. This will also fetch the initial
2594   // user policy for the device-local account now.
2595   UploadAndInstallDeviceLocalAccountPolicy();
2596   AddPublicSessionToDevicePolicy(kAccountId1);
2597   WaitForPolicy();
2598 
2599   const user_manager::User* user =
2600       user_manager::UserManager::Get()->FindUser(account_id_1_);
2601   ASSERT_TRUE(user);
2602   auto* broker = GetDeviceLocalAccountPolicyBroker();
2603   ASSERT_TRUE(broker);
2604 
2605   // Check that 'DeviceLocalAccountManagedSessionEnabled' policy was applied
2606   // correctly.
2607   ASSERT_TRUE(
2608       chromeos::ChromeUserManager::Get()->IsManagedSessionEnabledForUser(
2609           *user));
2610 
2611   // Check that setting a value to 'AllowCrossOriginAuthPrompt' activates
2612   // managed sessions mode.
2613   ASSERT_TRUE(
2614       chromeos::ChromeUserManager::Get()->IsFullManagementDisclosureNeeded(
2615           broker));
2616 }
2617 
2618 class TermsOfServiceDownloadTest : public DeviceLocalAccountTest,
2619                                    public testing::WithParamInterface<bool> {
2620 };
2621 
IN_PROC_BROWSER_TEST_P(TermsOfServiceDownloadTest,TermsOfServiceScreen)2622 IN_PROC_BROWSER_TEST_P(TermsOfServiceDownloadTest, TermsOfServiceScreen) {
2623   // Parameterization for using valid and invalid URLs.
2624   const bool use_valid_url = GetParam();
2625 
2626   // Specify Terms of Service URL.
2627   ASSERT_TRUE(embedded_test_server()->Start());
2628   device_local_account_policy_.payload().mutable_termsofserviceurl()->set_value(
2629       embedded_test_server()
2630           ->GetURL(std::string("/") + (use_valid_url
2631                                            ? kExistentTermsOfServicePath
2632                                            : kNonexistentTermsOfServicePath))
2633           .spec());
2634   UploadAndInstallDeviceLocalAccountPolicy();
2635   AddPublicSessionToDevicePolicy(kAccountId1);
2636 
2637   WaitForPolicy();
2638 
2639   ASSERT_NO_FATAL_FAILURE(StartLogin(std::string(), std::string()));
2640 
2641   // Set up an observer that will quit the message loop when login has succeeded
2642   // and the first wizard screen, if any, is being shown.
2643   base::RunLoop login_wait_run_loop;
2644   chromeos::MockAuthStatusConsumer login_status_consumer(
2645       login_wait_run_loop.QuitClosure());
2646   EXPECT_CALL(login_status_consumer, OnAuthSuccess(_)).Times(1).WillOnce(
2647       InvokeWithoutArgs(&login_wait_run_loop, &base::RunLoop::Quit));
2648 
2649   // Spin the loop until the observer fires. Then, unregister the observer.
2650   chromeos::ExistingUserController* controller =
2651       chromeos::ExistingUserController::current_controller();
2652   ASSERT_TRUE(controller);
2653   controller->AddLoginStatusConsumer(&login_status_consumer);
2654   login_wait_run_loop.Run();
2655   controller->RemoveLoginStatusConsumer(&login_status_consumer);
2656 
2657   // Verify that the Terms of Service screen is being shown.
2658   chromeos::WizardController* wizard_controller =
2659         chromeos::WizardController::default_controller();
2660   ASSERT_TRUE(wizard_controller);
2661   ASSERT_TRUE(wizard_controller->current_screen());
2662   EXPECT_EQ(chromeos::TermsOfServiceScreenView::kScreenId.AsId(),
2663             wizard_controller->current_screen()->screen_id());
2664 
2665   // Wait for the Terms of Service to finish loading.
2666 
2667   if (!use_valid_url) {
2668     // The Terms of Service URL was invalid. Verify that the screen is showing
2669     // an error and the accept button is disabled.
2670     chromeos::test::OobeJS()
2671         .CreateVisibilityWaiter(
2672             true, {"terms-of-service", "termsOfServiceErrorDialog"})
2673         ->Wait();
2674 
2675     chromeos::test::OobeJS().ExpectTrue(
2676         GetOobeElementPath({"terms-of-service"}) + ".uiState == " +
2677         base::NumberToString(static_cast<int>(
2678             chromeos::TermsOfServiceScreen::ScreenState::ERROR)));
2679 
2680     chromeos::test::OobeJS().ExpectDisabledPath(
2681         {"terms-of-service", "acceptButton"});
2682     return;
2683   }
2684 
2685   chromeos::test::OobeJS()
2686       .CreateWaiter(GetOobeElementPath({"terms-of-service"}) + ".uiState == " +
2687                     base::NumberToString(static_cast<int>(
2688                         chromeos::TermsOfServiceScreen::ScreenState::LOADED)))
2689       ->Wait();
2690 
2691   chromeos::test::OobeJS()
2692       .CreateVisibilityWaiter(true, {"terms-of-service", "termsOfServiceFrame"})
2693       ->Wait();
2694 
2695   // Get the Terms Of Service from the webview.
2696   const std::string content = chromeos::test::GetWebViewContents(
2697       {"terms-of-service", "termsOfServiceFrame"});
2698 
2699   // Get the expected values for heading and subheading.
2700   const std::string expected_heading = l10n_util::GetStringFUTF8(
2701       IDS_TERMS_OF_SERVICE_SCREEN_HEADING, base::UTF8ToUTF16(kDomain));
2702   const std::string expected_subheading = l10n_util::GetStringFUTF8(
2703       IDS_TERMS_OF_SERVICE_SCREEN_SUBHEADING, base::UTF8ToUTF16(kDomain));
2704 
2705   // Compare heading and subheading
2706   chromeos::test::OobeJS().ExpectEQ(
2707       GetOobeElementPath({"terms-of-service", "tosHeading"}) + ".textContent",
2708       expected_heading);
2709   chromeos::test::OobeJS().ExpectEQ(
2710       GetOobeElementPath({"terms-of-service", "tosSubheading"}) +
2711           ".textContent",
2712       expected_subheading);
2713 
2714   // The Terms of Service URL was valid. Verify that the screen is showing the
2715   // downloaded Terms of Service and the accept button is enabled.
2716   base::FilePath test_dir;
2717   ASSERT_TRUE(base::PathService::Get(chrome::DIR_TEST_DATA, &test_dir));
2718   std::string terms_of_service;
2719   {
2720     base::ScopedAllowBlockingForTesting allow_blocking;
2721     ASSERT_TRUE(base::ReadFileToString(
2722         test_dir.Append(kExistentTermsOfServicePath), &terms_of_service));
2723   }
2724   EXPECT_EQ(terms_of_service, content);
2725 
2726   chromeos::test::OobeJS().ExpectFalse(
2727       GetOobeElementPath({"terms-of-service"}) + ".uiState == " +
2728       base::NumberToString(static_cast<int>(
2729           chromeos::TermsOfServiceScreen::ScreenState::ERROR)));
2730 
2731   chromeos::test::OobeJS().ExpectEnabledPath(
2732       {"terms-of-service", "acceptButton"});
2733 
2734   // Click the accept button.
2735   chromeos::test::OobeJS().ClickOnPath({"terms-of-service", "acceptButton"});
2736 
2737   WaitForSessionStart();
2738 }
2739 
IN_PROC_BROWSER_TEST_P(TermsOfServiceDownloadTest,DeclineTermsOfService)2740 IN_PROC_BROWSER_TEST_P(TermsOfServiceDownloadTest, DeclineTermsOfService) {
2741   // Specify Terms of Service URL.
2742   ASSERT_TRUE(embedded_test_server()->Start());
2743   device_local_account_policy_.payload().mutable_termsofserviceurl()->set_value(
2744       embedded_test_server()
2745           ->GetURL(std::string("/") + (GetParam()
2746                                            ? kExistentTermsOfServicePath
2747                                            : kNonexistentTermsOfServicePath))
2748           .spec());
2749   UploadAndInstallDeviceLocalAccountPolicy();
2750   AddPublicSessionToDevicePolicy(kAccountId1);
2751 
2752   WaitForPolicy();
2753 
2754   ASSERT_NO_FATAL_FAILURE(StartLogin(std::string(), std::string()));
2755 
2756   // Set up an observer that will quit the message loop when login has succeeded
2757   // and the first wizard screen, if any, is being shown.
2758   base::RunLoop login_wait_run_loop;
2759   chromeos::MockAuthStatusConsumer login_status_consumer(
2760       login_wait_run_loop.QuitClosure());
2761   EXPECT_CALL(login_status_consumer, OnAuthSuccess(_))
2762       .Times(1)
2763       .WillOnce(InvokeWithoutArgs(&login_wait_run_loop, &base::RunLoop::Quit));
2764 
2765   // Spin the loop until the observer fires. Then, unregister the observer.
2766   chromeos::ExistingUserController* controller =
2767       chromeos::ExistingUserController::current_controller();
2768   ASSERT_TRUE(controller);
2769   controller->AddLoginStatusConsumer(&login_status_consumer);
2770   login_wait_run_loop.Run();
2771   controller->RemoveLoginStatusConsumer(&login_status_consumer);
2772 
2773   // Verify that the Terms of Service screen is being shown.
2774   chromeos::WizardController* wizard_controller =
2775       chromeos::WizardController::default_controller();
2776   ASSERT_TRUE(wizard_controller);
2777   ASSERT_TRUE(wizard_controller->current_screen());
2778   EXPECT_EQ(chromeos::TermsOfServiceScreenView::kScreenId.AsId(),
2779             wizard_controller->current_screen()->screen_id());
2780 
2781   // Click the back button.
2782   chromeos::test::OobeJS().ClickOnPath({"terms-of-service", "backButton"});
2783 
2784   EXPECT_TRUE(session_manager_client()->session_stopped());
2785 }
2786 
2787 INSTANTIATE_TEST_SUITE_P(TermsOfServiceDownloadTestInstance,
2788                          TermsOfServiceDownloadTest,
2789                          testing::Bool());
2790 
IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest,WebAppsInPublicSession)2791 IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, WebAppsInPublicSession) {
2792   UploadAndInstallDeviceLocalAccountPolicy();
2793   // Add an account with DeviceLocalAccount::Type::TYPE_PUBLIC_SESSION.
2794   AddPublicSessionToDevicePolicy(kAccountId1);
2795   WaitForPolicy();
2796 
2797   StartLogin(std::string(), std::string());
2798   WaitForSessionStart();
2799 
2800   // WebAppProvider should be enabled for TYPE_PUBLIC_SESSION user account.
2801   Profile* profile = GetProfileForTest();
2802   ASSERT_TRUE(profile);
2803   EXPECT_TRUE(web_app::WebAppProvider::Get(profile));
2804 }
2805 
2806 }  // namespace policy
2807 
2808 class AmbientAuthenticationManagedGuestSessionTest
2809     : public policy::DeviceLocalAccountTest,
2810       public testing::WithParamInterface<net::AmbientAuthAllowedProfileTypes> {
2811  public:
2812 
SetAmbientAuthPolicy(net::AmbientAuthAllowedProfileTypes value)2813   void SetAmbientAuthPolicy(net::AmbientAuthAllowedProfileTypes value) {
2814     device_local_account_policy_.payload()
2815         .mutable_ambientauthenticationinprivatemodesenabled()
2816         ->set_value(static_cast<int>(value));
2817     UploadDeviceLocalAccountPolicy();
2818   }
2819 
IsAmbientAuthAllowedForProfilesTest()2820   void IsAmbientAuthAllowedForProfilesTest() {
2821     int policy_value = device_local_account_policy_.payload()
2822                            .ambientauthenticationinprivatemodesenabled()
2823                            .value();
2824     Profile* regular_profile = GetCurrentBrowser()->profile();
2825     Profile* incognito_profile = regular_profile->GetPrimaryOTRProfile();
2826 
2827     EXPECT_TRUE(AmbientAuthenticationTestHelper::IsAmbientAuthAllowedForProfile(
2828         regular_profile));
2829     EXPECT_EQ(AmbientAuthenticationTestHelper::IsAmbientAuthAllowedForProfile(
2830                   incognito_profile),
2831               AmbientAuthenticationTestHelper::IsIncognitoAllowedInPolicy(
2832                   policy_value));
2833   }
2834 
GetCurrentBrowser()2835   Browser* GetCurrentBrowser() {
2836     BrowserList* browser_list = BrowserList::GetInstance();
2837     EXPECT_EQ(1U, browser_list->size());
2838     Browser* browser = browser_list->get(0);
2839     DCHECK(browser);
2840     return browser;
2841   }
2842 };
2843 
IN_PROC_BROWSER_TEST_P(AmbientAuthenticationManagedGuestSessionTest,AmbientAuthenticationInPrivateModesEnabledPolicy)2844 IN_PROC_BROWSER_TEST_P(AmbientAuthenticationManagedGuestSessionTest,
2845                        AmbientAuthenticationInPrivateModesEnabledPolicy) {
2846   SetManagedSessionsEnabled(true);
2847   SetAmbientAuthPolicy(GetParam());
2848 
2849   UploadAndInstallDeviceLocalAccountPolicy();
2850   AddPublicSessionToDevicePolicy(policy::kAccountId1);
2851   EnableAutoLogin();
2852 
2853   WaitForPolicy();
2854 
2855   WaitForSessionStart();
2856 
2857   CheckPublicSessionPresent(account_id_1_);
2858 
2859   IsAmbientAuthAllowedForProfilesTest();
2860 }
2861 
2862 INSTANTIATE_TEST_CASE_P(
2863     AmbientAuthAllPolicyValuesTest,
2864     AmbientAuthenticationManagedGuestSessionTest,
2865     testing::Values(net::AmbientAuthAllowedProfileTypes::REGULAR_ONLY,
2866                     net::AmbientAuthAllowedProfileTypes::INCOGNITO_AND_REGULAR,
2867                     net::AmbientAuthAllowedProfileTypes::GUEST_AND_REGULAR,
2868                     net::AmbientAuthAllowedProfileTypes::ALL));
2869