device_local_account_browsertest.cc revision 0529e5d033099cbfc42635f6f6183833b09dff6e
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 <map>
6#include <string>
7
8#include "apps/app_window_registry.h"
9#include "apps/ui/native_app_window.h"
10#include "ash/shell.h"
11#include "ash/system/chromeos/session/logout_confirmation_controller.h"
12#include "ash/system/chromeos/session/logout_confirmation_dialog.h"
13#include "base/basictypes.h"
14#include "base/bind.h"
15#include "base/bind_helpers.h"
16#include "base/callback.h"
17#include "base/command_line.h"
18#include "base/file_util.h"
19#include "base/files/file_path.h"
20#include "base/files/scoped_temp_dir.h"
21#include "base/json/json_reader.h"
22#include "base/json/json_writer.h"
23#include "base/location.h"
24#include "base/memory/ref_counted.h"
25#include "base/memory/scoped_ptr.h"
26#include "base/message_loop/message_loop.h"
27#include "base/message_loop/message_loop_proxy.h"
28#include "base/path_service.h"
29#include "base/prefs/pref_service.h"
30#include "base/run_loop.h"
31#include "base/sequenced_task_runner.h"
32#include "base/strings/string_number_conversions.h"
33#include "base/strings/string_util.h"
34#include "base/strings/stringprintf.h"
35#include "base/strings/utf_string_conversions.h"
36#include "base/test/scoped_path_override.h"
37#include "base/values.h"
38#include "chrome/browser/browser_process.h"
39#include "chrome/browser/chrome_notification_types.h"
40#include "chrome/browser/chromeos/login/existing_user_controller.h"
41#include "chrome/browser/chromeos/login/login_display_host.h"
42#include "chrome/browser/chromeos/login/login_display_host_impl.h"
43#include "chrome/browser/chromeos/login/mock_login_status_consumer.h"
44#include "chrome/browser/chromeos/login/screens/wizard_screen.h"
45#include "chrome/browser/chromeos/login/user.h"
46#include "chrome/browser/chromeos/login/user_image_manager.h"
47#include "chrome/browser/chromeos/login/user_image_manager_impl.h"
48#include "chrome/browser/chromeos/login/user_image_manager_test_util.h"
49#include "chrome/browser/chromeos/login/user_manager.h"
50#include "chrome/browser/chromeos/login/user_manager_impl.h"
51#include "chrome/browser/chromeos/login/webui_login_view.h"
52#include "chrome/browser/chromeos/login/wizard_controller.h"
53#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
54#include "chrome/browser/chromeos/policy/cloud_external_data_manager_base_test_util.h"
55#include "chrome/browser/chromeos/policy/device_local_account.h"
56#include "chrome/browser/chromeos/policy/device_local_account_policy_service.h"
57#include "chrome/browser/chromeos/policy/device_policy_builder.h"
58#include "chrome/browser/chromeos/policy/device_policy_cros_browser_test.h"
59#include "chrome/browser/chromeos/policy/proto/chrome_device_policy.pb.h"
60#include "chrome/browser/extensions/crx_installer.h"
61#include "chrome/browser/extensions/extension_service.h"
62#include "chrome/browser/lifetime/application_lifetime.h"
63#include "chrome/browser/policy/profile_policy_connector.h"
64#include "chrome/browser/policy/profile_policy_connector_factory.h"
65#include "chrome/browser/policy/test/local_policy_test_server.h"
66#include "chrome/browser/prefs/session_startup_pref.h"
67#include "chrome/browser/profiles/profile.h"
68#include "chrome/browser/profiles/profile_manager.h"
69#include "chrome/browser/ui/browser.h"
70#include "chrome/browser/ui/browser_commands.h"
71#include "chrome/browser/ui/browser_finder.h"
72#include "chrome/browser/ui/browser_list.h"
73#include "chrome/browser/ui/browser_list_observer.h"
74#include "chrome/browser/ui/browser_window.h"
75#include "chrome/browser/ui/extensions/application_launch.h"
76#include "chrome/browser/ui/host_desktop.h"
77#include "chrome/browser/ui/tabs/tab_strip_model.h"
78#include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h"
79#include "chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h"
80#include "chrome/common/chrome_paths.h"
81#include "chrome/common/extensions/extension_constants.h"
82#include "chromeos/chromeos_paths.h"
83#include "chromeos/chromeos_switches.h"
84#include "chromeos/dbus/fake_session_manager_client.h"
85#include "components/policy/core/common/cloud/cloud_policy_constants.h"
86#include "components/policy/core/common/cloud/cloud_policy_core.h"
87#include "components/policy/core/common/cloud/cloud_policy_store.h"
88#include "components/policy/core/common/cloud/policy_builder.h"
89#include "components/policy/core/common/external_data_fetcher.h"
90#include "components/policy/core/common/policy_map.h"
91#include "components/policy/core/common/policy_namespace.h"
92#include "components/policy/core/common/policy_service.h"
93#include "components/policy/core/common/policy_switches.h"
94#include "content/public/browser/notification_details.h"
95#include "content/public/browser/notification_service.h"
96#include "content/public/browser/notification_source.h"
97#include "content/public/browser/web_contents.h"
98#include "content/public/browser/web_ui.h"
99#include "content/public/test/browser_test_utils.h"
100#include "content/public/test/test_utils.h"
101#include "crypto/rsa_private_key.h"
102#include "extensions/browser/extension_system.h"
103#include "extensions/browser/management_policy.h"
104#include "extensions/common/extension.h"
105#include "grit/chromium_strings.h"
106#include "grit/generated_resources.h"
107#include "net/base/url_util.h"
108#include "net/http/http_status_code.h"
109#include "net/test/embedded_test_server/embedded_test_server.h"
110#include "net/test/embedded_test_server/http_request.h"
111#include "net/test/embedded_test_server/http_response.h"
112#include "net/url_request/test_url_fetcher_factory.h"
113#include "net/url_request/url_fetcher_delegate.h"
114#include "net/url_request/url_request_status.h"
115#include "policy/policy_constants.h"
116#include "testing/gmock/include/gmock/gmock.h"
117#include "ui/base/l10n/l10n_util.h"
118#include "ui/base/window_open_disposition.h"
119#include "ui/gfx/image/image_skia.h"
120#include "ui/views/widget/widget.h"
121#include "url/gurl.h"
122//#include "third_party/cros_system_api/dbus/service_constants.h"
123
124namespace em = enterprise_management;
125
126using chromeos::LoginScreenContext;
127using testing::InvokeWithoutArgs;
128using testing::Return;
129using testing::_;
130
131namespace policy {
132
133namespace {
134
135const char kDomain[] = "example.com";
136const char kAccountId1[] = "dla1@example.com";
137const char kAccountId2[] = "dla2@example.com";
138const char kDisplayName[] = "display name";
139const char* kStartupURLs[] = {
140  "chrome://policy",
141  "chrome://about",
142};
143const char kExistentTermsOfServicePath[] = "chromeos/enterprise/tos.txt";
144const char kNonexistentTermsOfServicePath[] = "chromeos/enterprise/tos404.txt";
145const char kRelativeUpdateURL[] = "/service/update2/crx";
146const char kUpdateManifestHeader[] =
147    "<?xml version='1.0' encoding='UTF-8'?>\n"
148    "<gupdate xmlns='http://www.google.com/update2/response' protocol='2.0'>\n";
149const char kUpdateManifestTemplate[] =
150    "  <app appid='%s'>\n"
151    "    <updatecheck codebase='%s' version='%s' />\n"
152    "  </app>\n";
153const char kUpdateManifestFooter[] =
154    "</gupdate>\n";
155const char kHostedAppID[] = "kbmnembihfiondgfjekmnmcbddelicoi";
156const char kHostedAppCRXPath[] = "extensions/hosted_app.crx";
157const char kHostedAppVersion[] = "1.0.0.0";
158const char kGoodExtensionID[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
159const char kGoodExtensionCRXPath[] = "extensions/good.crx";
160const char kGoodExtensionVersion[] = "1.0";
161const char kPackagedAppCRXPath[] = "extensions/platform_apps/app_window_2.crx";
162
163const char kExternalData[] = "External data";
164const char kExternalDataURL[] = "http://localhost/external_data";
165
166// Helper that serves extension update manifests to Chrome.
167class TestingUpdateManifestProvider {
168 public:
169  // Update manifests will be served at |relative_update_url|.
170  explicit TestingUpdateManifestProvider(
171      const std::string& relative_update_url);
172  ~TestingUpdateManifestProvider();
173
174  // When an update manifest is requested for the given extension |id|, indicate
175  // that |version| of the extension can be downloaded at |crx_url|.
176  void AddUpdate(const std::string& id,
177                 const std::string& version,
178                 const GURL& crx_url);
179
180  // This method must be registered with the test's EmbeddedTestServer to start
181  // serving update manifests.
182  scoped_ptr<net::test_server::HttpResponse> HandleRequest(
183      const net::test_server::HttpRequest& request);
184
185 private:
186  struct Update {
187   public:
188    Update(const std::string& version, const GURL& crx_url);
189    Update();
190
191    std::string version;
192    GURL crx_url;
193  };
194  typedef std::map<std::string, Update> UpdateMap;
195  UpdateMap updates_;
196
197  const std::string relative_update_url_;
198
199  DISALLOW_COPY_AND_ASSIGN(TestingUpdateManifestProvider);
200};
201
202TestingUpdateManifestProvider::Update::Update(const std::string& version,
203                                              const GURL& crx_url)
204    : version(version),
205      crx_url(crx_url) {
206}
207
208TestingUpdateManifestProvider::Update::Update() {
209}
210
211TestingUpdateManifestProvider::TestingUpdateManifestProvider(
212    const std::string& relative_update_url)
213    : relative_update_url_(relative_update_url) {
214}
215
216TestingUpdateManifestProvider::~TestingUpdateManifestProvider() {
217}
218
219void TestingUpdateManifestProvider::AddUpdate(const std::string& id,
220                                              const std::string& version,
221                                              const GURL& crx_url) {
222  updates_[id] = Update(version, crx_url);
223}
224
225scoped_ptr<net::test_server::HttpResponse>
226    TestingUpdateManifestProvider::HandleRequest(
227        const net::test_server::HttpRequest& request) {
228  const GURL url("http://localhost" + request.relative_url);
229  if (url.path() != relative_update_url_)
230    return scoped_ptr<net::test_server::HttpResponse>();
231
232  std::string content = kUpdateManifestHeader;
233  for (net::QueryIterator it(url); !it.IsAtEnd(); it.Advance()) {
234    if (it.GetKey() != "x")
235      continue;
236    // Extract the extension id from the subquery. Since GetValueForKeyInQuery()
237    // expects a complete URL, dummy scheme and host must be prepended.
238    std::string id;
239    net::GetValueForKeyInQuery(GURL("http://dummy?" + it.GetUnescapedValue()),
240                               "id", &id);
241    UpdateMap::const_iterator entry = updates_.find(id);
242    if (entry != updates_.end()) {
243      content += base::StringPrintf(kUpdateManifestTemplate,
244                                    id.c_str(),
245                                    entry->second.crx_url.spec().c_str(),
246                                    entry->second.version.c_str());
247    }
248  }
249  content += kUpdateManifestFooter;
250  scoped_ptr<net::test_server::BasicHttpResponse>
251      http_response(new net::test_server::BasicHttpResponse);
252  http_response->set_code(net::HTTP_OK);
253  http_response->set_content(content);
254  http_response->set_content_type("text/xml");
255  return http_response.PassAs<net::test_server::HttpResponse>();
256}
257
258bool DoesInstallSuccessReferToId(const std::string& id,
259                                 const content::NotificationSource& source,
260                                 const content::NotificationDetails& details) {
261  return content::Details<const extensions::InstalledExtensionInfo>(details)->
262      extension->id() == id;
263}
264
265bool DoesInstallFailureReferToId(const std::string& id,
266                                 const content::NotificationSource& source,
267                                 const content::NotificationDetails& details) {
268  return content::Details<const base::string16>(details)->
269      find(base::UTF8ToUTF16(id)) != base::string16::npos;
270}
271
272scoped_ptr<net::FakeURLFetcher> RunCallbackAndReturnFakeURLFetcher(
273    scoped_refptr<base::SequencedTaskRunner> task_runner,
274    const base::Closure& callback,
275    const GURL& url,
276    net::URLFetcherDelegate* delegate,
277    const std::string& response_data,
278    net::HttpStatusCode response_code,
279    net::URLRequestStatus::Status status) {
280  task_runner->PostTask(FROM_HERE, callback);
281  return make_scoped_ptr(new net::FakeURLFetcher(
282      url, delegate, response_data, response_code, status));
283}
284
285}  // namespace
286
287class DeviceLocalAccountTest : public DevicePolicyCrosBrowserTest,
288                               public chromeos::UserManager::Observer,
289                               public chrome::BrowserListObserver,
290                               public apps::AppWindowRegistry::Observer {
291 protected:
292  DeviceLocalAccountTest()
293      : user_id_1_(GenerateDeviceLocalAccountUserId(
294            kAccountId1, DeviceLocalAccount::TYPE_PUBLIC_SESSION)),
295        user_id_2_(GenerateDeviceLocalAccountUserId(
296            kAccountId2, DeviceLocalAccount::TYPE_PUBLIC_SESSION)) {
297    set_exit_when_last_browser_closes(false);
298  }
299
300  virtual ~DeviceLocalAccountTest() {}
301
302  virtual void SetUp() OVERRIDE {
303    // Configure and start the test server.
304    scoped_ptr<crypto::RSAPrivateKey> signing_key(
305        PolicyBuilder::CreateTestSigningKey());
306    ASSERT_TRUE(test_server_.SetSigningKeyAndSignature(
307        signing_key.get(), PolicyBuilder::GetTestSigningKeySignature()));
308    signing_key.reset();
309    test_server_.RegisterClient(PolicyBuilder::kFakeToken,
310                                PolicyBuilder::kFakeDeviceId);
311    ASSERT_TRUE(test_server_.Start());
312
313    ASSERT_TRUE(extension_cache_root_dir_.CreateUniqueTempDir());
314    extension_cache_root_dir_override_.reset(new base::ScopedPathOverride(
315        chromeos::DIR_DEVICE_LOCAL_ACCOUNT_EXTENSIONS,
316        extension_cache_root_dir_.path()));
317    ASSERT_TRUE(external_data_cache_dir_.CreateUniqueTempDir());
318    external_data_cache_dir_override_.reset(new base::ScopedPathOverride(
319        chromeos::DIR_DEVICE_LOCAL_ACCOUNT_EXTERNAL_DATA,
320        external_data_cache_dir_.path()));
321
322    BrowserList::AddObserver(this);
323
324    DevicePolicyCrosBrowserTest::SetUp();
325  }
326
327  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
328    DevicePolicyCrosBrowserTest::SetUpCommandLine(command_line);
329    command_line->AppendSwitch(chromeos::switches::kLoginManager);
330    command_line->AppendSwitch(chromeos::switches::kForceLoginManagerInTests);
331    command_line->AppendSwitchASCII(chromeos::switches::kLoginProfile, "user");
332    command_line->AppendSwitchASCII(policy::switches::kDeviceManagementUrl,
333                                    test_server_.GetServiceURL().spec());
334  }
335
336  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
337    DevicePolicyCrosBrowserTest::SetUpInProcessBrowserTestFixture();
338
339    // Clear command-line arguments (but keep command-line switches) so the
340    // startup pages policy takes effect.
341    CommandLine* command_line = CommandLine::ForCurrentProcess();
342    CommandLine::StringVector argv(command_line->argv());
343    argv.erase(argv.begin() + argv.size() - command_line->GetArgs().size(),
344               argv.end());
345    command_line->InitFromArgv(argv);
346
347    InstallOwnerKey();
348    MarkAsEnterpriseOwned();
349
350    InitializePolicy();
351  }
352
353  virtual void CleanUpOnMainThread() OVERRIDE {
354    BrowserList::RemoveObserver(this);
355
356    // This shuts down the login UI.
357    base::MessageLoop::current()->PostTask(FROM_HERE,
358                                           base::Bind(&chrome::AttemptExit));
359    base::RunLoop().RunUntilIdle();
360  }
361
362  virtual void LocalStateChanged(chromeos::UserManager* user_manager) OVERRIDE {
363    if (run_loop_)
364      run_loop_->Quit();
365  }
366
367  virtual void OnBrowserRemoved(Browser* browser) OVERRIDE {
368    if (run_loop_)
369      run_loop_->Quit();
370  }
371
372  virtual void OnAppWindowAdded(apps::AppWindow* app_window) OVERRIDE {
373    if (run_loop_)
374      run_loop_->Quit();
375  }
376
377  virtual void OnAppWindowIconChanged(apps::AppWindow* app_window) OVERRIDE {}
378
379  virtual void OnAppWindowRemoved(apps::AppWindow* app_window) OVERRIDE {
380    if (run_loop_)
381      run_loop_->Quit();
382  }
383
384  void InitializePolicy() {
385    device_policy()->policy_data().set_public_key_version(1);
386    em::ChromeDeviceSettingsProto& proto(device_policy()->payload());
387    proto.mutable_show_user_names()->set_show_user_names(true);
388
389    device_local_account_policy_.policy_data().set_policy_type(
390        dm_protocol::kChromePublicAccountPolicyType);
391    device_local_account_policy_.policy_data().set_username(kAccountId1);
392    device_local_account_policy_.policy_data().set_settings_entity_id(
393        kAccountId1);
394    device_local_account_policy_.policy_data().set_public_key_version(1);
395    device_local_account_policy_.payload().mutable_userdisplayname()->set_value(
396        kDisplayName);
397  }
398
399  void BuildDeviceLocalAccountPolicy() {
400    device_local_account_policy_.SetDefaultSigningKey();
401    device_local_account_policy_.Build();
402  }
403
404  void UploadDeviceLocalAccountPolicy() {
405    BuildDeviceLocalAccountPolicy();
406    test_server_.UpdatePolicy(
407        dm_protocol::kChromePublicAccountPolicyType, kAccountId1,
408        device_local_account_policy_.payload().SerializeAsString());
409  }
410
411  void UploadAndInstallDeviceLocalAccountPolicy() {
412    UploadDeviceLocalAccountPolicy();
413    session_manager_client()->set_device_local_account_policy(
414        kAccountId1, device_local_account_policy_.GetBlob());
415  }
416
417  void AddPublicSessionToDevicePolicy(const std::string& username) {
418    em::ChromeDeviceSettingsProto& proto(device_policy()->payload());
419    em::DeviceLocalAccountInfoProto* account =
420        proto.mutable_device_local_accounts()->add_account();
421    account->set_account_id(username);
422    account->set_type(
423        em::DeviceLocalAccountInfoProto::ACCOUNT_TYPE_PUBLIC_SESSION);
424    RefreshDevicePolicy();
425    test_server_.UpdatePolicy(dm_protocol::kChromeDevicePolicyType,
426                              std::string(), proto.SerializeAsString());
427  }
428
429  void CheckPublicSessionPresent(const std::string& id) {
430    const chromeos::User* user = chromeos::UserManager::Get()->FindUser(id);
431    ASSERT_TRUE(user);
432    EXPECT_EQ(id, user->email());
433    EXPECT_EQ(chromeos::User::USER_TYPE_PUBLIC_ACCOUNT, user->GetType());
434  }
435
436  base::FilePath GetCacheDirectoryForAccountID(const std::string& account_id) {
437    return extension_cache_root_dir_.path()
438        .Append(base::HexEncode(account_id.c_str(), account_id.size()));
439  }
440
441  base::FilePath GetCacheCRXFile(const std::string& account_id,
442                                 const std::string& id,
443                                 const std::string& version) {
444    return GetCacheDirectoryForAccountID(account_id)
445        .Append(base::StringPrintf("%s-%s.crx", id.c_str(), version.c_str()));
446  }
447
448  // Returns a profile which can be used for testing.
449  Profile* GetProfileForTest() {
450    // Any profile can be used here since this test does not test multi profile.
451    return ProfileManager::GetActiveUserProfile();
452  }
453
454  const std::string user_id_1_;
455  const std::string user_id_2_;
456
457  scoped_ptr<base::RunLoop> run_loop_;
458
459  UserPolicyBuilder device_local_account_policy_;
460  LocalPolicyTestServer test_server_;
461
462 private:
463  base::ScopedTempDir extension_cache_root_dir_;
464  base::ScopedTempDir external_data_cache_dir_;
465  scoped_ptr<base::ScopedPathOverride> extension_cache_root_dir_override_;
466  scoped_ptr<base::ScopedPathOverride> external_data_cache_dir_override_;
467
468  DISALLOW_COPY_AND_ASSIGN(DeviceLocalAccountTest);
469};
470
471static bool IsKnownUser(const std::string& account_id) {
472  return chromeos::UserManager::Get()->IsKnownUser(account_id);
473}
474
475IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, LoginScreen) {
476  AddPublicSessionToDevicePolicy(kAccountId1);
477  AddPublicSessionToDevicePolicy(kAccountId2);
478
479  content::WindowedNotificationObserver(chrome::NOTIFICATION_USER_LIST_CHANGED,
480                                        base::Bind(&IsKnownUser, user_id_1_))
481      .Wait();
482  content::WindowedNotificationObserver(chrome::NOTIFICATION_USER_LIST_CHANGED,
483                                        base::Bind(&IsKnownUser, user_id_2_))
484      .Wait();
485
486  CheckPublicSessionPresent(user_id_1_);
487  CheckPublicSessionPresent(user_id_2_);
488}
489
490static bool DisplayNameMatches(const std::string& account_id,
491                               const std::string& display_name) {
492  const chromeos::User* user =
493      chromeos::UserManager::Get()->FindUser(account_id);
494  if (!user || user->display_name().empty())
495    return false;
496  EXPECT_EQ(base::UTF8ToUTF16(display_name), user->display_name());
497  return true;
498}
499
500IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, DisplayName) {
501  UploadAndInstallDeviceLocalAccountPolicy();
502  AddPublicSessionToDevicePolicy(kAccountId1);
503
504  content::WindowedNotificationObserver(
505      chrome::NOTIFICATION_USER_LIST_CHANGED,
506      base::Bind(&DisplayNameMatches, user_id_1_, kDisplayName)).Wait();
507}
508
509IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, PolicyDownload) {
510  UploadDeviceLocalAccountPolicy();
511  AddPublicSessionToDevicePolicy(kAccountId1);
512
513  // Policy for the account is not installed in session_manager_client. Because
514  // of this, the presence of the display name (which comes from policy) can be
515  // used as a signal that indicates successful policy download.
516  content::WindowedNotificationObserver(
517      chrome::NOTIFICATION_USER_LIST_CHANGED,
518      base::Bind(&DisplayNameMatches, user_id_1_, kDisplayName)).Wait();
519
520  // Sanity check: The policy should be present now.
521  ASSERT_FALSE(session_manager_client()->device_local_account_policy(
522      kAccountId1).empty());
523}
524
525static bool IsNotKnownUser(const std::string& account_id) {
526  return !IsKnownUser(account_id);
527}
528
529IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, DevicePolicyChange) {
530  AddPublicSessionToDevicePolicy(kAccountId1);
531  AddPublicSessionToDevicePolicy(kAccountId2);
532
533  // Wait until the login screen is up.
534  content::WindowedNotificationObserver(chrome::NOTIFICATION_USER_LIST_CHANGED,
535                                        base::Bind(&IsKnownUser, user_id_1_))
536      .Wait();
537  content::WindowedNotificationObserver(chrome::NOTIFICATION_USER_LIST_CHANGED,
538                                        base::Bind(&IsKnownUser, user_id_2_))
539      .Wait();
540
541  // Update policy to remove kAccountId2.
542  em::ChromeDeviceSettingsProto& proto(device_policy()->payload());
543  proto.mutable_device_local_accounts()->clear_account();
544  AddPublicSessionToDevicePolicy(kAccountId1);
545
546  em::ChromeDeviceSettingsProto policy;
547  policy.mutable_show_user_names()->set_show_user_names(true);
548  em::DeviceLocalAccountInfoProto* account1 =
549      policy.mutable_device_local_accounts()->add_account();
550  account1->set_account_id(kAccountId1);
551  account1->set_type(
552      em::DeviceLocalAccountInfoProto::ACCOUNT_TYPE_PUBLIC_SESSION);
553
554  test_server_.UpdatePolicy(dm_protocol::kChromeDevicePolicyType, std::string(),
555                            policy.SerializeAsString());
556  g_browser_process->policy_service()->RefreshPolicies(base::Closure());
557
558  // Make sure the second device-local account disappears.
559  content::WindowedNotificationObserver(
560      chrome::NOTIFICATION_USER_LIST_CHANGED,
561      base::Bind(&IsNotKnownUser, user_id_2_)).Wait();
562}
563
564static bool IsSessionStarted() {
565  return chromeos::UserManager::Get()->IsSessionStarted();
566}
567
568IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, StartSession) {
569  // Specify startup pages.
570  device_local_account_policy_.payload().mutable_restoreonstartup()->set_value(
571      SessionStartupPref::kPrefValueURLs);
572  em::StringListPolicyProto* startup_urls_proto =
573      device_local_account_policy_.payload().mutable_restoreonstartupurls();
574  for (size_t i = 0; i < arraysize(kStartupURLs); ++i)
575    startup_urls_proto->mutable_value()->add_entries(kStartupURLs[i]);
576  UploadAndInstallDeviceLocalAccountPolicy();
577  AddPublicSessionToDevicePolicy(kAccountId1);
578
579  // This observes the display name becoming available as this indicates
580  // device-local account policy is fully loaded, which is a prerequisite for
581  // successful login.
582  content::WindowedNotificationObserver(
583      chrome::NOTIFICATION_USER_LIST_CHANGED,
584      base::Bind(&DisplayNameMatches, user_id_1_, kDisplayName)).Wait();
585
586  // Wait for the login UI to be ready.
587  chromeos::LoginDisplayHostImpl* host =
588      reinterpret_cast<chromeos::LoginDisplayHostImpl*>(
589          chromeos::LoginDisplayHostImpl::default_host());
590  ASSERT_TRUE(host);
591  chromeos::OobeUI* oobe_ui = host->GetOobeUI();
592  ASSERT_TRUE(oobe_ui);
593  base::RunLoop run_loop;
594  const bool oobe_ui_ready = oobe_ui->IsJSReady(run_loop.QuitClosure());
595  if (!oobe_ui_ready)
596    run_loop.Run();
597
598  // Start login into the device-local account.
599  host->StartSignInScreen(LoginScreenContext());
600  chromeos::ExistingUserController* controller =
601      chromeos::ExistingUserController::current_controller();
602  ASSERT_TRUE(controller);
603  controller->LoginAsPublicAccount(user_id_1_);
604
605  // Wait for the session to start.
606  content::WindowedNotificationObserver(chrome::NOTIFICATION_SESSION_STARTED,
607                                        base::Bind(IsSessionStarted)).Wait();
608
609  // Check that the startup pages specified in policy were opened.
610  BrowserList* browser_list =
611    BrowserList::GetInstance(chrome::HOST_DESKTOP_TYPE_ASH);
612  EXPECT_EQ(1U, browser_list->size());
613  Browser* browser = browser_list->get(0);
614  ASSERT_TRUE(browser);
615
616  TabStripModel* tabs = browser->tab_strip_model();
617  ASSERT_TRUE(tabs);
618  int expected_tab_count = static_cast<int>(arraysize(kStartupURLs));
619  EXPECT_EQ(expected_tab_count, tabs->count());
620  for (int i = 0; i < expected_tab_count && i < tabs->count(); ++i) {
621    EXPECT_EQ(GURL(kStartupURLs[i]),
622              tabs->GetWebContentsAt(i)->GetVisibleURL());
623  }
624}
625
626IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, FullscreenDisallowed) {
627  UploadAndInstallDeviceLocalAccountPolicy();
628  AddPublicSessionToDevicePolicy(kAccountId1);
629
630  // This observes the display name becoming available as this indicates
631  // device-local account policy is fully loaded, which is a prerequisite for
632  // successful login.
633  content::WindowedNotificationObserver(
634      chrome::NOTIFICATION_USER_LIST_CHANGED,
635      base::Bind(&DisplayNameMatches, user_id_1_, kDisplayName)).Wait();
636
637  // Wait for the login UI to be ready.
638  chromeos::LoginDisplayHostImpl* host =
639      reinterpret_cast<chromeos::LoginDisplayHostImpl*>(
640          chromeos::LoginDisplayHostImpl::default_host());
641  ASSERT_TRUE(host);
642  chromeos::OobeUI* oobe_ui = host->GetOobeUI();
643  ASSERT_TRUE(oobe_ui);
644  base::RunLoop run_loop;
645  const bool oobe_ui_ready = oobe_ui->IsJSReady(run_loop.QuitClosure());
646  if (!oobe_ui_ready)
647    run_loop.Run();
648
649  // Start login into the device-local account.
650  host->StartSignInScreen(LoginScreenContext());
651  chromeos::ExistingUserController* controller =
652      chromeos::ExistingUserController::current_controller();
653  ASSERT_TRUE(controller);
654  controller->LoginAsPublicAccount(user_id_1_);
655
656  // Wait for the session to start.
657  content::WindowedNotificationObserver(chrome::NOTIFICATION_SESSION_STARTED,
658                                        base::Bind(IsSessionStarted)).Wait();
659
660  BrowserList* browser_list =
661    BrowserList::GetInstance(chrome::HOST_DESKTOP_TYPE_ASH);
662  EXPECT_EQ(1U, browser_list->size());
663  Browser* browser = browser_list->get(0);
664  ASSERT_TRUE(browser);
665  BrowserWindow* browser_window = browser->window();
666  ASSERT_TRUE(browser_window);
667
668  // Verify that an attempt to enter fullscreen mode is denied.
669  EXPECT_FALSE(browser_window->IsFullscreen());
670  chrome::ToggleFullscreenMode(browser);
671  EXPECT_FALSE(browser_window->IsFullscreen());
672}
673
674IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, ExtensionsUncached) {
675  // Make it possible to force-install a hosted app and an extension.
676  ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
677  TestingUpdateManifestProvider testing_update_manifest_provider(
678      kRelativeUpdateURL);
679  testing_update_manifest_provider.AddUpdate(
680      kHostedAppID,
681      kHostedAppVersion,
682      embedded_test_server()->GetURL(std::string("/") + kHostedAppCRXPath));
683  testing_update_manifest_provider.AddUpdate(
684      kGoodExtensionID,
685      kGoodExtensionVersion,
686      embedded_test_server()->GetURL(std::string("/") + kGoodExtensionCRXPath));
687  embedded_test_server()->RegisterRequestHandler(
688      base::Bind(&TestingUpdateManifestProvider::HandleRequest,
689                 base::Unretained(&testing_update_manifest_provider)));
690
691  // Specify policy to force-install the hosted app and the extension.
692  em::StringList* forcelist = device_local_account_policy_.payload()
693      .mutable_extensioninstallforcelist()->mutable_value();
694  forcelist->add_entries(base::StringPrintf(
695      "%s;%s",
696      kHostedAppID,
697      embedded_test_server()->GetURL(kRelativeUpdateURL).spec().c_str()));
698  forcelist->add_entries(base::StringPrintf(
699      "%s;%s",
700      kGoodExtensionID,
701      embedded_test_server()->GetURL(kRelativeUpdateURL).spec().c_str()));
702
703  UploadAndInstallDeviceLocalAccountPolicy();
704  AddPublicSessionToDevicePolicy(kAccountId1);
705
706  // This observes the display name becoming available as this indicates
707  // device-local account policy is fully loaded, which is a prerequisite for
708  // successful login.
709  content::WindowedNotificationObserver(
710      chrome::NOTIFICATION_USER_LIST_CHANGED,
711      base::Bind(&DisplayNameMatches, user_id_1_, kDisplayName)).Wait();
712
713  // Wait for the login UI to be ready.
714  chromeos::LoginDisplayHostImpl* host =
715      reinterpret_cast<chromeos::LoginDisplayHostImpl*>(
716          chromeos::LoginDisplayHostImpl::default_host());
717  ASSERT_TRUE(host);
718  chromeos::OobeUI* oobe_ui = host->GetOobeUI();
719  ASSERT_TRUE(oobe_ui);
720  base::RunLoop run_loop;
721  const bool oobe_ui_ready = oobe_ui->IsJSReady(run_loop.QuitClosure());
722  if (!oobe_ui_ready)
723    run_loop.Run();
724
725  // Start listening for app/extension installation results.
726  content::WindowedNotificationObserver hosted_app_observer(
727      chrome::NOTIFICATION_EXTENSION_INSTALLED,
728      base::Bind(DoesInstallSuccessReferToId, kHostedAppID));
729  content::WindowedNotificationObserver extension_observer(
730      chrome::NOTIFICATION_EXTENSION_INSTALL_ERROR,
731      base::Bind(DoesInstallFailureReferToId, kGoodExtensionID));
732
733  // Start login into the device-local account.
734  host->StartSignInScreen(LoginScreenContext());
735  chromeos::ExistingUserController* controller =
736      chromeos::ExistingUserController::current_controller();
737  ASSERT_TRUE(controller);
738  controller->LoginAsPublicAccount(user_id_1_);
739
740  // Wait for the hosted app installation to succeed and the extension
741  // installation to fail (because hosted apps are whitelisted for use in
742  // device-local accounts and extensions are not).
743  hosted_app_observer.Wait();
744  extension_observer.Wait();
745
746  // Verify that the hosted app was installed.
747  Profile* profile = GetProfileForTest();
748  ASSERT_TRUE(profile);
749  ExtensionService* extension_service =
750      extensions::ExtensionSystem::Get(profile)->extension_service();
751  EXPECT_TRUE(extension_service->GetExtensionById(kHostedAppID, true));
752
753  // Verify that the extension was not installed.
754  EXPECT_FALSE(extension_service->GetExtensionById(kGoodExtensionID, true));
755
756  // Verify that the app was copied to the account's extension cache.
757  base::FilePath test_dir;
758  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_dir));
759  EXPECT_TRUE(ContentsEqual(
760          GetCacheCRXFile(kAccountId1, kHostedAppID, kHostedAppVersion),
761          test_dir.Append(kHostedAppCRXPath)));
762
763  // Verify that the extension was not copied to the account's extension cache.
764  EXPECT_FALSE(PathExists(GetCacheCRXFile(
765      kAccountId1, kGoodExtensionID, kGoodExtensionVersion)));
766}
767
768IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, ExtensionsCached) {
769  ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
770
771  // Pre-populate the device local account's extension cache with a hosted app
772  // and an extension.
773  EXPECT_TRUE(base::CreateDirectory(
774      GetCacheDirectoryForAccountID(kAccountId1)));
775  base::FilePath test_dir;
776  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_dir));
777  const base::FilePath cached_hosted_app =
778      GetCacheCRXFile(kAccountId1, kHostedAppID, kHostedAppVersion);
779  EXPECT_TRUE(CopyFile(test_dir.Append(kHostedAppCRXPath),
780                       cached_hosted_app));
781  const base::FilePath cached_extension =
782      GetCacheCRXFile(kAccountId1, kGoodExtensionID, kGoodExtensionVersion);
783  EXPECT_TRUE(CopyFile(test_dir.Append(kGoodExtensionCRXPath),
784                       cached_extension));
785
786  // Specify policy to force-install the hosted app.
787  em::StringList* forcelist = device_local_account_policy_.payload()
788      .mutable_extensioninstallforcelist()->mutable_value();
789  forcelist->add_entries(base::StringPrintf(
790      "%s;%s",
791      kHostedAppID,
792      embedded_test_server()->GetURL(kRelativeUpdateURL).spec().c_str()));
793  forcelist->add_entries(base::StringPrintf(
794      "%s;%s",
795      kGoodExtensionID,
796      embedded_test_server()->GetURL(kRelativeUpdateURL).spec().c_str()));
797
798  UploadAndInstallDeviceLocalAccountPolicy();
799  AddPublicSessionToDevicePolicy(kAccountId1);
800
801  // This observes the display name becoming available as this indicates
802  // device-local account policy is fully loaded, which is a prerequisite for
803  // successful login.
804  content::WindowedNotificationObserver(
805      chrome::NOTIFICATION_USER_LIST_CHANGED,
806      base::Bind(&DisplayNameMatches, user_id_1_, kDisplayName)).Wait();
807
808  // Wait for the login UI to be ready.
809  chromeos::LoginDisplayHostImpl* host =
810      reinterpret_cast<chromeos::LoginDisplayHostImpl*>(
811          chromeos::LoginDisplayHostImpl::default_host());
812  ASSERT_TRUE(host);
813  chromeos::OobeUI* oobe_ui = host->GetOobeUI();
814  ASSERT_TRUE(oobe_ui);
815  base::RunLoop run_loop;
816  const bool oobe_ui_ready = oobe_ui->IsJSReady(run_loop.QuitClosure());
817  if (!oobe_ui_ready)
818    run_loop.Run();
819
820  // Start listening for app/extension installation results.
821  content::WindowedNotificationObserver hosted_app_observer(
822      chrome::NOTIFICATION_EXTENSION_INSTALLED,
823      base::Bind(DoesInstallSuccessReferToId, kHostedAppID));
824  content::WindowedNotificationObserver extension_observer(
825      chrome::NOTIFICATION_EXTENSION_INSTALL_ERROR,
826      base::Bind(DoesInstallFailureReferToId, kGoodExtensionID));
827
828  // Start login into the device-local account.
829  host->StartSignInScreen(LoginScreenContext());
830  chromeos::ExistingUserController* controller =
831      chromeos::ExistingUserController::current_controller();
832  ASSERT_TRUE(controller);
833  controller->LoginAsPublicAccount(user_id_1_);
834
835  // Wait for the hosted app installation to succeed and the extension
836  // installation to fail.
837  hosted_app_observer.Wait();
838  extension_observer.Wait();
839
840  // Verify that the hosted app was installed.
841  Profile* profile = GetProfileForTest();
842  ASSERT_TRUE(profile);
843  ExtensionService* extension_service =
844      extensions::ExtensionSystem::Get(profile)->extension_service();
845  EXPECT_TRUE(extension_service->GetExtensionById(kHostedAppID, true));
846
847  // Verify that the extension was not installed.
848  EXPECT_FALSE(extension_service->GetExtensionById(kGoodExtensionID, true));
849
850  // Verify that the app is still in the account's extension cache.
851  EXPECT_TRUE(PathExists(cached_hosted_app));
852
853  // Verify that the extension was removed from the account's extension cache.
854  EXPECT_FALSE(PathExists(cached_extension));
855}
856
857IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, ExternalData) {
858  // chromeos::UserManager requests an external data fetch whenever
859  // the key::kUserAvatarImage policy is set. Since this test wants to
860  // verify that the underlying policy subsystem will start a fetch
861  // without this request as well, the chromeos::UserManager must be
862  // prevented from seeing the policy change.
863  reinterpret_cast<chromeos::UserManagerImpl*>(chromeos::UserManager::Get())->
864      StopPolicyObserverForTesting();
865
866  UploadDeviceLocalAccountPolicy();
867  AddPublicSessionToDevicePolicy(kAccountId1);
868
869  // This observes the display name becoming available as this indicates
870  // device-local account policy is fully loaded.
871  content::WindowedNotificationObserver(
872      chrome::NOTIFICATION_USER_LIST_CHANGED,
873      base::Bind(&DisplayNameMatches, user_id_1_, kDisplayName)).Wait();
874
875  // Start serving external data at |kExternalDataURL|.
876  scoped_ptr<base::RunLoop> run_loop(new base::RunLoop);
877  scoped_ptr<net::FakeURLFetcherFactory> fetcher_factory(
878      new net::FakeURLFetcherFactory(
879          NULL,
880          base::Bind(&RunCallbackAndReturnFakeURLFetcher,
881                     base::MessageLoopProxy::current(),
882                     run_loop->QuitClosure())));
883  fetcher_factory->SetFakeResponse(GURL(kExternalDataURL),
884                                   kExternalData,
885                                   net::HTTP_OK,
886                                   net::URLRequestStatus::SUCCESS);
887
888  // Specify an external data reference for the key::kUserAvatarImage policy.
889  scoped_ptr<base::DictionaryValue> metadata =
890      test::ConstructExternalDataReference(kExternalDataURL, kExternalData);
891  std::string policy;
892  base::JSONWriter::Write(metadata.get(), &policy);
893  device_local_account_policy_.payload().mutable_useravatarimage()->set_value(
894      policy);
895  UploadAndInstallDeviceLocalAccountPolicy();
896  policy::BrowserPolicyConnectorChromeOS* connector =
897      g_browser_process->platform_part()->browser_policy_connector_chromeos();
898  DeviceLocalAccountPolicyBroker* broker =
899      connector->GetDeviceLocalAccountPolicyService()->GetBrokerForUser(
900          user_id_1_);
901  ASSERT_TRUE(broker);
902  broker->core()->store()->Load();
903
904  // The external data should be fetched and cached automatically. Wait for this
905  // fetch.
906  run_loop->Run();
907
908  // Stop serving external data at |kExternalDataURL|.
909  fetcher_factory.reset();
910
911  const PolicyMap::Entry* policy_entry =
912      broker->core()->store()->policy_map().Get(key::kUserAvatarImage);
913  ASSERT_TRUE(policy_entry);
914  ASSERT_TRUE(policy_entry->external_data_fetcher);
915
916  // Retrieve the external data. Although the data is no longer being served at
917  // |kExternalDataURL|, the retrieval should succeed because the data has been
918  // cached.
919  run_loop.reset(new base::RunLoop);
920  scoped_ptr<std::string> fetched_external_data;
921  policy_entry->external_data_fetcher->Fetch(base::Bind(
922      &test::ExternalDataFetchCallback,
923      &fetched_external_data,
924      run_loop->QuitClosure()));
925  run_loop->Run();
926
927  ASSERT_TRUE(fetched_external_data);
928  EXPECT_EQ(kExternalData, *fetched_external_data);
929
930  // Wait for the login UI to be ready.
931  chromeos::LoginDisplayHostImpl* host =
932      reinterpret_cast<chromeos::LoginDisplayHostImpl*>(
933          chromeos::LoginDisplayHostImpl::default_host());
934  ASSERT_TRUE(host);
935  chromeos::OobeUI* oobe_ui = host->GetOobeUI();
936  ASSERT_TRUE(oobe_ui);
937  run_loop.reset(new base::RunLoop);
938  const bool oobe_ui_ready = oobe_ui->IsJSReady(run_loop->QuitClosure());
939  if (!oobe_ui_ready)
940    run_loop->Run();
941
942  // Start login into the device-local account.
943  host->StartSignInScreen(LoginScreenContext());
944  chromeos::ExistingUserController* controller =
945      chromeos::ExistingUserController::current_controller();
946  ASSERT_TRUE(controller);
947  controller->LoginAsPublicAccount(user_id_1_);
948
949  // Wait for the session to start.
950  content::WindowedNotificationObserver(chrome::NOTIFICATION_SESSION_STARTED,
951                                        base::Bind(IsSessionStarted)).Wait();
952
953  // Verify that the external data reference has propagated to the device-local
954  // account's ProfilePolicyConnector.
955  ProfilePolicyConnector* policy_connector =
956      ProfilePolicyConnectorFactory::GetForProfile(GetProfileForTest());
957  ASSERT_TRUE(policy_connector);
958  const PolicyMap& policies = policy_connector->policy_service()->GetPolicies(
959      PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()));
960  policy_entry = policies.Get(key::kUserAvatarImage);
961  ASSERT_TRUE(policy_entry);
962  EXPECT_TRUE(base::Value::Equals(metadata.get(), policy_entry->value));
963  ASSERT_TRUE(policy_entry->external_data_fetcher);
964
965  // Retrieve the external data via the ProfilePolicyConnector. The retrieval
966  // should succeed because the data has been cached.
967  run_loop.reset(new base::RunLoop);
968  fetched_external_data.reset();
969  policy_entry->external_data_fetcher->Fetch(base::Bind(
970      &test::ExternalDataFetchCallback,
971      &fetched_external_data,
972      run_loop->QuitClosure()));
973  run_loop->Run();
974
975  ASSERT_TRUE(fetched_external_data);
976  EXPECT_EQ(kExternalData, *fetched_external_data);
977}
978
979IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, UserAvatarImage) {
980  ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
981
982  UploadDeviceLocalAccountPolicy();
983  AddPublicSessionToDevicePolicy(kAccountId1);
984
985  // This observes the display name becoming available as this indicates
986  // device-local account policy is fully loaded.
987  content::WindowedNotificationObserver(
988      chrome::NOTIFICATION_USER_LIST_CHANGED,
989      base::Bind(&DisplayNameMatches, user_id_1_, kDisplayName)).Wait();
990
991  base::FilePath test_dir;
992  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_dir));
993  std::string image_data;
994  ASSERT_TRUE(base::ReadFileToString(
995      test_dir.Append(chromeos::test::kUserAvatarImage1RelativePath),
996      &image_data));
997
998  std::string policy;
999  base::JSONWriter::Write(test::ConstructExternalDataReference(
1000      embedded_test_server()->GetURL(std::string("/") +
1001          chromeos::test::kUserAvatarImage1RelativePath).spec(),
1002      image_data).get(),
1003      &policy);
1004  device_local_account_policy_.payload().mutable_useravatarimage()->set_value(
1005      policy);
1006  UploadAndInstallDeviceLocalAccountPolicy();
1007  policy::BrowserPolicyConnectorChromeOS* connector =
1008      g_browser_process->platform_part()->browser_policy_connector_chromeos();
1009  DeviceLocalAccountPolicyBroker* broker =
1010      connector->GetDeviceLocalAccountPolicyService()->GetBrokerForUser(
1011          user_id_1_);
1012  ASSERT_TRUE(broker);
1013
1014  run_loop_.reset(new base::RunLoop);
1015  chromeos::UserManager::Get()->AddObserver(this);
1016  broker->core()->store()->Load();
1017  run_loop_->Run();
1018  chromeos::UserManager::Get()->RemoveObserver(this);
1019
1020  scoped_ptr<gfx::ImageSkia> policy_image = chromeos::test::ImageLoader(
1021      test_dir.Append(chromeos::test::kUserAvatarImage1RelativePath)).Load();
1022  ASSERT_TRUE(policy_image);
1023
1024  const chromeos::User* user =
1025      chromeos::UserManager::Get()->FindUser(user_id_1_);
1026  ASSERT_TRUE(user);
1027
1028  base::FilePath user_data_dir;
1029  ASSERT_TRUE(PathService::Get(chrome::DIR_USER_DATA, &user_data_dir));
1030  const base::FilePath saved_image_path =
1031      user_data_dir.Append(user_id_1_).AddExtension("jpg");
1032
1033  EXPECT_FALSE(user->HasDefaultImage());
1034  EXPECT_EQ(chromeos::User::kExternalImageIndex, user->image_index());
1035  EXPECT_TRUE(chromeos::test::AreImagesEqual(*policy_image, user->image()));
1036  const base::DictionaryValue* images_pref =
1037      g_browser_process->local_state()->GetDictionary("user_image_info");
1038  ASSERT_TRUE(images_pref);
1039  const base::DictionaryValue* image_properties;
1040  ASSERT_TRUE(images_pref->GetDictionaryWithoutPathExpansion(
1041      user_id_1_,
1042      &image_properties));
1043  int image_index;
1044  std::string image_path;
1045  ASSERT_TRUE(image_properties->GetInteger("index", &image_index));
1046  ASSERT_TRUE(image_properties->GetString("path", &image_path));
1047  EXPECT_EQ(chromeos::User::kExternalImageIndex, image_index);
1048  EXPECT_EQ(saved_image_path.value(), image_path);
1049
1050  scoped_ptr<gfx::ImageSkia> saved_image =
1051      chromeos::test::ImageLoader(saved_image_path).Load();
1052  ASSERT_TRUE(saved_image);
1053
1054  // Check image dimensions. Images can't be compared since JPEG is lossy.
1055  EXPECT_EQ(policy_image->width(), saved_image->width());
1056  EXPECT_EQ(policy_image->height(), saved_image->height());
1057}
1058
1059IN_PROC_BROWSER_TEST_F(DeviceLocalAccountTest, LastWindowClosedLogoutReminder) {
1060  UploadAndInstallDeviceLocalAccountPolicy();
1061  AddPublicSessionToDevicePolicy(kAccountId1);
1062
1063  // This observes the display name becoming available as this indicates
1064  // device-local account policy is fully loaded.
1065  content::WindowedNotificationObserver(
1066      chrome::NOTIFICATION_USER_LIST_CHANGED,
1067      base::Bind(&DisplayNameMatches, user_id_1_, kDisplayName)).Wait();
1068
1069  // Wait for the login UI to be ready.
1070  chromeos::LoginDisplayHostImpl* host =
1071      reinterpret_cast<chromeos::LoginDisplayHostImpl*>(
1072          chromeos::LoginDisplayHostImpl::default_host());
1073  ASSERT_TRUE(host);
1074  chromeos::OobeUI* oobe_ui = host->GetOobeUI();
1075  ASSERT_TRUE(oobe_ui);
1076  base::RunLoop run_loop;
1077  const bool oobe_ui_ready = oobe_ui->IsJSReady(run_loop.QuitClosure());
1078  if (!oobe_ui_ready)
1079    run_loop.Run();
1080
1081  // Start login into the device-local account.
1082  host->StartSignInScreen(LoginScreenContext());
1083  chromeos::ExistingUserController* controller =
1084      chromeos::ExistingUserController::current_controller();
1085  ASSERT_TRUE(controller);
1086  controller->LoginAsPublicAccount(user_id_1_);
1087
1088  // Wait for the session to start.
1089  content::WindowedNotificationObserver(chrome::NOTIFICATION_SESSION_STARTED,
1090                                        base::Bind(IsSessionStarted)).Wait();
1091
1092  Profile* profile = GetProfileForTest();
1093  ASSERT_TRUE(profile);
1094  apps::AppWindowRegistry* app_window_registry =
1095      apps::AppWindowRegistry::Get(profile);
1096  app_window_registry->AddObserver(this);
1097
1098  // Verify that the logout confirmation dialog is not showing.
1099  ash::LogoutConfirmationController* logout_confirmation_controller =
1100      ash::Shell::GetInstance()->logout_confirmation_controller();
1101  ASSERT_TRUE(logout_confirmation_controller);
1102  EXPECT_FALSE(logout_confirmation_controller->dialog_for_testing());
1103
1104  // Remove policy that allows only explicitly whitelisted apps to be installed
1105  // in a public session.
1106  extensions::ExtensionSystem* extension_system =
1107      extensions::ExtensionSystem::Get(profile);
1108  ASSERT_TRUE(extension_system);
1109  extension_system->management_policy()->UnregisterAllProviders();
1110
1111  // Install and a platform app.
1112  scoped_refptr<extensions::CrxInstaller> installer =
1113      extensions::CrxInstaller::CreateSilent(
1114          extension_system->extension_service());
1115  installer->set_allow_silent_install(true);
1116  installer->set_install_cause(extension_misc::INSTALL_CAUSE_USER_DOWNLOAD);
1117  installer->set_creation_flags(extensions::Extension::FROM_WEBSTORE);
1118  content::WindowedNotificationObserver app_install_observer(
1119      chrome::NOTIFICATION_CRX_INSTALLER_DONE,
1120      content::NotificationService::AllSources());
1121  base::FilePath test_dir;
1122  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_dir));
1123  installer->InstallCrx(test_dir.Append(kPackagedAppCRXPath));
1124  app_install_observer.Wait();
1125  const extensions::Extension* app =
1126      content::Details<const extensions::Extension>(
1127          app_install_observer.details()).ptr();
1128
1129  // Start the platform app, causing it to open a window.
1130  run_loop_.reset(new base::RunLoop);
1131  OpenApplication(AppLaunchParams(
1132      profile, app, extensions::LAUNCH_CONTAINER_NONE, NEW_WINDOW));
1133  run_loop_->Run();
1134  EXPECT_EQ(1U, app_window_registry->app_windows().size());
1135
1136  // Close the only open browser window.
1137  BrowserList* browser_list =
1138      BrowserList::GetInstance(chrome::HOST_DESKTOP_TYPE_ASH);
1139  EXPECT_EQ(1U, browser_list->size());
1140  Browser* browser = browser_list->get(0);
1141  ASSERT_TRUE(browser);
1142  BrowserWindow* browser_window = browser->window();
1143  ASSERT_TRUE(browser_window);
1144  run_loop_.reset(new base::RunLoop);
1145  browser_window->Close();
1146  browser_window = NULL;
1147  run_loop_->Run();
1148  browser = NULL;
1149  EXPECT_TRUE(browser_list->empty());
1150
1151  // Verify that the logout confirmation dialog is not showing because an app
1152  // window is still open.
1153  EXPECT_FALSE(logout_confirmation_controller->dialog_for_testing());
1154
1155  // Open a browser window.
1156  Browser* first_browser = CreateBrowser(profile);
1157  EXPECT_EQ(1U, browser_list->size());
1158
1159  // Close the app window.
1160  run_loop_.reset(new base::RunLoop);
1161  ASSERT_EQ(1U, app_window_registry->app_windows().size());
1162  app_window_registry->app_windows().front()->GetBaseWindow()->Close();
1163  run_loop_->Run();
1164  EXPECT_TRUE(app_window_registry->app_windows().empty());
1165
1166  // Verify that the logout confirmation dialog is not showing because a browser
1167  // window is still open.
1168  EXPECT_FALSE(logout_confirmation_controller->dialog_for_testing());
1169
1170  // Open a second browser window.
1171  Browser* second_browser = CreateBrowser(profile);
1172  EXPECT_EQ(2U, browser_list->size());
1173
1174  // Close the first browser window.
1175  browser_window = first_browser->window();
1176  ASSERT_TRUE(browser_window);
1177  run_loop_.reset(new base::RunLoop);
1178  browser_window->Close();
1179  browser_window = NULL;
1180  run_loop_->Run();
1181  first_browser = NULL;
1182  EXPECT_EQ(1U, browser_list->size());
1183
1184  // Verify that the logout confirmation dialog is not showing because a browser
1185  // window is still open.
1186  EXPECT_FALSE(logout_confirmation_controller->dialog_for_testing());
1187
1188  // Close the second browser window.
1189  browser_window = second_browser->window();
1190  ASSERT_TRUE(browser_window);
1191  run_loop_.reset(new base::RunLoop);
1192  browser_window->Close();
1193  browser_window = NULL;
1194  run_loop_->Run();
1195  second_browser = NULL;
1196  EXPECT_TRUE(browser_list->empty());
1197
1198  // Verify that the logout confirmation dialog is showing.
1199  ash::LogoutConfirmationDialog* dialog =
1200      logout_confirmation_controller->dialog_for_testing();
1201  ASSERT_TRUE(dialog);
1202
1203  // Deny the logout.
1204  dialog->GetWidget()->Close();
1205  dialog = NULL;
1206  base::RunLoop().RunUntilIdle();
1207
1208  // Verify that the logout confirmation dialog is no longer showing.
1209  EXPECT_FALSE(logout_confirmation_controller->dialog_for_testing());
1210
1211  // Open a browser window.
1212  browser = CreateBrowser(profile);
1213  EXPECT_EQ(1U, browser_list->size());
1214
1215  // Close the browser window.
1216  browser_window = browser->window();
1217  ASSERT_TRUE(browser_window);
1218  run_loop_.reset(new base::RunLoop);
1219  browser_window->Close();
1220  browser_window = NULL;
1221  run_loop_->Run();
1222  browser = NULL;
1223  EXPECT_TRUE(browser_list->empty());
1224
1225  // Verify that the logout confirmation dialog is showing again.
1226  dialog = logout_confirmation_controller->dialog_for_testing();
1227  ASSERT_TRUE(dialog);
1228
1229  // Deny the logout.
1230  dialog->GetWidget()->Close();
1231  dialog = NULL;
1232  base::RunLoop().RunUntilIdle();
1233
1234  app_window_registry->RemoveObserver(this);
1235};
1236
1237class TermsOfServiceTest : public DeviceLocalAccountTest,
1238                           public testing::WithParamInterface<bool> {
1239};
1240
1241IN_PROC_BROWSER_TEST_P(TermsOfServiceTest, TermsOfServiceScreen) {
1242  // Specify Terms of Service URL.
1243  ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
1244  device_local_account_policy_.payload().mutable_termsofserviceurl()->set_value(
1245      embedded_test_server()->GetURL(
1246            std::string("/") +
1247                (GetParam() ? kExistentTermsOfServicePath
1248                            : kNonexistentTermsOfServicePath)).spec());
1249  UploadAndInstallDeviceLocalAccountPolicy();
1250  AddPublicSessionToDevicePolicy(kAccountId1);
1251
1252  // Wait for the device-local account policy to be fully loaded.
1253  content::WindowedNotificationObserver(
1254      chrome::NOTIFICATION_USER_LIST_CHANGED,
1255      base::Bind(&DisplayNameMatches, user_id_1_, kDisplayName)).Wait();
1256
1257  // Wait for the login UI to be ready.
1258  chromeos::LoginDisplayHostImpl* host =
1259      reinterpret_cast<chromeos::LoginDisplayHostImpl*>(
1260          chromeos::LoginDisplayHostImpl::default_host());
1261  ASSERT_TRUE(host);
1262  chromeos::OobeUI* oobe_ui = host->GetOobeUI();
1263  ASSERT_TRUE(oobe_ui);
1264  base::RunLoop oobe_ui_wait_run_loop;
1265  const bool oobe_ui_ready =
1266      oobe_ui->IsJSReady(oobe_ui_wait_run_loop.QuitClosure());
1267  if (!oobe_ui_ready)
1268    oobe_ui_wait_run_loop.Run();
1269
1270  // Start login into the device-local account.
1271  host->StartSignInScreen(LoginScreenContext());
1272  chromeos::ExistingUserController* controller =
1273      chromeos::ExistingUserController::current_controller();
1274  ASSERT_TRUE(controller);
1275  controller->LoginAsPublicAccount(user_id_1_);
1276
1277  // Set up an observer that will quit the message loop when login has succeeded
1278  // and the first wizard screen, if any, is being shown.
1279  base::RunLoop login_wait_run_loop;
1280  chromeos::MockConsumer login_status_consumer;
1281  EXPECT_CALL(login_status_consumer, OnLoginSuccess(_))
1282      .Times(1)
1283      .WillOnce(InvokeWithoutArgs(&login_wait_run_loop, &base::RunLoop::Quit));
1284
1285  // Spin the loop until the observer fires. Then, unregister the observer.
1286  controller->set_login_status_consumer(&login_status_consumer);
1287  login_wait_run_loop.Run();
1288  controller->set_login_status_consumer(NULL);
1289
1290  // Verify that the Terms of Service screen is being shown.
1291  chromeos::WizardController* wizard_controller =
1292        chromeos::WizardController::default_controller();
1293  ASSERT_TRUE(wizard_controller);
1294  ASSERT_TRUE(wizard_controller->current_screen());
1295  EXPECT_EQ(chromeos::WizardController::kTermsOfServiceScreenName,
1296            wizard_controller->current_screen()->GetName());
1297
1298  // Wait for the Terms of Service to finish downloading, then get the status of
1299  // the screen's UI elements.
1300  chromeos::WebUILoginView* web_ui_login_view = host->GetWebUILoginView();
1301  ASSERT_TRUE(web_ui_login_view);
1302  content::WebUI* web_ui = web_ui_login_view->GetWebUI();
1303  ASSERT_TRUE(web_ui);
1304  content::WebContents* contents = web_ui->GetWebContents();
1305  ASSERT_TRUE(contents);
1306  std::string json;
1307  ASSERT_TRUE(content::ExecuteScriptAndExtractString(contents,
1308      "var screenElement = document.getElementById('terms-of-service');"
1309      "function SendReplyIfDownloadDone() {"
1310      "  if (screenElement.classList.contains('tos-loading'))"
1311      "    return false;"
1312      "  var status = {};"
1313      "  status.heading = document.getElementById('tos-heading').textContent;"
1314      "  status.subheading ="
1315      "      document.getElementById('tos-subheading').textContent;"
1316      "  status.contentHeading ="
1317      "      document.getElementById('tos-content-heading').textContent;"
1318      "  status.content ="
1319      "      document.getElementById('tos-content-main').textContent;"
1320      "  status.error = screenElement.classList.contains('error');"
1321      "  status.acceptEnabled ="
1322      "      !document.getElementById('tos-accept-button').disabled;"
1323      "  domAutomationController.send(JSON.stringify(status));"
1324      "  observer.disconnect();"
1325      "  return true;"
1326      "}"
1327      "var observer = new MutationObserver(SendReplyIfDownloadDone);"
1328      "if (!SendReplyIfDownloadDone()) {"
1329      "  var options = { attributes: true, attributeFilter: [ 'class' ] };"
1330      "  observer.observe(screenElement, options);"
1331      "}",
1332      &json));
1333  scoped_ptr<base::Value> value_ptr(base::JSONReader::Read(json));
1334  const base::DictionaryValue* status = NULL;
1335  ASSERT_TRUE(value_ptr.get());
1336  ASSERT_TRUE(value_ptr->GetAsDictionary(&status));
1337  std::string heading;
1338  EXPECT_TRUE(status->GetString("heading", &heading));
1339  std::string subheading;
1340  EXPECT_TRUE(status->GetString("subheading", &subheading));
1341  std::string content_heading;
1342  EXPECT_TRUE(status->GetString("contentHeading", &content_heading));
1343  std::string content;
1344  EXPECT_TRUE(status->GetString("content", &content));
1345  bool error;
1346  EXPECT_TRUE(status->GetBoolean("error", &error));
1347  bool accept_enabled;
1348  EXPECT_TRUE(status->GetBoolean("acceptEnabled", &accept_enabled));
1349
1350  // Verify that the screen's headings have been set correctly.
1351  EXPECT_EQ(
1352      l10n_util::GetStringFUTF8(IDS_TERMS_OF_SERVICE_SCREEN_HEADING,
1353                                base::UTF8ToUTF16(kDomain)),
1354      heading);
1355  EXPECT_EQ(
1356      l10n_util::GetStringFUTF8(IDS_TERMS_OF_SERVICE_SCREEN_SUBHEADING,
1357                                base::UTF8ToUTF16(kDomain)),
1358      subheading);
1359  EXPECT_EQ(
1360      l10n_util::GetStringFUTF8(IDS_TERMS_OF_SERVICE_SCREEN_CONTENT_HEADING,
1361                                base::UTF8ToUTF16(kDomain)),
1362      content_heading);
1363
1364  if (!GetParam()) {
1365    // The Terms of Service URL was invalid. Verify that the screen is showing
1366    // an error and the accept button is disabled.
1367    EXPECT_TRUE(error);
1368    EXPECT_FALSE(accept_enabled);
1369    return;
1370  }
1371
1372  // The Terms of Service URL was valid. Verify that the screen is showing the
1373  // downloaded Terms of Service and the accept button is enabled.
1374  base::FilePath test_dir;
1375  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_dir));
1376  std::string terms_of_service;
1377  ASSERT_TRUE(base::ReadFileToString(
1378      test_dir.Append(kExistentTermsOfServicePath), &terms_of_service));
1379  EXPECT_EQ(terms_of_service, content);
1380  EXPECT_FALSE(error);
1381  EXPECT_TRUE(accept_enabled);
1382
1383  // Click the accept button.
1384  ASSERT_TRUE(content::ExecuteScript(contents,
1385                                     "$('tos-accept-button').click();"));
1386
1387  // Wait for the session to start.
1388  if (!IsSessionStarted()) {
1389    content::WindowedNotificationObserver(chrome::NOTIFICATION_SESSION_STARTED,
1390                                          base::Bind(IsSessionStarted)).Wait();
1391  }
1392}
1393
1394INSTANTIATE_TEST_CASE_P(TermsOfServiceTestInstance,
1395                        TermsOfServiceTest, testing::Bool());
1396
1397}  // namespace policy
1398