summaryrefslogtreecommitdiffstats
path: root/chrome/browser/signin/easy_unlock_service_unittest_chromeos.cc
blob: 074695c2b31265cff687e71abba5ada2c3c97495 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <stddef.h>

#include <map>
#include <string>

#include "base/macros.h"
#include "base/memory/scoped_ptr.h"
#include "base/run_loop.h"
#include "base/values.h"
#include "chrome/browser/chromeos/login/users/mock_user_manager.h"
#include "chrome/browser/chromeos/login/users/scoped_user_manager_enabler.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/signin/easy_unlock_app_manager.h"
#include "chrome/browser/signin/easy_unlock_service.h"
#include "chrome/browser/signin/easy_unlock_service_factory.h"
#include "chrome/browser/signin/easy_unlock_service_regular.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/testing_profile.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/fake_power_manager_client.h"
#include "components/signin/core/account_id/account_id.h"
#include "components/signin/core/browser/signin_manager_base.h"
#include "components/syncable_prefs/testing_pref_service_syncable.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "device/bluetooth/bluetooth_adapter_factory.h"
#include "device/bluetooth/test/mock_bluetooth_adapter.h"
#include "testing/gmock/include/gmock/gmock.h"

using chromeos::DBusThreadManagerSetter;
using chromeos::FakePowerManagerClient;
using chromeos::PowerManagerClient;
using chromeos::ProfileHelper;
using device::MockBluetoothAdapter;
using testing::_;
using testing::AnyNumber;
using testing::Return;

namespace {

// IDs for fake users used in tests.
const char kTestUserPrimary[] = "primary_user@nowhere.com";
const char kTestUserSecondary[] = "secondary_user@nowhere.com";

// App manager to be used in EasyUnlockService tests.
// This effectivelly abstracts the extension system from the tests.
class TestAppManager : public EasyUnlockAppManager {
 public:
  TestAppManager()
      : state_(STATE_NOT_LOADED),
        app_launch_count_(0u),
        reload_count_(0u),
        ready_(false) {}
  ~TestAppManager() override {}

  // The easy unlock app state.
  enum State { STATE_NOT_LOADED, STATE_LOADED, STATE_DISABLED };

  State state() const { return state_; }
  size_t app_launch_count() const { return app_launch_count_; }
  size_t reload_count() const { return reload_count_; }

  // Marks the manager as ready and runs |ready_callback_| if there is one set.
  void SetReady() {
    ready_ = true;
    if (!ready_callback_.is_null()) {
      ready_callback_.Run();
      ready_callback_ = base::Closure();
    }
  }

  void EnsureReady(const base::Closure& ready_callback) override {
    ASSERT_TRUE(ready_callback_.is_null());
    if (ready_) {
      ready_callback.Run();
      return;
    }
    ready_callback_ = ready_callback;
  }

  void LaunchSetup() override {
    ASSERT_EQ(STATE_LOADED, state_);
    ++app_launch_count_;
  }

  void LoadApp() override { state_ = STATE_LOADED; }

  void DisableAppIfLoaded() override {
    if (state_ == STATE_LOADED)
      state_ = STATE_DISABLED;
  }

  void ReloadApp() override {
    if (state_ == STATE_LOADED)
      ++reload_count_;
  }

  bool SendUserUpdatedEvent(const std::string& user_id,
                            bool is_logged_in,
                            bool data_ready) override {
    // TODO(tbarzic): Make this a bit smarter and add some test to utilize it.
    return true;
  }

  bool SendAuthAttemptEvent() override {
    ADD_FAILURE() << "Not reached.";
    return false;
  }

 private:
  // The current app state.
  State state_;

  // Number of times LaunchSetup was called.
  size_t app_launch_count_;

  // Number of times ReloadApp was called.
  size_t reload_count_;

  // Whether the manager is ready. Set using |SetReady|.
  bool ready_;
  // If |EnsureReady| was called before |SetReady|, cached callback that will be
  // called when manager becomes ready.
  base::Closure ready_callback_;

  DISALLOW_COPY_AND_ASSIGN(TestAppManager);
};

// Helper factory that tracks AppManagers passed to EasyUnlockServices per
// browser context owning a EasyUnlockService. Used to allow tests access to the
// TestAppManagers passed to the created services.
class TestAppManagerFactory {
 public:
  TestAppManagerFactory() {}
  ~TestAppManagerFactory() {}

