summaryrefslogtreecommitdiffstats
path: root/components/proximity_auth/ble/bluetooth_low_energy_connection_finder_unittest.cc
blob: 39ee9bcc9b6bbdb5416634a5eb32b1ecaad1cdc4 (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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
// 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 "components/proximity_auth/ble/bluetooth_low_energy_connection_finder.h"

#include <string>

#include "base/bind.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/time/time.h"
#include "components/proximity_auth/ble/bluetooth_low_energy_device_whitelist.h"
#include "components/proximity_auth/connection.h"
#include "components/proximity_auth/remote_device.h"
#include "components/proximity_auth/wire_message.h"
#include "device/bluetooth/bluetooth_adapter_factory.h"
#include "device/bluetooth/bluetooth_uuid.h"
#include "device/bluetooth/test/mock_bluetooth_adapter.h"
#include "device/bluetooth/test/mock_bluetooth_device.h"
#include "device/bluetooth/test/mock_bluetooth_discovery_session.h"
#include "device/bluetooth/test/mock_bluetooth_gatt_connection.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

using testing::_;
using testing::AtLeast;
using testing::NiceMock;
using testing::Return;
using testing::StrictMock;
using testing::SaveArg;

namespace proximity_auth {
namespace {

const char kDeviceName[] = "Device name";
const char kPublicKey[] = "Public key";
const char kBluetoothAddress[] = "11:22:33:44:55:66";
const char kPersistentSymmetricKey[] = "PSK";

const char kServiceUUID[] = "DEADBEEF-CAFE-FEED-FOOD-D15EA5EBEEEF";
const char kToPeripheralCharUUID[] = "FBAE09F2-0482-11E5-8418-1697F925EC7B";
const char kFromPeripheralCharUUID[] = "5539ED10-0483-11E5-8418-1697F925EC7B";

const char kOtherUUID[] = "AAAAAAAA-AAAA-AAAA-AAAA-D15EA5EBEEEF";
const char kOtherBluetoothAddress[] = "00:00:00:00:00:00";

const int kMaxNumberOfAttempts = 2;

class MockConnection : public Connection {
 public:
  MockConnection() : Connection(CreateRemoteDevice()) {}
  ~MockConnection() override {}

  MOCK_METHOD0(Connect, void());

  using Connection::SetStatus;

 private:
  void Disconnect() override {}
  void SendMessageImpl(scoped_ptr<WireMessage> message) override {}

  RemoteDevice CreateRemoteDevice() {
    return RemoteDevice(kDeviceName, kPublicKey, kBluetoothAddress,
                        kPersistentSymmetricKey);
  }

  DISALLOW_COPY_AND_ASSIGN(MockConnection);
};

class MockBluetoothLowEnergyDeviceWhitelist
    : public BluetoothLowEnergyDeviceWhitelist {
 public:
  MockBluetoothLowEnergyDeviceWhitelist()
      : BluetoothLowEnergyDeviceWhitelist(nullptr) {}
  ~MockBluetoothLowEnergyDeviceWhitelist() override {}

  MOCK_CONST_METHOD1(HasDeviceWithAddress, bool(const std::string&));
};

class MockBluetoothLowEnergyConnectionFinder
    : public BluetoothLowEnergyConnectionFinder {
 public:
  MockBluetoothLowEnergyConnectionFinder(
      const BluetoothLowEnergyDeviceWhitelist* device_whitelist)
      : BluetoothLowEnergyConnectionFinder(kServiceUUID,
                                           kToPeripheralCharUUID,
                                           kFromPeripheralCharUUID,
                                           device_whitelist,
                                           kMaxNumberOfAttempts) {
  }

  ~MockBluetoothLowEnergyConnectionFinder() override {}

  // Mock methods don't support return type scoped_ptr<>. This is a possible
  // workaround: mock a proxy method to be called by the target overrided method
  // (CreateConnection).
  MOCK_METHOD0(CreateConnectionProxy, Connection*());

  // Creates a mock connection and sets an expectation that the mock connection
  // finder's CreateConnection() method will be called and will return the
  // created connection. Returns a reference to the created connection.
  // NOTE: The returned connection's lifetime is managed by the connection
  // finder.
  MockConnection* ExpectCreateConnection() {
    scoped_ptr<MockConnection> connection(new NiceMock<MockConnection>());
    MockConnection* connection_alias = connection.get();
    EXPECT_CALL(*this, CreateConnectionProxy())
        .WillOnce(Return(connection.release()));
    return connection_alias;
  }

  MOCK_METHOD0(CloseGattConnectionProxy, void(void));

 protected:
  scoped_ptr<Connection> CreateConnection(
      const std::string& device_address) override {
    return make_scoped_ptr(CreateConnectionProxy());
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(MockBluetoothLowEnergyConnectionFinder);
};

}  // namespace

class ProximityAuthBluetoothLowEnergyConnectionFinderTest
    : public testing::Test {
 protected:
  ProximityAuthBluetoothLowEnergyConnectionFinderTest()
      : adapter_(new NiceMock<device::MockBluetoothAdapter>),
        connection_callback_(
            base::Bind(&ProximityAuthBluetoothLowEnergyConnectionFinderTest::
                           OnConnectionFound,
                       base::Unretained(this))),
        device_(new NiceMock<device::MockBluetoothDevice>(adapter_.get(),
                                                          0,
                                                          kDeviceName,
                                                          kBluetoothAddress,
                                                          false,
                                                          false)),
        device_whitelist_(new MockBluetoothLowEnergyDeviceWhitelist()),
        last_discovery_session_alias_(nullptr) {
    device::BluetoothAdapterFactory::SetAdapterForTesting(adapter_);

    std::vector<const device::BluetoothDevice*> devices;
    ON_CALL(*adapter_, GetDevices()).WillByDefault(Return(devices));

    ON_CALL(*adapter_, IsPresent()).WillByDefault(Return(true));
    ON_CALL(*adapter_, IsPowered()).WillByDefault(Return(true));

    ON_CALL(*device_whitelist_, HasDeviceWithAddress(_))
        .WillByDefault(Return(false));
  }

  void OnConnectionFound(scoped_ptr<Connection> connection) {
    last_found_connection_ = connection.Pass();
  }

  void FindAndExpectStartDiscovery(
      BluetoothLowEnergyConnectionFinder& connection_finder) {
    device::BluetoothAdapter::DiscoverySessionCallback discovery_callback;
    scoped_ptr<device::MockBluetoothDiscoverySession> discovery_session(
        new NiceMock<device::MockBluetoothDiscoverySession>());
    last_discovery_session_alias_ = discovery_session.get();

    // Starting a discovery session. StartDiscoveryWithFilterRaw is a proxy for
    // StartDiscoveryWithFilter.
    EXPECT_CALL(*adapter_, StartDiscoverySessionWithFilterRaw(_, _, _))
        .WillOnce(SaveArg<1>(&discovery_callback));
    EXPECT_CALL(*adapter_, AddObserver(_));
    ON_CALL(*last_discovery_session_alias_, IsActive())
        .WillByDefault(Return(true));
    connection_finder.Find(connection_callback_);
    ASSERT_FALSE(discovery_callback.is_null());
    discovery_callback.Run(discovery_session.Pass());
  }

  void ExpectStopDiscoveryAndRemoveObserver() {
    EXPECT_CALL(*last_discovery_session_alias_, Stop(_, _)).Times(AtLeast(1));
    EXPECT_CALL(*adapter_, RemoveObserver(_)).Times(AtLeast(1));
  }

  // Prepare |device_| with |uuid|.
  void PrepareDevice(const std::string& uuid) {
    std::vector<device::BluetoothUUID> uuids;
    uuids.push_back(device::BluetoothUUID(uuid));
    ON_CALL(*device_, GetUUIDs()).WillByDefault(Return(uuids));
  }

  // Prepare expectations to add/change a right device.
  void PrepareForNewRightDevice(const std::string& uuid) {
    PrepareDevice(uuid);
    ON_CALL(*device_, IsPaired()).WillByDefault(Return(true));
  }

  // Prepare expectations to add/change a wrong device.
  void PrepareForNewWrongDevice(const std::string& uuid) {
    PrepareDevice(uuid);
    ON_CALL(*device_, IsPaired()).WillByDefault(Return(true));
  }

  scoped_refptr<device::MockBluetoothAdapter> adapter_;
  ConnectionFinder::ConnectionCallback connection_callback_;
  scoped_ptr<device::MockBluetoothDevice> device_;
  scoped_ptr<Connection> last_found_connection_;
  scoped_ptr<MockBluetoothLowEnergyDeviceWhitelist> device_whitelist_;
  device::MockBluetoothDiscoverySession* last_discovery_session_alias_;

 private:
  base::MessageLoop message_loop_;
};

TEST_F(ProximityAuthBluetoothLowEnergyConnectionFinderTest,
       ConstructAndDestroyDoesntCrash) {
  // Destroying a BluetoothConnectionFinder for which Find() has not been called
  // should not crash.
  BluetoothLowEnergyConnectionFinder connection_finder(
      kServiceUUID, kToPeripheralCharUUID, kFromPeripheralCharUUID,
      device_whitelist_.get(), kMaxNumberOfAttempts);
}

TEST_F(ProximityAuthBluetoothLowEnergyConnectionFinderTest,
       Find_StartsDiscoverySession) {
  BluetoothLowEnergyConnectionFinder connection_finder(
      kServiceUUID, kToPeripheralCharUUID, kFromPeripheralCharUUID,
      device_whitelist_.get(), kMaxNumberOfAttempts);

  EXPECT_CALL(*adapter_, StartDiscoverySessionWithFilterRaw(_, _, _));
  EXPECT_CALL(*adapter_, AddObserver(_));
  connection_finder.Find(connection_callback_);
}

TEST_F(ProximityAuthBluetoothLowEnergyConnectionFinderTest,
       Find_StopsDiscoverySessionBeforeDestroying) {
  BluetoothLowEnergyConnectionFinder connection_finder(
      kServiceUUID, kToPeripheralCharUUID, kFromPeripheralCharUUID,
      device_whitelist_.get(), kMaxNumberOfAttempts);

  device::BluetoothAdapter::DiscoverySessionCallback discovery_callback;
  scoped_ptr<device::MockBluetoothDiscoverySession> discovery_session(
      new NiceMock<device::MockBluetoothDiscoverySession>());
  device::MockBluetoothDiscoverySession* discovery_session_alias =
      discovery_session.get();

  EXPECT_CALL(*adapter_, StartDiscoverySessionWithFilterRaw(_, _, _))
      .WillOnce(SaveArg<1>(&discovery_callback));
  ON_CALL(*discovery_session_alias, IsActive()).WillByDefault(Return(true));
  EXPECT_CALL(*adapter_, AddObserver(_));
  connection_finder.Find(connection_callback_);

  EXPECT_CALL(*discovery_session_alias, Stop(_, _));
  ASSERT_FALSE(discovery_callback.is_null());
  discovery_callback.Run(discovery_session.Pass());

  EXPECT_CALL(*adapter_, RemoveObserver(_));
}

TEST_F(ProximityAuthBluetoothLowEnergyConnectionFinderTest,
       Find_CreatesConnectionWhenWhitelistedDeviceIsAdded) {
  StrictMock<MockBluetoothLowEnergyConnectionFinder> connection_finder(
      device_whitelist_.get());
  FindAndExpectStartDiscovery(connection_finder);
  ExpectStopDiscoveryAndRemoveObserver();

  std::vector<device::BluetoothUUID> uuids;
  ON_CALL(*device_, GetUUIDs()).WillByDefault(Return(uuids));
  ON_CALL(*device_, IsPaired()).WillByDefault(Return(true));
  ON_CALL(*device_whitelist_, HasDeviceWithAddress(_))
      .WillByDefault(Return(true));

  connection_finder.ExpectCreateConnection();
  connection_finder.DeviceAdded(adapter_.get(), device_.get());
}

TEST_F(ProximityAuthBluetoothLowEnergyConnectionFinderTest,
       Find_CreatesConnectionWhenRightDeviceIsAdded) {
  StrictMock<MockBluetoothLowEnergyConnectionFinder> connection_finder(
      device_whitelist_.get());

  FindAndExpectStartDiscovery(connection_finder);
  ExpectStopDiscoveryAndRemoveObserver();

  PrepareForNewRightDevice(kServiceUUID);
  connection_finder.ExpectCreateConnection();
  connection_finder.DeviceAdded(adapter_.get(), device_.get());
}

TEST_F(ProximityAuthBluetoothLowEnergyConnectionFinderTest,
       Find_DoesntCreateConnectionWhenWrongDeviceIsAdded) {
  StrictMock<MockBluetoothLowEnergyConnectionFinder> connection_finder(
      device_whitelist_.get());
  FindAndExpectStartDiscovery(connection_finder);
  ExpectStopDiscoveryAndRemoveObserver();

  PrepareForNewWrongDevice(kOtherUUID);
  EXPECT_CALL(connection_finder, CreateConnectionProxy()).Times(0);
  connection_finder.DeviceAdded(adapter_.get(), device_.get());
}

TEST_F(ProximityAuthBluetoothLowEnergyConnectionFinderTest,
       Find_CreatesConnectionWhenRightDeviceIsChanged) {
  StrictMock<MockBluetoothLowEnergyConnectionFinder> connection_finder(
      device_whitelist_.get());

  FindAndExpectStartDiscovery(connection_finder);
  ExpectStopDiscoveryAndRemoveObserver();

  PrepareForNewRightDevice(kServiceUUID);
  connection_finder.ExpectCreateConnection();
  connection_finder.DeviceChanged(adapter_.get(), device_.get());
}

TEST_F(ProximityAuthBluetoothLowEnergyConnectionFinderTest,
       Find_DoesntCreateConnectionWhenWrongDeviceIsChanged) {
  StrictMock<MockBluetoothLowEnergyConnectionFinder> connection_finder(
      device_whitelist_.get());

  FindAndExpectStartDiscovery(connection_finder);
  ExpectStopDiscoveryAndRemoveObserver();

  PrepareForNewWrongDevice(kOtherUUID);
  EXPECT_CALL(connection_finder, CreateConnectionProxy()).Times(0);
  connection_finder.DeviceChanged(adapter_.get(), device_.get());
}

TEST_F(ProximityAuthBluetoothLowEnergyConnectionFinderTest,
       Find_CreatesOnlyOneConnection) {
  StrictMock<MockBluetoothLowEnergyConnectionFinder> connection_finder(
      device_whitelist_.get());
  FindAndExpectStartDiscovery(connection_finder);
  ExpectStopDiscoveryAndRemoveObserver();

  // Prepare to add |device_|.
  PrepareForNewRightDevice(kServiceUUID);

  // Prepare to add |other_device|.
  NiceMock<device::MockBluetoothDevice> other_device(
      adapter_.get(), 0, kDeviceName, kOtherBluetoothAddress, false, false);
  std::vector<device::BluetoothUUID> uuids;
  uuids.push_back(device::BluetoothUUID(kServiceUUID));
  ON_CALL(other_device, IsPaired()).WillByDefault(Return(true));
  ON_CALL(other_device, GetUUIDs()).WillByDefault((Return(uuids)));

  // Only one connection should be created.
  connection_finder.ExpectCreateConnection();

  // Add the devices.
  connection_finder.DeviceAdded(adapter_.get(), device_.get());
  connection_finder.DeviceAdded(adapter_.get(), &other_device);
}

TEST_F(ProximityAuthBluetoothLowEnergyConnectionFinderTest,
       Find_ConnectionSucceeds) {
  StrictMock<MockBluetoothLowEnergyConnectionFinder> connection_finder(
      device_whitelist_.get());
  // Starting discovery.
  FindAndExpectStartDiscovery(connection_finder);
  ExpectStopDiscoveryAndRemoveObserver();

  // Finding and creating a connection to the right device.
  MockConnection* connection = connection_finder.ExpectCreateConnection();
  PrepareForNewRightDevice(kServiceUUID);
  connection_finder.DeviceAdded(adapter_.get(), device_.get());

  // Creating a connection.
  EXPECT_FALSE(last_found_connection_);
  connection->SetStatus(Connection::IN_PROGRESS);
  connection->SetStatus(Connection::CONNECTED);
  EXPECT_TRUE(last_found_connection_);
}

TEST_F(ProximityAuthBluetoothLowEnergyConnectionFinderTest,
       Find_ConnectionFails_RestartDiscoveryAndConnectionSucceeds) {
  StrictMock<MockBluetoothLowEnergyConnectionFinder> connection_finder(
      device_whitelist_.get());

  // Starting discovery.
  FindAndExpectStartDiscovery(connection_finder);
  base::Closure stop_discovery_session_callback;
  EXPECT_CALL(*last_discovery_session_alias_, Stop(_, _))
      .WillOnce(SaveArg<0>(&stop_discovery_session_callback));

  // Preparing to create a GATT connection to the right device.
  PrepareForNewRightDevice(kServiceUUID);
  MockConnection* connection = connection_finder.ExpectCreateConnection();

  // Trying to create a connection.
  connection_finder.DeviceAdded(adapter_.get(), device_.get());
  ASSERT_FALSE(last_found_connection_);
  connection->SetStatus(Connection::IN_PROGRESS);

  // Stopping the discovery session.
  ASSERT_FALSE(stop_discovery_session_callback.is_null());
  stop_discovery_session_callback.Run();

  // Preparing to restart the discovery session.
  device::BluetoothAdapter::DiscoverySessionCallback discovery_callback;
  std::vector<const device::BluetoothDevice*> devices;
  ON_CALL(*adapter_, GetDevices()).WillByDefault(Return(devices));
  EXPECT_CALL(*adapter_, StartDiscoverySessionWithFilterRaw(_, _, _))
      .WillOnce(SaveArg<1>(&discovery_callback));

  // Connection fails.
  connection->SetStatus(Connection::DISCONNECTED);

  // Restarting the discovery session.
  scoped_ptr<device::MockBluetoothDiscoverySession> discovery_session(
      new NiceMock<device::MockBluetoothDiscoverySession>());
  last_discovery_session_alias_ = discovery_session.get();
  ON_CALL(*last_discovery_session_alias_, IsActive())
      .WillByDefault(Return(true));
  ASSERT_FALSE(discovery_callback.is_null());
  discovery_callback.Run(discovery_session.Pass());

  // Preparing to create a GATT connection to the right device.
  PrepareForNewRightDevice(kServiceUUID);
  connection = connection_finder.ExpectCreateConnection();

  // Trying to create a connection.
  connection_finder.DeviceAdded(adapter_.get(), device_.get());
  EXPECT_CALL(*last_discovery_session_alias_, Stop(_, _)).Times(AtLeast(1));

  // Completing the connection.
  EXPECT_FALSE(last_found_connection_);
  connection->SetStatus(Connection::IN_PROGRESS);
  connection->SetStatus(Connection::CONNECTED);
  EXPECT_TRUE(last_found_connection_);
}

TEST_F(ProximityAuthBluetoothLowEnergyConnectionFinderTest,
       Find_AdapterRemoved_RestartDiscoveryAndConnectionSucceeds) {
  StrictMock<MockBluetoothLowEnergyConnectionFinder> connection_finder(
      device_whitelist_.get());

  // Starting discovery.
  FindAndExpectStartDiscovery(connection_finder);

  // Removing the adapter.
  ON_CALL(*adapter_, IsPresent()).WillByDefault(Return(false));
  ON_CALL(*adapter_, IsPowered()).WillByDefault(Return(false));
  ON_CALL(*last_discovery_session_alias_, IsActive())
      .WillByDefault(Return(false));
  connection_finder.AdapterPoweredChanged(adapter_.get(), false);
  connection_finder.AdapterPresentChanged(adapter_.get(), false);

  // Adding the adapter.
  ON_CALL(*adapter_, IsPresent()).WillByDefault(Return(true));
  ON_CALL(*adapter_, IsPowered()).WillByDefault(Return(true));

  device::BluetoothAdapter::DiscoverySessionCallback discovery_callback;
  scoped_ptr<device::MockBluetoothDiscoverySession> discovery_session(
      new NiceMock<device::MockBluetoothDiscoverySession>());
  last_discovery_session_alias_ = discovery_session.get();

  // Restarting the discovery session.
  EXPECT_CALL(*adapter_, StartDiscoverySessionWithFilterRaw(_, _, _))
      .WillOnce(SaveArg<1>(&discovery_callback));
  connection_finder.AdapterPresentChanged(adapter_.get(), true);
  connection_finder.AdapterPoweredChanged(adapter_.get(), true);
  ON_CALL(*last_discovery_session_alias_, IsActive())
      .WillByDefault(Return(true));

  ASSERT_FALSE(discovery_callback.is_null());
  discovery_callback.Run(discovery_session.Pass());

  // Preparing to create a GATT connection to the right device.
  PrepareForNewRightDevice(kServiceUUID);
  MockConnection* connection = connection_finder.ExpectCreateConnection();

  // Trying to create a connection.
  connection_finder.DeviceAdded(adapter_.get(), device_.get());
  EXPECT_CALL(*last_discovery_session_alias_, Stop(_, _)).Times(AtLeast(1));

  // Completing the connection.
  ASSERT_FALSE(last_found_connection_);
  connection->SetStatus(Connection::IN_PROGRESS);
  connection->SetStatus(Connection::CONNECTED);
  EXPECT_TRUE(last_found_connection_);
}

}  // namespace proximity_auth