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