  // Creates a TestAppManager for the provided browser context. If a
  // TestAppManager was already created for the context, returns NULL.
  scoped_ptr<TestAppManager> Create(content::BrowserContext* context) {
    if (Find(context))
      return scoped_ptr<TestAppManager>();
    scoped_ptr<TestAppManager> app_manager(new TestAppManager());
    mapping_[context] = app_manager.get();
    return app_manager.Pass();
  }

  // Finds a TestAppManager created for |context|. Returns NULL if no
  // TestAppManagers have been created for the context.
  TestAppManager* Find(content::BrowserContext* context) {
    std::map<content::BrowserContext*, TestAppManager*>::iterator it =
        mapping_.find(context);
    if (it == mapping_.end())
      return NULL;
    return it->second;
  }

 private:
  // Mapping from browser contexts to test AppManagers. The AppManagers are not
  // owned by this.
  std::map<content::BrowserContext*, TestAppManager*> mapping_;

  DISALLOW_COPY_AND_ASSIGN(TestAppManagerFactory);
};

// Global TestAppManager factory. It should be created and desctructed in
// EasyUnlockServiceTest::SetUp and EasyUnlockServiceTest::TearDown
// respectively.
TestAppManagerFactory* app_manager_factory = NULL;

// EasyUnlockService factory function injected into testing profiles.
// It creates an EasyUnlockService with test AppManager.
scoped_ptr<KeyedService> CreateEasyUnlockServiceForTest(
    content::BrowserContext* context) {
  EXPECT_TRUE(app_manager_factory);
  if (!app_manager_factory)
    return nullptr;

  scoped_ptr<EasyUnlockAppManager> app_manager =
      app_manager_factory->Create(context);
  EXPECT_TRUE(app_manager.get());
  if (!app_manager.get())
    return nullptr;

  scoped_ptr<EasyUnlockServiceRegular> service(
      new EasyUnlockServiceRegular(Profile::FromBrowserContext(context)));
  service->Initialize(app_manager.Pass());
  return service.Pass();
}

class EasyUnlockServiceTest : public testing::Test {
 public:
  EasyUnlockServiceTest()
      : mock_user_manager_(new testing::NiceMock<chromeos::MockUserManager>()),
        scoped_user_manager_(mock_user_manager_),
        is_bluetooth_adapter_present_(true) {}

  ~EasyUnlockServiceTest() override {}

  void SetUp() override {
    app_manager_factory = new TestAppManagerFactory();

    mock_adapter_ = new testing::NiceMock<MockBluetoothAdapter>();
    device::BluetoothAdapterFactory::SetAdapterForTesting(mock_adapter_);
    EXPECT_CALL(*mock_adapter_, IsPresent())
        .WillRepeatedly(testing::Invoke(
            this, &EasyUnlockServiceTest::is_bluetooth_adapter_present));

    scoped_ptr<DBusThreadManagerSetter> dbus_setter =
        chromeos::DBusThreadManager::GetSetterForTesting();
    power_manager_client_ = new FakePowerManagerClient;
    dbus_setter->SetPowerManagerClient(
        scoped_ptr<PowerManagerClient>(power_manager_client_));

    ON_CALL(*mock_user_manager_, Shutdown()).WillByDefault(Return());
    ON_CALL(*mock_user_manager_, IsLoggedInAsUserWithGaiaAccount())
        .WillByDefault(Return(true));
    ON_CALL(*mock_user_manager_, IsCurrentUserNonCryptohomeDataEphemeral())
        .WillByDefault(Return(false));

    SetUpProfile(&profile_, AccountId::FromUserEmail(kTestUserPrimary));
  }

  void TearDown() override {
    delete app_manager_factory;
    app_manager_factory = NULL;
  }

  void SetEasyUnlockAllowedPolicy(bool allowed) {
    profile_->GetTestingPrefService()->SetManagedPref(
        prefs::kEasyUnlockAllowed, new base::FundamentalValue(allowed));
  }

  void set_is_bluetooth_adapter_present(bool is_present) {
    is_bluetooth_adapter_present_ = is_present;
  }

  bool is_bluetooth_adapter_present() const {
    return is_bluetooth_adapter_present_;
  }

  FakePowerManagerClient* power_manager_client() {
    return power_manager_client_;
  }

  // Checks whether AppManager passed to EasyUnlockservice for |profile| has
  // Easy Unlock app loaded.
  bool EasyUnlockAppInState(Profile* profile, TestAppManager::State state) {
    EXPECT_TRUE(app_manager_factory);
    if (!app_manager_factory)
      return false;
    TestAppManager* app_manager = app_manager_factory->Find(profile);
    EXPECT_TRUE(app_manager);
    return app_manager && app_manager->state() == state;
  }

  void SetAppManagerReady(content::BrowserContext* context) {
    ASSERT_TRUE(app_manager_factory);
    TestAppManager* app_manager = app_manager_factory->Find(context);
    ASSERT_TRUE(app_manager);
    app_manager->SetReady();
  }

  void SetUpSecondaryProfile() {
    SetUpProfile(&secondary_profile_,
                 AccountId::FromUserEmail(kTestUserSecondary));
  }

 private:
  // Sets up a test profile with a user id.
  void SetUpProfile(scoped_ptr<TestingProfile>* profile,
                    const AccountId& account_id) {
    ASSERT_TRUE(profile);
    ASSERT_FALSE(profile->get());

    TestingProfile::Builder builder;
    builder.AddTestingFactory(EasyUnlockServiceFactory::GetInstance(),
                              &CreateEasyUnlockServiceForTest);
    *profile = builder.Build();

    mock_user_manager_->AddUser(account_id);
    profile->get()->set_profile_name(account_id.GetUserEmail());

    SigninManagerBase* signin_manager =
        SigninManagerFactory::GetForProfile(profile->get());
    signin_manager->SetAuthenticatedAccountInfo(account_id.GetUserEmail(),
                                                account_id.GetUserEmail());
  }

 protected:
  scoped_ptr<TestingProfile> profile_;
  scoped_ptr<TestingProfile> secondary_profile_;
  chromeos::MockUserManager* mock_user_manager_;

 private:
  content::TestBrowserThreadBundle thread_bundle_;

  chromeos::ScopedUserManagerEnabler scoped_user_manager_;

  FakePowerManagerClient* power_manager_client_;

  bool is_bluetooth_adapter_present_;
  scoped_refptr<testing::NiceMock<MockBluetoothAdapter>> mock_adapter_;

  DISALLOW_COPY_AND_ASSIGN(EasyUnlockServiceTest);
};

TEST_F(EasyUnlockServiceTest, NoBluetoothNoService) {
  set_is_bluetooth_adapter_present(false);

  // This should start easy unlock service initialization.
  SetAppManagerReady(profile_.get());

  EasyUnlockService* service = EasyUnlockService::Get(profile_.get());
  ASSERT_TRUE(service);

  EXPECT_FALSE(service->IsAllowed());
  EXPECT_TRUE(
      EasyUnlockAppInState(profile_.get(), TestAppManager::STATE_NOT_LOADED));
}

TEST_F(EasyUnlockServiceTest, DisabledOnSuspend) {
  // This should start easy unlock service initialization.
  SetAppManagerReady(profile_.get());

  EasyUnlockService* service = EasyUnlockService::Get(profile_.get());
  ASSERT_TRUE(service);

  EXPECT_TRUE(service->IsAllowed());
  EXPECT_TRUE(
      EasyUnlockAppInState(profile_.get(), TestAppManager::STATE_LOADED));

  power_manager_client()->SendSuspendImminent();
  EXPECT_TRUE(
      EasyUnlockAppInState(profile_.get(), TestAppManager::STATE_DISABLED));

  power_manager_client()->SendSuspendDone();
  EXPECT_TRUE(
      EasyUnlockAppInState(profile_.get(), TestAppManager::STATE_LOADED));
}

TEST_F(EasyUnlockServiceTest, NotAllowedForSecondaryProfile) {
  SetAppManagerReady(profile_.get());

  EasyUnlockService* primary_service = EasyUnlockService::Get(profile_.get());
  ASSERT_TRUE(primary_service);

  // A sanity check for the test to confirm that the primary profile service
  // is allowed under these conditions..
  ASSERT_TRUE(primary_service->IsAllowed());

  SetUpSecondaryProfile();
  SetAppManagerReady(secondary_profile_.get());

  EasyUnlockService* secondary_service =
      EasyUnlockService::Get(secondary_profile_.get());
  ASSERT_TRUE(secondary_service);

  EXPECT_FALSE(secondary_service->IsAllowed());
  EXPECT_TRUE(EasyUnlockAppInState(secondary_profile_.get(),
                                   TestAppManager::STATE_NOT_LOADED));
}

TEST_F(EasyUnlockServiceTest, NotAllowedForEphemeralAccounts) {
  ON_CALL(*mock_user_manager_, IsCurrentUserNonCryptohomeDataEphemeral())
      .WillByDefault(Return(true));

  SetAppManagerReady(profile_.get());
  EXPECT_FALSE(EasyUnlockService::Get(profile_.get())->IsAllowed());
  EXPECT_TRUE(
      EasyUnlockAppInState(profile_.get(), TestAppManager::STATE_NOT_LOADED));
}

}  // namespace