• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2023 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 
15 // inclusive-language: disable
16 
17 #include "pw_bluetooth_sapphire/internal/host/gap/bredr_connection_manager.h"
18 
19 #include <cpp-string/string_printf.h>
20 
21 #include "pw_bluetooth_sapphire/internal/host/common/byte_buffer.h"
22 #include "pw_bluetooth_sapphire/internal/host/common/error.h"
23 #include "pw_bluetooth_sapphire/internal/host/gap/fake_pairing_delegate.h"
24 #include "pw_bluetooth_sapphire/internal/host/gap/peer_cache.h"
25 #include "pw_bluetooth_sapphire/internal/host/hci-spec/constants.h"
26 #include "pw_bluetooth_sapphire/internal/host/hci-spec/link_key.h"
27 #include "pw_bluetooth_sapphire/internal/host/hci-spec/protocol.h"
28 #include "pw_bluetooth_sapphire/internal/host/l2cap/fake_channel.h"
29 #include "pw_bluetooth_sapphire/internal/host/l2cap/fake_l2cap.h"
30 #include "pw_bluetooth_sapphire/internal/host/l2cap/l2cap_defs.h"
31 #include "pw_bluetooth_sapphire/internal/host/sdp/sdp.h"
32 #include "pw_bluetooth_sapphire/internal/host/sm/test_security_manager.h"
33 #include "pw_bluetooth_sapphire/internal/host/testing/controller_test.h"
34 #include "pw_bluetooth_sapphire/internal/host/testing/gtest_helpers.h"
35 #include "pw_bluetooth_sapphire/internal/host/testing/inspect.h"
36 #include "pw_bluetooth_sapphire/internal/host/testing/mock_controller.h"
37 #include "pw_bluetooth_sapphire/internal/host/testing/test_helpers.h"
38 #include "pw_bluetooth_sapphire/internal/host/testing/test_packets.h"
39 #include "pw_bluetooth_sapphire/internal/host/transport/error.h"
40 #include "pw_bluetooth_sapphire/internal/host/transport/fake_acl_connection.h"
41 
42 namespace bt::gap {
43 namespace {
44 
45 using namespace inspect::testing;
46 
47 using pw::bluetooth::emboss::AuthenticationRequirements;
48 using pw::bluetooth::emboss::IoCapability;
49 
50 using TestingBase =
51     bt::testing::FakeDispatcherControllerTest<bt::testing::MockController>;
52 
53 constexpr hci_spec::ConnectionHandle kConnectionHandle = 0x0BAA;
54 constexpr hci_spec::ConnectionHandle kConnectionHandle2 = 0x0BAB;
55 const DeviceAddress kLocalDevLEAddr(DeviceAddress::Type::kLEPublic, {0});
56 const DeviceAddress kLocalDevAddr(DeviceAddress::Type::kBREDR, {0});
57 const DeviceAddress kTestDevAddr(DeviceAddress::Type::kBREDR, {1});
58 const DeviceAddress kTestDevAddrLe(DeviceAddress::Type::kLEPublic, {2});
59 const DeviceAddress kTestDevAddr2(DeviceAddress::Type::kBREDR, {3});
60 const UInt128 kIrk{{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}};
61 constexpr uint32_t kPasskey = 123456;
62 constexpr uint16_t kDefaultPinCode = 0000;
63 const hci_spec::LinkKey kRawKey({0xc0,
64                                  0xde,
65                                  0xfa,
66                                  0x57,
67                                  0x4b,
68                                  0xad,
69                                  0xf0,
70                                  0x0d,
71                                  0xa7,
72                                  0x60,
73                                  0x06,
74                                  0x1e,
75                                  0xca,
76                                  0x1e,
77                                  0xca,
78                                  0xfe},
79                                 0,
80                                 0);
81 const hci_spec::LinkKey kChangedKey({0xfa,
82                                      0xce,
83                                      0xb0,
84                                      0x0c,
85                                      0xa5,
86                                      0x1c,
87                                      0xcd,
88                                      0x15,
89                                      0xea,
90                                      0x5e,
91                                      0xfe,
92                                      0xdb,
93                                      0x1d,
94                                      0x0d,
95                                      0x0a,
96                                      0xd5},
97                                     0,
98                                     0);
99 const hci_spec::LinkKey kLegacyKey({0x41,
100                                     0x33,
101                                     0x7c,
102                                     0x0d,
103                                     0xef,
104                                     0xee,
105                                     0xda,
106                                     0xda,
107                                     0xba,
108                                     0xad,
109                                     0x0f,
110                                     0xf1,
111                                     0xce,
112                                     0xc0,
113                                     0xff,
114                                     0xee},
115                                    0,
116                                    0);
117 const sm::LTK kLinkKey(
118     sm::SecurityProperties(hci_spec::LinkKeyType::kAuthenticatedCombination192),
119     kRawKey);
120 const bt::sm::LTK kLELtk(sm::SecurityProperties(/*encrypted=*/true,
121                                                 /*authenticated=*/true,
122                                                 /*secure_connections=*/true,
123                                                 sm::kMaxEncryptionKeySize),
124                          hci_spec::LinkKey(UInt128{4}, 5, 6));
125 
126 constexpr BrEdrSecurityRequirements kNoSecurityRequirements{
127     .authentication = false, .secure_connections = false};
128 constexpr BrEdrSecurityRequirements kAuthSecurityRequirements{
129     .authentication = true, .secure_connections = false};
130 
131 // A default size for PDUs when generating responses for testing.
132 const uint16_t PDU_MAX = 0xFFF;
133 
134 const DeviceAddress TEST_DEV_ADDR(DeviceAddress::Type::kLEPublic,
135                                   {0x01, 0x00, 0x00, 0x00, 0x00, 0x00});
136 
137 const auto kReadScanEnable = testing::ReadScanEnable();
138 const auto kReadScanEnableRspNone = testing::ReadScanEnableResponse(0x00);
139 const auto kReadScanEnableRspInquiry = testing::ReadScanEnableResponse(0x01);
140 const auto kReadScanEnableRspPage = testing::ReadScanEnableResponse(0x02);
141 const auto kReadScanEnableRspBoth = testing::ReadScanEnableResponse(0x03);
142 
143 const auto kWriteScanEnableNone = testing::WriteScanEnable(0x00);
144 const auto kWriteScanEnableInq = testing::WriteScanEnable(0x01);
145 const auto kWriteScanEnablePage = testing::WriteScanEnable(0x02);
146 const auto kWriteScanEnableBoth = testing::WriteScanEnable(0x03);
147 const auto kWriteScanEnableRsp =
148     testing::CommandCompletePacket(hci_spec::kWriteScanEnable);
149 
150 #define COMMAND_COMPLETE_RSP(opcode)                    \
151   StaticByteBuffer(hci_spec::kCommandCompleteEventCode, \
152                    0x04,                                \
153                    0xF0,                                \
154                    LowerBits((opcode)),                 \
155                    UpperBits((opcode)),                 \
156                    pw::bluetooth::emboss::StatusCode::SUCCESS)
157 
158 const uint16_t kScanInterval = 0x0800;  // 1280 ms
159 const uint16_t kScanWindow = 0x0011;    // 10.625 ms
160 const auto kWritePageScanActivity =
161     testing::WritePageScanActivityPacket(kScanInterval, kScanWindow);
162 const auto kWritePageScanActivityRsp =
163     testing::CommandCompletePacket(hci_spec::kWritePageScanActivity);
164 
165 const uint8_t kScanType = 0x01;  // Interlaced scan
166 const auto kWritePageScanType = testing::WritePageScanTypePacket(kScanType);
167 const auto kWritePageScanTypeRsp =
168     testing::CommandCompletePacket(hci_spec::kWritePageScanType);
169 
170 #define COMMAND_STATUS_RSP(opcode, statuscode)        \
171   StaticByteBuffer(hci_spec::kCommandStatusEventCode, \
172                    0x04,                              \
173                    (statuscode),                      \
174                    0xF0,                              \
175                    LowerBits((opcode)),               \
176                    UpperBits((opcode)))
177 
178 const auto kWritePageTimeoutRsp =
179     COMMAND_COMPLETE_RSP(hci_spec::kWritePageTimeout);
180 
181 const auto kWritePinTypeRsp =
182     testing::CommandCompletePacket(hci_spec::kWritePinType);
183 
184 const auto kConnectionRequest = testing::ConnectionRequestPacket(kTestDevAddr);
185 
186 const auto kAcceptConnectionRequest =
187     testing::AcceptConnectionRequestPacket(kTestDevAddr);
188 
189 const auto kAcceptConnectionRequestRsp =
190     testing::CommandStatusPacket(hci_spec::kAcceptConnectionRequest);
191 
192 const auto kConnectionComplete =
193     testing::ConnectionCompletePacket(kTestDevAddr, kConnectionHandle);
194 
195 const auto kConnectionCompletePageTimeout = testing::ConnectionCompletePacket(
196     kTestDevAddr,
197     kConnectionHandle,
198     pw::bluetooth::emboss::StatusCode::PAGE_TIMEOUT);
199 
200 const auto kConnectionCompleteError = testing::ConnectionCompletePacket(
201     TEST_DEV_ADDR,
202     0x0000,
203     pw::bluetooth::emboss::StatusCode::CONNECTION_FAILED_TO_BE_ESTABLISHED);
204 
205 const auto kConnectionCompleteCanceled = testing::ConnectionCompletePacket(
206     TEST_DEV_ADDR,
207     0x0000,
208     pw::bluetooth::emboss::StatusCode::UNKNOWN_CONNECTION_ID);
209 
210 const auto kCreateConnection = testing::CreateConnectionPacket(TEST_DEV_ADDR);
211 
212 const auto kCreateConnectionRsp = COMMAND_STATUS_RSP(
213     hci_spec::kCreateConnection, pw::bluetooth::emboss::StatusCode::SUCCESS);
214 
215 const auto kCreateConnectionRspError = COMMAND_STATUS_RSP(
216     hci_spec::kCreateConnection,
217     pw::bluetooth::emboss::StatusCode::CONNECTION_FAILED_TO_BE_ESTABLISHED);
218 
219 const auto kCreateConnectionCancel =
220     testing::CreateConnectionCancelPacket(TEST_DEV_ADDR);
221 
222 const auto kCreateConnectionCancelRsp =
223     testing::CommandCompletePacket(hci_spec::kCreateConnectionCancel);
224 
225 const auto kRemoteNameRequest = testing::RemoteNameRequestPacket(TEST_DEV_ADDR);
226 const auto kRemoteNameRequestRsp = COMMAND_STATUS_RSP(
227     hci_spec::kRemoteNameRequest, pw::bluetooth::emboss::StatusCode::SUCCESS);
228 
229 const auto kRemoteNameRequestComplete =
230     testing::RemoteNameRequestCompletePacket(
231         kTestDevAddr,
232         {'F',    'u',    'c',    'h',    's',    'i',    'a',    '\xF0', '\x9F',
233          '\x92', '\x96', '\x00', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19',
234          '\x1a', '\x1b', '\x1c', '\x1d', '\x1e', '\x1f', '\x20'}
235         // remote name (Fuchsia��)
236         // Everything after the 0x00 should be ignored.
237     );
238 const StaticByteBuffer kReadRemoteVersionInfo(
239     LowerBits(hci_spec::kReadRemoteVersionInfo),
240     UpperBits(hci_spec::kReadRemoteVersionInfo),
241     0x02,  // Parameter_total_size (2 bytes)
242     0xAA,
243     0x0B  // connection_handle
244 );
245 
246 const auto kReadRemoteVersionInfoRsp =
247     COMMAND_STATUS_RSP(hci_spec::kReadRemoteVersionInfo,
248                        pw::bluetooth::emboss::StatusCode::SUCCESS);
249 
250 const auto kRemoteVersionInfoComplete = StaticByteBuffer(
251     hci_spec::kReadRemoteVersionInfoCompleteEventCode,
252     0x08,  // parameter_total_size (8 bytes)
253     pw::bluetooth::emboss::StatusCode::SUCCESS,  // status
254     0xAA,
255     0x0B,                                                   // connection_handle
256     pw::bluetooth::emboss::CoreSpecificationVersion::V4_2,  // version
257     0xE0,
258     0x00,  // company_identifier (Google)
259     0xAD,
260     0xDE  // subversion (anything)
261 );
262 
263 const auto kReadRemoteSupportedFeaturesRsp =
264     COMMAND_STATUS_RSP(hci_spec::kReadRemoteSupportedFeatures,
265                        pw::bluetooth::emboss::StatusCode::SUCCESS);
266 
267 const auto kReadRemoteSupportedFeaturesComplete =
268     StaticByteBuffer(hci_spec::kReadRemoteSupportedFeaturesCompleteEventCode,
269                      0x0B,  // parameter_total_size (11 bytes)
270                      pw::bluetooth::emboss::StatusCode::SUCCESS,  // status
271                      0xAA,
272                      0x0B,  // connection_handle,
273                      0xFF,
274                      0x00,
275                      0x00,
276                      0x00,
277                      0x40,
278                      0x00,
279                      0x08,
280                      0x80
281                      // lmp_features_page0: 3 slot packets, 5 slot packets,
282                      // Encryption, Slot Offset, Timing Accuracy, Role Switch,
283                      // Hold Mode, Sniff Mode, Secure Simple Pairing (Controller
284                      // Support), LE Supported, Extended Features
285     );
286 
287 const auto kReadRemoteExtended1 =
288     StaticByteBuffer(LowerBits(hci_spec::kReadRemoteExtendedFeatures),
289                      UpperBits(hci_spec::kReadRemoteExtendedFeatures),
290                      0x03,  // parameter_total_size (3 bytes)
291                      0xAA,
292                      0x0B,  // connection_handle
293                      0x01   // page_number (1)
294     );
295 
296 const auto kReadRemoteExtendedFeaturesRsp =
297     COMMAND_STATUS_RSP(hci_spec::kReadRemoteExtendedFeatures,
298                        pw::bluetooth::emboss::StatusCode::SUCCESS);
299 
300 const auto kReadRemoteExtended1Complete =
301     testing::ReadRemoteExtended1CompletePacket(kConnectionHandle);
302 
303 const auto kReadRemoteExtended1CompleteNoSsp =
304     testing::ReadRemoteExtended1CompletePacketNoSsp(kConnectionHandle);
305 
306 const auto kReadRemoteExtended2 =
307     StaticByteBuffer(LowerBits(hci_spec::kReadRemoteExtendedFeatures),
308                      UpperBits(hci_spec::kReadRemoteExtendedFeatures),
309                      0x03,  // parameter_total_size (3 bytes)
310                      0xAA,
311                      0x0B,  // connection_handle
312                      0x02   // page_number (2)
313     );
314 
315 const auto kReadRemoteExtended2Complete =
316     StaticByteBuffer(hci_spec::kReadRemoteExtendedFeaturesCompleteEventCode,
317                      0x0D,  // parameter_total_size (13 bytes)
318                      pw::bluetooth::emboss::StatusCode::SUCCESS,  // status
319                      0xAA,
320                      0x0B,  // connection_handle,
321                      0x02,  // page_number
322                      0x02,  // max_page_number
323                      0x00,
324                      0x00,
325                      0x00,
326                      0x00,
327                      0x02,
328                      0x00,
329                      0xFF,
330                      0x00
331                      // lmp_features_page2  - All the bits should be ignored.
332     );
333 
334 const auto kDisconnect = testing::DisconnectPacket(kConnectionHandle);
335 
336 const auto kDisconnectRsp = COMMAND_STATUS_RSP(
337     hci_spec::kDisconnect, pw::bluetooth::emboss::StatusCode::SUCCESS);
338 
339 const auto kDisconnectionComplete = testing::DisconnectionCompletePacket(
340     kConnectionHandle,
341     pw::bluetooth::emboss::StatusCode::REMOTE_USER_TERMINATED_CONNECTION);
342 
343 const auto kAuthenticationRequested =
344     testing::AuthenticationRequestedPacket(kConnectionHandle);
345 
346 const auto kAuthenticationRequestedStatus =
347     COMMAND_STATUS_RSP(hci_spec::kAuthenticationRequested,
348                        pw::bluetooth::emboss::StatusCode::SUCCESS);
349 
350 const auto kAuthenticationComplete =
351     StaticByteBuffer(hci_spec::kAuthenticationCompleteEventCode,
352                      0x03,  // parameter_total_size (3 bytes)
353                      pw::bluetooth::emboss::StatusCode::SUCCESS,  // status
354                      0xAA,
355                      0x0B  // connection_handle
356     );
357 
358 const auto kAuthenticationCompleteFailed = StaticByteBuffer(
359     hci_spec::kAuthenticationCompleteEventCode,
360     0x03,  // parameter_total_size (3 bytes)
361     pw::bluetooth::emboss::StatusCode::PAIRING_NOT_ALLOWED,  // status
362     0xAA,
363     0x0B  // connection_handle
364 );
365 
366 const auto kLinkKeyRequest = testing::LinkKeyRequestPacket(TEST_DEV_ADDR);
367 
368 const auto kLinkKeyRequestNegativeReply =
369     testing::LinkKeyRequestNegativeReplyPacket(TEST_DEV_ADDR);
370 
371 const auto kLinkKeyRequestNegativeReplyRsp =
372     testing::LinkKeyRequestNegativeReplyResponse(TEST_DEV_ADDR);
373 
MakeIoCapabilityResponse(IoCapability io_cap,AuthenticationRequirements auth_req)374 DynamicByteBuffer MakeIoCapabilityResponse(
375     IoCapability io_cap, AuthenticationRequirements auth_req) {
376   return testing::IoCapabilityResponsePacket(TEST_DEV_ADDR, io_cap, auth_req);
377 }
378 
379 const auto kIoCapabilityRequest =
380     testing::IoCapabilityRequestPacket(TEST_DEV_ADDR);
381 
MakeIoCapabilityRequestReply(IoCapability io_cap,AuthenticationRequirements auth_req)382 DynamicByteBuffer MakeIoCapabilityRequestReply(
383     IoCapability io_cap, AuthenticationRequirements auth_req) {
384   return testing::IoCapabilityRequestReplyPacket(
385       TEST_DEV_ADDR, io_cap, auth_req);
386 }
387 
388 const auto kIoCapabilityRequestReplyRsp =
389     testing::IoCapabilityRequestReplyResponse(TEST_DEV_ADDR);
390 
391 const auto kIoCapabilityRequestNegativeReply =
392     testing::IoCapabilityRequestNegativeReplyPacket(
393         TEST_DEV_ADDR, pw::bluetooth::emboss::StatusCode::PAIRING_NOT_ALLOWED);
394 
395 const auto kIoCapabilityRequestNegativeReplyRsp =
396     testing::IoCapabilityRequestNegativeReplyResponse(TEST_DEV_ADDR);
397 
MakeUserConfirmationRequest(uint32_t)398 DynamicByteBuffer MakeUserConfirmationRequest(uint32_t) {
399   return testing::UserConfirmationRequestPacket(TEST_DEV_ADDR, kPasskey);
400 }
401 
402 const auto kUserConfirmationRequestReply =
403     testing::UserConfirmationRequestReplyPacket(TEST_DEV_ADDR);
404 
405 const auto kUserConfirmationRequestReplyRsp =
406     COMMAND_COMPLETE_RSP(hci_spec::kUserConfirmationRequestReply);
407 
408 const auto kUserConfirmationRequestNegativeReply =
409     testing::UserConfirmationRequestNegativeReplyPacket(TEST_DEV_ADDR);
410 
411 const auto kUserConfirmationRequestNegativeReplyRsp =
412     COMMAND_COMPLETE_RSP(hci_spec::kUserConfirmationRequestNegativeReply);
413 
414 const auto kSimplePairingCompleteSuccess = testing::SimplePairingCompletePacket(
415     TEST_DEV_ADDR, pw::bluetooth::emboss::StatusCode::SUCCESS);
416 
417 const auto kSimplePairingCompleteError = testing::SimplePairingCompletePacket(
418     TEST_DEV_ADDR, pw::bluetooth::emboss::StatusCode::AUTHENTICATION_FAILURE);
419 
420 const auto kPinCodeRequest = testing::PinCodeRequestPacket(TEST_DEV_ADDR);
421 const auto kPinCodeRequestReply = testing::PinCodeRequestReplyPacket(
422     TEST_DEV_ADDR, /*pin_length=*/4, std::to_string(kDefaultPinCode));
423 const auto kPinCodeRequestReplyRsp =
424     testing::PinCodeRequestReplyResponse(TEST_DEV_ADDR);
425 const auto kPinCodeRequestNegativeReply =
426     testing::PinCodeRequestNegativeReplyPacket(TEST_DEV_ADDR);
427 const auto kPinCodeRequestNegativeReplyRsp =
428     testing::PinCodeRequestNegativeReplyResponse(TEST_DEV_ADDR);
429 
MakeLinkKeyNotification(hci_spec::LinkKeyType key_type)430 DynamicByteBuffer MakeLinkKeyNotification(hci_spec::LinkKeyType key_type) {
431   return testing::LinkKeyNotificationPacket(
432       TEST_DEV_ADDR, kRawKey.value(), key_type);
433 }
434 
435 const auto kLinkKeyNotificationLegacy = testing::LinkKeyNotificationPacket(
436     TEST_DEV_ADDR, kLegacyKey.value(), hci_spec::LinkKeyType::kCombination);
437 
438 const auto kLinkKeyNotification = MakeLinkKeyNotification(
439     hci_spec::LinkKeyType::kAuthenticatedCombination192);
440 
441 const auto kLinkKeyRequestReply =
442     testing::LinkKeyRequestReplyPacket(TEST_DEV_ADDR, kRawKey.value());
443 
444 const auto kLinkKeyRequestReplyRsp =
445     testing::LinkKeyRequestReplyResponse(TEST_DEV_ADDR);
446 
447 const auto kLinkKeyNotificationChanged = testing::LinkKeyNotificationPacket(
448     TEST_DEV_ADDR,
449     kChangedKey.value(),
450     hci_spec::LinkKeyType::kChangedCombination);
451 
452 const StaticByteBuffer kSetConnectionEncryption(
453     LowerBits(hci_spec::kSetConnectionEncryption),
454     UpperBits(hci_spec::kSetConnectionEncryption),
455     0x03,  // parameter total size
456     0xAA,
457     0x0B,  // connection handle
458     0x01   // encryption enable
459 );
460 
461 const auto kSetConnectionEncryptionRsp =
462     COMMAND_STATUS_RSP(hci_spec::kSetConnectionEncryption,
463                        pw::bluetooth::emboss::StatusCode::SUCCESS);
464 
465 const StaticByteBuffer kEncryptionChangeEvent(
466     hci_spec::kEncryptionChangeEventCode,
467     4,     // parameter total size
468     0x00,  // status
469     0xAA,
470     0x0B,  // connection handle
471     0x01   // encryption enabled: E0 for BR/EDR or AES-CCM for LE
472 );
473 
474 const StaticByteBuffer kReadEncryptionKeySize(
475     LowerBits(hci_spec::kReadEncryptionKeySize),
476     UpperBits(hci_spec::kReadEncryptionKeySize),
477     0x02,  // parameter size
478     0xAA,
479     0x0B  // connection handle
480 );
481 
482 const StaticByteBuffer kReadEncryptionKeySizeRsp(
483     hci_spec::kCommandCompleteEventCode,
484     0x07,  // parameters total size
485     0xFF,  // num command packets allowed (255)
486     LowerBits(hci_spec::kReadEncryptionKeySize),
487     UpperBits(hci_spec::kReadEncryptionKeySize),
488     pw::bluetooth::emboss::StatusCode::SUCCESS,  // status
489     0xAA,
490     0x0B,  // connection handle
491     0x10   // encryption key size: 16
492 );
493 
MakeUserPasskeyRequestReply()494 DynamicByteBuffer MakeUserPasskeyRequestReply() {
495   return testing::UserPasskeyRequestReplyPacket(TEST_DEV_ADDR, kPasskey);
496 }
497 
498 const auto kUserPasskeyRequestReplyRsp =
499     testing::UserPasskeyRequestReplyResponse(TEST_DEV_ADDR);
500 
MakeUserPasskeyNotification(uint32_t)501 DynamicByteBuffer MakeUserPasskeyNotification(uint32_t) {
502   return testing::UserPasskeyNotificationPacket(TEST_DEV_ADDR, kPasskey);
503 }
504 
505 const hci::DataBufferInfo kBrEdrBufferInfo(1024, 1);
506 const hci::DataBufferInfo kLeBufferInfo(1024, 1);
507 
508 constexpr l2cap::ChannelParameters kChannelParams;
509 
IsInitializing(Peer * peer)510 ::testing::AssertionResult IsInitializing(Peer* peer) {
511   if (Peer::ConnectionState::kInitializing !=
512       peer->bredr()->connection_state()) {
513     return ::testing::AssertionFailure()
514            << "Expected peer connection_state: kInitializing, found "
515            << Peer::ConnectionStateToString(peer->bredr()->connection_state());
516   }
517   return ::testing::AssertionSuccess()
518          << "Peer connection state is kInitializing";
519 }
IsConnected(Peer * peer)520 ::testing::AssertionResult IsConnected(Peer* peer) {
521   if (Peer::ConnectionState::kConnected != peer->bredr()->connection_state()) {
522     return ::testing::AssertionFailure()
523            << "Expected peer to be in a connected state: kConnected, found "
524            << Peer::ConnectionStateToString(peer->bredr()->connection_state());
525   }
526   if (peer->temporary()) {
527     return ::testing::AssertionFailure()
528            << "Expected peer to be non-temporary, but found temporary";
529   }
530   return ::testing::AssertionSuccess() << "Peer connection state is kConnected";
531 }
IsNotConnected(Peer * peer)532 ::testing::AssertionResult IsNotConnected(Peer* peer) {
533   if (Peer::ConnectionState::kNotConnected !=
534       peer->bredr()->connection_state()) {
535     return ::testing::AssertionFailure()
536            << "Expected peer connection_state: kNotConnected, found "
537            << Peer::ConnectionStateToString(peer->bredr()->connection_state());
538   }
539   return ::testing::AssertionSuccess()
540          << "Peer connection state is kNotConnected";
541   ;
542 }
543 
HasConnectionTo(Peer * peer,BrEdrConnection * conn)544 ::testing::AssertionResult HasConnectionTo(Peer* peer, BrEdrConnection* conn) {
545   if (!conn) {
546     return ::testing::AssertionFailure()
547            << "Expected BrEdrConnection, but found nullptr";
548   }
549   if (peer->identifier() != conn->peer_id()) {
550     return ::testing::AssertionFailure()
551            << "Expected connection peer_id " << peer->identifier()
552            << " but found " << conn->peer_id();
553   }
554   return ::testing::AssertionSuccess() << "Peer " << peer->identifier()
555                                        << " connected to the connection given";
556 }
557 
558 #define CALLBACK_EXPECT_FAILURE(status_param)       \
559   ([&status_param](auto cb_status, auto conn_ref) { \
560     EXPECT_FALSE(conn_ref);                         \
561     status_param = cb_status;                       \
562   })
563 
564 class BrEdrConnectionManagerTest : public TestingBase,
565                                    public hci::LocalAddressDelegate {
566  public:
567   BrEdrConnectionManagerTest() = default;
568   ~BrEdrConnectionManagerTest() override = default;
569 
SetUp()570   void SetUp() override {
571     TestingBase::SetUp();
572     InitializeACLDataChannel(kBrEdrBufferInfo, kLeBufferInfo);
573 
574     peer_cache_ = std::make_unique<PeerCache>(dispatcher());
575     l2cap_ = std::make_unique<l2cap::testing::FakeL2cap>(dispatcher());
576 
577     // Respond to BrEdrConnectionManager controller setup with success.
578     EXPECT_CMD_PACKET_OUT(test_device(),
579                           testing::WritePageTimeoutPacket(static_cast<uint16_t>(
580                               pw::bluetooth::emboss::PageTimeout::DEFAULT)),
581                           &kWritePageTimeoutRsp);
582     EXPECT_CMD_PACKET_OUT(test_device(),
583                           testing::WritePinTypePacket(static_cast<uint8_t>(
584                               pw::bluetooth::emboss::PinType::VARIABLE)),
585                           &kWritePinTypeRsp);
586 
587     connection_manager_ = std::make_unique<BrEdrConnectionManager>(
588         transport()->GetWeakPtr(),
589         peer_cache_.get(),
590         kLocalDevAddr,
591         /*low_energy_address_delegate=*/this,
592         l2cap_.get(),
593         /*use_interlaced_scan=*/true,
594         /*local_secure_connections_supported=*/true,
595         /*legacy_pairing_enabled=*/false,
596         /*controller_remote_public_key_validation_supported=*/true,
597         fit::bind_member<&sm::testing::TestSecurityManagerFactory::CreateBrEdr>(
598             &security_manager_factory_),
599         dispatcher());
600 
601     RunUntilIdle();
602 
603     test_device()->SetTransactionCallback([this] { transaction_count_++; });
604   }
605 
TearDown()606   void TearDown() override {
607     int expected_transaction_count = transaction_count();
608     if (connection_manager_ != nullptr) {
609       expected_transaction_count += 2;
610       // deallocating the connection manager disables connectivity.
611       EXPECT_CMD_PACKET_OUT(
612           test_device(), kReadScanEnable, &kReadScanEnableRspBoth);
613       EXPECT_CMD_PACKET_OUT(
614           test_device(), kWriteScanEnableInq, &kWriteScanEnableRsp);
615       connection_manager_ = nullptr;
616     }
617     RunUntilIdle();
618     // A disconnection may also occur for a queued disconnection, allow up to 1
619     // extra transaction.
620     EXPECT_LE(expected_transaction_count, transaction_count());
621     EXPECT_GE(expected_transaction_count + 1, transaction_count());
622     // Don't trigger the transaction callback for the rest.
623     test_device()->ClearTransactionCallback();
624     test_device()->Stop();
625     l2cap_ = nullptr;
626     peer_cache_ = nullptr;
627     TestingBase::TearDown();
628   }
629 
inspector()630   inspect::Inspector inspector() { return inspector_; }
631 
632  protected:
633   static constexpr const int kShortInterrogationTransactions = 3;
634   static constexpr const int kInterrogationTransactions =
635       kShortInterrogationTransactions + 2;
636   static constexpr const int kIncomingConnTransactions =
637       1 + kInterrogationTransactions;
638   static constexpr const int kDisconnectionTransactions = 1;
639   // Currently unused, for reference:
640   // static constexpr const int kIncomingConnShortTransactions = 1 +
641   // kShortInterrogationTransactions;
642 
connmgr() const643   BrEdrConnectionManager* connmgr() const { return connection_manager_.get(); }
SetConnectionManager(std::unique_ptr<BrEdrConnectionManager> mgr)644   void SetConnectionManager(std::unique_ptr<BrEdrConnectionManager> mgr) {
645     connection_manager_ = std::move(mgr);
646   }
647 
peer_cache() const648   PeerCache* peer_cache() const { return peer_cache_.get(); }
649 
l2cap() const650   l2cap::testing::FakeL2cap* l2cap() const { return l2cap_.get(); }
651 
transaction_count() const652   int transaction_count() const { return transaction_count_; }
653 
654   // Expect an incoming connection that is accepted.
QueueSuccessfulAccept(DeviceAddress addr=kTestDevAddr,hci_spec::ConnectionHandle handle=kConnectionHandle,std::optional<pw::bluetooth::emboss::ConnectionRole> role_change=std::nullopt) const655   void QueueSuccessfulAccept(
656       DeviceAddress addr = kTestDevAddr,
657       hci_spec::ConnectionHandle handle = kConnectionHandle,
658       std::optional<pw::bluetooth::emboss::ConnectionRole> role_change =
659           std::nullopt) const {
660     const auto connection_complete =
661         testing::ConnectionCompletePacket(addr, handle);
662     if (role_change) {
663       const auto role_change_event =
664           testing::RoleChangePacket(addr, role_change.value());
665       EXPECT_CMD_PACKET_OUT(test_device(),
666                             testing::AcceptConnectionRequestPacket(addr),
667                             &kAcceptConnectionRequestRsp,
668                             &role_change_event,
669                             &connection_complete);
670     } else {
671       EXPECT_CMD_PACKET_OUT(test_device(),
672                             testing::AcceptConnectionRequestPacket(addr),
673                             &kAcceptConnectionRequestRsp,
674                             &connection_complete);
675     }
676   }
677 
678   // Add expectations and simulated responses for the outbound commands sent
679   // after an inbound Connection Request Event is received, for a peer that is
680   // already interrogated. Results in kIncomingConnShortTransactions
681   // transaction.
QueueRepeatIncomingConn(DeviceAddress addr=kTestDevAddr,hci_spec::ConnectionHandle handle=kConnectionHandle,std::optional<pw::bluetooth::emboss::ConnectionRole> role_change=std::nullopt) const682   void QueueRepeatIncomingConn(
683       DeviceAddress addr = kTestDevAddr,
684       hci_spec::ConnectionHandle handle = kConnectionHandle,
685       std::optional<pw::bluetooth::emboss::ConnectionRole> role_change =
686           std::nullopt) const {
687     QueueSuccessfulAccept(addr, handle, role_change);
688     QueueShortInterrogation(handle);
689   }
690 
691   // Add expectations and simulated responses for the outbound commands sent
692   // after an inbound Connection Request Event is received, for a peer that is
693   // already interrogated.
694   //  Results in |kIncomingConnTransactions| transactions.
QueueSuccessfulIncomingConn(DeviceAddress addr=kTestDevAddr,hci_spec::ConnectionHandle handle=kConnectionHandle,std::optional<pw::bluetooth::emboss::ConnectionRole> role_change=std::nullopt) const695   void QueueSuccessfulIncomingConn(
696       DeviceAddress addr = kTestDevAddr,
697       hci_spec::ConnectionHandle handle = kConnectionHandle,
698       std::optional<pw::bluetooth::emboss::ConnectionRole> role_change =
699           std::nullopt) const {
700     QueueSuccessfulAccept(addr, handle, role_change);
701     QueueSuccessfulInterrogation(addr, handle);
702   }
703 
QueueSuccessfulCreateConnection(Peer * peer,hci_spec::ConnectionHandle conn) const704   void QueueSuccessfulCreateConnection(Peer* peer,
705                                        hci_spec::ConnectionHandle conn) const {
706     const DynamicByteBuffer complete_packet =
707         testing::ConnectionCompletePacket(peer->address(), conn);
708     EXPECT_CMD_PACKET_OUT(test_device(),
709                           testing::CreateConnectionPacket(peer->address()),
710                           &kCreateConnectionRsp,
711                           &complete_packet);
712   }
713 
QueueShortInterrogation(hci_spec::ConnectionHandle conn) const714   void QueueShortInterrogation(hci_spec::ConnectionHandle conn) const {
715     const DynamicByteBuffer remote_extended1_complete_packet =
716         testing::ReadRemoteExtended1CompletePacket(conn);
717     const DynamicByteBuffer remote_extended2_complete_packet =
718         testing::ReadRemoteExtended2CompletePacket(conn);
719     EXPECT_CMD_PACKET_OUT(test_device(),
720                           testing::ReadRemoteExtended1Packet(conn),
721                           &kReadRemoteExtendedFeaturesRsp,
722                           &remote_extended1_complete_packet);
723     EXPECT_CMD_PACKET_OUT(test_device(),
724                           testing::ReadRemoteExtended2Packet(conn),
725                           &kReadRemoteExtendedFeaturesRsp,
726                           &remote_extended2_complete_packet);
727   }
728 
QueueSuccessfulInterrogation(DeviceAddress addr,hci_spec::ConnectionHandle conn) const729   void QueueSuccessfulInterrogation(DeviceAddress addr,
730                                     hci_spec::ConnectionHandle conn) const {
731     const DynamicByteBuffer remote_name_complete_packet =
732         testing::RemoteNameRequestCompletePacket(addr);
733     const DynamicByteBuffer remote_version_complete_packet =
734         testing::ReadRemoteVersionInfoCompletePacket(conn);
735     const DynamicByteBuffer remote_supported_complete_packet =
736         testing::ReadRemoteSupportedFeaturesCompletePacket(
737             conn, /*extended_features=*/true);
738 
739     EXPECT_CMD_PACKET_OUT(test_device(),
740                           testing::RemoteNameRequestPacket(addr),
741                           &kRemoteNameRequestRsp,
742                           &remote_name_complete_packet);
743     EXPECT_CMD_PACKET_OUT(test_device(),
744                           testing::ReadRemoteVersionInfoPacket(conn),
745                           &kReadRemoteVersionInfoRsp,
746                           &remote_version_complete_packet);
747     EXPECT_CMD_PACKET_OUT(test_device(),
748                           testing::ReadRemoteSupportedFeaturesPacket(conn),
749                           &kReadRemoteSupportedFeaturesRsp,
750                           &remote_supported_complete_packet);
751     QueueShortInterrogation(conn);
752   }
753 
QueueSuccessfulInterrogationNoSsp(DeviceAddress addr,hci_spec::ConnectionHandle conn) const754   void QueueSuccessfulInterrogationNoSsp(
755       DeviceAddress addr, hci_spec::ConnectionHandle conn) const {
756     const DynamicByteBuffer remote_name_complete_packet =
757         testing::RemoteNameRequestCompletePacket(addr);
758     const DynamicByteBuffer remote_version_complete_packet =
759         testing::ReadRemoteVersionInfoCompletePacket(conn);
760     const DynamicByteBuffer remote_supported_complete_packet =
761         testing::ReadRemoteSupportedFeaturesCompletePacket(
762             conn, /*extended_features=*/true);
763     const DynamicByteBuffer remote_extended1_complete_packet =
764         testing::ReadRemoteExtended1CompletePacketNoSsp(conn);
765 
766     EXPECT_CMD_PACKET_OUT(test_device(),
767                           testing::RemoteNameRequestPacket(addr),
768                           &kRemoteNameRequestRsp,
769                           &remote_name_complete_packet);
770     EXPECT_CMD_PACKET_OUT(test_device(),
771                           testing::ReadRemoteVersionInfoPacket(conn),
772                           &kReadRemoteVersionInfoRsp,
773                           &remote_version_complete_packet);
774     EXPECT_CMD_PACKET_OUT(test_device(),
775                           testing::ReadRemoteSupportedFeaturesPacket(conn),
776                           &kReadRemoteSupportedFeaturesRsp,
777                           &remote_supported_complete_packet);
778     EXPECT_CMD_PACKET_OUT(test_device(),
779                           testing::ReadRemoteExtended1Packet(conn),
780                           &kReadRemoteExtendedFeaturesRsp,
781                           &remote_extended1_complete_packet);
782     EXPECT_CMD_PACKET_OUT(test_device(),
783                           testing::ReadRemoteExtended2Packet(conn),
784                           &kReadRemoteExtendedFeaturesRsp,
785                           &remote_extended1_complete_packet);
786   }
787 
788   // Queue all interrogation packets except for the remote extended complete
789   // packet 2.
QueueIncompleteInterrogation(DeviceAddress addr,hci_spec::ConnectionHandle conn) const790   void QueueIncompleteInterrogation(DeviceAddress addr,
791                                     hci_spec::ConnectionHandle conn) const {
792     const DynamicByteBuffer remote_name_complete_packet =
793         testing::RemoteNameRequestCompletePacket(addr);
794     const DynamicByteBuffer remote_version_complete_packet =
795         testing::ReadRemoteVersionInfoCompletePacket(conn);
796     const DynamicByteBuffer remote_supported_complete_packet =
797         testing::ReadRemoteSupportedFeaturesCompletePacket(
798             conn, /*extended_features=*/true);
799     const DynamicByteBuffer remote_extended1_complete_packet =
800         testing::ReadRemoteExtended1CompletePacket(conn);
801 
802     EXPECT_CMD_PACKET_OUT(test_device(),
803                           testing::RemoteNameRequestPacket(addr),
804                           &kRemoteNameRequestRsp,
805                           &remote_name_complete_packet);
806     EXPECT_CMD_PACKET_OUT(test_device(),
807                           testing::ReadRemoteVersionInfoPacket(conn),
808                           &kReadRemoteVersionInfoRsp,
809                           &remote_version_complete_packet);
810     EXPECT_CMD_PACKET_OUT(test_device(),
811                           testing::ReadRemoteSupportedFeaturesPacket(conn),
812                           &kReadRemoteSupportedFeaturesRsp,
813                           &remote_supported_complete_packet);
814     EXPECT_CMD_PACKET_OUT(test_device(),
815                           testing::ReadRemoteExtended1Packet(conn),
816                           &kReadRemoteExtendedFeaturesRsp,
817                           &remote_extended1_complete_packet);
818     EXPECT_CMD_PACKET_OUT(test_device(),
819                           testing::ReadRemoteExtended2Packet(conn),
820                           &kReadRemoteExtendedFeaturesRsp);
821   }
822 
823   // Completes an interrogation started with QueueIncompleteInterrogation.
CompleteInterrogation(hci_spec::ConnectionHandle conn)824   void CompleteInterrogation(hci_spec::ConnectionHandle conn) {
825     const DynamicByteBuffer remote_extended2_complete_packet =
826         testing::ReadRemoteExtended2CompletePacket(conn);
827 
828     test_device()->SendCommandChannelPacket(remote_extended2_complete_packet);
829   }
830 
QueueSuccessfulPairing(hci_spec::LinkKeyType key_type=hci_spec::LinkKeyType::kAuthenticatedCombination192)831   void QueueSuccessfulPairing(
832       hci_spec::LinkKeyType key_type =
833           hci_spec::LinkKeyType::kAuthenticatedCombination192) {
834     EXPECT_CMD_PACKET_OUT(test_device(),
835                           kAuthenticationRequested,
836                           &kAuthenticationRequestedStatus,
837                           &kLinkKeyRequest);
838     EXPECT_CMD_PACKET_OUT(test_device(),
839                           kLinkKeyRequestNegativeReply,
840                           &kLinkKeyRequestNegativeReplyRsp,
841                           &kIoCapabilityRequest);
842     const auto kIoCapabilityResponse = MakeIoCapabilityResponse(
843         IoCapability::DISPLAY_YES_NO,
844         AuthenticationRequirements::MITM_GENERAL_BONDING);
845     const auto kUserConfirmationRequest = MakeUserConfirmationRequest(kPasskey);
846     EXPECT_CMD_PACKET_OUT(test_device(),
847                           MakeIoCapabilityRequestReply(
848                               IoCapability::DISPLAY_YES_NO,
849                               AuthenticationRequirements::MITM_GENERAL_BONDING),
850                           &kIoCapabilityRequestReplyRsp,
851                           &kIoCapabilityResponse,
852                           &kUserConfirmationRequest);
853     const auto kLinkKeyNotificationWithKeyType =
854         MakeLinkKeyNotification(key_type);
855     EXPECT_CMD_PACKET_OUT(test_device(),
856                           kUserConfirmationRequestReply,
857                           &kUserConfirmationRequestReplyRsp,
858                           &kSimplePairingCompleteSuccess,
859                           &kLinkKeyNotificationWithKeyType,
860                           &kAuthenticationComplete);
861     EXPECT_CMD_PACKET_OUT(test_device(),
862                           kSetConnectionEncryption,
863                           &kSetConnectionEncryptionRsp,
864                           &kEncryptionChangeEvent);
865     EXPECT_CMD_PACKET_OUT(
866         test_device(), kReadEncryptionKeySize, &kReadEncryptionKeySizeRsp);
867   }
868 
869   // Use when pairing with no IO, where authenticated pairing is not possible.
QueueSuccessfulUnauthenticatedPairing(hci_spec::LinkKeyType key_type=hci_spec::LinkKeyType::kUnauthenticatedCombination192)870   void QueueSuccessfulUnauthenticatedPairing(
871       hci_spec::LinkKeyType key_type =
872           hci_spec::LinkKeyType::kUnauthenticatedCombination192) {
873     EXPECT_CMD_PACKET_OUT(test_device(),
874                           kAuthenticationRequested,
875                           &kAuthenticationRequestedStatus,
876                           &kLinkKeyRequest);
877     EXPECT_CMD_PACKET_OUT(test_device(),
878                           kLinkKeyRequestNegativeReply,
879                           &kLinkKeyRequestNegativeReplyRsp,
880                           &kIoCapabilityRequest);
881     const auto kIoCapabilityReply = MakeIoCapabilityRequestReply(
882         IoCapability::NO_INPUT_NO_OUTPUT,
883         AuthenticationRequirements::GENERAL_BONDING);
884     const auto kIoCapabilityResponse =
885         MakeIoCapabilityResponse(IoCapability::NO_INPUT_NO_OUTPUT,
886                                  AuthenticationRequirements::GENERAL_BONDING);
887     const auto kUserConfirmationRequest = MakeUserConfirmationRequest(kPasskey);
888     EXPECT_CMD_PACKET_OUT(test_device(),
889                           kIoCapabilityReply,
890                           &kIoCapabilityRequestReplyRsp,
891                           &kIoCapabilityResponse,
892                           &kUserConfirmationRequest);
893     const auto kLinkKeyNotificationWithKeyType =
894         MakeLinkKeyNotification(key_type);
895     // User Confirmation Request Reply will be automatic due to no IO.
896     EXPECT_CMD_PACKET_OUT(test_device(),
897                           kUserConfirmationRequestReply,
898                           &kUserConfirmationRequestReplyRsp,
899                           &kSimplePairingCompleteSuccess,
900                           &kLinkKeyNotificationWithKeyType,
901                           &kAuthenticationComplete);
902     EXPECT_CMD_PACKET_OUT(test_device(),
903                           kSetConnectionEncryption,
904                           &kSetConnectionEncryptionRsp,
905                           &kEncryptionChangeEvent);
906     EXPECT_CMD_PACKET_OUT(
907         test_device(), kReadEncryptionKeySize, &kReadEncryptionKeySizeRsp);
908   }
909 
QueueDisconnection(hci_spec::ConnectionHandle conn,pw::bluetooth::emboss::StatusCode reason=pw::bluetooth::emboss::StatusCode::REMOTE_USER_TERMINATED_CONNECTION) const910   void QueueDisconnection(
911       hci_spec::ConnectionHandle conn,
912       pw::bluetooth::emboss::StatusCode reason =
913           pw::bluetooth::emboss::StatusCode::REMOTE_USER_TERMINATED_CONNECTION)
914       const {
915     const DynamicByteBuffer disconnect_complete =
916         testing::DisconnectionCompletePacket(conn, reason);
917     EXPECT_CMD_PACKET_OUT(test_device(),
918                           testing::DisconnectPacket(conn, reason),
919                           &kDisconnectRsp,
920                           &disconnect_complete);
921   }
922 
security_manager_factory()923   sm::testing::TestSecurityManagerFactory* security_manager_factory() {
924     return &security_manager_factory_;
925   }
926 
927  private:
irk() const928   std::optional<UInt128> irk() const override { return kIrk; }
identity_address() const929   DeviceAddress identity_address() const override { return kLocalDevLEAddr; }
EnsureLocalAddress(std::optional<DeviceAddress::Type>,AddressCallback)930   void EnsureLocalAddress(std::optional<DeviceAddress::Type>,
931                           AddressCallback) override {
932     ADD_FAILURE();
933   }
934 
935   sm::testing::TestSecurityManagerFactory security_manager_factory_;
936   std::unique_ptr<BrEdrConnectionManager> connection_manager_;
937   std::unique_ptr<PeerCache> peer_cache_;
938   std::unique_ptr<l2cap::testing::FakeL2cap> l2cap_;
939   int transaction_count_ = 0;
940 
941   inspect::Inspector inspector_;
942 
943   BT_DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(BrEdrConnectionManagerTest);
944 };
945 
946 class BrEdrConnectionManagerLegacyPairingTest
947     : public BrEdrConnectionManagerTest {
948  public:
SetUp()949   void SetUp() override {
950     TestingBase::SetUp();
951     InitializeACLDataChannel(kBrEdrBufferInfo, kLeBufferInfo);
952 
953     peer_cache_ = std::make_unique<PeerCache>(dispatcher());
954     l2cap_ = std::make_unique<l2cap::testing::FakeL2cap>(dispatcher());
955 
956     // Respond to BrEdrConnectionManager controller setup with success.
957     EXPECT_CMD_PACKET_OUT(test_device(),
958                           testing::WritePageTimeoutPacket(static_cast<uint16_t>(
959                               pw::bluetooth::emboss::PageTimeout::DEFAULT)),
960                           &kWritePageTimeoutRsp);
961     EXPECT_CMD_PACKET_OUT(test_device(),
962                           testing::WritePinTypePacket(static_cast<uint8_t>(
963                               pw::bluetooth::emboss::PinType::VARIABLE)),
964                           &kWritePinTypeRsp);
965 
966     connection_manager_ = std::make_unique<BrEdrConnectionManager>(
967         transport()->GetWeakPtr(),
968         peer_cache_.get(),
969         kLocalDevAddr,
970         /*low_energy_address_delegate=*/this,
971         l2cap_.get(),
972         /*use_interlaced_scan=*/true,
973         /*local_secure_connections_supported=*/true,
974         /*legacy_pairing_enabled=*/true,
975         /*controller_remote_public_key_validation_supported=*/true,
976         fit::bind_member<&sm::testing::TestSecurityManagerFactory::CreateBrEdr>(
977             security_manager_factory()),
978         dispatcher());
979 
980     RunUntilIdle();
981 
982     test_device()->SetTransactionCallback([this] { transaction_count_++; });
983   }
984 
TearDown()985   void TearDown() override {
986     int expected_transaction_count = transaction_count();
987     if (connection_manager_ != nullptr) {
988       expected_transaction_count += 2;
989       // deallocating the connection manager disables connectivity.
990       EXPECT_CMD_PACKET_OUT(
991           test_device(), kReadScanEnable, &kReadScanEnableRspBoth);
992       EXPECT_CMD_PACKET_OUT(
993           test_device(), kWriteScanEnableInq, &kWriteScanEnableRsp);
994       connection_manager_ = nullptr;
995     }
996     RunUntilIdle();
997     // A disconnection may also occur for a queued disconnection, allow up to 1
998     // extra transaction.
999     EXPECT_LE(expected_transaction_count, transaction_count());
1000     EXPECT_GE(expected_transaction_count + 1, transaction_count());
1001     // Don't trigger the transaction callback for the rest.
1002     test_device()->ClearTransactionCallback();
1003     test_device()->Stop();
1004     l2cap_ = nullptr;
1005     peer_cache_ = nullptr;
1006     TestingBase::TearDown();
1007   }
1008 
1009  protected:
connmgr() const1010   BrEdrConnectionManager* connmgr() const { return connection_manager_.get(); }
peer_cache() const1011   PeerCache* peer_cache() const { return peer_cache_.get(); }
l2cap() const1012   l2cap::testing::FakeL2cap* l2cap() const { return l2cap_.get(); }
transaction_count() const1013   int transaction_count() const { return transaction_count_; }
1014 
1015  private:
1016   std::unique_ptr<BrEdrConnectionManager> connection_manager_;
1017   std::unique_ptr<PeerCache> peer_cache_;
1018   std::unique_ptr<l2cap::testing::FakeL2cap> l2cap_;
1019   int transaction_count_ = 0;
1020 };
1021 
1022 // Legacy pairing requires a PIN code to be displayed for the peer to enter, so
1023 // this cannot happen when we do not have any display output capabilities.
TEST_F(BrEdrConnectionManagerLegacyPairingTest,NeverInitiateLegacyPairingWithoutDisplayOutputCapability)1024 TEST_F(BrEdrConnectionManagerLegacyPairingTest,
1025        NeverInitiateLegacyPairingWithoutDisplayOutputCapability) {
1026   FakePairingDelegate pairing_delegate(sm::IOCapability::kNoInputNoOutput);
1027   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
1028 
1029   // Complete connection and interrogation successfully.
1030   QueueSuccessfulAccept();
1031   QueueSuccessfulInterrogationNoSsp(kTestDevAddr, kConnectionHandle);
1032   test_device()->SendCommandChannelPacket(kConnectionRequest);
1033 
1034   RunUntilIdle();
1035 
1036   ASSERT_EQ(kIncomingConnTransactions, transaction_count());
1037   Peer* const peer = peer_cache()->FindByAddress(kTestDevAddr);
1038   ASSERT_TRUE(peer);
1039   ASSERT_TRUE(IsInitializing(peer));
1040   ASSERT_FALSE(peer->bredr()->bonded());
1041 
1042   // Initiating pairing results in disconnection with peer because we have no
1043   // display output capabilities. Because of this, the pairing callback passed
1044   // into Pair() should never be called.
1045   QueueDisconnection(kConnectionHandle);
1046   connmgr()->Pair(peer->identifier(),
1047                   kNoSecurityRequirements,
1048                   [](hci::Result<>) { FAIL(); });
1049 
1050   RunUntilIdle();
1051 
1052   ASSERT_TRUE(IsNotConnected(peer));
1053 }
1054 
1055 // Responding to a legacy pairing request (HCI_Link_Key_Request event) after
1056 // connection and after interrogation completes should succeed.
TEST_F(BrEdrConnectionManagerLegacyPairingTest,RespondToLegacyPairingLinkKeyRequestAfterAclConnectionAndInterrogationCompletesSucceeds)1057 TEST_F(
1058     BrEdrConnectionManagerLegacyPairingTest,
1059     RespondToLegacyPairingLinkKeyRequestAfterAclConnectionAndInterrogationCompletesSucceeds) {
1060   FakePairingDelegate pairing_delegate(sm::IOCapability::kDisplayOnly);
1061   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
1062 
1063   // Approve pairing requests
1064   pairing_delegate.SetRequestPasskeyCallback([](PeerId, auto response_cb) {
1065     ASSERT_TRUE(response_cb);
1066     response_cb(kDefaultPinCode);
1067   });
1068 
1069   // Complete connection and interrogation successfully.
1070   QueueSuccessfulAccept();
1071   QueueSuccessfulInterrogationNoSsp(kTestDevAddr, kConnectionHandle);
1072   test_device()->SendCommandChannelPacket(kConnectionRequest);
1073 
1074   RunUntilIdle();
1075 
1076   ASSERT_EQ(kIncomingConnTransactions, transaction_count());
1077   Peer* const peer = peer_cache()->FindByAddress(kTestDevAddr);
1078   ASSERT_TRUE(peer);
1079   ASSERT_TRUE(IsInitializing(peer));
1080   ASSERT_FALSE(peer->bredr()->bonded());
1081 
1082   EXPECT_TRUE(l2cap()->IsLinkConnected(kConnectionHandle));
1083 
1084   // Initiate pairing from the peer with an HCI_Link_Key_Request event
1085   EXPECT_CMD_PACKET_OUT(test_device(),
1086                         kLinkKeyRequestNegativeReply,
1087                         &kLinkKeyRequestNegativeReplyRsp,
1088                         &kPinCodeRequest);
1089   EXPECT_CMD_PACKET_OUT(test_device(),
1090                         kPinCodeRequestReply,
1091                         &kPinCodeRequestReplyRsp,
1092                         &kLinkKeyNotificationLegacy);
1093   EXPECT_CMD_PACKET_OUT(test_device(),
1094                         kSetConnectionEncryption,
1095                         &kSetConnectionEncryptionRsp,
1096                         &kEncryptionChangeEvent);
1097   EXPECT_CMD_PACKET_OUT(
1098       test_device(), kReadEncryptionKeySize, &kReadEncryptionKeySizeRsp);
1099   test_device()->SendCommandChannelPacket(kLinkKeyRequest);
1100 
1101   RETURN_IF_FATAL(RunUntilIdle());
1102 
1103   ASSERT_TRUE(peer->bredr()->bonded());
1104 
1105   QueueDisconnection(kConnectionHandle);
1106 }
1107 
1108 // Responding to a legacy pairing request (HCI_Link_Key_Request event) before
1109 // connection should succeed.
TEST_F(BrEdrConnectionManagerLegacyPairingTest,RespondToLegacyPairingLinkKeyRequestBeforeAclConnection)1110 TEST_F(BrEdrConnectionManagerLegacyPairingTest,
1111        RespondToLegacyPairingLinkKeyRequestBeforeAclConnection) {
1112   FakePairingDelegate pairing_delegate(sm::IOCapability::kNoInputNoOutput);
1113   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
1114 
1115   ASSERT_TRUE(
1116       peer_cache()->AddBondedPeer(BondingData{.identifier = PeerId(999),
1117                                               .address = kTestDevAddr,
1118                                               .name = std::nullopt,
1119                                               .le_pairing_data = {},
1120                                               .bredr_link_key = kLinkKey,
1121                                               .bredr_services = {}}));
1122   auto* peer = peer_cache()->FindByAddress(kTestDevAddr);
1123   ASSERT_TRUE(peer);
1124   ASSERT_TRUE(IsNotConnected(peer));
1125   ASSERT_TRUE(peer->bonded());
1126 
1127   EXPECT_CMD_PACKET_OUT(test_device(), kAcceptConnectionRequest);
1128   test_device()->SendCommandChannelPacket(kConnectionRequest);
1129   RunUntilIdle();
1130 
1131   test_device()->SendCommandChannelPacket(testing::RoleChangePacket(
1132       kTestDevAddr, pw::bluetooth::emboss::ConnectionRole::CENTRAL));
1133   RunUntilIdle();
1134 
1135   EXPECT_CMD_PACKET_OUT(
1136       test_device(), kLinkKeyRequestReply, &kLinkKeyRequestReplyRsp);
1137 
1138   test_device()->SendCommandChannelPacket(kLinkKeyRequest);
1139   RunUntilIdle();
1140 
1141   // Complete connection and interrogation successfully.
1142   QueueSuccessfulInterrogation(kTestDevAddr, kConnectionHandle);
1143   test_device()->SendCommandChannelPacket(kConnectionComplete);
1144   RunUntilIdle();
1145 
1146   // Our pairing delegate should not have been invalidated at any point
1147   EXPECT_TRUE(connmgr()->pairing_delegate().is_alive());
1148 
1149   QueueDisconnection(kConnectionHandle);
1150 }
1151 
1152 // Responding to a legacy pairing request (HCI_PIN_Code_Request event) before
1153 // the ACL connection is complete should succeed.
TEST_F(BrEdrConnectionManagerLegacyPairingTest,RespondToLegacyPairingPinCodeRequestBeforeAclConnectionCompletesSucceeds)1154 TEST_F(
1155     BrEdrConnectionManagerLegacyPairingTest,
1156     RespondToLegacyPairingPinCodeRequestBeforeAclConnectionCompletesSucceeds) {
1157   FakePairingDelegate pairing_delegate(sm::IOCapability::kDisplayYesNo);
1158   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
1159 
1160   // Approve pairing requests
1161   pairing_delegate.SetRequestPasskeyCallback([](PeerId, auto response_cb) {
1162     ASSERT_TRUE(response_cb);
1163     response_cb(kDefaultPinCode);
1164   });
1165 
1166   // Trigger inbound connection but don't complete the connection
1167   EXPECT_CMD_PACKET_OUT(
1168       test_device(), kAcceptConnectionRequest, &kAcceptConnectionRequestRsp);
1169   test_device()->SendCommandChannelPacket(kConnectionRequest);
1170 
1171   RunUntilIdle();
1172 
1173   EXPECT_EQ(1, transaction_count());
1174   Peer* const peer = peer_cache()->FindByAddress(kTestDevAddr);
1175   ASSERT_TRUE(peer);
1176   ASSERT_TRUE(IsInitializing(peer));
1177   ASSERT_FALSE(peer->bredr()->bonded());
1178 
1179   // Initiate pairing from the peer with an HCI_PIN_Code_Request event before
1180   // the connection completes
1181   EXPECT_CMD_PACKET_OUT(test_device(),
1182                         kPinCodeRequestReply,
1183                         &kPinCodeRequestReplyRsp,
1184                         &kLinkKeyNotificationLegacy);
1185   test_device()->SendCommandChannelPacket(kPinCodeRequest);
1186 
1187   RETURN_IF_FATAL(RunUntilIdle());
1188 
1189   // At this point the peer is still not bonded so the host-side L2CAP should
1190   // still be inactive on this link (though it may be buffering packets).
1191   EXPECT_FALSE(l2cap()->IsLinkConnected(kConnectionHandle));
1192 
1193   // Complete connection and interrogation successfully.
1194   QueueSuccessfulInterrogationNoSsp(kTestDevAddr, kConnectionHandle);
1195   test_device()->SendCommandChannelPacket(kConnectionComplete);
1196 
1197   RETURN_IF_FATAL(RunUntilIdle());
1198 
1199   EXPECT_TRUE(l2cap()->IsLinkConnected(kConnectionHandle));
1200 
1201   // Our pairing delegate should not have been invalidated at any point
1202   EXPECT_TRUE(connmgr()->pairing_delegate().is_alive());
1203 
1204   QueueDisconnection(kConnectionHandle);
1205 }
1206 
1207 // Responding to a legacy pairing request (HCI_PIN_Code_Request event) after
1208 // connection but before interrogation completes should succeed.
TEST_F(BrEdrConnectionManagerLegacyPairingTest,RespondToLegacyPairingPinCodeRequestAfterAclConnectionButBeforeInterrogationSucceeds)1209 TEST_F(
1210     BrEdrConnectionManagerLegacyPairingTest,
1211     RespondToLegacyPairingPinCodeRequestAfterAclConnectionButBeforeInterrogationSucceeds) {
1212   FakePairingDelegate pairing_delegate(sm::IOCapability::kDisplayYesNo);
1213   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
1214 
1215   // Approve pairing requests
1216   pairing_delegate.SetRequestPasskeyCallback([](PeerId, auto response_cb) {
1217     ASSERT_TRUE(response_cb);
1218     response_cb(kDefaultPinCode);
1219   });
1220 
1221   // Trigger inbound connection and respond to some (but not all) of
1222   // interrogation.
1223   EXPECT_CMD_PACKET_OUT(test_device(),
1224                         kAcceptConnectionRequest,
1225                         &kAcceptConnectionRequestRsp,
1226                         &kConnectionComplete);
1227   EXPECT_CMD_PACKET_OUT(test_device(),
1228                         kRemoteNameRequest,
1229                         &kRemoteNameRequestRsp,
1230                         &kRemoteNameRequestComplete);
1231   EXPECT_CMD_PACKET_OUT(test_device(),
1232                         kReadRemoteVersionInfo,
1233                         &kReadRemoteVersionInfoRsp,
1234                         &kRemoteVersionInfoComplete);
1235   EXPECT_CMD_PACKET_OUT(test_device(),
1236                         hci_spec::kReadRemoteSupportedFeatures,
1237                         &kReadRemoteSupportedFeaturesRsp);
1238   test_device()->SendCommandChannelPacket(kConnectionRequest);
1239 
1240   RunUntilIdle();
1241 
1242   // Ensure that the interrogation has begun but the peer hasn't yet bonded
1243   EXPECT_EQ(4, transaction_count());
1244   Peer* const peer = peer_cache()->FindByAddress(kTestDevAddr);
1245   ASSERT_TRUE(peer);
1246   ASSERT_TRUE(IsInitializing(peer));
1247   ASSERT_FALSE(peer->bredr()->bonded());
1248 
1249   // Initiate pairing from the peer with an HCI_PIN_Code_Request event before
1250   // interrogation completes
1251   EXPECT_CMD_PACKET_OUT(test_device(),
1252                         kPinCodeRequestReply,
1253                         &kPinCodeRequestReplyRsp,
1254                         &kLinkKeyNotificationLegacy);
1255   EXPECT_CMD_PACKET_OUT(test_device(),
1256                         kSetConnectionEncryption,
1257                         &kSetConnectionEncryptionRsp,
1258                         &kEncryptionChangeEvent);
1259   EXPECT_CMD_PACKET_OUT(
1260       test_device(), kReadEncryptionKeySize, &kReadEncryptionKeySizeRsp);
1261   test_device()->SendCommandChannelPacket(kPinCodeRequest);
1262 
1263   RETURN_IF_FATAL(RunUntilIdle());
1264 
1265   // At this point the peer is bonded and the link is encrypted but
1266   // interrogation has not completed so host-side L2CAP should still be inactive
1267   // on this link (though it may be buffering packets).
1268   EXPECT_FALSE(l2cap()->IsLinkConnected(kConnectionHandle));
1269 
1270   bool socket_cb_called = false;
1271   auto socket_fails_cb = [&socket_cb_called](const auto& chan_sock) {
1272     EXPECT_FALSE(chan_sock.is_alive());
1273     socket_cb_called = true;
1274   };
1275   connmgr()->OpenL2capChannel(peer->identifier(),
1276                               l2cap::kAVDTP,
1277                               kNoSecurityRequirements,
1278                               kChannelParams,
1279                               socket_fails_cb);
1280 
1281   RETURN_IF_FATAL(RunUntilIdle());
1282   EXPECT_TRUE(socket_cb_called);
1283 
1284   // Complete interrogation successfully.
1285   EXPECT_CMD_PACKET_OUT(test_device(),
1286                         kReadRemoteExtended1,
1287                         &kReadRemoteExtendedFeaturesRsp,
1288                         &kReadRemoteExtended1CompleteNoSsp);
1289   EXPECT_CMD_PACKET_OUT(test_device(),
1290                         kReadRemoteExtended2,
1291                         &kReadRemoteExtendedFeaturesRsp,
1292                         &kReadRemoteExtended1CompleteNoSsp);
1293   test_device()->SendCommandChannelPacket(kReadRemoteSupportedFeaturesComplete);
1294 
1295   RETURN_IF_FATAL(RunUntilIdle());
1296 
1297   EXPECT_TRUE(l2cap()->IsLinkConnected(kConnectionHandle));
1298 
1299   QueueDisconnection(kConnectionHandle);
1300 }
1301 
1302 // Responding to a legacy pairing request (HCI_Link_Key_Request event) after
1303 // the ACL connection is complete but before interrogation completes stops
1304 // pairing because we assume SSP.
TEST_F(BrEdrConnectionManagerLegacyPairingTest,RespondToLegacyPairingLinkKeyRequestAfterAclConnectionButBeforeInterrogationFails)1305 TEST_F(
1306     BrEdrConnectionManagerLegacyPairingTest,
1307     RespondToLegacyPairingLinkKeyRequestAfterAclConnectionButBeforeInterrogationFails) {
1308   FakePairingDelegate pairing_delegate(sm::IOCapability::kDisplayYesNo);
1309   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
1310 
1311   // Trigger inbound connection and respond to some (but not all) of
1312   // interrogation.
1313   EXPECT_CMD_PACKET_OUT(test_device(),
1314                         kAcceptConnectionRequest,
1315                         &kAcceptConnectionRequestRsp,
1316                         &kConnectionComplete);
1317   EXPECT_CMD_PACKET_OUT(test_device(),
1318                         kRemoteNameRequest,
1319                         &kRemoteNameRequestRsp,
1320                         &kRemoteNameRequestComplete);
1321   EXPECT_CMD_PACKET_OUT(test_device(),
1322                         kReadRemoteVersionInfo,
1323                         &kReadRemoteVersionInfoRsp,
1324                         &kRemoteVersionInfoComplete);
1325   EXPECT_CMD_PACKET_OUT(test_device(),
1326                         hci_spec::kReadRemoteSupportedFeatures,
1327                         &kReadRemoteSupportedFeaturesRsp);
1328   test_device()->SendCommandChannelPacket(kConnectionRequest);
1329 
1330   RunUntilIdle();
1331 
1332   // Ensure that the interrogation has begun but the peer hasn't yet bonded
1333   EXPECT_EQ(4, transaction_count());
1334   Peer* const peer = peer_cache()->FindByAddress(kTestDevAddr);
1335   ASSERT_TRUE(peer);
1336   ASSERT_TRUE(IsInitializing(peer));
1337   ASSERT_FALSE(peer->bredr()->bonded());
1338 
1339   // Initiate pairing from the peer with an HCI_Link_Key_Request event before
1340   // interrogation completes
1341   EXPECT_CMD_PACKET_OUT(test_device(),
1342                         kLinkKeyRequestNegativeReply,
1343                         &kLinkKeyRequestNegativeReplyRsp,
1344                         &kPinCodeRequest);
1345   EXPECT_CMD_PACKET_OUT(test_device(),
1346                         kPinCodeRequestNegativeReply,
1347                         &kPinCodeRequestNegativeReplyRsp);
1348   test_device()->SendCommandChannelPacket(kLinkKeyRequest);
1349 
1350   RETURN_IF_FATAL(RunUntilIdle());
1351 
1352   // At this point the peer is bonded and the link is encrypted but
1353   // interrogation has not completed so host-side L2CAP should still be inactive
1354   // on this link (though it may be buffering packets).
1355   EXPECT_FALSE(l2cap()->IsLinkConnected(kConnectionHandle));
1356 
1357   QueueDisconnection(kConnectionHandle);
1358 }
1359 
1360 // Responding to an SSP request (HCI_Link_Key_Request event) after the ACL
1361 // connection is complete but before interrogation completes should succeed.
TEST_F(BrEdrConnectionManagerLegacyPairingTest,RespondToSspLinkKeyRequestAfterAclConnectionButBeforeInterrogationSucceeds)1362 TEST_F(
1363     BrEdrConnectionManagerLegacyPairingTest,
1364     RespondToSspLinkKeyRequestAfterAclConnectionButBeforeInterrogationSucceeds) {
1365   FakePairingDelegate pairing_delegate(sm::IOCapability::kDisplayYesNo);
1366   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
1367 
1368   // Approve pairing requests.
1369   pairing_delegate.SetDisplayPasskeyCallback(
1370       [](PeerId, uint32_t, auto, auto confirm_cb) {
1371         ASSERT_TRUE(confirm_cb);
1372         confirm_cb(true);
1373       });
1374 
1375   pairing_delegate.SetCompletePairingCallback(
1376       [](PeerId, sm::Result<> status) { EXPECT_EQ(fit::ok(), status); });
1377 
1378   // Trigger inbound connection and respond to some (but not all) of
1379   // interrogation.
1380   EXPECT_CMD_PACKET_OUT(test_device(),
1381                         kAcceptConnectionRequest,
1382                         &kAcceptConnectionRequestRsp,
1383                         &kConnectionComplete);
1384   EXPECT_CMD_PACKET_OUT(test_device(),
1385                         kRemoteNameRequest,
1386                         &kRemoteNameRequestRsp,
1387                         &kRemoteNameRequestComplete);
1388   EXPECT_CMD_PACKET_OUT(test_device(),
1389                         kReadRemoteVersionInfo,
1390                         &kReadRemoteVersionInfoRsp,
1391                         &kRemoteVersionInfoComplete);
1392   EXPECT_CMD_PACKET_OUT(test_device(),
1393                         hci_spec::kReadRemoteSupportedFeatures,
1394                         &kReadRemoteSupportedFeaturesRsp);
1395   test_device()->SendCommandChannelPacket(kConnectionRequest);
1396 
1397   RunUntilIdle();
1398 
1399   // Ensure that the interrogation has begun but the peer hasn't yet bonded
1400   EXPECT_EQ(4, transaction_count());
1401   Peer* const peer = peer_cache()->FindByAddress(kTestDevAddr);
1402   ASSERT_TRUE(peer);
1403   ASSERT_TRUE(IsInitializing(peer));
1404   ASSERT_FALSE(peer->bredr()->bonded());
1405 
1406   // Initiate pairing from the peer with an HCI_Link_Key_Request event before
1407   // interrogation completes
1408   const auto kIoCapabilityResponse = MakeIoCapabilityResponse(
1409       IoCapability::DISPLAY_YES_NO,
1410       AuthenticationRequirements::MITM_GENERAL_BONDING);
1411   const auto kUserConfirmationRequest = MakeUserConfirmationRequest(kPasskey);
1412   EXPECT_CMD_PACKET_OUT(test_device(),
1413                         kLinkKeyRequestNegativeReply,
1414                         &kLinkKeyRequestNegativeReplyRsp,
1415                         &kIoCapabilityResponse,
1416                         &kIoCapabilityRequest);
1417   EXPECT_CMD_PACKET_OUT(test_device(),
1418                         MakeIoCapabilityRequestReply(
1419                             IoCapability::DISPLAY_YES_NO,
1420                             AuthenticationRequirements::MITM_GENERAL_BONDING),
1421                         &kIoCapabilityRequestReplyRsp,
1422                         &kUserConfirmationRequest);
1423   EXPECT_CMD_PACKET_OUT(test_device(),
1424                         kUserConfirmationRequestReply,
1425                         &kUserConfirmationRequestReplyRsp,
1426                         &kSimplePairingCompleteSuccess,
1427                         &kLinkKeyNotification);
1428   EXPECT_CMD_PACKET_OUT(test_device(),
1429                         kSetConnectionEncryption,
1430                         &kSetConnectionEncryptionRsp,
1431                         &kEncryptionChangeEvent);
1432   EXPECT_CMD_PACKET_OUT(
1433       test_device(), kReadEncryptionKeySize, &kReadEncryptionKeySizeRsp);
1434   test_device()->SendCommandChannelPacket(kLinkKeyRequest);
1435 
1436   RETURN_IF_FATAL(RunUntilIdle());
1437 
1438   // At this point the peer is bonded and the link is encrypted but
1439   // interrogation has not completed so host-side L2CAP should still be inactive
1440   // on this link (though it may be buffering packets).
1441   EXPECT_FALSE(l2cap()->IsLinkConnected(kConnectionHandle));
1442 
1443   bool socket_cb_called = false;
1444   auto socket_fails_cb = [&socket_cb_called](const auto& chan_sock) {
1445     EXPECT_FALSE(chan_sock.is_alive());
1446     socket_cb_called = true;
1447   };
1448   connmgr()->OpenL2capChannel(peer->identifier(),
1449                               l2cap::kAVDTP,
1450                               kNoSecurityRequirements,
1451                               kChannelParams,
1452                               socket_fails_cb);
1453 
1454   RETURN_IF_FATAL(RunUntilIdle());
1455   EXPECT_TRUE(socket_cb_called);
1456 
1457   // Complete interrogation successfully.
1458   EXPECT_CMD_PACKET_OUT(test_device(),
1459                         kReadRemoteExtended1,
1460                         &kReadRemoteExtendedFeaturesRsp,
1461                         &kReadRemoteExtended1CompleteNoSsp);
1462   EXPECT_CMD_PACKET_OUT(test_device(),
1463                         kReadRemoteExtended2,
1464                         &kReadRemoteExtendedFeaturesRsp,
1465                         &kReadRemoteExtended1CompleteNoSsp);
1466   test_device()->SendCommandChannelPacket(kReadRemoteSupportedFeaturesComplete);
1467 
1468   RETURN_IF_FATAL(RunUntilIdle());
1469 
1470   EXPECT_TRUE(l2cap()->IsLinkConnected(kConnectionHandle));
1471 
1472   QueueDisconnection(kConnectionHandle);
1473 }
1474 
TEST_F(BrEdrConnectionManagerTest,DisableConnectivity)1475 TEST_F(BrEdrConnectionManagerTest, DisableConnectivity) {
1476   size_t cb_count = 0;
1477   auto cb = [&cb_count](const auto& status) {
1478     cb_count++;
1479     EXPECT_EQ(fit::ok(), status);
1480   };
1481 
1482   EXPECT_CMD_PACKET_OUT(
1483       test_device(), kReadScanEnable, &kReadScanEnableRspPage);
1484   EXPECT_CMD_PACKET_OUT(
1485       test_device(), kWriteScanEnableNone, &kWriteScanEnableRsp);
1486 
1487   connmgr()->SetConnectable(/*connectable=*/false, cb);
1488 
1489   RunUntilIdle();
1490 
1491   EXPECT_EQ(1u, cb_count);
1492 
1493   EXPECT_CMD_PACKET_OUT(
1494       test_device(), kReadScanEnable, &kReadScanEnableRspBoth);
1495   EXPECT_CMD_PACKET_OUT(
1496       test_device(), kWriteScanEnableInq, &kWriteScanEnableRsp);
1497 
1498   connmgr()->SetConnectable(/*connectable=*/false, cb);
1499 
1500   RunUntilIdle();
1501 
1502   EXPECT_EQ(2u, cb_count);
1503 }
1504 
TEST_F(BrEdrConnectionManagerTest,EnableConnectivity)1505 TEST_F(BrEdrConnectionManagerTest, EnableConnectivity) {
1506   size_t cb_count = 0;
1507   auto cb = [&cb_count](const auto& status) {
1508     cb_count++;
1509     EXPECT_EQ(fit::ok(), status);
1510   };
1511 
1512   EXPECT_CMD_PACKET_OUT(
1513       test_device(), kWritePageScanActivity, &kWritePageScanActivityRsp);
1514   EXPECT_CMD_PACKET_OUT(
1515       test_device(), kWritePageScanType, &kWritePageScanTypeRsp);
1516   EXPECT_CMD_PACKET_OUT(
1517       test_device(), kReadScanEnable, &kReadScanEnableRspNone);
1518   EXPECT_CMD_PACKET_OUT(
1519       test_device(), kWriteScanEnablePage, &kWriteScanEnableRsp);
1520 
1521   connmgr()->SetConnectable(/*connectable=*/true, cb);
1522 
1523   RunUntilIdle();
1524 
1525   EXPECT_EQ(1u, cb_count);
1526 
1527   EXPECT_CMD_PACKET_OUT(
1528       test_device(), kWritePageScanActivity, &kWritePageScanActivityRsp);
1529   EXPECT_CMD_PACKET_OUT(
1530       test_device(), kWritePageScanType, &kWritePageScanTypeRsp);
1531   EXPECT_CMD_PACKET_OUT(
1532       test_device(), kReadScanEnable, &kReadScanEnableRspInquiry);
1533   EXPECT_CMD_PACKET_OUT(
1534       test_device(), kWriteScanEnableBoth, &kWriteScanEnableRsp);
1535 
1536   connmgr()->SetConnectable(/*connectable=*/true, cb);
1537 
1538   RunUntilIdle();
1539 
1540   EXPECT_EQ(2u, cb_count);
1541 }
1542 
1543 // Test: An incoming connection request should trigger an acceptance and
1544 // interrogation should allow a peer that only report the first Extended
1545 // Features page.
TEST_F(BrEdrConnectionManagerTest,IncomingConnection_BrokenExtendedPageResponse)1546 TEST_F(BrEdrConnectionManagerTest,
1547        IncomingConnection_BrokenExtendedPageResponse) {
1548   EXPECT_CMD_PACKET_OUT(test_device(),
1549                         kAcceptConnectionRequest,
1550                         &kAcceptConnectionRequestRsp,
1551                         &kConnectionComplete);
1552   EXPECT_CMD_PACKET_OUT(test_device(),
1553                         kRemoteNameRequest,
1554                         &kRemoteNameRequestRsp,
1555                         &kRemoteNameRequestComplete);
1556   EXPECT_CMD_PACKET_OUT(test_device(),
1557                         kReadRemoteVersionInfo,
1558                         &kReadRemoteVersionInfoRsp,
1559                         &kRemoteVersionInfoComplete);
1560   EXPECT_CMD_PACKET_OUT(test_device(),
1561                         hci_spec::kReadRemoteSupportedFeatures,
1562                         &kReadRemoteSupportedFeaturesRsp,
1563                         &kReadRemoteSupportedFeaturesComplete);
1564   EXPECT_CMD_PACKET_OUT(test_device(),
1565                         kReadRemoteExtended1,
1566                         &kReadRemoteExtendedFeaturesRsp,
1567                         &kReadRemoteExtended1Complete);
1568   EXPECT_CMD_PACKET_OUT(test_device(),
1569                         kReadRemoteExtended2,
1570                         &kReadRemoteExtendedFeaturesRsp,
1571                         &kReadRemoteExtended1Complete);
1572 
1573   test_device()->SendCommandChannelPacket(kConnectionRequest);
1574 
1575   RunUntilIdle();
1576 
1577   EXPECT_EQ(6, transaction_count());
1578 
1579   // When we deallocate the connection manager during teardown, we should
1580   // disconnect.
1581   QueueDisconnection(kConnectionHandle);
1582 }
1583 
1584 // Test: An incoming connection request should trigger an acceptance and an
1585 // interrogation to discover capabilities.
TEST_F(BrEdrConnectionManagerTest,IncomingConnectionSuccess)1586 TEST_F(BrEdrConnectionManagerTest, IncomingConnectionSuccess) {
1587   EXPECT_EQ(kInvalidPeerId, connmgr()->GetPeerId(kConnectionHandle));
1588 
1589   QueueSuccessfulIncomingConn();
1590 
1591   test_device()->SendCommandChannelPacket(kConnectionRequest);
1592 
1593   RunUntilIdle();
1594 
1595   auto* peer = peer_cache()->FindByAddress(kTestDevAddr);
1596   ASSERT_TRUE(peer);
1597   EXPECT_EQ(peer->identifier(), connmgr()->GetPeerId(kConnectionHandle));
1598   EXPECT_EQ(kIncomingConnTransactions, transaction_count());
1599   // Confirm remote name request during interrogation sets proper name source.
1600   EXPECT_EQ(peer->name_source(), Peer::NameSource::kNameDiscoveryProcedure);
1601   // We should have set the Class Of Device from the incoming connection request
1602   ASSERT_TRUE(peer->bredr()->device_class().has_value());
1603   // endianness so this magic number is backwards from the packet definition
1604   EXPECT_EQ(*peer->bredr()->device_class(), DeviceClass(0x000C425A));
1605 
1606   // When we deallocate the connection manager during teardown, we should
1607   // disconnect.
1608   QueueDisconnection(kConnectionHandle);
1609 }
1610 
1611 // Test: An incoming connection request should upgrade a known LE peer with a
1612 // matching address to a dual mode peer.
TEST_F(BrEdrConnectionManagerTest,IncomingConnectionUpgradesKnownLowEnergyPeerToDualMode)1613 TEST_F(BrEdrConnectionManagerTest,
1614        IncomingConnectionUpgradesKnownLowEnergyPeerToDualMode) {
1615   const DeviceAddress le_alias_addr(DeviceAddress::Type::kLEPublic,
1616                                     kTestDevAddr.value());
1617   Peer* const peer = peer_cache()->NewPeer(le_alias_addr, /*connectable=*/true);
1618   ASSERT_TRUE(peer);
1619   ASSERT_EQ(TechnologyType::kLowEnergy, peer->technology());
1620 
1621   QueueSuccessfulIncomingConn();
1622 
1623   test_device()->SendCommandChannelPacket(kConnectionRequest);
1624 
1625   RunUntilIdle();
1626 
1627   ASSERT_EQ(peer, peer_cache()->FindByAddress(kTestDevAddr));
1628   EXPECT_EQ(peer->identifier(), connmgr()->GetPeerId(kConnectionHandle));
1629   EXPECT_EQ(TechnologyType::kDualMode, peer->technology());
1630 
1631   // Prepare for disconnection upon teardown.
1632   QueueDisconnection(kConnectionHandle);
1633 }
1634 
1635 // Test: A remote disconnect should correctly remove the connection.
TEST_F(BrEdrConnectionManagerTest,RemoteDisconnect)1636 TEST_F(BrEdrConnectionManagerTest, RemoteDisconnect) {
1637   EXPECT_EQ(kInvalidPeerId, connmgr()->GetPeerId(kConnectionHandle));
1638   QueueSuccessfulIncomingConn();
1639 
1640   test_device()->SendCommandChannelPacket(kConnectionRequest);
1641   RunUntilIdle();
1642 
1643   auto* peer = peer_cache()->FindByAddress(kTestDevAddr);
1644   ASSERT_TRUE(peer);
1645   EXPECT_EQ(peer->identifier(), connmgr()->GetPeerId(kConnectionHandle));
1646 
1647   EXPECT_EQ(kIncomingConnTransactions, transaction_count());
1648 
1649   // Remote end disconnects.
1650   test_device()->SendCommandChannelPacket(kDisconnectionComplete);
1651 
1652   RunUntilIdle();
1653 
1654   EXPECT_EQ(kInvalidPeerId, connmgr()->GetPeerId(kConnectionHandle));
1655 }
1656 
1657 const auto kRemoteNameRequestCompleteFailed =
1658     StaticByteBuffer(hci_spec::kRemoteNameRequestCompleteEventCode,
1659                      0x01,  // parameter_total_size (1 bytes)
1660                      pw::bluetooth::emboss::StatusCode::HARDWARE_FAILURE);
1661 
1662 const auto kReadRemoteSupportedFeaturesCompleteFailed =
1663     StaticByteBuffer(hci_spec::kReadRemoteSupportedFeaturesCompleteEventCode,
1664                      0x01,  // parameter_total_size (1 bytes)
1665                      pw::bluetooth::emboss::StatusCode::HARDWARE_FAILURE);
1666 
1667 // Test: if the interrogation fails, we disconnect.
1668 //  - Receiving extra responses after a command fails will not fail
1669 //  - We don't query extended features if we don't receive an answer.
TEST_F(BrEdrConnectionManagerTest,IncomingConnectionFailedInterrogation)1670 TEST_F(BrEdrConnectionManagerTest, IncomingConnectionFailedInterrogation) {
1671   EXPECT_CMD_PACKET_OUT(test_device(),
1672                         kAcceptConnectionRequest,
1673                         &kAcceptConnectionRequestRsp,
1674                         &kConnectionComplete);
1675   EXPECT_CMD_PACKET_OUT(test_device(),
1676                         kRemoteNameRequest,
1677                         &kRemoteNameRequestRsp,
1678                         &kRemoteNameRequestCompleteFailed);
1679   EXPECT_CMD_PACKET_OUT(test_device(),
1680                         kReadRemoteVersionInfo,
1681                         &kReadRemoteVersionInfoRsp,
1682                         &kRemoteVersionInfoComplete);
1683   EXPECT_CMD_PACKET_OUT(test_device(),
1684                         hci_spec::kReadRemoteSupportedFeatures,
1685                         &kReadRemoteSupportedFeaturesRsp,
1686                         &kReadRemoteSupportedFeaturesCompleteFailed);
1687 
1688   EXPECT_CMD_PACKET_OUT(
1689       test_device(), kDisconnect, &kDisconnectRsp, &kDisconnectionComplete);
1690 
1691   test_device()->SendCommandChannelPacket(kConnectionRequest);
1692 
1693   RunUntilIdle();
1694 
1695   EXPECT_EQ(5, transaction_count());
1696 }
1697 
1698 // Test: replies negative to IO Capability Requests before PairingDelegate is
1699 // set
TEST_F(BrEdrConnectionManagerTest,IoCapabilityRequestNegativeReplyWithNoPairingDelegate)1700 TEST_F(BrEdrConnectionManagerTest,
1701        IoCapabilityRequestNegativeReplyWithNoPairingDelegate) {
1702   EXPECT_CMD_PACKET_OUT(test_device(),
1703                         kIoCapabilityRequestNegativeReply,
1704                         &kIoCapabilityRequestNegativeReplyRsp);
1705 
1706   test_device()->SendCommandChannelPacket(kIoCapabilityRequest);
1707 
1708   RunUntilIdle();
1709 
1710   EXPECT_EQ(1, transaction_count());
1711 }
1712 
1713 // Test: replies negative to IO Capability Requests for unconnected peers
TEST_F(BrEdrConnectionManagerTest,IoCapabilityRequestNegativeReplyWhenNotConnected)1714 TEST_F(BrEdrConnectionManagerTest,
1715        IoCapabilityRequestNegativeReplyWhenNotConnected) {
1716   FakePairingDelegate pairing_delegate(sm::IOCapability::kNoInputNoOutput);
1717   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
1718 
1719   EXPECT_CMD_PACKET_OUT(test_device(),
1720                         kIoCapabilityRequestNegativeReply,
1721                         &kIoCapabilityRequestNegativeReplyRsp);
1722 
1723   test_device()->SendCommandChannelPacket(kIoCapabilityRequest);
1724 
1725   RunUntilIdle();
1726 
1727   EXPECT_EQ(1, transaction_count());
1728 }
1729 
1730 // Test: replies to IO Capability Requests for connected peers
TEST_F(BrEdrConnectionManagerTest,IoCapabilityRequestReplyWhenConnected)1731 TEST_F(BrEdrConnectionManagerTest, IoCapabilityRequestReplyWhenConnected) {
1732   FakePairingDelegate pairing_delegate(sm::IOCapability::kNoInputNoOutput);
1733   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
1734 
1735   QueueSuccessfulIncomingConn();
1736 
1737   test_device()->SendCommandChannelPacket(kConnectionRequest);
1738 
1739   RunUntilIdle();
1740 
1741   ASSERT_EQ(kIncomingConnTransactions, transaction_count());
1742 
1743   EXPECT_CMD_PACKET_OUT(
1744       test_device(),
1745       MakeIoCapabilityRequestReply(IoCapability::NO_INPUT_NO_OUTPUT,
1746                                    AuthenticationRequirements::GENERAL_BONDING),
1747       &kIoCapabilityRequestReplyRsp);
1748 
1749   test_device()->SendCommandChannelPacket(MakeIoCapabilityResponse(
1750       IoCapability::DISPLAY_ONLY,
1751       AuthenticationRequirements::MITM_GENERAL_BONDING));
1752   test_device()->SendCommandChannelPacket(kIoCapabilityRequest);
1753 
1754   RunUntilIdle();
1755 
1756   EXPECT_EQ(kIncomingConnTransactions + 1, transaction_count());
1757 
1758   QueueDisconnection(kConnectionHandle);
1759 }
1760 
1761 // Test: Responds to Secure Simple Pairing with user rejection of Numeric
1762 // Comparison association
TEST_F(BrEdrConnectionManagerTest,RespondToNumericComparisonPairingAfterUserRejects)1763 TEST_F(BrEdrConnectionManagerTest,
1764        RespondToNumericComparisonPairingAfterUserRejects) {
1765   QueueSuccessfulIncomingConn();
1766 
1767   test_device()->SendCommandChannelPacket(kConnectionRequest);
1768 
1769   RunUntilIdle();
1770 
1771   EXPECT_EQ(kIncomingConnTransactions, transaction_count());
1772 
1773   FakePairingDelegate pairing_delegate(sm::IOCapability::kDisplayYesNo);
1774   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
1775 
1776   EXPECT_CMD_PACKET_OUT(test_device(),
1777                         MakeIoCapabilityRequestReply(
1778                             IoCapability::DISPLAY_YES_NO,
1779                             AuthenticationRequirements::MITM_GENERAL_BONDING),
1780                         &kIoCapabilityRequestReplyRsp);
1781 
1782   test_device()->SendCommandChannelPacket(MakeIoCapabilityResponse(
1783       IoCapability::DISPLAY_ONLY, AuthenticationRequirements::GENERAL_BONDING));
1784   test_device()->SendCommandChannelPacket(kIoCapabilityRequest);
1785 
1786   pairing_delegate.SetDisplayPasskeyCallback(
1787       [](PeerId, uint32_t passkey, auto method, auto confirm_cb) {
1788         EXPECT_EQ(kPasskey, passkey);
1789         EXPECT_EQ(PairingDelegate::DisplayMethod::kComparison, method);
1790         ASSERT_TRUE(confirm_cb);
1791         confirm_cb(false);
1792       });
1793 
1794   EXPECT_CMD_PACKET_OUT(test_device(),
1795                         kUserConfirmationRequestNegativeReply,
1796                         &kUserConfirmationRequestNegativeReplyRsp);
1797   test_device()->SendCommandChannelPacket(
1798       MakeUserConfirmationRequest(kPasskey));
1799 
1800   pairing_delegate.SetCompletePairingCallback([](PeerId, sm::Result<> status) {
1801     EXPECT_EQ(ToResult(HostError::kFailed), status);
1802   });
1803 
1804   test_device()->SendCommandChannelPacket(kSimplePairingCompleteError);
1805 
1806   // We disconnect the peer when authentication fails.
1807   QueueDisconnection(kConnectionHandle);
1808 
1809   RunUntilIdle();
1810 }
1811 
1812 const auto kUserPasskeyRequest =
1813     testing::UserPasskeyRequestPacket(TEST_DEV_ADDR);
1814 
1815 const auto kUserPasskeyRequestNegativeReply =
1816     testing::UserPasskeyRequestNegativeReply(TEST_DEV_ADDR);
1817 
1818 const auto kUserPasskeyRequestNegativeReplyRsp =
1819     testing::UserPasskeyRequestNegativeReplyResponse(TEST_DEV_ADDR);
1820 
1821 // Test: Responds to Secure Simple Pairing as the input side of Passkey Entry
1822 // association after the user declines or provides invalid input
TEST_F(BrEdrConnectionManagerTest,RespondToPasskeyEntryPairingAfterUserProvidesInvalidPasskey)1823 TEST_F(BrEdrConnectionManagerTest,
1824        RespondToPasskeyEntryPairingAfterUserProvidesInvalidPasskey) {
1825   QueueSuccessfulIncomingConn();
1826 
1827   test_device()->SendCommandChannelPacket(kConnectionRequest);
1828 
1829   RunUntilIdle();
1830 
1831   EXPECT_EQ(kIncomingConnTransactions, transaction_count());
1832 
1833   FakePairingDelegate pairing_delegate(sm::IOCapability::kKeyboardOnly);
1834   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
1835 
1836   EXPECT_CMD_PACKET_OUT(test_device(),
1837                         MakeIoCapabilityRequestReply(
1838                             IoCapability::KEYBOARD_ONLY,
1839                             AuthenticationRequirements::MITM_GENERAL_BONDING),
1840                         &kIoCapabilityRequestReplyRsp);
1841 
1842   test_device()->SendCommandChannelPacket(MakeIoCapabilityResponse(
1843       IoCapability::DISPLAY_ONLY, AuthenticationRequirements::GENERAL_BONDING));
1844   test_device()->SendCommandChannelPacket(kIoCapabilityRequest);
1845 
1846   pairing_delegate.SetRequestPasskeyCallback([](PeerId, auto response_cb) {
1847     ASSERT_TRUE(response_cb);
1848     response_cb(-128);  // Negative values indicate rejection.
1849   });
1850 
1851   EXPECT_CMD_PACKET_OUT(test_device(),
1852                         kUserPasskeyRequestNegativeReply,
1853                         &kUserPasskeyRequestNegativeReplyRsp);
1854   test_device()->SendCommandChannelPacket(kUserPasskeyRequest);
1855 
1856   pairing_delegate.SetCompletePairingCallback([](PeerId, sm::Result<> status) {
1857     EXPECT_EQ(ToResult(HostError::kFailed), status);
1858   });
1859 
1860   test_device()->SendCommandChannelPacket(kSimplePairingCompleteError);
1861 
1862   // We disconnect the peer when authentication fails.
1863   QueueDisconnection(kConnectionHandle);
1864 
1865   RunUntilIdle();
1866 }
1867 
1868 // Test: replies negative to Link Key Requests for unknown and unbonded peers
TEST_F(BrEdrConnectionManagerTest,LinkKeyRequestAndNegativeReply)1869 TEST_F(BrEdrConnectionManagerTest, LinkKeyRequestAndNegativeReply) {
1870   EXPECT_CMD_PACKET_OUT(test_device(),
1871                         kLinkKeyRequestNegativeReply,
1872                         &kLinkKeyRequestNegativeReplyRsp);
1873 
1874   test_device()->SendCommandChannelPacket(kLinkKeyRequest);
1875 
1876   RunUntilIdle();
1877 
1878   EXPECT_EQ(1, transaction_count());
1879 
1880   QueueSuccessfulIncomingConn();
1881 
1882   test_device()->SendCommandChannelPacket(kConnectionRequest);
1883 
1884   RunUntilIdle();
1885 
1886   EXPECT_EQ(kIncomingConnTransactions + 1, transaction_count());
1887 
1888   auto* peer = peer_cache()->FindByAddress(kTestDevAddr);
1889   ASSERT_TRUE(peer);
1890   ASSERT_FALSE(IsNotConnected(peer));
1891   ASSERT_FALSE(peer->bonded());
1892 
1893   EXPECT_CMD_PACKET_OUT(test_device(),
1894                         kLinkKeyRequestNegativeReply,
1895                         &kLinkKeyRequestNegativeReplyRsp);
1896 
1897   test_device()->SendCommandChannelPacket(kLinkKeyRequest);
1898 
1899   RunUntilIdle();
1900 
1901   EXPECT_EQ(kIncomingConnTransactions + 2, transaction_count());
1902 
1903   // Queue disconnection for teardown
1904   QueueDisconnection(kConnectionHandle);
1905 }
1906 
1907 // Test: Link Key request arrives after we have received a connect request, but
1908 // before we have been notified of connect completion (see http://b/393629914).
TEST_F(BrEdrConnectionManagerTest,ConnectLinkKeySandwich)1909 TEST_F(BrEdrConnectionManagerTest, ConnectLinkKeySandwich) {
1910   EXPECT_CMD_PACKET_OUT(test_device(),
1911                         testing::AcceptConnectionRequestPacket(kTestDevAddr),
1912                         &kAcceptConnectionRequestRsp);
1913   test_device()->SendCommandChannelPacket(kConnectionRequest);
1914   RunUntilIdle();
1915 
1916   auto* peer = peer_cache()->FindByAddress(kTestDevAddr);
1917   ASSERT_TRUE(peer);
1918   ASSERT_FALSE(IsNotConnected(peer));  // connecting
1919   ASSERT_FALSE(peer->bonded());
1920 
1921   EXPECT_CMD_PACKET_OUT(test_device(),
1922                         kLinkKeyRequestNegativeReply,
1923                         &kLinkKeyRequestNegativeReplyRsp);
1924   test_device()->SendCommandChannelPacket(kLinkKeyRequest);
1925   RunUntilIdle();
1926 
1927   QueueSuccessfulInterrogation(kTestDevAddr, kConnectionHandle);
1928   test_device()->SendCommandChannelPacket(kConnectionComplete);
1929   RunUntilIdle();
1930 
1931   // Queue disconnection for teardown
1932   QueueDisconnection(kConnectionHandle);
1933 }
1934 
1935 // Test: replies to Link Key Requests for bonded peer
TEST_F(BrEdrConnectionManagerTest,RecallLinkKeyForBondedPeer)1936 TEST_F(BrEdrConnectionManagerTest, RecallLinkKeyForBondedPeer) {
1937   ASSERT_TRUE(
1938       peer_cache()->AddBondedPeer(BondingData{.identifier = PeerId(999),
1939                                               .address = kTestDevAddr,
1940                                               .name = std::nullopt,
1941                                               .le_pairing_data = {},
1942                                               .bredr_link_key = kLinkKey,
1943                                               .bredr_services = {}}));
1944   auto* peer = peer_cache()->FindByAddress(kTestDevAddr);
1945   ASSERT_TRUE(peer);
1946   ASSERT_TRUE(IsNotConnected(peer));
1947   ASSERT_TRUE(peer->bonded());
1948 
1949   QueueSuccessfulIncomingConn();
1950 
1951   test_device()->SendCommandChannelPacket(kConnectionRequest);
1952 
1953   RunUntilIdle();
1954 
1955   EXPECT_EQ(kIncomingConnTransactions, transaction_count());
1956   ASSERT_TRUE(IsInitializing(peer));
1957 
1958   EXPECT_CMD_PACKET_OUT(
1959       test_device(), kLinkKeyRequestReply, &kLinkKeyRequestReplyRsp);
1960 
1961   test_device()->SendCommandChannelPacket(kLinkKeyRequest);
1962 
1963   RunUntilIdle();
1964   /// Peer is still initializing until the Pairing is complete
1965   /// (OnPairingComplete)
1966   ASSERT_TRUE(IsInitializing(peer));
1967 
1968   EXPECT_EQ(kIncomingConnTransactions + 1, transaction_count());
1969 
1970   // Queue disconnection for teardown.
1971   QueueDisconnection(kConnectionHandle);
1972 }
1973 
1974 // Test: Responds to Secure Simple Pairing as the input side of Passkey Entry
1975 // association after the user provides the correct passkey
TEST_F(BrEdrConnectionManagerTest,EncryptAfterPasskeyEntryPairingAndUserProvidesAcceptedPasskey)1976 TEST_F(BrEdrConnectionManagerTest,
1977        EncryptAfterPasskeyEntryPairingAndUserProvidesAcceptedPasskey) {
1978   QueueSuccessfulIncomingConn();
1979 
1980   test_device()->SendCommandChannelPacket(kConnectionRequest);
1981 
1982   RunUntilIdle();
1983 
1984   auto* peer = peer_cache()->FindByAddress(kTestDevAddr);
1985   ASSERT_TRUE(peer);
1986   ASSERT_TRUE(IsInitializing(peer));
1987   ASSERT_FALSE(peer->bonded());
1988 
1989   EXPECT_EQ(kIncomingConnTransactions, transaction_count());
1990 
1991   FakePairingDelegate pairing_delegate(sm::IOCapability::kKeyboardOnly);
1992   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
1993 
1994   EXPECT_CMD_PACKET_OUT(test_device(),
1995                         MakeIoCapabilityRequestReply(
1996                             IoCapability::KEYBOARD_ONLY,
1997                             AuthenticationRequirements::MITM_GENERAL_BONDING),
1998                         &kIoCapabilityRequestReplyRsp);
1999 
2000   test_device()->SendCommandChannelPacket(MakeIoCapabilityResponse(
2001       IoCapability::DISPLAY_ONLY, AuthenticationRequirements::GENERAL_BONDING));
2002   test_device()->SendCommandChannelPacket(kIoCapabilityRequest);
2003 
2004   pairing_delegate.SetRequestPasskeyCallback([](PeerId, auto response_cb) {
2005     ASSERT_TRUE(response_cb);
2006     response_cb(kPasskey);
2007   });
2008 
2009   EXPECT_CMD_PACKET_OUT(test_device(),
2010                         MakeUserPasskeyRequestReply(),
2011                         &kUserPasskeyRequestReplyRsp);
2012   test_device()->SendCommandChannelPacket(kUserPasskeyRequest);
2013 
2014   pairing_delegate.SetCompletePairingCallback(
2015       [](PeerId, sm::Result<> status) { EXPECT_EQ(fit::ok(), status); });
2016 
2017   test_device()->SendCommandChannelPacket(kSimplePairingCompleteSuccess);
2018   test_device()->SendCommandChannelPacket(kLinkKeyNotification);
2019 
2020   EXPECT_CMD_PACKET_OUT(test_device(),
2021                         kSetConnectionEncryption,
2022                         &kSetConnectionEncryptionRsp,
2023                         &kEncryptionChangeEvent);
2024   EXPECT_CMD_PACKET_OUT(
2025       test_device(), kReadEncryptionKeySize, &kReadEncryptionKeySizeRsp);
2026 
2027   RETURN_IF_FATAL(RunUntilIdle());
2028   ASSERT_TRUE(IsConnected(peer));
2029   EXPECT_TRUE(peer->bonded());
2030 
2031   QueueDisconnection(kConnectionHandle);
2032 }
2033 
2034 // Test: Responds to Secure Simple Pairing as the display side of Passkey Entry
2035 // association after the user provides the correct passkey on the peer
TEST_F(BrEdrConnectionManagerTest,EncryptAfterPasskeyDisplayPairing)2036 TEST_F(BrEdrConnectionManagerTest, EncryptAfterPasskeyDisplayPairing) {
2037   QueueSuccessfulIncomingConn();
2038 
2039   test_device()->SendCommandChannelPacket(kConnectionRequest);
2040 
2041   RunUntilIdle();
2042 
2043   auto* peer = peer_cache()->FindByAddress(kTestDevAddr);
2044   ASSERT_TRUE(peer);
2045   ASSERT_TRUE(IsInitializing(peer));
2046   ASSERT_FALSE(peer->bonded());
2047 
2048   EXPECT_EQ(kIncomingConnTransactions, transaction_count());
2049 
2050   FakePairingDelegate pairing_delegate(sm::IOCapability::kDisplayOnly);
2051   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
2052 
2053   EXPECT_CMD_PACKET_OUT(test_device(),
2054                         MakeIoCapabilityRequestReply(
2055                             IoCapability::DISPLAY_ONLY,
2056                             AuthenticationRequirements::MITM_GENERAL_BONDING),
2057                         &kIoCapabilityRequestReplyRsp);
2058 
2059   test_device()->SendCommandChannelPacket(
2060       MakeIoCapabilityResponse(IoCapability::KEYBOARD_ONLY,
2061                                AuthenticationRequirements::GENERAL_BONDING));
2062   test_device()->SendCommandChannelPacket(kIoCapabilityRequest);
2063 
2064   pairing_delegate.SetDisplayPasskeyCallback(
2065       [](PeerId, uint32_t passkey, auto method, auto confirm_cb) {
2066         EXPECT_EQ(kPasskey, passkey);
2067         EXPECT_EQ(PairingDelegate::DisplayMethod::kPeerEntry, method);
2068         EXPECT_TRUE(confirm_cb);
2069       });
2070 
2071   test_device()->SendCommandChannelPacket(
2072       MakeUserPasskeyNotification(kPasskey));
2073 
2074   pairing_delegate.SetCompletePairingCallback(
2075       [](PeerId, sm::Result<> status) { EXPECT_EQ(fit::ok(), status); });
2076 
2077   RETURN_IF_FATAL(RunUntilIdle());
2078   ASSERT_TRUE(IsInitializing(peer));
2079 
2080   test_device()->SendCommandChannelPacket(kSimplePairingCompleteSuccess);
2081   test_device()->SendCommandChannelPacket(kLinkKeyNotification);
2082 
2083   EXPECT_CMD_PACKET_OUT(test_device(),
2084                         kSetConnectionEncryption,
2085                         &kSetConnectionEncryptionRsp,
2086                         &kEncryptionChangeEvent);
2087   EXPECT_CMD_PACKET_OUT(
2088       test_device(), kReadEncryptionKeySize, &kReadEncryptionKeySizeRsp);
2089 
2090   RETURN_IF_FATAL(RunUntilIdle());
2091   ASSERT_TRUE(IsConnected(peer));
2092   EXPECT_TRUE(peer->bonded());
2093 
2094   QueueDisconnection(kConnectionHandle);
2095 }
2096 
2097 // Test: Responds to Secure Simple Pairing and user confirmation of Numeric
2098 // Comparison association, then bonds and encrypts using resulting link key
TEST_F(BrEdrConnectionManagerTest,EncryptAndBondAfterNumericComparisonPairingAndUserConfirms)2099 TEST_F(BrEdrConnectionManagerTest,
2100        EncryptAndBondAfterNumericComparisonPairingAndUserConfirms) {
2101   QueueSuccessfulIncomingConn();
2102 
2103   test_device()->SendCommandChannelPacket(kConnectionRequest);
2104 
2105   RunUntilIdle();
2106 
2107   auto* peer = peer_cache()->FindByAddress(kTestDevAddr);
2108   ASSERT_TRUE(peer);
2109   ASSERT_TRUE(IsInitializing(peer));
2110   ASSERT_FALSE(peer->bonded());
2111 
2112   EXPECT_EQ(kIncomingConnTransactions, transaction_count());
2113 
2114   FakePairingDelegate pairing_delegate(sm::IOCapability::kDisplayYesNo);
2115   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
2116 
2117   EXPECT_CMD_PACKET_OUT(test_device(),
2118                         MakeIoCapabilityRequestReply(
2119                             IoCapability::DISPLAY_YES_NO,
2120                             AuthenticationRequirements::MITM_GENERAL_BONDING),
2121                         &kIoCapabilityRequestReplyRsp);
2122 
2123   test_device()->SendCommandChannelPacket(
2124       MakeIoCapabilityResponse(IoCapability::DISPLAY_YES_NO,
2125                                AuthenticationRequirements::GENERAL_BONDING));
2126   test_device()->SendCommandChannelPacket(kIoCapabilityRequest);
2127 
2128   pairing_delegate.SetDisplayPasskeyCallback(
2129       [](PeerId, uint32_t passkey, auto method, auto confirm_cb) {
2130         EXPECT_EQ(kPasskey, passkey);
2131         EXPECT_EQ(PairingDelegate::DisplayMethod::kComparison, method);
2132         ASSERT_TRUE(confirm_cb);
2133         confirm_cb(true);
2134       });
2135 
2136   EXPECT_CMD_PACKET_OUT(test_device(),
2137                         kUserConfirmationRequestReply,
2138                         &kUserConfirmationRequestReplyRsp);
2139   test_device()->SendCommandChannelPacket(
2140       MakeUserConfirmationRequest(kPasskey));
2141 
2142   pairing_delegate.SetCompletePairingCallback(
2143       [](PeerId, sm::Result<> status) { EXPECT_EQ(fit::ok(), status); });
2144 
2145   RETURN_IF_FATAL(RunUntilIdle());
2146   ASSERT_TRUE(IsInitializing(peer));
2147 
2148   test_device()->SendCommandChannelPacket(kSimplePairingCompleteSuccess);
2149   test_device()->SendCommandChannelPacket(kLinkKeyNotification);
2150 
2151   EXPECT_CMD_PACKET_OUT(test_device(),
2152                         kSetConnectionEncryption,
2153                         &kSetConnectionEncryptionRsp,
2154                         &kEncryptionChangeEvent);
2155   EXPECT_CMD_PACKET_OUT(
2156       test_device(), kReadEncryptionKeySize, &kReadEncryptionKeySizeRsp);
2157 
2158   RETURN_IF_FATAL(RunUntilIdle());
2159   ASSERT_TRUE(IsConnected(peer));
2160   EXPECT_TRUE(peer->bonded());
2161 
2162   EXPECT_CMD_PACKET_OUT(
2163       test_device(), kLinkKeyRequestReply, &kLinkKeyRequestReplyRsp);
2164   test_device()->SendCommandChannelPacket(kLinkKeyRequest);
2165 
2166   RunUntilIdle();
2167 
2168   QueueDisconnection(kConnectionHandle);
2169 }
2170 
2171 // Test: can't change the link key of an unbonded peer
TEST_F(BrEdrConnectionManagerTest,UnbondedPeerChangeLinkKey)2172 TEST_F(BrEdrConnectionManagerTest, UnbondedPeerChangeLinkKey) {
2173   QueueSuccessfulIncomingConn();
2174 
2175   test_device()->SendCommandChannelPacket(kConnectionRequest);
2176 
2177   RunUntilIdle();
2178 
2179   EXPECT_EQ(kIncomingConnTransactions, transaction_count());
2180 
2181   auto* peer = peer_cache()->FindByAddress(kTestDevAddr);
2182   ASSERT_TRUE(peer);
2183   ASSERT_TRUE(IsInitializing(peer));
2184   ASSERT_FALSE(peer->bonded());
2185 
2186   // Change the link key.
2187   test_device()->SendCommandChannelPacket(kLinkKeyNotificationChanged);
2188 
2189   RunUntilIdle();
2190   ASSERT_FALSE(IsConnected(peer));
2191   EXPECT_FALSE(peer->bonded());
2192 
2193   EXPECT_CMD_PACKET_OUT(
2194       test_device(), kLinkKeyRequestNegativeReply, &kLinkKeyRequestReplyRsp);
2195 
2196   test_device()->SendCommandChannelPacket(kLinkKeyRequest);
2197 
2198   RunUntilIdle();
2199 
2200   ASSERT_FALSE(IsConnected(peer));
2201   EXPECT_FALSE(peer->bonded());
2202   EXPECT_EQ(kIncomingConnTransactions + 1, transaction_count());
2203 
2204   QueueDisconnection(kConnectionHandle);
2205 }
2206 
2207 // Test: if L2CAP gets a link error, we disconnect the connection
TEST_F(BrEdrConnectionManagerTest,DisconnectOnLinkError)2208 TEST_F(BrEdrConnectionManagerTest, DisconnectOnLinkError) {
2209   QueueSuccessfulIncomingConn();
2210 
2211   test_device()->SendCommandChannelPacket(kConnectionRequest);
2212 
2213   RunUntilIdle();
2214 
2215   EXPECT_EQ(kIncomingConnTransactions, transaction_count());
2216 
2217   // When we deallocate the connection manager next, we should disconnect.
2218   QueueDisconnection(kConnectionHandle);
2219 
2220   l2cap()->TriggerLinkError(kConnectionHandle);
2221 
2222   RunUntilIdle();
2223 
2224   EXPECT_EQ(kIncomingConnTransactions + 1, transaction_count());
2225 }
2226 
TEST_F(BrEdrConnectionManagerTest,InitializingPeerDoesNotTimeout)2227 TEST_F(BrEdrConnectionManagerTest, InitializingPeerDoesNotTimeout) {
2228   QueueSuccessfulIncomingConn();
2229 
2230   test_device()->SendCommandChannelPacket(kConnectionRequest);
2231 
2232   RunUntilIdle();
2233 
2234   EXPECT_EQ(kIncomingConnTransactions, transaction_count());
2235 
2236   auto* peer = peer_cache()->FindByAddress(kTestDevAddr);
2237   ASSERT_TRUE(peer);
2238   EXPECT_FALSE(IsNotConnected(peer));
2239   EXPECT_FALSE(peer->bonded());
2240 
2241   // We want to make sure the connection doesn't expire just because they didn't
2242   // pair.
2243   RunFor(std::chrono::seconds(600));
2244 
2245   auto* peer_still = peer_cache()->FindByAddress(kTestDevAddr);
2246   ASSERT_TRUE(peer_still);
2247   ASSERT_EQ(peer->identifier(), peer_still->identifier());
2248 
2249   // Remote end disconnects.
2250   test_device()->SendCommandChannelPacket(kDisconnectionComplete);
2251 
2252   RunUntilIdle();
2253 
2254   // Peer should still be there, but not connected anymore, until they time out.
2255   peer = peer_cache()->FindByAddress(kTestDevAddr);
2256   ASSERT_TRUE(peer);
2257   EXPECT_TRUE(IsNotConnected(peer));
2258   EXPECT_FALSE(peer->bonded());
2259   EXPECT_EQ(kInvalidPeerId, connmgr()->GetPeerId(kConnectionHandle));
2260 }
2261 
tid_from_sdp_packet(const ByteBufferPtr & packet)2262 inline uint16_t tid_from_sdp_packet(const ByteBufferPtr& packet) {
2263   return (*packet)[1] << CHAR_BIT | (*packet)[2];
2264 }
2265 
TEST_F(BrEdrConnectionManagerTest,PeerServicesAddedBySearchAndRetainedIfNotSearchedFor)2266 TEST_F(BrEdrConnectionManagerTest,
2267        PeerServicesAddedBySearchAndRetainedIfNotSearchedFor) {
2268   constexpr UUID kServiceUuid1 = sdp::profile::kAudioSink;
2269   auto* const peer = peer_cache()->NewPeer(kTestDevAddr, /*connectable=*/true);
2270   peer->MutBrEdr().AddService(kServiceUuid1);
2271 
2272   // Search for different service.
2273   constexpr UUID kServiceUuid2 = sdp::profile::kAudioSource;
2274   size_t search_cb_count = 0;
2275   connmgr()->AddServiceSearch(kServiceUuid2,
2276                               {sdp::kServiceId},
2277                               [&](auto, auto&) { search_cb_count++; });
2278 
2279   l2cap::testing::FakeChannel::WeakPtr sdp_chan;
2280   std::optional<uint32_t> sdp_request_tid;
2281 
2282   l2cap()->set_channel_callback(
2283       [this, &sdp_chan, &sdp_request_tid](auto new_chan) {
2284         new_chan->SetSendCallback(
2285             [&sdp_request_tid](auto packet) {
2286               sdp_request_tid = tid_from_sdp_packet(packet);
2287             },
2288             dispatcher());
2289         sdp_chan = std::move(new_chan);
2290       });
2291 
2292   // No searches in this connection.
2293   QueueSuccessfulIncomingConn();
2294   l2cap()->ExpectOutboundL2capChannel(
2295       kConnectionHandle, l2cap::kSDP, 0x40, 0x41, kChannelParams);
2296 
2297   test_device()->SendCommandChannelPacket(kConnectionRequest);
2298 
2299   RunUntilIdle();
2300 
2301   ASSERT_TRUE(sdp_chan.is_alive());
2302   ASSERT_EQ(0u, search_cb_count);
2303 
2304   // Positive response to search.
2305   sdp::ServiceSearchAttributeResponse rsp;
2306   rsp.SetAttribute(0, sdp::kServiceId, sdp::DataElement(UUID()));
2307   auto rsp_ptr = rsp.GetPDU(0xFFFF /* max attribute bytes */,
2308                             *sdp_request_tid,
2309                             PDU_MAX,
2310                             BufferView());
2311 
2312   sdp_chan->Receive(*rsp_ptr);
2313 
2314   RunUntilIdle();
2315 
2316   ASSERT_EQ(1u, search_cb_count);
2317 
2318   // Prior connections' services retained and newly discovered service added.
2319   EXPECT_EQ(1u, peer->bredr()->services().count(kServiceUuid1));
2320   EXPECT_EQ(1u, peer->bredr()->services().count(kServiceUuid2));
2321 
2322   QueueDisconnection(kConnectionHandle);
2323 }
2324 
TEST_F(BrEdrConnectionManagerTest,PeerServiceNotErasedByEmptyResultsForSearchOfSameService)2325 TEST_F(BrEdrConnectionManagerTest,
2326        PeerServiceNotErasedByEmptyResultsForSearchOfSameService) {
2327   constexpr UUID kServiceUuid = sdp::profile::kAudioSink;
2328   auto* const peer = peer_cache()->NewPeer(kTestDevAddr, /*connectable=*/true);
2329   peer->MutBrEdr().AddService(kServiceUuid);
2330 
2331   size_t search_cb_count = 0;
2332   connmgr()->AddServiceSearch(
2333       kServiceUuid, {sdp::kServiceId}, [&](auto, auto&) { search_cb_count++; });
2334 
2335   l2cap::testing::FakeChannel::WeakPtr sdp_chan;
2336   std::optional<uint32_t> sdp_request_tid;
2337 
2338   l2cap()->set_channel_callback(
2339       [this, &sdp_chan, &sdp_request_tid](auto new_chan) {
2340         new_chan->SetSendCallback(
2341             [&sdp_request_tid](auto packet) {
2342               sdp_request_tid = tid_from_sdp_packet(packet);
2343             },
2344             dispatcher());
2345         sdp_chan = std::move(new_chan);
2346       });
2347 
2348   QueueSuccessfulIncomingConn();
2349   l2cap()->ExpectOutboundL2capChannel(
2350       kConnectionHandle, l2cap::kSDP, 0x40, 0x41, kChannelParams);
2351 
2352   test_device()->SendCommandChannelPacket(kConnectionRequest);
2353 
2354   RunUntilIdle();
2355 
2356   ASSERT_TRUE(sdp_chan.is_alive());
2357   ASSERT_EQ(0u, search_cb_count);
2358 
2359   sdp::ServiceSearchAttributeResponse empty_rsp;
2360   auto rsp_ptr = empty_rsp.GetPDU(0xFFFF /* max attribute bytes */,
2361                                   *sdp_request_tid,
2362                                   PDU_MAX,
2363                                   BufferView());
2364 
2365   sdp_chan->Receive(*rsp_ptr);
2366 
2367   RunUntilIdle();
2368 
2369   // Search callback isn't called by empty attribute list from peer.
2370   ASSERT_EQ(0u, search_cb_count);
2371 
2372   EXPECT_EQ(1u, peer->bredr()->services().count(kServiceUuid));
2373 
2374   QueueDisconnection(kConnectionHandle);
2375 }
2376 
MakeAudioSinkSearchExpected(std::optional<uint16_t> * tid)2377 l2cap::testing::FakeChannel::SendCallback MakeAudioSinkSearchExpected(
2378     std::optional<uint16_t>* tid) {
2379   return [tid](auto packet) {
2380     const StaticByteBuffer kSearchExpectedParams(
2381         // ServiceSearchPattern
2382         0x35,
2383         0x03,  // Sequence uint8 3 bytes
2384         0x19,
2385         0x11,
2386         0x0B,  // UUID (kAudioSink)
2387         0xFF,
2388         0xFF,  // MaxAttributeByteCount (no max)
2389         // Attribute ID list
2390         0x35,
2391         0x03,  // Sequence uint8 3 bytes
2392         0x09,
2393         0x00,
2394         0x03,  // uint16_t (kServiceId)
2395         0x00   // No continuation state
2396     );
2397     // First byte should be type.
2398     ASSERT_LE(3u, packet->size());
2399     ASSERT_EQ(sdp::kServiceSearchAttributeRequest, (*packet)[0]);
2400     ASSERT_EQ(kSearchExpectedParams, packet->view(sizeof(bt::sdp::Header)));
2401     if (tid != nullptr) {
2402     }
2403     *tid = tid_from_sdp_packet(packet);
2404   };
2405 }
2406 
TEST_F(BrEdrConnectionManagerTest,ServiceSearch)2407 TEST_F(BrEdrConnectionManagerTest, ServiceSearch) {
2408   size_t search_cb_count = 0;
2409   auto search_cb = [&](auto id, const auto& attributes) {
2410     auto* peer = peer_cache()->FindByAddress(kTestDevAddr);
2411     ASSERT_TRUE(peer);
2412     ASSERT_EQ(id, peer->identifier());
2413     ASSERT_EQ(1u, attributes.count(sdp::kServiceId));
2414     search_cb_count++;
2415   };
2416 
2417   auto search_id = connmgr()->AddServiceSearch(
2418       sdp::profile::kAudioSink, {sdp::kServiceId}, search_cb);
2419 
2420   l2cap::testing::FakeChannel::WeakPtr sdp_chan;
2421   std::optional<uint16_t> sdp_request_tid;
2422 
2423   l2cap()->set_channel_callback(
2424       [&sdp_chan, &sdp_request_tid, this](auto new_chan) {
2425         new_chan->SetSendCallback(MakeAudioSinkSearchExpected(&sdp_request_tid),
2426                                   dispatcher());
2427         sdp_chan = std::move(new_chan);
2428       });
2429 
2430   QueueSuccessfulIncomingConn();
2431   l2cap()->ExpectOutboundL2capChannel(
2432       kConnectionHandle, l2cap::kSDP, 0x40, 0x41, kChannelParams);
2433 
2434   test_device()->SendCommandChannelPacket(kConnectionRequest);
2435 
2436   RunUntilIdle();
2437 
2438   ASSERT_TRUE(sdp_chan.is_alive());
2439   ASSERT_TRUE(sdp_request_tid);
2440   ASSERT_EQ(0u, search_cb_count);
2441 
2442   sdp::ServiceSearchAttributeResponse rsp;
2443   rsp.SetAttribute(0, sdp::kServiceId, sdp::DataElement(UUID()));
2444   auto rsp_ptr = rsp.GetPDU(0xFFFF /* max attribute bytes */,
2445                             *sdp_request_tid,
2446                             PDU_MAX,
2447                             BufferView());
2448 
2449   sdp_chan->Receive(*rsp_ptr);
2450 
2451   RunUntilIdle();
2452 
2453   ASSERT_EQ(1u, search_cb_count);
2454 
2455   // Remote end disconnects.
2456   test_device()->SendCommandChannelPacket(kDisconnectionComplete);
2457 
2458   RunUntilIdle();
2459 
2460   sdp_request_tid.reset();
2461 
2462   EXPECT_TRUE(connmgr()->RemoveServiceSearch(search_id));
2463   EXPECT_FALSE(connmgr()->RemoveServiceSearch(search_id));
2464 
2465   // Second connection is shortened because we have already interrogated,
2466   // and we don't search for SDP services because none are registered
2467   EXPECT_CMD_PACKET_OUT(test_device(),
2468                         kAcceptConnectionRequest,
2469                         &kAcceptConnectionRequestRsp,
2470                         &kConnectionComplete);
2471   EXPECT_CMD_PACKET_OUT(test_device(),
2472                         kReadRemoteExtended1,
2473                         &kReadRemoteExtendedFeaturesRsp,
2474                         &kReadRemoteExtended1Complete);
2475   EXPECT_CMD_PACKET_OUT(test_device(),
2476                         kReadRemoteExtended2,
2477                         &kReadRemoteExtendedFeaturesRsp,
2478                         &kReadRemoteExtended2Complete);
2479 
2480   test_device()->SendCommandChannelPacket(kConnectionRequest);
2481   RunUntilIdle();
2482 
2483   // We shouldn't have searched for anything.
2484   ASSERT_FALSE(sdp_request_tid);
2485   ASSERT_EQ(1u, search_cb_count);
2486 
2487   QueueDisconnection(kConnectionHandle);
2488 }
2489 
TEST_F(BrEdrConnectionManagerTest,SearchAfterConnected)2490 TEST_F(BrEdrConnectionManagerTest, SearchAfterConnected) {
2491   // We have no services registered, so this will not start a SDP search.
2492   QueueSuccessfulIncomingConn();
2493   test_device()->SendCommandChannelPacket(kConnectionRequest);
2494 
2495   RunUntilIdle();
2496 
2497   size_t search_cb_count = 0;
2498   auto search_cb = [&](auto id, const auto& attributes) {
2499     auto* peer = peer_cache()->FindByAddress(kTestDevAddr);
2500     ASSERT_TRUE(peer);
2501     ASSERT_EQ(id, peer->identifier());
2502     ASSERT_EQ(1u, attributes.count(sdp::kServiceId));
2503     search_cb_count++;
2504   };
2505 
2506   l2cap::testing::FakeChannel::WeakPtr sdp_chan;
2507   std::optional<uint16_t> sdp_request_tid;
2508 
2509   l2cap()->set_channel_callback(
2510       [&sdp_chan, &sdp_request_tid, this](auto new_chan) {
2511         new_chan->SetSendCallback(MakeAudioSinkSearchExpected(&sdp_request_tid),
2512                                   dispatcher());
2513         sdp_chan = std::move(new_chan);
2514       });
2515 
2516   l2cap()->ExpectOutboundL2capChannel(
2517       kConnectionHandle, l2cap::kSDP, 0x40, 0x41, kChannelParams);
2518 
2519   // When this gets added, the service search will immediately be done on the
2520   // already-connected peer.
2521   auto search_id = connmgr()->AddServiceSearch(
2522       sdp::profile::kAudioSink, {sdp::kServiceId}, search_cb);
2523 
2524   ASSERT_NE(sdp::ServiceDiscoverer::kInvalidSearchId, search_id);
2525 
2526   RunUntilIdle();
2527 
2528   ASSERT_TRUE(sdp_chan.is_alive());
2529   ASSERT_TRUE(sdp_request_tid);
2530   ASSERT_EQ(0u, search_cb_count);
2531 
2532   sdp::ServiceSearchAttributeResponse rsp;
2533   rsp.SetAttribute(0, sdp::kServiceId, sdp::DataElement(UUID()));
2534   auto rsp_ptr = rsp.GetPDU(0xFFFF /* max attribute bytes */,
2535                             *sdp_request_tid,
2536                             PDU_MAX,
2537                             BufferView());
2538 
2539   sdp_chan->Receive(*rsp_ptr);
2540 
2541   RunUntilIdle();
2542 
2543   ASSERT_EQ(1u, search_cb_count);
2544 
2545   // Remote end disconnects.
2546   test_device()->SendCommandChannelPacket(kDisconnectionComplete);
2547 
2548   RunUntilIdle();
2549 
2550   sdp_request_tid.reset();
2551   sdp_chan.reset();
2552 
2553   // Second connection is shortened because we have already interrogated,
2554   // we repeat the search for SDP services.
2555   EXPECT_CMD_PACKET_OUT(test_device(),
2556                         kAcceptConnectionRequest,
2557                         &kAcceptConnectionRequestRsp,
2558                         &kConnectionComplete);
2559   EXPECT_CMD_PACKET_OUT(test_device(),
2560                         kReadRemoteExtended1,
2561                         &kReadRemoteExtendedFeaturesRsp,
2562                         &kReadRemoteExtended1Complete);
2563   EXPECT_CMD_PACKET_OUT(test_device(),
2564                         kReadRemoteExtended2,
2565                         &kReadRemoteExtendedFeaturesRsp,
2566                         &kReadRemoteExtended2Complete);
2567 
2568   l2cap()->ExpectOutboundL2capChannel(
2569       kConnectionHandle, l2cap::kSDP, 0x40, 0x41, kChannelParams);
2570 
2571   test_device()->SendCommandChannelPacket(kConnectionRequest);
2572   RunUntilIdle();
2573 
2574   ASSERT_TRUE(sdp_chan.is_alive());
2575   ASSERT_TRUE(sdp_request_tid);
2576   ASSERT_EQ(1u, search_cb_count);
2577 
2578   // Reusing the (empty) answer from before
2579   rsp_ptr = rsp.GetPDU(0xFFFF /* max attribute bytes */,
2580                        *sdp_request_tid,
2581                        PDU_MAX,
2582                        BufferView());
2583 
2584   sdp_chan->Receive(*rsp_ptr);
2585 
2586   // We should have another search callback.
2587   ASSERT_EQ(2u, search_cb_count);
2588 
2589   QueueDisconnection(kConnectionHandle);
2590 }
2591 
TEST_F(BrEdrConnectionManagerLegacyPairingTest,SearchOnReconnect)2592 TEST_F(BrEdrConnectionManagerLegacyPairingTest, SearchOnReconnect) {
2593   size_t search_cb_count = 0;
2594   auto search_cb = [&](auto id, const auto& attributes) {
2595     auto* peer = peer_cache()->FindByAddress(kTestDevAddr);
2596     ASSERT_TRUE(peer);
2597     ASSERT_EQ(id, peer->identifier());
2598     ASSERT_EQ(1u, attributes.count(sdp::kServiceId));
2599     search_cb_count++;
2600   };
2601 
2602   connmgr()->AddServiceSearch(
2603       sdp::profile::kAudioSink, {sdp::kServiceId}, search_cb);
2604 
2605   l2cap::testing::FakeChannel::WeakPtr sdp_chan;
2606   std::optional<uint16_t> sdp_request_tid;
2607 
2608   l2cap()->set_channel_callback(
2609       [&sdp_chan, &sdp_request_tid, this](auto new_chan) {
2610         new_chan->SetSendCallback(MakeAudioSinkSearchExpected(&sdp_request_tid),
2611                                   dispatcher());
2612         sdp_chan = std::move(new_chan);
2613       });
2614 
2615   // This test uses a modified peer and interrogation which doesn't use extended
2616   // pages.
2617   EXPECT_CMD_PACKET_OUT(test_device(),
2618                         kAcceptConnectionRequest,
2619                         &kAcceptConnectionRequestRsp,
2620                         &kConnectionComplete);
2621   const DynamicByteBuffer remote_name_complete_packet =
2622       testing::RemoteNameRequestCompletePacket(kTestDevAddr);
2623   const DynamicByteBuffer remote_version_complete_packet =
2624       testing::ReadRemoteVersionInfoCompletePacket(kConnectionHandle);
2625   const DynamicByteBuffer remote_supported_complete_packet =
2626       testing::ReadRemoteSupportedFeaturesCompletePacket(
2627           kConnectionHandle,
2628           /*extended_features=*/false);
2629 
2630   EXPECT_CMD_PACKET_OUT(test_device(),
2631                         testing::RemoteNameRequestPacket(kTestDevAddr),
2632                         &kRemoteNameRequestRsp,
2633                         &remote_name_complete_packet);
2634   EXPECT_CMD_PACKET_OUT(test_device(),
2635                         testing::ReadRemoteVersionInfoPacket(kConnectionHandle),
2636                         &kReadRemoteVersionInfoRsp,
2637                         &remote_version_complete_packet);
2638   EXPECT_CMD_PACKET_OUT(
2639       test_device(),
2640       testing::ReadRemoteSupportedFeaturesPacket(kConnectionHandle),
2641       &kReadRemoteSupportedFeaturesRsp,
2642       &remote_supported_complete_packet);
2643 
2644   l2cap()->ExpectOutboundL2capChannel(
2645       kConnectionHandle, l2cap::kSDP, 0x40, 0x41, kChannelParams);
2646 
2647   test_device()->SendCommandChannelPacket(kConnectionRequest);
2648 
2649   RunUntilIdle();
2650 
2651   ASSERT_TRUE(sdp_chan.is_alive());
2652   ASSERT_TRUE(sdp_request_tid);
2653   ASSERT_EQ(0u, search_cb_count);
2654 
2655   sdp::ServiceSearchAttributeResponse rsp;
2656   rsp.SetAttribute(0, sdp::kServiceId, sdp::DataElement(UUID()));
2657   auto rsp_ptr = rsp.GetPDU(0xFFFF /* max attribute bytes */,
2658                             *sdp_request_tid,
2659                             PDU_MAX,
2660                             BufferView());
2661 
2662   sdp_chan->Receive(*rsp_ptr);
2663 
2664   RunUntilIdle();
2665 
2666   ASSERT_EQ(1u, search_cb_count);
2667 
2668   // Remote end disconnects.
2669   test_device()->SendCommandChannelPacket(kDisconnectionComplete);
2670 
2671   RunUntilIdle();
2672 
2673   sdp_request_tid.reset();
2674   sdp_chan.reset();
2675 
2676   // Second connection is shortened because we have already interrogated.
2677   // We still search for SDP services.
2678   EXPECT_CMD_PACKET_OUT(test_device(),
2679                         kAcceptConnectionRequest,
2680                         &kAcceptConnectionRequestRsp,
2681                         &kConnectionComplete);
2682   // We don't send any interrogation packets, because there is none to be done.
2683 
2684   l2cap()->ExpectOutboundL2capChannel(
2685       kConnectionHandle, l2cap::kSDP, 0x40, 0x41, kChannelParams);
2686 
2687   test_device()->SendCommandChannelPacket(kConnectionRequest);
2688   RunUntilIdle();
2689 
2690   // We should have searched again.
2691   ASSERT_TRUE(sdp_chan.is_alive());
2692   ASSERT_TRUE(sdp_request_tid);
2693   ASSERT_EQ(1u, search_cb_count);
2694 
2695   rsp_ptr = rsp.GetPDU(0xFFFF /* max attribute bytes */,
2696                        *sdp_request_tid,
2697                        PDU_MAX,
2698                        BufferView());
2699 
2700   sdp_chan->Receive(*rsp_ptr);
2701 
2702   RunUntilIdle();
2703 
2704   ASSERT_EQ(2u, search_cb_count);
2705 
2706   QueueDisconnection(kConnectionHandle);
2707 }
2708 
2709 // Test: when opening an L2CAP channel on an unbonded peer, indicate that we
2710 // have no link key then pair, authenticate, bond, and encrypt the link, then
2711 // try to open the channel.
TEST_F(BrEdrConnectionManagerTest,OpenL2capPairsAndEncryptsThenRetries)2712 TEST_F(BrEdrConnectionManagerTest, OpenL2capPairsAndEncryptsThenRetries) {
2713   QueueSuccessfulIncomingConn();
2714 
2715   test_device()->SendCommandChannelPacket(kConnectionRequest);
2716 
2717   RunUntilIdle();
2718 
2719   EXPECT_EQ(kIncomingConnTransactions, transaction_count());
2720   auto* const peer = peer_cache()->FindByAddress(kTestDevAddr);
2721   ASSERT_TRUE(peer);
2722   ASSERT_FALSE(IsNotConnected(peer));
2723 
2724   std::optional<l2cap::Channel::WeakPtr> connected_chan;
2725 
2726   auto chan_cb = [&](auto chan) { connected_chan = std::move(chan); };
2727 
2728   FakePairingDelegate pairing_delegate(sm::IOCapability::kDisplayYesNo);
2729   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
2730 
2731   // Approve pairing requests.
2732   pairing_delegate.SetDisplayPasskeyCallback(
2733       [](PeerId, uint32_t, auto, auto confirm_cb) {
2734         ASSERT_TRUE(confirm_cb);
2735         confirm_cb(true);
2736       });
2737 
2738   pairing_delegate.SetCompletePairingCallback(
2739       [](PeerId, sm::Result<> status) { EXPECT_EQ(fit::ok(), status); });
2740 
2741   // Initial connection request
2742 
2743   // Pairing initiation and flow that results in bonding then encryption, but
2744   // verifying the strength of the encryption key doesn't complete
2745   EXPECT_CMD_PACKET_OUT(test_device(),
2746                         kAuthenticationRequested,
2747                         &kAuthenticationRequestedStatus,
2748                         &kLinkKeyRequest);
2749   EXPECT_CMD_PACKET_OUT(test_device(),
2750                         kLinkKeyRequestNegativeReply,
2751                         &kLinkKeyRequestNegativeReplyRsp,
2752                         &kIoCapabilityRequest);
2753   const auto kIoCapabilityResponse = MakeIoCapabilityResponse(
2754       IoCapability::DISPLAY_YES_NO,
2755       AuthenticationRequirements::MITM_GENERAL_BONDING);
2756   const auto kUserConfirmationRequest = MakeUserConfirmationRequest(kPasskey);
2757   EXPECT_CMD_PACKET_OUT(test_device(),
2758                         MakeIoCapabilityRequestReply(
2759                             IoCapability::DISPLAY_YES_NO,
2760                             AuthenticationRequirements::MITM_GENERAL_BONDING),
2761                         &kIoCapabilityRequestReplyRsp,
2762                         &kIoCapabilityResponse,
2763                         &kUserConfirmationRequest);
2764   EXPECT_CMD_PACKET_OUT(test_device(),
2765                         kUserConfirmationRequestReply,
2766                         &kUserConfirmationRequestReplyRsp,
2767                         &kSimplePairingCompleteSuccess,
2768                         &kLinkKeyNotification,
2769                         &kAuthenticationComplete);
2770   EXPECT_CMD_PACKET_OUT(test_device(),
2771                         kSetConnectionEncryption,
2772                         &kSetConnectionEncryptionRsp,
2773                         &kEncryptionChangeEvent);
2774   EXPECT_CMD_PACKET_OUT(test_device(), kReadEncryptionKeySize, );
2775 
2776   connmgr()->OpenL2capChannel(peer->identifier(),
2777                               l2cap::kAVDTP,
2778                               kNoSecurityRequirements,
2779                               kChannelParams,
2780                               chan_cb);
2781 
2782   RETURN_IF_FATAL(RunUntilIdle());
2783 
2784   // We should not have a channel because the L2CAP open callback shouldn't have
2785   // been called, but the LTK should be stored since the link key got received.
2786   ASSERT_FALSE(connected_chan);
2787   // We should be initializing, since we have not completed pairing.
2788   ASSERT_TRUE(IsInitializing(peer));
2789 
2790   test_device()->SendCommandChannelPacket(kReadEncryptionKeySizeRsp);
2791 
2792   l2cap()->ExpectOutboundL2capChannel(
2793       kConnectionHandle, l2cap::kAVDTP, 0x40, 0x41, kChannelParams);
2794 
2795   RETURN_IF_FATAL(RunUntilIdle());
2796   // We should signal to PeerCache as connected once we finish pairing.
2797   ASSERT_TRUE(IsConnected(peer));
2798 
2799   // The socket should be returned.
2800   ASSERT_TRUE(connected_chan);
2801 
2802   connected_chan.reset();
2803 
2804   l2cap()->ExpectOutboundL2capChannel(
2805       kConnectionHandle, l2cap::kAVDTP, 0x40, 0x41, kChannelParams);
2806 
2807   // A second connection request should not require another authentication.
2808   connmgr()->OpenL2capChannel(peer->identifier(),
2809                               l2cap::kAVDTP,
2810                               kNoSecurityRequirements,
2811                               kChannelParams,
2812                               chan_cb);
2813 
2814   RunUntilIdle();
2815 
2816   ASSERT_TRUE(connected_chan);
2817 
2818   QueueDisconnection(kConnectionHandle);
2819 }
2820 
2821 // Test: when the peer is already bonded, the link key gets stored when it is
2822 // provided to the connection.
TEST_F(BrEdrConnectionManagerTest,OpenL2capEncryptsForBondedPeerThenRetries)2823 TEST_F(BrEdrConnectionManagerTest, OpenL2capEncryptsForBondedPeerThenRetries) {
2824   ASSERT_TRUE(
2825       peer_cache()->AddBondedPeer(BondingData{.identifier = PeerId(999),
2826                                               .address = kTestDevAddr,
2827                                               .name = std::nullopt,
2828                                               .le_pairing_data = {},
2829                                               .bredr_link_key = kLinkKey,
2830                                               .bredr_services = {}}));
2831   auto* const peer = peer_cache()->FindByAddress(kTestDevAddr);
2832   ASSERT_TRUE(peer);
2833   ASSERT_TRUE(IsNotConnected(peer));
2834   ASSERT_TRUE(peer->bonded());
2835 
2836   FakePairingDelegate pairing_delegate(sm::IOCapability::kDisplayYesNo);
2837   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
2838 
2839   QueueSuccessfulIncomingConn();
2840 
2841   test_device()->SendCommandChannelPacket(kConnectionRequest);
2842 
2843   RunUntilIdle();
2844 
2845   EXPECT_EQ(kIncomingConnTransactions, transaction_count());
2846   ASSERT_FALSE(IsNotConnected(peer));
2847 
2848   std::optional<l2cap::Channel::WeakPtr> connected_chan;
2849 
2850   auto socket_cb = [&](auto chan) { connected_chan = std::move(chan); };
2851 
2852   // Initial connection request
2853 
2854   // Note: this skips some parts of the pairing flow, because the link key being
2855   // received is the important part of this. The key is not received when the
2856   // authentication fails.
2857   EXPECT_CMD_PACKET_OUT(
2858       test_device(), kAuthenticationRequested, &kAuthenticationRequestedStatus);
2859 
2860   connmgr()->OpenL2capChannel(peer->identifier(),
2861                               l2cap::kAVDTP,
2862                               kNoSecurityRequirements,
2863                               kChannelParams,
2864                               socket_cb);
2865 
2866   RunUntilIdle();
2867 
2868   // L2CAP connect shouldn't have been called, and callback shouldn't be called.
2869   // We should not have a socket.
2870   ASSERT_FALSE(connected_chan);
2871   ASSERT_FALSE(IsNotConnected(peer));
2872 
2873   // The authentication flow will request the existing link key, which should be
2874   // returned and stored, and then the authentication is complete.
2875   EXPECT_CMD_PACKET_OUT(test_device(),
2876                         kLinkKeyRequestReply,
2877                         &kLinkKeyRequestReplyRsp,
2878                         &kAuthenticationComplete);
2879 
2880   test_device()->SendCommandChannelPacket(kLinkKeyRequest);
2881 
2882   EXPECT_CMD_PACKET_OUT(test_device(),
2883                         kSetConnectionEncryption,
2884                         &kSetConnectionEncryptionRsp,
2885                         &kEncryptionChangeEvent);
2886   EXPECT_CMD_PACKET_OUT(test_device(), kReadEncryptionKeySize, );
2887 
2888   RunUntilIdle();
2889 
2890   // No socket until the encryption verification completes.
2891   ASSERT_FALSE(connected_chan);
2892 
2893   test_device()->SendCommandChannelPacket(kReadEncryptionKeySizeRsp);
2894 
2895   l2cap()->ExpectOutboundL2capChannel(
2896       kConnectionHandle, l2cap::kAVDTP, 0x40, 0x41, kChannelParams);
2897 
2898   RunUntilIdle();
2899 
2900   // Once the L2CAP channel has connected, we have connected.
2901   ASSERT_TRUE(IsConnected(peer));
2902 
2903   // The socket should be connected.
2904   ASSERT_TRUE(connected_chan);
2905 
2906   QueueDisconnection(kConnectionHandle);
2907 }
2908 
TEST_F(BrEdrConnectionManagerTest,OpenL2capAuthenticationFailureReturnsInvalidSocketAndDisconnects)2909 TEST_F(BrEdrConnectionManagerTest,
2910        OpenL2capAuthenticationFailureReturnsInvalidSocketAndDisconnects) {
2911   QueueSuccessfulIncomingConn();
2912 
2913   FakePairingDelegate pairing_delegate(sm::IOCapability::kDisplayYesNo);
2914   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
2915 
2916   test_device()->SendCommandChannelPacket(kConnectionRequest);
2917 
2918   RunUntilIdle();
2919 
2920   EXPECT_EQ(kIncomingConnTransactions, transaction_count());
2921   auto* const peer = peer_cache()->FindByAddress(kTestDevAddr);
2922   ASSERT_TRUE(peer);
2923   ASSERT_FALSE(IsNotConnected(peer));
2924 
2925   std::optional<l2cap::Channel::WeakPtr> connected_chan;
2926 
2927   auto socket_cb = [&](auto chan) { connected_chan = std::move(chan); };
2928 
2929   // Initial connection request
2930 
2931   // Note: this skips some parts of the pairing flow, because the link key being
2932   // received is the important part of this. The key is not received when the
2933   // authentication fails.
2934   EXPECT_CMD_PACKET_OUT(
2935       test_device(), kAuthenticationRequested, &kAuthenticationRequestedStatus);
2936 
2937   connmgr()->OpenL2capChannel(peer->identifier(),
2938                               l2cap::kAVDTP,
2939                               kNoSecurityRequirements,
2940                               kChannelParams,
2941                               socket_cb);
2942 
2943   RunUntilIdle();
2944 
2945   // The L2CAP shouldn't have been called
2946   // We should not have a channel, and the callback shouldn't have been called.
2947   ASSERT_FALSE(connected_chan);
2948 
2949   test_device()->SendCommandChannelPacket(kAuthenticationCompleteFailed);
2950 
2951   int count = transaction_count();
2952 
2953   // We disconnect the peer when authentication fails.
2954   QueueDisconnection(kConnectionHandle);
2955 
2956   RunUntilIdle();
2957 
2958   // An invalid channel should have been sent because the connection failed.
2959   ASSERT_TRUE(connected_chan);
2960   ASSERT_FALSE(connected_chan.value().is_alive());
2961 
2962   ASSERT_EQ(count + kDisconnectionTransactions, transaction_count());
2963 }
2964 
TEST_F(BrEdrConnectionManagerTest,OpenL2capPairingFinishesButDisconnects)2965 TEST_F(BrEdrConnectionManagerTest, OpenL2capPairingFinishesButDisconnects) {
2966   QueueSuccessfulIncomingConn();
2967 
2968   test_device()->SendCommandChannelPacket(kConnectionRequest);
2969 
2970   RunUntilIdle();
2971 
2972   EXPECT_EQ(kIncomingConnTransactions, transaction_count());
2973   auto* const peer = peer_cache()->FindByAddress(kTestDevAddr);
2974   ASSERT_TRUE(peer);
2975   ASSERT_FALSE(IsNotConnected(peer));
2976 
2977   FakePairingDelegate pairing_delegate(sm::IOCapability::kDisplayYesNo);
2978   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
2979 
2980   // Approve pairing requests.
2981   pairing_delegate.SetDisplayPasskeyCallback(
2982       [](PeerId, uint32_t, auto, auto confirm_cb) {
2983         ASSERT_TRUE(confirm_cb);
2984         confirm_cb(true);
2985       });
2986 
2987   pairing_delegate.SetCompletePairingCallback(
2988       [](PeerId, sm::Result<> status) { EXPECT_EQ(fit::ok(), status); });
2989 
2990   // Initial connection request
2991 
2992   // Pairing initiation and flow that results in bonding then encryption, but
2993   // verifying the strength of the encryption key doesn't complete
2994   EXPECT_CMD_PACKET_OUT(test_device(),
2995                         kAuthenticationRequested,
2996                         &kAuthenticationRequestedStatus,
2997                         &kLinkKeyRequest);
2998   EXPECT_CMD_PACKET_OUT(test_device(),
2999                         kLinkKeyRequestNegativeReply,
3000                         &kLinkKeyRequestNegativeReplyRsp,
3001                         &kIoCapabilityRequest);
3002   const auto kIoCapabilityResponse = MakeIoCapabilityResponse(
3003       IoCapability::DISPLAY_YES_NO,
3004       AuthenticationRequirements::MITM_GENERAL_BONDING);
3005   const auto kUserConfirmationRequest = MakeUserConfirmationRequest(kPasskey);
3006   EXPECT_CMD_PACKET_OUT(test_device(),
3007                         MakeIoCapabilityRequestReply(
3008                             IoCapability::DISPLAY_YES_NO,
3009                             AuthenticationRequirements::MITM_GENERAL_BONDING),
3010                         &kIoCapabilityRequestReplyRsp,
3011                         &kIoCapabilityResponse,
3012                         &kUserConfirmationRequest);
3013   EXPECT_CMD_PACKET_OUT(test_device(),
3014                         kUserConfirmationRequestReply,
3015                         &kUserConfirmationRequestReplyRsp,
3016                         &kSimplePairingCompleteSuccess,
3017                         &kLinkKeyNotification,
3018                         &kAuthenticationComplete);
3019   EXPECT_CMD_PACKET_OUT(test_device(),
3020                         kSetConnectionEncryption,
3021                         &kSetConnectionEncryptionRsp,
3022                         &kEncryptionChangeEvent);
3023   EXPECT_CMD_PACKET_OUT(test_device(), kReadEncryptionKeySize, );
3024 
3025   std::optional<l2cap::Channel::WeakPtr> connected_chan;
3026 
3027   auto chan_cb = [&](auto chan) { connected_chan = std::move(chan); };
3028   connmgr()->OpenL2capChannel(peer->identifier(),
3029                               l2cap::kAVDTP,
3030                               kNoSecurityRequirements,
3031                               kChannelParams,
3032                               chan_cb);
3033 
3034   RETURN_IF_FATAL(RunUntilIdle());
3035 
3036   // We should not have a channel because the L2CAP open callback shouldn't have
3037   // been called, but the LTK should be stored since the link key got received.
3038   ASSERT_FALSE(connected_chan);
3039 
3040   // The remote device disconnects now, when the pairing has been started, then
3041   // pairing completes.
3042   test_device()->SendCommandChannelPacket(kDisconnectionComplete);
3043   test_device()->SendCommandChannelPacket(kReadEncryptionKeySizeRsp);
3044   RunUntilIdle();
3045 
3046   // We should get a callback from the OpenL2capChannel
3047   ASSERT_TRUE(connected_chan);
3048   EXPECT_FALSE(connected_chan.value().is_alive());
3049 
3050   connected_chan.reset();
3051 
3052   connmgr()->OpenL2capChannel(peer->identifier(),
3053                               l2cap::kAVDTP,
3054                               kNoSecurityRequirements,
3055                               kChannelParams,
3056                               chan_cb);
3057 
3058   // The L2CAP should be called right away without a channel.
3059   ASSERT_TRUE(connected_chan);
3060   EXPECT_FALSE(connected_chan.value().is_alive());
3061 
3062   connected_chan.reset();
3063 }
3064 
3065 // Test: when pairing is in progress, opening an L2CAP channel waits for the
3066 // pairing to complete before retrying.
TEST_F(BrEdrConnectionManagerTest,OpenL2capDuringPairingWaitsForPairingToComplete)3067 TEST_F(BrEdrConnectionManagerTest,
3068        OpenL2capDuringPairingWaitsForPairingToComplete) {
3069   QueueSuccessfulIncomingConn();
3070 
3071   test_device()->SendCommandChannelPacket(kConnectionRequest);
3072 
3073   RunUntilIdle();
3074 
3075   EXPECT_EQ(kIncomingConnTransactions, transaction_count());
3076   auto* const peer = peer_cache()->FindByAddress(kTestDevAddr);
3077   ASSERT_TRUE(peer);
3078   ASSERT_FALSE(IsNotConnected(peer));
3079 
3080   std::optional<l2cap::Channel::WeakPtr> connected_chan;
3081 
3082   auto socket_cb = [&](auto chan) { connected_chan = std::move(chan); };
3083 
3084   FakePairingDelegate pairing_delegate(sm::IOCapability::kDisplayYesNo);
3085   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
3086 
3087   // Approve pairing requests
3088   pairing_delegate.SetDisplayPasskeyCallback(
3089       [](PeerId, uint32_t, auto, auto confirm_cb) {
3090         ASSERT_TRUE(confirm_cb);
3091         confirm_cb(true);
3092       });
3093 
3094   pairing_delegate.SetCompletePairingCallback(
3095       [](PeerId, sm::Result<> status) { EXPECT_EQ(fit::ok(), status); });
3096 
3097   // Initiate pairing from the peer
3098   test_device()->SendCommandChannelPacket(MakeIoCapabilityResponse(
3099       IoCapability::DISPLAY_YES_NO,
3100       AuthenticationRequirements::MITM_GENERAL_BONDING));
3101 
3102   RETURN_IF_FATAL(RunUntilIdle());
3103 
3104   // Initial connection request
3105 
3106   // Pair and bond as the responder. Note that Authentication Requested is not
3107   // sent even though we are opening the L2CAP channel because the peer started
3108   // pairing first.
3109   test_device()->SendCommandChannelPacket(kIoCapabilityRequest);
3110   const auto kUserConfirmationRequest = MakeUserConfirmationRequest(kPasskey);
3111   EXPECT_CMD_PACKET_OUT(test_device(),
3112                         MakeIoCapabilityRequestReply(
3113                             IoCapability::DISPLAY_YES_NO,
3114                             AuthenticationRequirements::MITM_GENERAL_BONDING),
3115                         &kIoCapabilityRequestReplyRsp,
3116                         &kUserConfirmationRequest);
3117   EXPECT_CMD_PACKET_OUT(test_device(),
3118                         kUserConfirmationRequestReply,
3119                         &kUserConfirmationRequestReplyRsp,
3120                         &kSimplePairingCompleteSuccess,
3121                         &kLinkKeyNotification);
3122   EXPECT_CMD_PACKET_OUT(test_device(),
3123                         kSetConnectionEncryption,
3124                         &kSetConnectionEncryptionRsp,
3125                         &kEncryptionChangeEvent);
3126   EXPECT_CMD_PACKET_OUT(test_device(), kReadEncryptionKeySize, );
3127 
3128   connmgr()->OpenL2capChannel(peer->identifier(),
3129                               l2cap::kAVDTP,
3130                               kNoSecurityRequirements,
3131                               kChannelParams,
3132                               socket_cb);
3133 
3134   RETURN_IF_FATAL(RunUntilIdle());
3135 
3136   // We should not have a socket because the L2CAP open callback shouldn't have
3137   // been called, but the LTK should be stored since the link key got received.
3138   ASSERT_FALSE(connected_chan);
3139 
3140   test_device()->SendCommandChannelPacket(kReadEncryptionKeySizeRsp);
3141 
3142   l2cap()->ExpectOutboundL2capChannel(
3143       kConnectionHandle, l2cap::kAVDTP, 0x40, 0x41, kChannelParams);
3144 
3145   RETURN_IF_FATAL(RunUntilIdle());
3146 
3147   // The socket should be returned.
3148   ASSERT_TRUE(connected_chan);
3149 
3150   QueueDisconnection(kConnectionHandle);
3151 }
3152 
3153 // Test: when pairing is in progress, opening an L2CAP channel waits for the
3154 // pairing to complete before retrying.
TEST_F(BrEdrConnectionManagerTest,InterrogationInProgressAllowsBondingButNotL2cap)3155 TEST_F(BrEdrConnectionManagerTest,
3156        InterrogationInProgressAllowsBondingButNotL2cap) {
3157   FakePairingDelegate pairing_delegate(sm::IOCapability::kDisplayYesNo);
3158   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
3159 
3160   // Trigger inbound connection and respond to some (but not all) of
3161   // interrogation.
3162   EXPECT_CMD_PACKET_OUT(test_device(),
3163                         kAcceptConnectionRequest,
3164                         &kAcceptConnectionRequestRsp,
3165                         &kConnectionComplete);
3166   EXPECT_CMD_PACKET_OUT(test_device(),
3167                         kRemoteNameRequest,
3168                         &kRemoteNameRequestRsp,
3169                         &kRemoteNameRequestComplete);
3170   EXPECT_CMD_PACKET_OUT(test_device(),
3171                         kReadRemoteVersionInfo,
3172                         &kReadRemoteVersionInfoRsp,
3173                         &kRemoteVersionInfoComplete);
3174   EXPECT_CMD_PACKET_OUT(test_device(),
3175                         hci_spec::kReadRemoteSupportedFeatures,
3176                         &kReadRemoteSupportedFeaturesRsp);
3177 
3178   test_device()->SendCommandChannelPacket(kConnectionRequest);
3179 
3180   RunUntilIdle();
3181 
3182   // Ensure that the interrogation has begun but the peer hasn't yet bonded
3183   EXPECT_EQ(4, transaction_count());
3184   auto* const peer = peer_cache()->FindByAddress(kTestDevAddr);
3185   ASSERT_TRUE(peer);
3186   ASSERT_TRUE(IsInitializing(peer));
3187   ASSERT_FALSE(peer->bredr()->bonded());
3188 
3189   // Approve pairing requests
3190   pairing_delegate.SetDisplayPasskeyCallback(
3191       [](PeerId, uint32_t, auto, auto confirm_cb) {
3192         ASSERT_TRUE(confirm_cb);
3193         confirm_cb(true);
3194       });
3195 
3196   pairing_delegate.SetCompletePairingCallback(
3197       [](PeerId, sm::Result<> status) { EXPECT_EQ(fit::ok(), status); });
3198 
3199   // Initiate pairing from the peer before interrogation completes
3200   test_device()->SendCommandChannelPacket(MakeIoCapabilityResponse(
3201       IoCapability::DISPLAY_YES_NO,
3202       AuthenticationRequirements::MITM_GENERAL_BONDING));
3203   test_device()->SendCommandChannelPacket(kIoCapabilityRequest);
3204   const auto kUserConfirmationRequest = MakeUserConfirmationRequest(kPasskey);
3205   EXPECT_CMD_PACKET_OUT(test_device(),
3206                         MakeIoCapabilityRequestReply(
3207                             IoCapability::DISPLAY_YES_NO,
3208                             AuthenticationRequirements::MITM_GENERAL_BONDING),
3209                         &kIoCapabilityRequestReplyRsp,
3210                         &kUserConfirmationRequest);
3211   EXPECT_CMD_PACKET_OUT(test_device(),
3212                         kUserConfirmationRequestReply,
3213                         &kUserConfirmationRequestReplyRsp,
3214                         &kSimplePairingCompleteSuccess,
3215                         &kLinkKeyNotification);
3216   EXPECT_CMD_PACKET_OUT(test_device(),
3217                         kSetConnectionEncryption,
3218                         &kSetConnectionEncryptionRsp,
3219                         &kEncryptionChangeEvent);
3220   EXPECT_CMD_PACKET_OUT(
3221       test_device(), kReadEncryptionKeySize, &kReadEncryptionKeySizeRsp);
3222 
3223   RETURN_IF_FATAL(RunUntilIdle());
3224 
3225   // At this point the peer is bonded and the link is encrypted but
3226   // interrogation has not completed so host-side L2CAP should still be inactive
3227   // on this link (though it may be buffering packets).
3228   EXPECT_FALSE(l2cap()->IsLinkConnected(kConnectionHandle));
3229 
3230   bool socket_cb_called = false;
3231   auto socket_fails_cb = [&socket_cb_called](auto chan_sock) {
3232     EXPECT_FALSE(chan_sock.is_alive());
3233     socket_cb_called = true;
3234   };
3235   connmgr()->OpenL2capChannel(peer->identifier(),
3236                               l2cap::kAVDTP,
3237                               kNoSecurityRequirements,
3238                               kChannelParams,
3239                               socket_fails_cb);
3240 
3241   RETURN_IF_FATAL(RunUntilIdle());
3242   EXPECT_TRUE(socket_cb_called);
3243 
3244   // Complete interrogation successfully.
3245   EXPECT_CMD_PACKET_OUT(test_device(),
3246                         kReadRemoteExtended1,
3247                         &kReadRemoteExtendedFeaturesRsp,
3248                         &kReadRemoteExtended1Complete);
3249   EXPECT_CMD_PACKET_OUT(test_device(),
3250                         kReadRemoteExtended2,
3251                         &kReadRemoteExtendedFeaturesRsp,
3252                         &kReadRemoteExtended1Complete);
3253   test_device()->SendCommandChannelPacket(kReadRemoteSupportedFeaturesComplete);
3254 
3255   RETURN_IF_FATAL(RunUntilIdle());
3256 
3257   EXPECT_TRUE(l2cap()->IsLinkConnected(kConnectionHandle));
3258 
3259   QueueDisconnection(kConnectionHandle);
3260 }
3261 
TEST_F(BrEdrConnectionManagerTest,ConnectUnknownPeer)3262 TEST_F(BrEdrConnectionManagerTest, ConnectUnknownPeer) {
3263   EXPECT_FALSE(connmgr()->Connect(PeerId(456), {}));
3264 }
3265 
TEST_F(BrEdrConnectionManagerTest,ConnectLowEnergyPeer)3266 TEST_F(BrEdrConnectionManagerTest, ConnectLowEnergyPeer) {
3267   auto* peer = peer_cache()->NewPeer(kTestDevAddrLe, /*connectable=*/true);
3268   EXPECT_FALSE(connmgr()->Connect(peer->identifier(), {}));
3269 }
3270 
TEST_F(BrEdrConnectionManagerTest,DisconnectUnknownPeerDoesNothing)3271 TEST_F(BrEdrConnectionManagerTest, DisconnectUnknownPeerDoesNothing) {
3272   EXPECT_TRUE(
3273       connmgr()->Disconnect(PeerId(999), DisconnectReason::kApiRequest));
3274 
3275   RunUntilIdle();
3276 
3277   EXPECT_EQ(0, transaction_count());
3278 }
3279 
3280 // Test: user-initiated disconnection
TEST_F(BrEdrConnectionManagerTest,DisconnectClosesHciConnection)3281 TEST_F(BrEdrConnectionManagerTest, DisconnectClosesHciConnection) {
3282   QueueSuccessfulIncomingConn();
3283 
3284   test_device()->SendCommandChannelPacket(kConnectionRequest);
3285 
3286   RunUntilIdle();
3287 
3288   EXPECT_EQ(kIncomingConnTransactions, transaction_count());
3289   auto* const peer = peer_cache()->FindByAddress(kTestDevAddr);
3290   ASSERT_TRUE(peer);
3291   EXPECT_FALSE(IsNotConnected(peer));
3292 
3293   QueueDisconnection(kConnectionHandle);
3294 
3295   EXPECT_TRUE(
3296       connmgr()->Disconnect(peer->identifier(), DisconnectReason::kApiRequest));
3297   EXPECT_TRUE(IsNotConnected(peer));
3298 
3299   RunUntilIdle();
3300 
3301   EXPECT_EQ(kIncomingConnTransactions + 1, transaction_count());
3302   EXPECT_TRUE(IsNotConnected(peer));
3303 }
3304 
TEST_F(BrEdrConnectionManagerTest,DisconnectSamePeerIsIdempotent)3305 TEST_F(BrEdrConnectionManagerTest, DisconnectSamePeerIsIdempotent) {
3306   QueueSuccessfulIncomingConn();
3307 
3308   test_device()->SendCommandChannelPacket(kConnectionRequest);
3309 
3310   RunUntilIdle();
3311 
3312   auto* const peer = peer_cache()->FindByAddress(kTestDevAddr);
3313   ASSERT_TRUE(peer);
3314   ASSERT_FALSE(IsNotConnected(peer));
3315 
3316   QueueDisconnection(kConnectionHandle);
3317 
3318   EXPECT_TRUE(
3319       connmgr()->Disconnect(peer->identifier(), DisconnectReason::kApiRequest));
3320   ASSERT_TRUE(IsNotConnected(peer));
3321 
3322   // Try to disconnect again while the first disconnect is in progress (HCI
3323   // Disconnection Complete not yet received).
3324   EXPECT_TRUE(
3325       connmgr()->Disconnect(peer->identifier(), DisconnectReason::kApiRequest));
3326 
3327   RunUntilIdle();
3328 
3329   EXPECT_EQ(kIncomingConnTransactions + 1, transaction_count());
3330   ASSERT_TRUE(IsNotConnected(peer));
3331 
3332   // Try to disconnect once more, now that the link is gone.
3333   EXPECT_TRUE(
3334       connmgr()->Disconnect(peer->identifier(), DisconnectReason::kApiRequest));
3335 }
3336 
TEST_F(BrEdrConnectionManagerTest,RemovePeerFromPeerCacheDuringDisconnection)3337 TEST_F(BrEdrConnectionManagerTest, RemovePeerFromPeerCacheDuringDisconnection) {
3338   QueueSuccessfulIncomingConn();
3339 
3340   test_device()->SendCommandChannelPacket(kConnectionRequest);
3341 
3342   RunUntilIdle();
3343 
3344   auto* const peer = peer_cache()->FindByAddress(kTestDevAddr);
3345   ASSERT_TRUE(peer);
3346   ASSERT_FALSE(IsNotConnected(peer));
3347 
3348   QueueDisconnection(kConnectionHandle);
3349 
3350   const PeerId id = peer->identifier();
3351   EXPECT_TRUE(connmgr()->Disconnect(id, DisconnectReason::kApiRequest));
3352   ASSERT_TRUE(IsNotConnected(peer));
3353 
3354   // Remove the peer from PeerCache before receiving HCI Disconnection Complete.
3355   EXPECT_TRUE(peer_cache()->RemoveDisconnectedPeer(id));
3356 
3357   RunUntilIdle();
3358 
3359   EXPECT_EQ(kIncomingConnTransactions + 1, transaction_count());
3360   EXPECT_FALSE(peer_cache()->FindById(id));
3361   EXPECT_FALSE(peer_cache()->FindByAddress(kTestDevAddr));
3362 }
3363 
TEST_F(BrEdrConnectionManagerTest,AddServiceSearchAll)3364 TEST_F(BrEdrConnectionManagerTest, AddServiceSearchAll) {
3365   size_t search_cb_count = 0;
3366   auto search_cb = [&](auto id, const auto&) {
3367     auto* peer = peer_cache()->FindByAddress(kTestDevAddr);
3368     ASSERT_TRUE(peer);
3369     ASSERT_EQ(id, peer->identifier());
3370     search_cb_count++;
3371   };
3372 
3373   connmgr()->AddServiceSearch(sdp::profile::kAudioSink, {}, search_cb);
3374 
3375   l2cap::testing::FakeChannel::WeakPtr sdp_chan;
3376   std::optional<uint32_t> sdp_request_tid;
3377 
3378   l2cap()->set_channel_callback(
3379       [this, &sdp_chan, &sdp_request_tid](auto new_chan) {
3380         new_chan->SetSendCallback(
3381             [&sdp_request_tid](auto packet) {
3382               const StaticByteBuffer kSearchExpectedParams(
3383                   // ServiceSearchPattern
3384                   0x35,
3385                   0x03,  // Sequence uint8 3 bytes
3386                   0x19,
3387                   0x11,
3388                   0x0B,  // UUID (kAudioSink)
3389                   0xFF,
3390                   0xFF,  // MaxAttributeByteCount (none)
3391                   // Attribute ID list
3392                   0x35,
3393                   0x05,  // Sequence uint8 5 bytes
3394                   0x0A,
3395                   0x00,
3396                   0x00,
3397                   0xFF,
3398                   0xFF,  // uint32_t (all attributes)
3399                   0x00   // No continuation state
3400               );
3401               // First byte should be type.
3402               ASSERT_LE(3u, packet->size());
3403               ASSERT_EQ(sdp::kServiceSearchAttributeRequest, (*packet)[0]);
3404               ASSERT_EQ(kSearchExpectedParams,
3405                         packet->view(sizeof(bt::sdp::Header)));
3406               sdp_request_tid = tid_from_sdp_packet(packet);
3407             },
3408             dispatcher());
3409         sdp_chan = std::move(new_chan);
3410       });
3411 
3412   QueueSuccessfulIncomingConn();
3413   l2cap()->ExpectOutboundL2capChannel(
3414       kConnectionHandle, l2cap::kSDP, 0x40, 0x41, kChannelParams);
3415 
3416   test_device()->SendCommandChannelPacket(kConnectionRequest);
3417 
3418   RunUntilIdle();
3419 
3420   ASSERT_TRUE(sdp_chan.is_alive());
3421   ASSERT_TRUE(sdp_request_tid);
3422   ASSERT_EQ(0u, search_cb_count);
3423 
3424   sdp::ServiceSearchAttributeResponse rsp;
3425   rsp.SetAttribute(0, sdp::kServiceId, sdp::DataElement(UUID()));
3426   auto rsp_ptr = rsp.GetPDU(0xFFFF /* max attribute bytes */,
3427                             *sdp_request_tid,
3428                             PDU_MAX,
3429                             BufferView());
3430 
3431   sdp_chan->Receive(*rsp_ptr);
3432 
3433   RunUntilIdle();
3434 
3435   ASSERT_EQ(1u, search_cb_count);
3436 
3437   QueueDisconnection(kConnectionHandle);
3438 }
3439 
3440 // An error is received via the HCI Command cb_status event
TEST_F(BrEdrConnectionManagerTest,ConnectSinglePeerErrorStatus)3441 TEST_F(BrEdrConnectionManagerTest, ConnectSinglePeerErrorStatus) {
3442   auto* peer = peer_cache()->NewPeer(kTestDevAddr, /*connectable=*/true);
3443 
3444   EXPECT_CMD_PACKET_OUT(
3445       test_device(), kCreateConnection, &kCreateConnectionRspError);
3446 
3447   ASSERT_TRUE(peer->bredr());
3448   EXPECT_TRUE(IsNotConnected(peer));
3449 
3450   hci::Result<> status = fit::ok();
3451   EXPECT_TRUE(
3452       connmgr()->Connect(peer->identifier(), CALLBACK_EXPECT_FAILURE(status)));
3453   EXPECT_TRUE(IsInitializing(peer));
3454   RunUntilIdle();
3455 
3456   EXPECT_EQ(ToResult(pw::bluetooth::emboss::StatusCode::
3457                          CONNECTION_FAILED_TO_BE_ESTABLISHED),
3458             status);
3459   EXPECT_TRUE(IsNotConnected(peer));
3460 }
3461 
3462 // Connection Complete event reports error
TEST_F(BrEdrConnectionManagerTest,ConnectSinglePeerFailure)3463 TEST_F(BrEdrConnectionManagerTest, ConnectSinglePeerFailure) {
3464   auto* peer = peer_cache()->NewPeer(kTestDevAddr, /*connectable=*/true);
3465 
3466   EXPECT_CMD_PACKET_OUT(test_device(),
3467                         kCreateConnection,
3468                         &kCreateConnectionRsp,
3469                         &kConnectionCompleteError);
3470 
3471   hci::Result<> status = ToResult(HostError::kFailed);
3472   bool callback_run = false;
3473 
3474   auto callback = [&status, &callback_run](auto cb_status, auto conn_ref) {
3475     EXPECT_FALSE(conn_ref);
3476     status = cb_status;
3477     callback_run = true;
3478   };
3479   EXPECT_TRUE(connmgr()->Connect(peer->identifier(), callback));
3480   ASSERT_TRUE(peer->bredr());
3481   EXPECT_TRUE(IsInitializing(peer));
3482 
3483   RunUntilIdle();
3484 
3485   EXPECT_TRUE(callback_run);
3486 
3487   EXPECT_EQ(ToResult(pw::bluetooth::emboss::StatusCode::
3488                          CONNECTION_FAILED_TO_BE_ESTABLISHED),
3489             status);
3490   EXPECT_TRUE(IsNotConnected(peer));
3491 }
3492 
TEST_F(BrEdrConnectionManagerTest,ConnectSinglePeerTimeout)3493 TEST_F(BrEdrConnectionManagerTest, ConnectSinglePeerTimeout) {
3494   auto* peer = peer_cache()->NewPeer(kTestDevAddr, /*connectable=*/true);
3495 
3496   EXPECT_CMD_PACKET_OUT(
3497       test_device(), kCreateConnection, &kCreateConnectionRsp);
3498   EXPECT_CMD_PACKET_OUT(test_device(),
3499                         kCreateConnectionCancel,
3500                         &kCreateConnectionCancelRsp,
3501                         &kConnectionCompleteCanceled);
3502 
3503   hci::Result<> status = fit::ok();
3504   auto callback = [&status](auto cb_status, auto conn_ref) {
3505     EXPECT_FALSE(conn_ref);
3506     status = cb_status;
3507   };
3508 
3509   EXPECT_TRUE(connmgr()->Connect(peer->identifier(), callback));
3510   ASSERT_TRUE(peer->bredr());
3511   EXPECT_TRUE(IsInitializing(peer));
3512   RunFor(kBrEdrCreateConnectionTimeout);
3513   RunFor(kBrEdrCreateConnectionTimeout);
3514   EXPECT_EQ(ToResult(HostError::kTimedOut), status);
3515   EXPECT_TRUE(IsNotConnected(peer));
3516 }
3517 
3518 // Successful connection to single peer
TEST_F(BrEdrConnectionManagerTest,ConnectSinglePeer)3519 TEST_F(BrEdrConnectionManagerTest, ConnectSinglePeer) {
3520   auto* peer = peer_cache()->NewPeer(kTestDevAddr, /*connectable=*/true);
3521   EXPECT_TRUE(peer->temporary());
3522 
3523   // Queue up the connection
3524   EXPECT_CMD_PACKET_OUT(test_device(),
3525                         kCreateConnection,
3526                         &kCreateConnectionRsp,
3527                         &kConnectionComplete);
3528   QueueSuccessfulInterrogation(peer->address(), kConnectionHandle);
3529   QueueDisconnection(kConnectionHandle);
3530 
3531   // Initialize as error to verify that |callback| assigns success.
3532   hci::Result<> status = ToResult(HostError::kFailed);
3533   BrEdrConnection* conn_ref = nullptr;
3534   auto callback = [&status, &conn_ref](auto cb_status, auto cb_conn_ref) {
3535     EXPECT_TRUE(cb_conn_ref);
3536     status = cb_status;
3537     conn_ref = std::move(cb_conn_ref);
3538   };
3539 
3540   EXPECT_TRUE(connmgr()->Connect(peer->identifier(), callback));
3541   ASSERT_TRUE(peer->bredr());
3542   EXPECT_TRUE(IsInitializing(peer));
3543   RunUntilIdle();
3544   EXPECT_EQ(fit::ok(), status);
3545   EXPECT_TRUE(HasConnectionTo(peer, conn_ref));
3546   EXPECT_FALSE(IsNotConnected(peer));
3547   EXPECT_EQ(conn_ref->link().role(),
3548             pw::bluetooth::emboss::ConnectionRole::CENTRAL);
3549 }
3550 
TEST_F(BrEdrConnectionManagerTest,ConnectSinglePeerFailedInterrogation)3551 TEST_F(BrEdrConnectionManagerTest, ConnectSinglePeerFailedInterrogation) {
3552   auto* peer = peer_cache()->NewPeer(kTestDevAddr, /*connectable=*/true);
3553   EXPECT_TRUE(peer->temporary());
3554 
3555   // Queue up outbound connection.
3556   EXPECT_CMD_PACKET_OUT(test_device(),
3557                         kCreateConnection,
3558                         &kCreateConnectionRsp,
3559                         &kConnectionComplete);
3560 
3561   // Queue up most of interrogation.
3562   EXPECT_CMD_PACKET_OUT(test_device(),
3563                         kRemoteNameRequest,
3564                         &kRemoteNameRequestRsp,
3565                         &kRemoteNameRequestComplete);
3566   EXPECT_CMD_PACKET_OUT(test_device(),
3567                         kReadRemoteVersionInfo,
3568                         &kReadRemoteVersionInfoRsp,
3569                         &kRemoteVersionInfoComplete);
3570   EXPECT_CMD_PACKET_OUT(test_device(),
3571                         hci_spec::kReadRemoteSupportedFeatures,
3572                         &kReadRemoteSupportedFeaturesRsp);
3573 
3574   hci::Result<> status = fit::ok();
3575   BrEdrConnection* conn_ref = nullptr;
3576   auto callback = [&status, &conn_ref](auto cb_status, auto cb_conn_ref) {
3577     EXPECT_FALSE(cb_conn_ref);
3578     status = cb_status;
3579     conn_ref = std::move(cb_conn_ref);
3580   };
3581 
3582   EXPECT_TRUE(connmgr()->Connect(peer->identifier(), callback));
3583   RETURN_IF_FATAL(RunUntilIdle());
3584 
3585   test_device()->SendCommandChannelPacket(
3586       kReadRemoteSupportedFeaturesCompleteFailed);
3587   QueueDisconnection(kConnectionHandle);
3588   RETURN_IF_FATAL(RunUntilIdle());
3589 
3590   EXPECT_EQ(ToResult(HostError::kNotSupported), status);
3591   EXPECT_TRUE(IsNotConnected(peer));
3592 }
3593 
3594 // Connecting to an already connected peer should complete instantly
TEST_F(BrEdrConnectionManagerTest,ConnectSinglePeerAlreadyConnected)3595 TEST_F(BrEdrConnectionManagerTest, ConnectSinglePeerAlreadyConnected) {
3596   auto* peer = peer_cache()->NewPeer(kTestDevAddr, /*connectable=*/true);
3597   EXPECT_TRUE(peer->temporary());
3598 
3599   // Queue up the connection
3600   EXPECT_CMD_PACKET_OUT(test_device(),
3601                         kCreateConnection,
3602                         &kCreateConnectionRsp,
3603                         &kConnectionComplete);
3604   QueueSuccessfulInterrogation(peer->address(), kConnectionHandle);
3605   QueueDisconnection(kConnectionHandle);
3606 
3607   // Initialize as error to verify that |callback| assigns success.
3608   hci::Result<> status = ToResult(HostError::kFailed);
3609   int num_callbacks = 0;
3610   BrEdrConnection* conn_ref = nullptr;
3611   auto callback = [&status, &conn_ref, &num_callbacks](auto cb_status,
3612                                                        auto cb_conn_ref) {
3613     EXPECT_TRUE(cb_conn_ref);
3614     status = cb_status;
3615     conn_ref = std::move(cb_conn_ref);
3616     ++num_callbacks;
3617   };
3618 
3619   // Connect to the peer for the first time
3620   EXPECT_TRUE(connmgr()->Connect(peer->identifier(), callback));
3621   ASSERT_TRUE(peer->bredr());
3622   EXPECT_TRUE(IsInitializing(peer));
3623   RunUntilIdle();
3624   EXPECT_EQ(fit::ok(), status);
3625   EXPECT_TRUE(HasConnectionTo(peer, conn_ref));
3626   EXPECT_FALSE(IsNotConnected(peer));
3627   EXPECT_EQ(num_callbacks, 1);
3628 
3629   // Attempt to connect again to the already connected peer. callback should be
3630   // called synchronously.
3631   EXPECT_TRUE(connmgr()->Connect(peer->identifier(), callback));
3632   EXPECT_EQ(num_callbacks, 2);
3633   EXPECT_EQ(fit::ok(), status);
3634   EXPECT_TRUE(HasConnectionTo(peer, conn_ref));
3635   EXPECT_FALSE(IsNotConnected(peer));
3636 }
3637 
3638 // Initiating Two Connections to the same (currently unconnected) peer should
3639 // successfully establish both
TEST_F(BrEdrConnectionManagerTest,ConnectSinglePeerTwoInFlight)3640 TEST_F(BrEdrConnectionManagerTest, ConnectSinglePeerTwoInFlight) {
3641   auto* peer = peer_cache()->NewPeer(kTestDevAddr, /*connectable=*/true);
3642   EXPECT_TRUE(peer->temporary());
3643 
3644   // Queue up the connection
3645   EXPECT_CMD_PACKET_OUT(test_device(),
3646                         kCreateConnection,
3647                         &kCreateConnectionRsp,
3648                         &kConnectionComplete);
3649   QueueSuccessfulInterrogation(peer->address(), kConnectionHandle);
3650   QueueDisconnection(kConnectionHandle);
3651 
3652   // Initialize as error to verify that |callback| assigns success.
3653   hci::Result<> status = ToResult(HostError::kFailed);
3654   int num_callbacks = 0;
3655   BrEdrConnection* conn_ref = nullptr;
3656   auto callback = [&status, &conn_ref, &num_callbacks](auto cb_status,
3657                                                        auto cb_conn_ref) {
3658     EXPECT_TRUE(cb_conn_ref);
3659     status = cb_status;
3660     conn_ref = std::move(cb_conn_ref);
3661     ++num_callbacks;
3662   };
3663 
3664   // Launch one request, but don't run the loop
3665   EXPECT_TRUE(connmgr()->Connect(peer->identifier(), callback));
3666   ASSERT_TRUE(peer->bredr());
3667   EXPECT_TRUE(IsInitializing(peer));
3668 
3669   // Launch second inflight request
3670   EXPECT_TRUE(connmgr()->Connect(peer->identifier(), callback));
3671 
3672   // Run the loop which should complete both requests
3673   RunUntilIdle();
3674 
3675   EXPECT_EQ(fit::ok(), status);
3676   EXPECT_TRUE(HasConnectionTo(peer, conn_ref));
3677   EXPECT_FALSE(IsNotConnected(peer));
3678   EXPECT_EQ(num_callbacks, 2);
3679 }
3680 
TEST_F(BrEdrConnectionManagerTest,ConnectInterrogatingPeerOnlyCompletesAfterInterrogation)3681 TEST_F(BrEdrConnectionManagerTest,
3682        ConnectInterrogatingPeerOnlyCompletesAfterInterrogation) {
3683   auto* peer = peer_cache()->NewPeer(kTestDevAddr, /*connectable=*/true);
3684   EXPECT_TRUE(peer->temporary());
3685 
3686   EXPECT_CMD_PACKET_OUT(test_device(),
3687                         kCreateConnection,
3688                         &kCreateConnectionRsp,
3689                         &kConnectionComplete);
3690   // Prevent interrogation from completing so that we can queue a second request
3691   // during interrogation.
3692   QueueIncompleteInterrogation(kTestDevAddr, kConnectionHandle);
3693   QueueDisconnection(kConnectionHandle);
3694 
3695   // Initialize as error to verify that |callback| assigns success.
3696   hci::Result<> status = ToResult(HostError::kFailed);
3697   int num_callbacks = 0;
3698   BrEdrConnection* conn_ref = nullptr;
3699   auto callback = [&status, &conn_ref, &num_callbacks](auto cb_status,
3700                                                        auto cb_conn_ref) {
3701     EXPECT_TRUE(cb_conn_ref);
3702     status = cb_status;
3703     conn_ref = std::move(cb_conn_ref);
3704     ++num_callbacks;
3705   };
3706 
3707   EXPECT_TRUE(connmgr()->Connect(peer->identifier(), callback));
3708   ASSERT_TRUE(peer->bredr());
3709   EXPECT_TRUE(IsInitializing(peer));
3710   RunUntilIdle();
3711 
3712   // Launch second request, which should not complete immediately.
3713   EXPECT_TRUE(connmgr()->Connect(peer->identifier(), callback));
3714   EXPECT_EQ(num_callbacks, 0);
3715 
3716   // Finishing interrogation should complete both requests.
3717   CompleteInterrogation(kConnectionHandle);
3718   RunUntilIdle();
3719 
3720   EXPECT_EQ(fit::ok(), status);
3721   EXPECT_TRUE(HasConnectionTo(peer, conn_ref));
3722   EXPECT_FALSE(IsNotConnected(peer));
3723   EXPECT_EQ(num_callbacks, 2);
3724 }
3725 
TEST_F(BrEdrConnectionManagerTest,ConnectSecondPeerFirstTimesOut)3726 TEST_F(BrEdrConnectionManagerTest, ConnectSecondPeerFirstTimesOut) {
3727   auto* peer_a = peer_cache()->NewPeer(kTestDevAddr, /*connectable=*/true);
3728   auto* peer_b = peer_cache()->NewPeer(kTestDevAddr2, /*connectable=*/true);
3729 
3730   // Enqueue first connection request (which will timeout and be cancelled)
3731   EXPECT_CMD_PACKET_OUT(
3732       test_device(), kCreateConnection, &kCreateConnectionRsp);
3733   EXPECT_CMD_PACKET_OUT(test_device(),
3734                         kCreateConnectionCancel,
3735                         &kCreateConnectionCancelRsp,
3736                         &kConnectionCompleteCanceled);
3737 
3738   // Enqueue second connection (which will succeed once previous has ended)
3739   QueueSuccessfulCreateConnection(peer_b, kConnectionHandle2);
3740   QueueSuccessfulInterrogation(peer_b->address(), kConnectionHandle2);
3741   QueueDisconnection(kConnectionHandle2);
3742 
3743   // Initialize as success to verify that |callback_a| assigns failure.
3744   hci::Result<> status_a = fit::ok();
3745   auto callback_a = [&status_a](auto cb_status, auto cb_conn_ref) {
3746     status_a = cb_status;
3747     EXPECT_FALSE(cb_conn_ref);
3748   };
3749 
3750   // Initialize as error to verify that |callback_b| assigns success.
3751   hci::Result<> status_b = ToResult(HostError::kFailed);
3752   BrEdrConnection* connection = nullptr;
3753   auto callback_b = [&status_b, &connection](auto cb_status, auto cb_conn_ref) {
3754     EXPECT_TRUE(cb_conn_ref);
3755     status_b = cb_status;
3756     connection = std::move(cb_conn_ref);
3757   };
3758 
3759   // Launch one request (this will timeout)
3760   EXPECT_TRUE(connmgr()->Connect(peer_a->identifier(), callback_a));
3761   ASSERT_TRUE(peer_a->bredr());
3762   EXPECT_TRUE(IsInitializing(peer_a));
3763 
3764   RunUntilIdle();
3765 
3766   // Launch second inflight request (this will wait for the first)
3767   EXPECT_TRUE(connmgr()->Connect(peer_b->identifier(), callback_b));
3768   ASSERT_TRUE(peer_b->bredr());
3769 
3770   // Run the loop which should complete both requests
3771   RunFor(kBrEdrCreateConnectionTimeout);
3772   RunFor(kBrEdrCreateConnectionTimeout);
3773 
3774   EXPECT_TRUE(status_a.is_error());
3775   EXPECT_EQ(fit::ok(), status_b);
3776   EXPECT_TRUE(HasConnectionTo(peer_b, connection));
3777   EXPECT_TRUE(IsNotConnected(peer_a));
3778   EXPECT_FALSE(IsNotConnected(peer_b));
3779 }
3780 
3781 class FirstLowEnergyOnlyPeer : public BrEdrConnectionManagerTest,
3782                                public ::testing::WithParamInterface<bool> {};
3783 
TEST_P(FirstLowEnergyOnlyPeer,ConnectToDualModePeerThatWasFirstLowEnergyOnly)3784 TEST_P(FirstLowEnergyOnlyPeer, ConnectToDualModePeerThatWasFirstLowEnergyOnly) {
3785   const DeviceAddress kTestDevAddrLeAlias(DeviceAddress::Type::kLEPublic,
3786                                           kTestDevAddr.value());
3787   auto* peer =
3788       peer_cache()->NewPeer(kTestDevAddrLeAlias, /*connectable=*/GetParam());
3789   EXPECT_TRUE(peer->temporary());
3790   EXPECT_EQ(TechnologyType::kLowEnergy, peer->technology());
3791 
3792   // Make peer dual mode
3793   peer->MutBrEdr();
3794   EXPECT_EQ(TechnologyType::kDualMode, peer->technology());
3795 
3796   // Queue up the connection
3797   EXPECT_CMD_PACKET_OUT(
3798       test_device(), kCreateConnection, &kCreateConnectionRsp);
3799 
3800   // Initialize as error to verify that |callback| assigns success.
3801   hci::Result<> status = ToResult(HostError::kFailed);
3802   BrEdrConnection* conn_ref = nullptr;
3803   auto callback = [&status, &conn_ref](auto cb_status, auto cb_conn_ref) {
3804     EXPECT_TRUE(cb_conn_ref);
3805     status = cb_status;
3806     conn_ref = std::move(cb_conn_ref);
3807   };
3808 
3809   EXPECT_TRUE(connmgr()->Connect(peer->identifier(), callback));
3810   ASSERT_TRUE(peer->bredr());
3811   EXPECT_TRUE(IsInitializing(peer));
3812   RunUntilIdle();
3813 
3814   test_device()->SendCommandChannelPacket(kConnectionComplete);
3815   QueueSuccessfulInterrogation(peer->address(), kConnectionHandle);
3816   QueueDisconnection(kConnectionHandle);
3817   RunUntilIdle();
3818 
3819   EXPECT_EQ(fit::ok(), status);
3820   EXPECT_TRUE(HasConnectionTo(peer, conn_ref));
3821   EXPECT_FALSE(IsNotConnected(peer));
3822   EXPECT_EQ(conn_ref->link().role(),
3823             pw::bluetooth::emboss::ConnectionRole::CENTRAL);
3824 }
3825 
3826 INSTANTIATE_TEST_SUITE_P(BrEdrConnectionManagerTest,
3827                          FirstLowEnergyOnlyPeer,
3828                          ::testing::Values(true, false));
3829 
3830 // Tests the successful retry case. "don't retry for other error codes" is
3831 // implicitly tested in ConnectSinglePeerFailure - MockController would error if
3832 // we unexpectedly retried.
TEST_F(BrEdrConnectionManagerTest,SuccessfulHciRetriesAfterPageTimeout)3833 TEST_F(BrEdrConnectionManagerTest, SuccessfulHciRetriesAfterPageTimeout) {
3834   auto* peer = peer_cache()->NewPeer(kTestDevAddr, /*connectable=*/true);
3835   EXPECT_TRUE(peer->temporary());
3836 
3837   // We send a first HCI Create Connection which will hang for 14s, and then
3838   // respond on the test device with a ConnectionCompletePageTimeout event,
3839   // which will cause a retry. The retry will also hang for 14s, then will
3840   // receive another PageTimeout response, which will cause another retry, which
3841   // will finally be permitted to succeed
3842   EXPECT_CMD_PACKET_OUT(
3843       test_device(), kCreateConnection, &kCreateConnectionRsp);
3844   EXPECT_CMD_PACKET_OUT(
3845       test_device(), kCreateConnection, &kCreateConnectionRsp);
3846   EXPECT_CMD_PACKET_OUT(test_device(),
3847                         kCreateConnection,
3848                         &kCreateConnectionRsp,
3849                         &kConnectionComplete);
3850   QueueSuccessfulInterrogation(peer->address(), kConnectionHandle);
3851   QueueDisconnection(kConnectionHandle);
3852 
3853   // Initialize as error to verify that |callback| assigns success.
3854   hci::Result<> status = ToResult(HostError::kFailed);
3855   BrEdrConnection* conn_ref = nullptr;
3856   auto callback = [&status, &conn_ref](auto cb_status, auto cb_conn_ref) {
3857     EXPECT_TRUE(cb_conn_ref);
3858     status = cb_status;
3859     conn_ref = std::move(cb_conn_ref);
3860   };
3861 
3862   EXPECT_TRUE(connmgr()->Connect(peer->identifier(), callback));
3863   ASSERT_TRUE(peer->bredr());
3864   // Cause the initial Create Connection to wait for 14s for Connection Complete
3865   RunFor(std::chrono::seconds(14));
3866   ASSERT_TRUE(
3867       test_device()->SendCommandChannelPacket(kConnectionCompletePageTimeout));
3868   // Verify higher layers have not been notified of failure.
3869   EXPECT_EQ(ToResult(HostError::kFailed), status);
3870   // Cause the first retry Create Connection to wait for 14s for Connection
3871   // Complete - now 28s since the first Create Connection, bumping up on the
3872   // retry window limit of 30s.
3873   RunFor(std::chrono::seconds(14));
3874   // Cause a second retry.
3875   ASSERT_TRUE(
3876       test_device()->SendCommandChannelPacket(kConnectionCompletePageTimeout));
3877   // Verify higher layers have not been notified of failure until the Connection
3878   // Complete propagates
3879   EXPECT_EQ(ToResult(HostError::kFailed), status);
3880 
3881   RunUntilIdle();
3882   EXPECT_EQ(fit::ok(), status);
3883   EXPECT_TRUE(HasConnectionTo(peer, conn_ref));
3884   EXPECT_EQ(conn_ref->link().role(),
3885             pw::bluetooth::emboss::ConnectionRole::CENTRAL);
3886 }
3887 
TEST_F(BrEdrConnectionManagerTest,DontRetryAfterWindowClosed)3888 TEST_F(BrEdrConnectionManagerTest, DontRetryAfterWindowClosed) {
3889   auto* peer = peer_cache()->NewPeer(kTestDevAddr, /*connectable=*/true);
3890   EXPECT_TRUE(peer->temporary());
3891 
3892   // We send a first HCI Create Connection which will hang for 15s, and then
3893   // respond on the test device with a ConnectionCompletePageTimeout event,
3894   // which will cause a retry. The retry will hang for 16s, then will receive
3895   // another PageTimeout response. Because this will be 31s after the initial
3896   // HCI Create Connection, the retry window will be closed and the Connect()
3897   // will fail.
3898   EXPECT_CMD_PACKET_OUT(
3899       test_device(), kCreateConnection, &kCreateConnectionRsp);
3900   EXPECT_CMD_PACKET_OUT(
3901       test_device(), kCreateConnection, &kCreateConnectionRsp);
3902 
3903   // Initialize as success to verify that |callback| assigns error.
3904   hci::Result<> status = fit::ok();
3905   auto callback = [&status](auto cb_status, auto cb_conn_ref) {
3906     EXPECT_FALSE(cb_conn_ref);
3907     status = cb_status;
3908   };
3909 
3910   EXPECT_TRUE(connmgr()->Connect(peer->identifier(), callback));
3911   ASSERT_TRUE(peer->bredr());
3912   RunFor(std::chrono::seconds(15));
3913   // Higher layers should not be notified yet.
3914   EXPECT_EQ(fit::ok(), status);
3915   ASSERT_TRUE(
3916       test_device()->SendCommandChannelPacket(kConnectionCompletePageTimeout));
3917 
3918   // Create Connection will retry, and it hangs for 16s before
3919   // ConnectionCompletePageTimeout
3920   RunFor(std::chrono::seconds(16));
3921   ASSERT_TRUE(
3922       test_device()->SendCommandChannelPacket(kConnectionCompletePageTimeout));
3923   RunUntilIdle();
3924   // Create Connection will *not* be tried again as we are outside of the retry
3925   // window.
3926   EXPECT_EQ(ToResult(pw::bluetooth::emboss::StatusCode::PAGE_TIMEOUT), status);
3927 }
3928 
TEST_F(BrEdrConnectionManagerTest,ConnectSecondPeerFirstFailsWithPageTimeoutAndDoesNotRetry)3929 TEST_F(BrEdrConnectionManagerTest,
3930        ConnectSecondPeerFirstFailsWithPageTimeoutAndDoesNotRetry) {
3931   auto* peer_a = peer_cache()->NewPeer(kTestDevAddr, /*connectable=*/true);
3932   auto* peer_b = peer_cache()->NewPeer(kTestDevAddr2, /*connectable=*/true);
3933 
3934   // First peer's Create Connection Request will complete with a page timeout
3935   EXPECT_CMD_PACKET_OUT(test_device(),
3936                         kCreateConnection,
3937                         &kCreateConnectionRsp,
3938                         &kConnectionCompletePageTimeout);
3939 
3940   // Immediately enqueue successful connection request to peer_b, without any
3941   // retry in between for the Connect() call to peer_a.
3942   QueueSuccessfulCreateConnection(peer_b, kConnectionHandle2);
3943   QueueSuccessfulInterrogation(peer_b->address(), kConnectionHandle2);
3944   QueueDisconnection(kConnectionHandle2);
3945 
3946   // Initialize as success to verify that |callback_a| assigns failure.
3947   hci::Result<> status_a = fit::ok();
3948   auto callback_a = [&status_a](auto cb_status, auto cb_conn_ref) {
3949     status_a = cb_status;
3950     EXPECT_FALSE(cb_conn_ref);
3951   };
3952 
3953   // Initialize as error to verify that |callback_b| assigns success.
3954   hci::Result<> status_b = ToResult(HostError::kFailed);
3955   BrEdrConnection* connection = nullptr;
3956   auto callback_b = [&status_b, &connection](auto cb_status, auto cb_conn_ref) {
3957     EXPECT_TRUE(cb_conn_ref);
3958     status_b = cb_status;
3959     connection = std::move(cb_conn_ref);
3960   };
3961 
3962   // Launch one request, which will cause a Connection Complete: page timeout
3963   // controller event.
3964   EXPECT_TRUE(connmgr()->Connect(peer_a->identifier(), callback_a));
3965   EXPECT_TRUE(IsInitializing(peer_a));
3966 
3967   // Launch second inflight request (this will wait for the first)
3968   EXPECT_TRUE(connmgr()->Connect(peer_b->identifier(), callback_b));
3969   EXPECT_TRUE(IsInitializing(peer_b));
3970 
3971   // Run the loop which should complete both requests
3972   RunUntilIdle();
3973 
3974   // The Connect() request to peer_a should fail with the Page Timeout status
3975   // code without retrying
3976   EXPECT_EQ(ToResult(pw::bluetooth::emboss::StatusCode::PAGE_TIMEOUT),
3977             status_a);
3978   EXPECT_EQ(fit::ok(), status_b);
3979   EXPECT_TRUE(HasConnectionTo(peer_b, connection));
3980   EXPECT_TRUE(IsNotConnected(peer_a));
3981   EXPECT_FALSE(IsNotConnected(peer_b));
3982 }
3983 
TEST_F(BrEdrConnectionManagerTest,DisconnectPendingConnections)3984 TEST_F(BrEdrConnectionManagerTest, DisconnectPendingConnections) {
3985   auto* peer_a = peer_cache()->NewPeer(kTestDevAddr, /*connectable=*/true);
3986   auto* peer_b = peer_cache()->NewPeer(kTestDevAddr2, /*connectable=*/true);
3987 
3988   // Enqueue first connection request (which will await Connection Complete)
3989   EXPECT_CMD_PACKET_OUT(
3990       test_device(), kCreateConnection, &kCreateConnectionRsp);
3991   EXPECT_CMD_PACKET_OUT(test_device(),
3992                         kCreateConnectionCancel,
3993                         &kCreateConnectionCancelRsp,
3994                         &kConnectionCompleteCanceled);
3995 
3996   // No-op connection callbacks
3997   auto callback_a = [](auto, auto) {};
3998   auto callback_b = [](auto, auto) {};
3999 
4000   // Launch both requests (second one is queued. Neither completes.)
4001   EXPECT_TRUE(connmgr()->Connect(peer_a->identifier(), callback_a));
4002   EXPECT_TRUE(connmgr()->Connect(peer_b->identifier(), callback_b));
4003 
4004   // Put the first connection into flight.
4005   RETURN_IF_FATAL(RunUntilIdle());
4006 
4007   ASSERT_TRUE(IsInitializing(peer_a));
4008   ASSERT_TRUE(IsInitializing(peer_b));
4009 
4010   EXPECT_FALSE(connmgr()->Disconnect(peer_a->identifier(),
4011                                      DisconnectReason::kApiRequest));
4012   EXPECT_FALSE(connmgr()->Disconnect(peer_b->identifier(),
4013                                      DisconnectReason::kApiRequest));
4014 }
4015 
TEST_F(BrEdrConnectionManagerTest,DisconnectCooldownIncoming)4016 TEST_F(BrEdrConnectionManagerTest, DisconnectCooldownIncoming) {
4017   auto* peer = peer_cache()->NewPeer(kTestDevAddr, /*connectable=*/true);
4018 
4019   // Peer successfully connects to us.
4020   QueueSuccessfulIncomingConn(kTestDevAddr);
4021   test_device()->SendCommandChannelPacket(kConnectionRequest);
4022   RETURN_IF_FATAL(RunUntilIdle());
4023   EXPECT_FALSE(IsNotConnected(peer));
4024 
4025   // Disconnect locally from an API Request.
4026   QueueDisconnection(kConnectionHandle);
4027   EXPECT_TRUE(
4028       connmgr()->Disconnect(peer->identifier(), DisconnectReason::kApiRequest));
4029 
4030   RETURN_IF_FATAL(RunUntilIdle());
4031   EXPECT_TRUE(IsNotConnected(peer));
4032 
4033   // Peer tries to connect to us. We should reject the connection.
4034   auto status_event =
4035       testing::CommandStatusPacket(hci_spec::kRejectConnectionRequest,
4036                                    pw::bluetooth::emboss::StatusCode::SUCCESS);
4037   auto reject_packet = testing::RejectConnectionRequestPacket(
4038       kTestDevAddr,
4039       pw::bluetooth::emboss::StatusCode::CONNECTION_REJECTED_BAD_BD_ADDR);
4040 
4041   EXPECT_CMD_PACKET_OUT(test_device(), reject_packet, &status_event);
4042 
4043   test_device()->SendCommandChannelPacket(kConnectionRequest);
4044 
4045   RETURN_IF_FATAL(RunUntilIdle());
4046   EXPECT_TRUE(IsNotConnected(peer));
4047 
4048   // After the cooldown time, a successful incoming connection can happen.
4049   RunFor(BrEdrConnectionManager::kLocalDisconnectCooldownDuration);
4050 
4051   QueueRepeatIncomingConn(kTestDevAddr);
4052   test_device()->SendCommandChannelPacket(kConnectionRequest);
4053   RETURN_IF_FATAL(RunUntilIdle());
4054   EXPECT_FALSE(IsNotConnected(peer));
4055 
4056   // Can still connect out if we disconnect locally.
4057   QueueDisconnection(kConnectionHandle);
4058   EXPECT_TRUE(
4059       connmgr()->Disconnect(peer->identifier(), DisconnectReason::kApiRequest));
4060   RETURN_IF_FATAL(RunUntilIdle());
4061 
4062   EXPECT_TRUE(IsNotConnected(peer));
4063 
4064   QueueSuccessfulCreateConnection(peer, kConnectionHandle);
4065   // Interrogation is short because the peer is already known
4066   QueueShortInterrogation(kConnectionHandle);
4067 
4068   // Initialize as error to verify that |callback| assigns success.
4069   hci::Result<> status = ToResult(HostError::kFailed);
4070   BrEdrConnection* connection = nullptr;
4071   auto callback = [&status, &connection](auto cb_status, auto cb_conn_ref) {
4072     EXPECT_TRUE(cb_conn_ref);
4073     status = cb_status;
4074     connection = std::move(cb_conn_ref);
4075   };
4076 
4077   // Launch request.
4078   EXPECT_TRUE(connmgr()->Connect(peer->identifier(), callback));
4079 
4080   // Complete connection.
4081   RETURN_IF_FATAL(RunUntilIdle());
4082 
4083   EXPECT_EQ(fit::ok(), status);
4084   EXPECT_TRUE(HasConnectionTo(peer, connection));
4085   EXPECT_FALSE(IsNotConnected(peer));
4086 
4087   // Remote disconnections can reconnect immediately
4088   test_device()->SendCommandChannelPacket(kDisconnectionComplete);
4089   RETURN_IF_FATAL(RunUntilIdle());
4090   EXPECT_TRUE(IsNotConnected(peer));
4091 
4092   QueueRepeatIncomingConn(kTestDevAddr);
4093   test_device()->SendCommandChannelPacket(kConnectionRequest);
4094   RETURN_IF_FATAL(RunUntilIdle());
4095   EXPECT_FALSE(IsNotConnected(peer));
4096 
4097   // If the reason is not kApiRequest, then the remote peer can reconnect
4098   // immediately.
4099   QueueDisconnection(kConnectionHandle);
4100   EXPECT_TRUE(connmgr()->Disconnect(peer->identifier(),
4101                                     DisconnectReason::kPairingFailed));
4102   RETURN_IF_FATAL(RunUntilIdle());
4103   EXPECT_TRUE(IsNotConnected(peer));
4104 
4105   QueueRepeatIncomingConn(kTestDevAddr);
4106   test_device()->SendCommandChannelPacket(kConnectionRequest);
4107   RETURN_IF_FATAL(RunUntilIdle());
4108   EXPECT_FALSE(IsNotConnected(peer));
4109 
4110   // Queue disconnection for teardown.
4111   QueueDisconnection(kConnectionHandle);
4112 }
4113 
TEST_F(BrEdrConnectionManagerTest,DisconnectCooldownCancelOnOutgoing)4114 TEST_F(BrEdrConnectionManagerTest, DisconnectCooldownCancelOnOutgoing) {
4115   auto* peer = peer_cache()->NewPeer(kTestDevAddr, /*connectable=*/true);
4116 
4117   // Peer successfully connects to us.
4118   QueueSuccessfulIncomingConn(kTestDevAddr);
4119   test_device()->SendCommandChannelPacket(kConnectionRequest);
4120   RETURN_IF_FATAL(RunUntilIdle());
4121   EXPECT_FALSE(IsNotConnected(peer));
4122 
4123   // Disconnect locally from an API Request.
4124   QueueDisconnection(kConnectionHandle);
4125   EXPECT_TRUE(
4126       connmgr()->Disconnect(peer->identifier(), DisconnectReason::kApiRequest));
4127 
4128   RETURN_IF_FATAL(RunUntilIdle());
4129   EXPECT_TRUE(IsNotConnected(peer));
4130 
4131   // Peer tries to connect to us. We should reject the connection.
4132   auto status_event =
4133       testing::CommandStatusPacket(hci_spec::kRejectConnectionRequest,
4134                                    pw::bluetooth::emboss::StatusCode::SUCCESS);
4135   auto reject_packet = testing::RejectConnectionRequestPacket(
4136       kTestDevAddr,
4137       pw::bluetooth::emboss::StatusCode::CONNECTION_REJECTED_BAD_BD_ADDR);
4138 
4139   EXPECT_CMD_PACKET_OUT(test_device(), reject_packet, &status_event);
4140 
4141   test_device()->SendCommandChannelPacket(kConnectionRequest);
4142 
4143   RETURN_IF_FATAL(RunUntilIdle());
4144   EXPECT_TRUE(IsNotConnected(peer));
4145 
4146   // If we initiate a connection out, then an incoming connection can succeed,
4147   // even if we fail to make the connection out.
4148   EXPECT_CMD_PACKET_OUT(
4149       test_device(), kCreateConnection, &kCreateConnectionRspError);
4150 
4151   // Initialize as ok to verify that |callback| assigns failure
4152   hci::Result<> status = fit::ok();
4153   EXPECT_TRUE(
4154       connmgr()->Connect(peer->identifier(), CALLBACK_EXPECT_FAILURE(status)));
4155   EXPECT_TRUE(IsInitializing(peer));
4156   RunUntilIdle();
4157 
4158   // The outgoing connection failed to succeed
4159   EXPECT_TRUE(IsNotConnected(peer));
4160 
4161   // but an incoming connection can now succeed, since our intent is to connect
4162   // now
4163   QueueRepeatIncomingConn(kTestDevAddr);
4164   test_device()->SendCommandChannelPacket(kConnectionRequest);
4165   RETURN_IF_FATAL(RunUntilIdle());
4166   EXPECT_FALSE(IsNotConnected(peer));
4167 
4168   // Queue disconnection for teardown.
4169   QueueDisconnection(kConnectionHandle);
4170 }
4171 
4172 // If SDP channel creation fails, null channel should be caught and
4173 // not be dereferenced. Search should fail to return results.
TEST_F(BrEdrConnectionManagerTest,SDPChannelCreationFailsGracefully)4174 TEST_F(BrEdrConnectionManagerTest, SDPChannelCreationFailsGracefully) {
4175   constexpr l2cap::ChannelId kLocalCId = 0x40;
4176   constexpr l2cap::ChannelId kRemoteCId = 0x41;
4177 
4178   // Channel creation should fail.
4179   l2cap()->set_channel_callback(
4180       [](auto new_chan) { ASSERT_FALSE(new_chan.is_alive()); });
4181 
4182   // Since SDP channel creation fails, search_cb should not be called by SDP.
4183   auto search_cb = [&](auto, const auto&) { FAIL(); };
4184   connmgr()->AddServiceSearch(
4185       sdp::profile::kAudioSink, {sdp::kServiceId}, search_cb);
4186 
4187   QueueSuccessfulIncomingConn();
4188   l2cap()->set_simulate_open_channel_failure(true);
4189   l2cap()->ExpectOutboundL2capChannel(
4190       kConnectionHandle, l2cap::kSDP, kLocalCId, kRemoteCId, kChannelParams);
4191 
4192   test_device()->SendCommandChannelPacket(kConnectionRequest);
4193   RunUntilIdle();
4194 
4195   // Peer should still connect successfully.
4196   auto* peer = peer_cache()->FindByAddress(kTestDevAddr);
4197   ASSERT_TRUE(peer);
4198   EXPECT_EQ(peer->identifier(), connmgr()->GetPeerId(kConnectionHandle));
4199   EXPECT_EQ(kIncomingConnTransactions, transaction_count());
4200   EXPECT_FALSE(IsNotConnected(peer));
4201 
4202   test_device()->SendCommandChannelPacket(kDisconnectionComplete);
4203   RunUntilIdle();
4204 
4205   EXPECT_TRUE(IsNotConnected(peer));
4206 }
4207 
TEST_F(BrEdrConnectionManagerTest,PendingPacketsNotClearedOnDisconnectAndClearedOnDisconnectionCompleteEvent)4208 TEST_F(
4209     BrEdrConnectionManagerTest,
4210     PendingPacketsNotClearedOnDisconnectAndClearedOnDisconnectionCompleteEvent) {
4211   constexpr size_t kMaxNumPackets = 1;
4212 
4213   ASSERT_EQ(kMaxNumPackets, kBrEdrBufferInfo.max_num_packets());
4214 
4215   EXPECT_EQ(kInvalidPeerId, connmgr()->GetPeerId(kConnectionHandle));
4216   EXPECT_EQ(kInvalidPeerId, connmgr()->GetPeerId(kConnectionHandle2));
4217 
4218   QueueSuccessfulIncomingConn(kTestDevAddr, kConnectionHandle);
4219   test_device()->SendCommandChannelPacket(kConnectionRequest);
4220 
4221   RunUntilIdle();
4222 
4223   auto* peer = peer_cache()->FindByAddress(kTestDevAddr);
4224   ASSERT_TRUE(peer);
4225   EXPECT_EQ(peer->identifier(), connmgr()->GetPeerId(kConnectionHandle));
4226 
4227   QueueSuccessfulIncomingConn(kTestDevAddr2, kConnectionHandle2);
4228   test_device()->SendCommandChannelPacket(
4229       testing::ConnectionRequestPacket(kTestDevAddr2));
4230 
4231   RunUntilIdle();
4232 
4233   auto* peer2 = peer_cache()->FindByAddress(kTestDevAddr2);
4234   ASSERT_TRUE(peer2);
4235   EXPECT_EQ(peer2->identifier(), connmgr()->GetPeerId(kConnectionHandle2));
4236 
4237   EXPECT_EQ(2 * kIncomingConnTransactions, transaction_count());
4238 
4239   size_t packet_count = 0;
4240   test_device()->SetDataCallback([&](const auto&) { packet_count++; });
4241 
4242   // Should register connection with ACL Data Channel.
4243   hci::FakeAclConnection connection_0(
4244       acl_data_channel(), kConnectionHandle, LinkType::kACL);
4245   hci::FakeAclConnection connection_1(
4246       acl_data_channel(), kConnectionHandle2, LinkType::kACL);
4247 
4248   acl_data_channel()->RegisterConnection(connection_0.GetWeakPtr());
4249   acl_data_channel()->RegisterConnection(connection_1.GetWeakPtr());
4250 
4251   EXPECT_ACL_PACKET_OUT(test_device(),
4252                         StaticByteBuffer(
4253                             // ACL data header (handle: 0, length 1)
4254                             LowerBits(kConnectionHandle),
4255                             UpperBits(kConnectionHandle),
4256                             // payload length
4257                             0x01,
4258                             0x00,
4259                             // payload
4260                             1));
4261   // Create packet to send on |acl_connection_0|
4262   hci::ACLDataPacketPtr packet_0 = hci::ACLDataPacket::New(
4263       kConnectionHandle,
4264       hci_spec::ACLPacketBoundaryFlag::kFirstNonFlushable,
4265       hci_spec::ACLBroadcastFlag::kPointToPoint,
4266       /*payload_size=*/1);
4267   packet_0->mutable_view()->mutable_payload_data()[0] = static_cast<uint8_t>(1);
4268   connection_0.QueuePacket(std::move(packet_0));
4269   RunUntilIdle();
4270 
4271   EXPECT_ACL_PACKET_OUT(test_device(),
4272                         StaticByteBuffer(
4273                             // ACL data header (handle: 0, length 1)
4274                             LowerBits(kConnectionHandle2),
4275                             UpperBits(kConnectionHandle2),
4276                             // payload length
4277                             0x01,
4278                             0x00,
4279                             // payload
4280                             1));
4281   hci::ACLDataPacketPtr packet_1 = hci::ACLDataPacket::New(
4282       kConnectionHandle2,
4283       hci_spec::ACLPacketBoundaryFlag::kFirstNonFlushable,
4284       hci_spec::ACLBroadcastFlag::kPointToPoint,
4285       /*payload_size=*/1);
4286   packet_1->mutable_view()->mutable_payload_data()[0] = static_cast<uint8_t>(1);
4287   connection_1.QueuePacket(std::move(packet_1));
4288   RunUntilIdle();
4289 
4290   EXPECT_EQ(connection_0.queued_packets().size(), 0u);
4291   EXPECT_EQ(connection_1.queued_packets().size(), 1u);
4292   EXPECT_FALSE(test_device()->AllExpectedDataPacketsSent());
4293 
4294   EXPECT_CMD_PACKET_OUT(test_device(), kDisconnect, &kDisconnectRsp);
4295 
4296   EXPECT_TRUE(
4297       connmgr()->Disconnect(peer->identifier(), DisconnectReason::kApiRequest));
4298   RunUntilIdle();
4299 
4300   // Packet for |kConnectionHandle2| should not have been sent before
4301   // Disconnection Complete event.
4302   EXPECT_EQ(connection_0.queued_packets().size(), 0u);
4303   EXPECT_EQ(connection_1.queued_packets().size(), 1u);
4304   EXPECT_FALSE(test_device()->AllExpectedDataPacketsSent());
4305 
4306   acl_data_channel()->UnregisterConnection(kConnectionHandle);
4307 
4308   test_device()->SendCommandChannelPacket(kDisconnectionComplete);
4309   RunUntilIdle();
4310 
4311   EXPECT_TRUE(IsNotConnected(peer));
4312 
4313   // Disconnection Complete handler should clear controller packet counts, so
4314   // packet for |kConnectionHandle2| should be sent
4315   EXPECT_EQ(connection_0.queued_packets().size(), 0u);
4316   EXPECT_EQ(connection_1.queued_packets().size(), 0u);
4317   EXPECT_TRUE(test_device()->AllExpectedDataPacketsSent());
4318 
4319   // Connection handle |kConnectionHandle| should have been unregistered with
4320   // ACL Data Channel.
4321   QueueDisconnection(kConnectionHandle2);
4322 }
4323 
TEST_F(BrEdrConnectionManagerTest,PairUnconnectedPeer)4324 TEST_F(BrEdrConnectionManagerTest, PairUnconnectedPeer) {
4325   auto* peer = peer_cache()->NewPeer(kTestDevAddr, /*connectable=*/true);
4326   EXPECT_TRUE(peer->temporary());
4327   ASSERT_EQ(peer_cache()->count(), 1u);
4328   uint count_cb_called = 0;
4329   auto cb = [&count_cb_called](hci::Result<> status) {
4330     ASSERT_EQ(ToResult(bt::HostError::kNotFound), status);
4331     count_cb_called++;
4332   };
4333   connmgr()->Pair(peer->identifier(), kNoSecurityRequirements, cb);
4334   ASSERT_EQ(count_cb_called, 1u);
4335 }
4336 
TEST_F(BrEdrConnectionManagerTest,Pair)4337 TEST_F(BrEdrConnectionManagerTest, Pair) {
4338   QueueSuccessfulIncomingConn();
4339 
4340   test_device()->SendCommandChannelPacket(kConnectionRequest);
4341 
4342   RunUntilIdle();
4343 
4344   EXPECT_EQ(kIncomingConnTransactions, transaction_count());
4345   auto* const peer = peer_cache()->FindByAddress(kTestDevAddr);
4346   ASSERT_TRUE(peer);
4347   ASSERT_TRUE(IsInitializing(peer));
4348   ASSERT_FALSE(peer->bonded());
4349 
4350   FakePairingDelegate pairing_delegate(sm::IOCapability::kDisplayYesNo);
4351   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
4352 
4353   // Approve pairing requests.
4354   pairing_delegate.SetDisplayPasskeyCallback(
4355       [](PeerId, uint32_t, auto, auto confirm_cb) {
4356         ASSERT_TRUE(confirm_cb);
4357         confirm_cb(true);
4358       });
4359 
4360   pairing_delegate.SetCompletePairingCallback(
4361       [](PeerId, sm::Result<> status) { EXPECT_EQ(fit::ok(), status); });
4362 
4363   QueueSuccessfulPairing();
4364 
4365   // Make the pairing error a "bad" error to confirm the callback is called at
4366   // the end of the pairing process.
4367   hci::Result<> pairing_status = ToResult(HostError::kPacketMalformed);
4368   auto pairing_complete_cb = [&pairing_status](hci::Result<> status) {
4369     ASSERT_EQ(fit::ok(), status);
4370     pairing_status = status;
4371   };
4372 
4373   connmgr()->Pair(
4374       peer->identifier(), kNoSecurityRequirements, pairing_complete_cb);
4375   ASSERT_TRUE(IsInitializing(peer));
4376   ASSERT_FALSE(peer->bonded());
4377   RunUntilIdle();
4378 
4379   ASSERT_EQ(fit::ok(), pairing_status);
4380   ASSERT_TRUE(IsConnected(peer));
4381   ASSERT_TRUE(peer->bonded());
4382 
4383   QueueDisconnection(kConnectionHandle);
4384 }
4385 
TEST_F(BrEdrConnectionManagerTest,PairTwice)4386 TEST_F(BrEdrConnectionManagerTest, PairTwice) {
4387   QueueSuccessfulIncomingConn();
4388 
4389   test_device()->SendCommandChannelPacket(kConnectionRequest);
4390 
4391   RunUntilIdle();
4392 
4393   EXPECT_EQ(kIncomingConnTransactions, transaction_count());
4394   auto* const peer = peer_cache()->FindByAddress(kTestDevAddr);
4395   ASSERT_TRUE(peer);
4396   ASSERT_TRUE(IsInitializing(peer));
4397   ASSERT_FALSE(peer->bonded());
4398 
4399   FakePairingDelegate pairing_delegate(sm::IOCapability::kDisplayYesNo);
4400   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
4401 
4402   // Approve pairing requests.
4403   pairing_delegate.SetDisplayPasskeyCallback(
4404       [](PeerId, uint32_t, auto, auto confirm_cb) {
4405         ASSERT_TRUE(confirm_cb);
4406         confirm_cb(true);
4407       });
4408 
4409   pairing_delegate.SetCompletePairingCallback(
4410       [](PeerId, sm::Result<> status) { EXPECT_EQ(fit::ok(), status); });
4411 
4412   QueueSuccessfulPairing();
4413 
4414   // Make the pairing error a "bad" error to confirm the callback is called at
4415   // the end of the pairing process.
4416   hci::Result<> pairing_status = ToResult(HostError::kPacketMalformed);
4417   auto pairing_complete_cb = [&pairing_status](hci::Result<> status) {
4418     ASSERT_EQ(fit::ok(), status);
4419     pairing_status = status;
4420   };
4421 
4422   connmgr()->Pair(
4423       peer->identifier(), kNoSecurityRequirements, pairing_complete_cb);
4424   RunUntilIdle();
4425 
4426   ASSERT_EQ(fit::ok(), pairing_status);
4427   ASSERT_TRUE(IsConnected(peer));
4428   ASSERT_TRUE(peer->bonded());
4429 
4430   pairing_status = ToResult(HostError::kPacketMalformed);
4431   connmgr()->Pair(
4432       peer->identifier(), kNoSecurityRequirements, pairing_complete_cb);
4433 
4434   // Note that we do not call QueueSuccessfulPairing twice, even though we pair
4435   // twice - this is to test that pairing on an already-paired link succeeds
4436   // without sending any messages to the peer.
4437   RunUntilIdle();
4438   ASSERT_EQ(fit::ok(), pairing_status);
4439   ASSERT_TRUE(peer->bonded());
4440 
4441   QueueDisconnection(kConnectionHandle);
4442 }
4443 
TEST_F(BrEdrConnectionManagerTest,OpenL2capChannelCreatesChannelWithChannelParameters)4444 TEST_F(BrEdrConnectionManagerTest,
4445        OpenL2capChannelCreatesChannelWithChannelParameters) {
4446   constexpr l2cap::Psm kPsm = l2cap::kAVDTP;
4447   constexpr l2cap::ChannelId kLocalId = l2cap::kFirstDynamicChannelId;
4448   l2cap::ChannelParameters params;
4449   params.mode =
4450       l2cap::RetransmissionAndFlowControlMode::kEnhancedRetransmission;
4451   params.max_rx_sdu_size = l2cap::kMinACLMTU;
4452 
4453   QueueSuccessfulIncomingConn(kTestDevAddr, kConnectionHandle);
4454   test_device()->SendCommandChannelPacket(kConnectionRequest);
4455 
4456   RunUntilIdle();
4457 
4458   auto* peer = peer_cache()->FindByAddress(kTestDevAddr);
4459   ASSERT_TRUE(peer);
4460   EXPECT_EQ(peer->identifier(), connmgr()->GetPeerId(kConnectionHandle));
4461 
4462   FakePairingDelegate pairing_delegate(sm::IOCapability::kDisplayYesNo);
4463   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
4464   // Approve pairing requests.
4465   pairing_delegate.SetDisplayPasskeyCallback(
4466       [](PeerId, uint32_t, auto, auto confirm_cb) { confirm_cb(true); });
4467   pairing_delegate.SetCompletePairingCallback(
4468       [](PeerId, sm::Result<> status) { EXPECT_EQ(fit::ok(), status); });
4469 
4470   QueueSuccessfulPairing();
4471   RunUntilIdle();
4472 
4473   l2cap()->ExpectOutboundL2capChannel(
4474       kConnectionHandle, kPsm, kLocalId, 0x41, params);
4475 
4476   std::optional<l2cap::ChannelInfo> chan_info;
4477   size_t sock_cb_count = 0;
4478   auto sock_cb = [&](auto chan) {
4479     sock_cb_count++;
4480     ASSERT_TRUE(chan.is_alive());
4481     chan_info = chan->info();
4482   };
4483   connmgr()->OpenL2capChannel(
4484       peer->identifier(), kPsm, kNoSecurityRequirements, params, sock_cb);
4485 
4486   RunUntilIdle();
4487   EXPECT_EQ(1u, sock_cb_count);
4488   ASSERT_TRUE(chan_info);
4489   EXPECT_EQ(*params.mode, chan_info->mode);
4490   EXPECT_EQ(*params.max_rx_sdu_size, chan_info->max_rx_sdu_size);
4491 
4492   QueueDisconnection(kConnectionHandle);
4493 }
4494 
4495 // Tests that the connection manager cleans up its connection map correctly
4496 // following a disconnection due to encryption failure.
TEST_F(BrEdrConnectionManagerTest,ConnectionCleanUpFollowingEncryptionFailure)4497 TEST_F(BrEdrConnectionManagerTest,
4498        ConnectionCleanUpFollowingEncryptionFailure) {
4499   auto* peer = peer_cache()->NewPeer(kTestDevAddr, /*connectable=*/true);
4500   EXPECT_TRUE(peer->temporary());
4501 
4502   // Queue up the connection
4503   EXPECT_CMD_PACKET_OUT(test_device(),
4504                         kCreateConnection,
4505                         &kCreateConnectionRsp,
4506                         &kConnectionComplete);
4507   QueueSuccessfulInterrogation(peer->address(), kConnectionHandle);
4508   QueueDisconnection(kConnectionHandle,
4509                      pw::bluetooth::emboss::StatusCode::AUTHENTICATION_FAILURE);
4510 
4511   // Initialize as error to verify that |callback| assigns success.
4512   hci::Result<> status = ToResult(HostError::kFailed);
4513   BrEdrConnection* conn_ref = nullptr;
4514   auto callback = [&status, &conn_ref](auto cb_status, auto cb_conn_ref) {
4515     EXPECT_TRUE(cb_conn_ref);
4516     status = cb_status;
4517     conn_ref = std::move(cb_conn_ref);
4518   };
4519 
4520   EXPECT_TRUE(connmgr()->Connect(peer->identifier(), callback));
4521   ASSERT_TRUE(peer->bredr());
4522   RunUntilIdle();
4523   ASSERT_EQ(fit::ok(), status);
4524 
4525   test_device()->SendCommandChannelPacket(testing::EncryptionChangeEventPacket(
4526       pw::bluetooth::emboss::StatusCode::CONNECTION_TERMINATED_MIC_FAILURE,
4527       kConnectionHandle,
4528       hci_spec::EncryptionStatus::kOff));
4529   test_device()->SendCommandChannelPacket(testing::DisconnectionCompletePacket(
4530       kConnectionHandle,
4531       pw::bluetooth::emboss::StatusCode::CONNECTION_TERMINATED_MIC_FAILURE));
4532   RunUntilIdle();
4533 
4534   EXPECT_TRUE(IsNotConnected(peer));
4535 }
4536 
TEST_F(BrEdrConnectionManagerTest,OpenL2capChannelUpgradesLinkKey)4537 TEST_F(BrEdrConnectionManagerTest, OpenL2capChannelUpgradesLinkKey) {
4538   QueueSuccessfulIncomingConn(kTestDevAddr, kConnectionHandle);
4539   test_device()->SendCommandChannelPacket(kConnectionRequest);
4540 
4541   RunUntilIdle();
4542 
4543   auto* peer = peer_cache()->FindByAddress(kTestDevAddr);
4544   ASSERT_TRUE(peer);
4545   EXPECT_EQ(peer->identifier(), connmgr()->GetPeerId(kConnectionHandle));
4546 
4547   FakePairingDelegate pairing_delegate_no_io(
4548       sm::IOCapability::kNoInputNoOutput);
4549   connmgr()->SetPairingDelegate(pairing_delegate_no_io.GetWeakPtr());
4550   pairing_delegate_no_io.SetConfirmPairingCallback(
4551       [&peer](PeerId peer_id, auto cb) {
4552         EXPECT_EQ(peer->identifier(), peer_id);
4553         ASSERT_TRUE(cb);
4554         cb(true);
4555       });
4556   pairing_delegate_no_io.SetCompletePairingCallback(
4557       [](PeerId, sm::Result<> status) { EXPECT_EQ(fit::ok(), status); });
4558 
4559   size_t sock_cb_count = 0;
4560   auto sock_cb = [&](auto chan_sock) {
4561     sock_cb_count++;
4562     EXPECT_TRUE(chan_sock.is_alive());
4563   };
4564 
4565   // Pairing caused by missing link key.
4566   QueueSuccessfulUnauthenticatedPairing();
4567 
4568   constexpr auto kPsm0 = l2cap::kHIDControl;
4569   constexpr l2cap::ChannelId kLocalId0 = l2cap::kFirstDynamicChannelId;
4570   constexpr l2cap::ChannelId kRemoteId0 = 0x41;
4571   l2cap()->ExpectOutboundL2capChannel(kConnectionHandle,
4572                                       kPsm0,
4573                                       kLocalId0,
4574                                       kRemoteId0,
4575                                       l2cap::ChannelParameters());
4576   connmgr()->OpenL2capChannel(peer->identifier(),
4577                               kPsm0,
4578                               kNoSecurityRequirements,
4579                               l2cap::ChannelParameters(),
4580                               sock_cb);
4581 
4582   RunUntilIdle();
4583   EXPECT_EQ(1u, sock_cb_count);
4584 
4585   // New pairing delegate with display can support authenticated pairing.
4586   FakePairingDelegate pairing_delegate_with_display(
4587       sm::IOCapability::kDisplayYesNo);
4588   connmgr()->SetPairingDelegate(pairing_delegate_with_display.GetWeakPtr());
4589   pairing_delegate_with_display.SetDisplayPasskeyCallback(
4590       [](PeerId, uint32_t, auto, auto confirm_cb) { confirm_cb(true); });
4591   pairing_delegate_with_display.SetCompletePairingCallback(
4592       [](PeerId, sm::Result<> status) { EXPECT_EQ(fit::ok(), status); });
4593 
4594   // Pairing caused by insufficient link key.
4595   QueueSuccessfulPairing();
4596 
4597   constexpr auto kPsm1 = l2cap::kHIDInteerup;
4598   constexpr l2cap::ChannelId kLocalId1 = kLocalId0 + 1;
4599   constexpr l2cap::ChannelId kRemoteId1 = kRemoteId0 + 1;
4600   l2cap()->ExpectOutboundL2capChannel(kConnectionHandle,
4601                                       kPsm1,
4602                                       kLocalId1,
4603                                       kRemoteId1,
4604                                       l2cap::ChannelParameters());
4605   connmgr()->OpenL2capChannel(peer->identifier(),
4606                               kPsm1,
4607                               kAuthSecurityRequirements,
4608                               l2cap::ChannelParameters(),
4609                               sock_cb);
4610 
4611   RunUntilIdle();
4612   EXPECT_EQ(2u, sock_cb_count);
4613 
4614   QueueDisconnection(kConnectionHandle);
4615 }
4616 
TEST_F(BrEdrConnectionManagerTest,OpenL2capChannelUpgradeLinkKeyFails)4617 TEST_F(BrEdrConnectionManagerTest, OpenL2capChannelUpgradeLinkKeyFails) {
4618   QueueSuccessfulIncomingConn(kTestDevAddr, kConnectionHandle);
4619   test_device()->SendCommandChannelPacket(kConnectionRequest);
4620 
4621   RunUntilIdle();
4622 
4623   auto* peer = peer_cache()->FindByAddress(kTestDevAddr);
4624   ASSERT_TRUE(peer);
4625   EXPECT_EQ(peer->identifier(), connmgr()->GetPeerId(kConnectionHandle));
4626 
4627   FakePairingDelegate pairing_delegate_no_io(
4628       sm::IOCapability::kNoInputNoOutput);
4629   connmgr()->SetPairingDelegate(pairing_delegate_no_io.GetWeakPtr());
4630   pairing_delegate_no_io.SetConfirmPairingCallback(
4631       [&peer](PeerId peer_id, auto cb) {
4632         EXPECT_EQ(peer->identifier(), peer_id);
4633         ASSERT_TRUE(cb);
4634         cb(true);
4635       });
4636   pairing_delegate_no_io.SetCompletePairingCallback(
4637       [](PeerId, sm::Result<> status) { EXPECT_EQ(fit::ok(), status); });
4638 
4639   size_t sock_cb_count = 0;
4640   auto sock_cb = [&](auto chan_sock) {
4641     if (sock_cb_count == 0) {
4642       EXPECT_TRUE(chan_sock.is_alive());
4643     } else {
4644       // Second OpenL2capChannel fails due to insufficient security.
4645       EXPECT_FALSE(chan_sock.is_alive());
4646     }
4647     sock_cb_count++;
4648   };
4649 
4650   // Initial pairing.
4651   QueueSuccessfulUnauthenticatedPairing();
4652 
4653   constexpr auto kPsm0 = l2cap::kHIDControl;
4654   constexpr l2cap::ChannelId kLocalId = l2cap::kFirstDynamicChannelId;
4655   constexpr l2cap::ChannelId kRemoteId = 0x41;
4656   l2cap()->ExpectOutboundL2capChannel(kConnectionHandle,
4657                                       kPsm0,
4658                                       kLocalId,
4659                                       kRemoteId,
4660                                       l2cap::ChannelParameters());
4661   connmgr()->OpenL2capChannel(peer->identifier(),
4662                               kPsm0,
4663                               kNoSecurityRequirements,
4664                               l2cap::ChannelParameters(),
4665                               sock_cb);
4666 
4667   RunUntilIdle();
4668   EXPECT_EQ(1u, sock_cb_count);
4669 
4670   // Pairing caused by insufficient link key.
4671   QueueSuccessfulUnauthenticatedPairing();
4672 
4673   constexpr auto kPsm1 = l2cap::kHIDInteerup;
4674 
4675   connmgr()->OpenL2capChannel(peer->identifier(),
4676                               kPsm1,
4677                               kAuthSecurityRequirements,
4678                               l2cap::ChannelParameters(),
4679                               sock_cb);
4680 
4681   RunUntilIdle();
4682   EXPECT_EQ(2u, sock_cb_count);
4683 
4684   // Pairing should not be attempted a third time.
4685 
4686   QueueDisconnection(kConnectionHandle);
4687 }
4688 
TEST_F(BrEdrConnectionManagerTest,OpenScoConnectionWithoutExistingBrEdrConnectionFails)4689 TEST_F(BrEdrConnectionManagerTest,
4690        OpenScoConnectionWithoutExistingBrEdrConnectionFails) {
4691   std::optional<sco::ScoConnectionManager::OpenConnectionResult> conn_result;
4692   auto conn_cb = [&conn_result](auto result) {
4693     conn_result = std::move(result);
4694   };
4695   auto handle = connmgr()->OpenScoConnection(
4696       PeerId(1),
4697       {bt::StaticPacket<
4698           pw::bluetooth::emboss::SynchronousConnectionParametersWriter>{}},
4699       std::move(conn_cb));
4700   EXPECT_FALSE(handle.has_value());
4701   ASSERT_TRUE(conn_result.has_value());
4702   ASSERT_TRUE(conn_result->is_error());
4703   EXPECT_EQ(conn_result->error_value(), HostError::kNotFound);
4704 }
4705 
TEST_F(BrEdrConnectionManagerTest,OpenScoConnectionInitiator)4706 TEST_F(BrEdrConnectionManagerTest, OpenScoConnectionInitiator) {
4707   QueueSuccessfulIncomingConn();
4708   test_device()->SendCommandChannelPacket(kConnectionRequest);
4709   RunUntilIdle();
4710   auto* peer = peer_cache()->FindByAddress(kTestDevAddr);
4711   ASSERT_TRUE(peer);
4712 
4713   bt::StaticPacket<pw::bluetooth::emboss::SynchronousConnectionParametersWriter>
4714       kScoConnection;
4715   kScoConnection.SetToZeros();
4716   constexpr hci_spec::ConnectionHandle kScoConnectionHandle = 0x41;
4717   auto setup_status_packet = testing::CommandStatusPacket(
4718       hci_spec::kEnhancedSetupSynchronousConnection,
4719       pw::bluetooth::emboss::StatusCode::SUCCESS);
4720   auto conn_complete_packet = testing::SynchronousConnectionCompletePacket(
4721       kScoConnectionHandle,
4722       peer->address(),
4723       hci_spec::LinkType::kExtendedSCO,
4724       pw::bluetooth::emboss::StatusCode::SUCCESS);
4725   EXPECT_CMD_PACKET_OUT(
4726       test_device(),
4727       testing::EnhancedSetupSynchronousConnectionPacket(kConnectionHandle, {}),
4728       &setup_status_packet,
4729       &conn_complete_packet);
4730 
4731   std::optional<sco::ScoConnectionManager::OpenConnectionResult> conn_result;
4732   auto conn_cb = [&conn_result](auto result) {
4733     conn_result = std::move(result);
4734   };
4735 
4736   auto req_handle = connmgr()->OpenScoConnection(
4737       peer->identifier(), {kScoConnection}, std::move(conn_cb));
4738 
4739   RunUntilIdle();
4740   ASSERT_TRUE(conn_result.has_value());
4741   ASSERT_TRUE(conn_result->is_ok());
4742   EXPECT_EQ(conn_result->value()->handle(), kScoConnectionHandle);
4743 
4744   // Disconnecting from a peer should first disconnect SCO connections, then
4745   // disconnect the ACL connection.
4746   QueueDisconnection(kScoConnectionHandle);
4747   QueueDisconnection(kConnectionHandle);
4748   connmgr()->Disconnect(peer->identifier(), DisconnectReason::kApiRequest);
4749   RunUntilIdle();
4750 }
4751 
4752 class ScoLinkTypesTest
4753     : public BrEdrConnectionManagerTest,
4754       public ::testing::WithParamInterface<hci_spec::LinkType> {};
4755 
TEST_P(ScoLinkTypesTest,OpenScoConnectionResponder)4756 TEST_P(ScoLinkTypesTest, OpenScoConnectionResponder) {
4757   QueueSuccessfulIncomingConn();
4758   test_device()->SendCommandChannelPacket(kConnectionRequest);
4759   RunUntilIdle();
4760   auto* peer = peer_cache()->FindByAddress(kTestDevAddr);
4761   ASSERT_TRUE(peer);
4762 
4763   bt::StaticPacket<pw::bluetooth::emboss::SynchronousConnectionParametersWriter>
4764       sco_conn_params;
4765   if (GetParam() == hci_spec::LinkType::kSCO) {
4766     sco_conn_params.view().packet_types().hv3().Write(true);
4767   } else {
4768     sco_conn_params.view().packet_types().ev3().Write(true);
4769   }
4770   std::optional<sco::ScoConnectionManager::AcceptConnectionResult> conn_result;
4771   auto conn_cb =
4772       [&conn_result](sco::ScoConnectionManager::AcceptConnectionResult result) {
4773         EXPECT_TRUE(result.is_ok());
4774         conn_result = std::move(result);
4775       };
4776   auto req_handle = connmgr()->AcceptScoConnection(
4777       peer->identifier(), {sco_conn_params}, std::move(conn_cb));
4778 
4779   auto conn_req_packet = testing::ConnectionRequestPacket(
4780       peer->address(), /*link_type=*/GetParam());
4781   test_device()->SendCommandChannelPacket(conn_req_packet);
4782 
4783   auto accept_status_packet = testing::CommandStatusPacket(
4784       hci_spec::kEnhancedAcceptSynchronousConnectionRequest,
4785       pw::bluetooth::emboss::StatusCode::SUCCESS);
4786   EXPECT_CMD_PACKET_OUT(
4787       test_device(),
4788       testing::EnhancedAcceptSynchronousConnectionRequestPacket(
4789           peer->address(), sco_conn_params),
4790       &accept_status_packet);
4791   RunUntilIdle();
4792   EXPECT_FALSE(conn_result.has_value());
4793 
4794   constexpr hci_spec::ConnectionHandle kScoConnectionHandle = 0x41;
4795   test_device()->SendCommandChannelPacket(
4796       testing::SynchronousConnectionCompletePacket(
4797           kScoConnectionHandle,
4798           peer->address(),
4799           /*link_type=*/GetParam(),
4800           pw::bluetooth::emboss::StatusCode::SUCCESS));
4801 
4802   RunUntilIdle();
4803   ASSERT_TRUE(conn_result.has_value());
4804   ASSERT_TRUE(conn_result->is_ok());
4805   EXPECT_EQ(conn_result->value().first->handle(), kScoConnectionHandle);
4806 
4807   // Disconnecting from a peer should first disconnect SCO connections, then
4808   // disconnect the ACL connection.
4809   QueueDisconnection(kScoConnectionHandle);
4810   QueueDisconnection(kConnectionHandle);
4811   connmgr()->Disconnect(peer->identifier(), DisconnectReason::kApiRequest);
4812   RunUntilIdle();
4813 }
4814 
4815 INSTANTIATE_TEST_SUITE_P(BrEdrConnectionManagerTest,
4816                          ScoLinkTypesTest,
4817                          ::testing::Values(hci_spec::LinkType::kSCO,
4818                                            hci_spec::LinkType::kExtendedSCO));
4819 
4820 class UnconnectedLinkTypesTest
4821     : public BrEdrConnectionManagerTest,
4822       public ::testing::WithParamInterface<hci_spec::LinkType> {};
4823 
4824 // Test that an unexpected SCO connection request is rejected for
4825 // kUnacceptableConnectionParameters
TEST_P(UnconnectedLinkTypesTest,RejectUnsupportedSCOConnectionRequests)4826 TEST_P(UnconnectedLinkTypesTest, RejectUnsupportedSCOConnectionRequests) {
4827   auto status_event = testing::CommandStatusPacket(
4828       hci_spec::kRejectSynchronousConnectionRequest,
4829       pw::bluetooth::emboss::StatusCode::SUCCESS);
4830   auto complete_event = testing::ConnectionCompletePacket(
4831       kTestDevAddr,
4832       kConnectionHandle,
4833       pw::bluetooth::emboss::StatusCode::UNACCEPTABLE_CONNECTION_PARAMETERS);
4834   EXPECT_CMD_PACKET_OUT(test_device(),
4835                         testing::RejectSynchronousConnectionRequest(
4836                             kTestDevAddr,
4837                             pw::bluetooth::emboss::StatusCode::
4838                                 UNACCEPTABLE_CONNECTION_PARAMETERS),
4839                         &status_event,
4840                         &complete_event);
4841   test_device()->SendCommandChannelPacket(
4842       testing::ConnectionRequestPacket(kTestDevAddr, /*link_type=*/GetParam()));
4843   RunUntilIdle();
4844 }
4845 
4846 INSTANTIATE_TEST_SUITE_P(BrEdrConnectionManagerTest,
4847                          UnconnectedLinkTypesTest,
4848                          ::testing::Values(hci_spec::LinkType::kSCO,
4849                                            hci_spec::LinkType::kExtendedSCO));
4850 
4851 // Test that an unexpected link type connection request is rejected for
4852 // kUnsupportedFeatureOrParameter
TEST_F(BrEdrConnectionManagerTest,RejectUnsupportedConnectionRequest)4853 TEST_F(BrEdrConnectionManagerTest, RejectUnsupportedConnectionRequest) {
4854   auto linktype = static_cast<hci_spec::LinkType>(0x09);
4855   auto status_event =
4856       testing::CommandStatusPacket(hci_spec::kRejectConnectionRequest,
4857                                    pw::bluetooth::emboss::StatusCode::SUCCESS);
4858   auto complete_event = testing::ConnectionCompletePacket(
4859       kTestDevAddr,
4860       kConnectionHandle,
4861       pw::bluetooth::emboss::StatusCode::UNSUPPORTED_FEATURE_OR_PARAMETER);
4862   EXPECT_CMD_PACKET_OUT(
4863       test_device(),
4864       testing::RejectConnectionRequestPacket(
4865           kTestDevAddr,
4866           pw::bluetooth::emboss::StatusCode::UNSUPPORTED_FEATURE_OR_PARAMETER),
4867       &status_event,
4868       &complete_event);
4869   test_device()->SendCommandChannelPacket(
4870       testing::ConnectionRequestPacket(kTestDevAddr, linktype));
4871   RunUntilIdle();
4872 }
4873 
TEST_F(BrEdrConnectionManagerTest,IncomingConnectionRacesOutgoing)4874 TEST_F(BrEdrConnectionManagerTest, IncomingConnectionRacesOutgoing) {
4875   auto* peer = peer_cache()->NewPeer(kTestDevAddr, /*connectable=*/true);
4876   ASSERT_TRUE(peer->bredr() && IsNotConnected(peer));
4877 
4878   hci::Result<> status = ToResult(HostError::kFailed);
4879   BrEdrConnection* conn_ref = nullptr;
4880   auto should_succeed = [&status, &conn_ref](auto cb_status, auto cb_conn_ref) {
4881     // We expect this callback to be executed, with a succesful connection
4882     EXPECT_TRUE(cb_conn_ref);
4883     EXPECT_EQ(fit::ok(), cb_status);
4884     status = cb_status;
4885     conn_ref = std::move(cb_conn_ref);
4886   };
4887 
4888   // A client calls Connect() for the Peer, beginning an outgoing connection. We
4889   // expect a CreateConnection, and ack with a status response but don't
4890   // complete yet
4891   EXPECT_CMD_PACKET_OUT(
4892       test_device(), kCreateConnection, &kCreateConnectionRsp);
4893   EXPECT_TRUE(connmgr()->Connect(peer->identifier(), should_succeed));
4894 
4895   // Meanwhile, an incoming connection is requested from the Peer
4896   test_device()->SendCommandChannelPacket(kConnectionRequest);
4897   // We expect it to be accepted, and then return a command status response, but
4898   // not a ConnectionComplete event yet
4899   EXPECT_CMD_PACKET_OUT(
4900       test_device(), kAcceptConnectionRequest, &kAcceptConnectionRequestRsp);
4901   RunUntilIdle();
4902 
4903   // The controller now establishes the link, but will respond to the outgoing
4904   // connection with the hci error: `ConnectionAlreadyExists` First, the
4905   // controller notifies us of the failed outgoing connection - as from its
4906   // perspective, we've already connected
4907   const auto complete_already = testing::ConnectionCompletePacket(
4908       kTestDevAddr,
4909       kConnectionHandle,
4910       pw::bluetooth::emboss::StatusCode::CONNECTION_ALREADY_EXISTS);
4911   test_device()->SendCommandChannelPacket(complete_already);
4912   // Then the controller notifies us of the successful incoming connection
4913   test_device()->SendCommandChannelPacket(kConnectionComplete);
4914   // We expect to connect and begin interrogation, and for our connect()
4915   // callback to have been run
4916   QueueSuccessfulInterrogation(kTestDevAddr, kConnectionHandle);
4917   RunUntilIdle();
4918   EXPECT_EQ(fit::ok(), status);
4919 
4920   // Peers are marked as initializing until a pairing procedure finishes.
4921   EXPECT_TRUE(IsInitializing(peer));
4922   // Prepare for disconnection upon teardown.
4923   QueueDisconnection(kConnectionHandle);
4924 }
4925 
TEST_F(BrEdrConnectionManagerTest,OutgoingConnectionRacesIncoming)4926 TEST_F(BrEdrConnectionManagerTest, OutgoingConnectionRacesIncoming) {
4927   auto* peer = peer_cache()->NewPeer(kTestDevAddr, /*connectable=*/true);
4928   ASSERT_TRUE(peer->bredr() && IsNotConnected(peer));
4929   hci::Result<> status = ToResult(HostError::kFailed);
4930   BrEdrConnection* conn_ref = nullptr;
4931   auto should_succeed = [&status, &conn_ref](auto cb_status, auto cb_conn_ref) {
4932     EXPECT_TRUE(cb_conn_ref);
4933     EXPECT_EQ(fit::ok(), cb_status);
4934     status = cb_status;
4935     conn_ref = std::move(cb_conn_ref);
4936   };
4937 
4938   // An incoming connection is requested from the Peer
4939   test_device()->SendCommandChannelPacket(kConnectionRequest);
4940   // We expect it to be accepted, and then return a command status response, but
4941   // not a ConnectionComplete event yet
4942   EXPECT_CMD_PACKET_OUT(
4943       test_device(), kAcceptConnectionRequest, &kAcceptConnectionRequestRsp);
4944   RunUntilIdle();
4945   // Meanwhile, a client calls Connect() for the peer. We don't expect any
4946   // packets out as the connection manager will defer requests that have an
4947   // active incoming request. Instead, this request will be completed when the
4948   // incoming procedure completes.
4949   EXPECT_TRUE(connmgr()->Connect(peer->identifier(), should_succeed));
4950   // We should still expect to connect
4951   RunUntilIdle();
4952 
4953   // The controller now notifies us of the complete incoming connection
4954   test_device()->SendCommandChannelPacket(kConnectionComplete);
4955   // We expect to connect and begin interrogation, and for the callback passed
4956   // to Connect() to have been executed when the incoming connection succeeded.
4957   QueueSuccessfulInterrogation(kTestDevAddr, kConnectionHandle);
4958   RunUntilIdle();
4959   EXPECT_EQ(fit::ok(), status);
4960 
4961   // Peers are marked as initializing until a pairing procedure finishes.
4962   EXPECT_TRUE(IsInitializing(peer));
4963   // Prepare for disconnection upon teardown.
4964   QueueDisconnection(kConnectionHandle);
4965 }
4966 
TEST_F(BrEdrConnectionManagerTest,DuplicateIncomingConnectionsFromSamePeerRejected)4967 TEST_F(BrEdrConnectionManagerTest,
4968        DuplicateIncomingConnectionsFromSamePeerRejected) {
4969   auto* peer = peer_cache()->NewPeer(kTestDevAddr, /*connectable=*/true);
4970   ASSERT_TRUE(peer->bredr() && IsNotConnected(peer));
4971 
4972   // Our first request should be accepted - we send back a success status, not
4973   // the connection complete yet
4974   EXPECT_CMD_PACKET_OUT(
4975       test_device(), kAcceptConnectionRequest, &kAcceptConnectionRequestRsp);
4976   test_device()->SendCommandChannelPacket(kConnectionRequest);
4977   RunUntilIdle();
4978 
4979   auto status_event =
4980       testing::CommandStatusPacket(hci_spec::kRejectConnectionRequest,
4981                                    pw::bluetooth::emboss::StatusCode::SUCCESS);
4982   auto complete_error = testing::ConnectionCompletePacket(
4983       kTestDevAddr,
4984       kConnectionHandle,
4985       pw::bluetooth::emboss::StatusCode::UNSUPPORTED_FEATURE_OR_PARAMETER);
4986   auto reject_packet = testing::RejectConnectionRequestPacket(
4987       kTestDevAddr,
4988       pw::bluetooth::emboss::StatusCode::CONNECTION_REJECTED_BAD_BD_ADDR);
4989 
4990   // Our second request should be rejected - we already have an incoming request
4991   EXPECT_CMD_PACKET_OUT(test_device(), reject_packet, &status_event);
4992   test_device()->SendCommandChannelPacket(kConnectionRequest);
4993   RunUntilIdle();
4994 
4995   QueueSuccessfulInterrogation(kTestDevAddr, kConnectionHandle);
4996   test_device()->SendCommandChannelPacket(kConnectionComplete);
4997   RunUntilIdle();
4998   test_device()->SendCommandChannelPacket(complete_error);
4999 
5000   RunUntilIdle();
5001 
5002   EXPECT_FALSE(IsNotConnected(peer));
5003 
5004   // Prepare for disconnection upon teardown.
5005   QueueDisconnection(kConnectionHandle);
5006 }
5007 
TEST_F(BrEdrConnectionManagerTest,IncomingRequestInitializesPeer)5008 TEST_F(BrEdrConnectionManagerTest, IncomingRequestInitializesPeer) {
5009   // Initially, we should not have a peer for the given address
5010   auto peer = peer_cache()->FindByAddress(kTestDevAddr);
5011   EXPECT_FALSE(peer);
5012   // Send a request, and once accepted send back a success status but not the
5013   // connection complete yet
5014   EXPECT_CMD_PACKET_OUT(
5015       test_device(), kAcceptConnectionRequest, &kAcceptConnectionRequestRsp);
5016   test_device()->SendCommandChannelPacket(kConnectionRequest);
5017   RunUntilIdle();
5018 
5019   // We should now have a peer in the cache to track our incoming request
5020   // address The peer is marked as 'Initializing` immediately.
5021   peer = peer_cache()->FindByAddress(kTestDevAddr);
5022   ASSERT_TRUE(peer);
5023   ASSERT_TRUE(peer->bredr());
5024   ASSERT_EQ(peer->bredr()->connection_state(),
5025             Peer::ConnectionState::kInitializing);
5026 }
5027 
5028 #ifndef NINSPECT
TEST_F(BrEdrConnectionManagerTest,Inspect)5029 TEST_F(BrEdrConnectionManagerTest, Inspect) {
5030   connmgr()->AttachInspect(inspector().GetRoot(), "bredr_connection_manager");
5031 
5032   // Don't receive connection complete yet in order to keep request pending.
5033   EXPECT_CMD_PACKET_OUT(test_device(),
5034                         testing::AcceptConnectionRequestPacket(kTestDevAddr),
5035                         &kAcceptConnectionRequestRsp);
5036   test_device()->SendCommandChannelPacket(kConnectionRequest);
5037   RunUntilIdle();
5038 
5039   auto requests_one_request_matcher = AllOf(
5040       NodeMatches(NameMatches("connection_requests")),
5041       ChildrenMatch(ElementsAre(NodeMatches(NameMatches("request_0x0")))));
5042 
5043   auto conn_mgr_with_request_matcher = AllOf(
5044       NodeMatches(NameMatches("bredr_connection_manager")),
5045       ChildrenMatch(::testing::IsSupersetOf({requests_one_request_matcher})));
5046 
5047   EXPECT_THAT(inspect::ReadFromVmo(inspector().DuplicateVmo()).value(),
5048               ChildrenMatch(ElementsAre(conn_mgr_with_request_matcher)));
5049 
5050   QueueSuccessfulInterrogation(kTestDevAddr, kConnectionHandle);
5051   const auto connection_complete =
5052       testing::ConnectionCompletePacket(kTestDevAddr, kConnectionHandle);
5053   test_device()->SendCommandChannelPacket(connection_complete);
5054   RunUntilIdle();
5055   auto* const peer = peer_cache()->FindByAddress(kTestDevAddr);
5056   ASSERT_TRUE(peer);
5057   ASSERT_EQ(peer->bredr()->connection_state(),
5058             Peer::ConnectionState::kInitializing);
5059 
5060   auto empty_requests_matcher =
5061       AllOf(NodeMatches(NameMatches("connection_requests")),
5062             ChildrenMatch(::testing::IsEmpty()));
5063 
5064   auto connection_matcher =
5065       NodeMatches(AllOf(NameMatches("connection_0x1"),
5066                         PropertyList(ElementsAre(StringIs(
5067                             "peer_id", peer->identifier().ToString())))));
5068 
5069   auto connections_matcher =
5070       AllOf(NodeMatches(NameMatches("connections")),
5071             ChildrenMatch(ElementsAre(connection_matcher)));
5072 
5073   auto recent_conn_list_matcher =
5074       AllOf(NodeMatches(NameMatches("last_disconnected")),
5075             ChildrenMatch(::testing::IsEmpty()));
5076 
5077   auto incoming_matcher =
5078       AllOf(NodeMatches(AllOf(NameMatches("incoming"),
5079                               PropertyList(UnorderedElementsAre(
5080                                   UintIs("connection_attempts", 1),
5081                                   UintIs("failed_connections", 0),
5082                                   UintIs("successful_connections", 1))))));
5083 
5084   auto outgoing_matcher =
5085       AllOf(NodeMatches(AllOf(NameMatches("outgoing"),
5086                               PropertyList(UnorderedElementsAre(
5087                                   UintIs("connection_attempts", 0),
5088                                   UintIs("failed_connections", 0),
5089                                   UintIs("successful_connections", 0))))));
5090 
5091   auto conn_mgr_matcher = AllOf(
5092       NodeMatches(AllOf(NameMatches("bredr_connection_manager"),
5093                         PropertyList(UnorderedElementsAre(
5094                             UintIs("disconnect_acl_link_error_count", 0),
5095                             UintIs("disconnect_interrogation_failed_count", 0),
5096                             UintIs("disconnect_local_api_request_count", 0),
5097                             UintIs("disconnect_pairing_failed_count", 0),
5098                             UintIs("disconnect_peer_disconnection_count", 0),
5099                             UintIs("interrogation_complete_count", 1),
5100                             StringIs("security_mode", "Mode 4"))))),
5101       ChildrenMatch(UnorderedElementsAre(empty_requests_matcher,
5102                                          connections_matcher,
5103                                          recent_conn_list_matcher,
5104                                          incoming_matcher,
5105                                          outgoing_matcher)));
5106 
5107   auto hierarchy = inspect::ReadFromVmo(inspector().DuplicateVmo());
5108   EXPECT_THAT(hierarchy.value(), ChildrenMatch(ElementsAre(conn_mgr_matcher)));
5109 
5110   // Delay disconnect so connection has non-zero duration.
5111   RunFor(std::chrono::seconds(1));
5112   QueueDisconnection(kConnectionHandle);
5113   EXPECT_TRUE(
5114       connmgr()->Disconnect(peer->identifier(), DisconnectReason::kApiRequest));
5115   RunUntilIdle();
5116 
5117   auto incoming_matcher_after_disconnect =
5118       AllOf(NodeMatches(AllOf(NameMatches("incoming"),
5119                               PropertyList(UnorderedElementsAre(
5120                                   UintIs("connection_attempts", 1),
5121                                   UintIs("failed_connections", 0),
5122                                   UintIs("successful_connections", 1))))));
5123 
5124   auto requests_matcher = AllOf(NodeMatches(NameMatches("connection_requests")),
5125                                 ChildrenMatch(::testing::IsEmpty()));
5126   auto connections_after_disconnect_matcher =
5127       AllOf(NodeMatches(NameMatches("connections")),
5128             ChildrenMatch(::testing::IsEmpty()));
5129   auto recent_conn_list_after_disconnect_matcher =
5130       AllOf(NodeMatches(NameMatches("last_disconnected")),
5131             ChildrenMatch(ElementsAre(NodeMatches(
5132                 AllOf(NameMatches("0"),
5133                       PropertyList(UnorderedElementsAre(
5134                           StringIs("peer_id", peer->identifier().ToString()),
5135                           UintIs("duration_s", 1u),
5136                           IntIs("@time", 1'000'000'000))))))));
5137 
5138   auto conn_mgr_after_disconnect_matcher = AllOf(
5139       NodeMatches(AllOf(NameMatches("bredr_connection_manager"),
5140                         PropertyList(UnorderedElementsAre(
5141                             UintIs("disconnect_acl_link_error_count", 0),
5142                             UintIs("disconnect_interrogation_failed_count", 0),
5143                             UintIs("disconnect_local_api_request_count", 1),
5144                             UintIs("disconnect_pairing_failed_count", 0),
5145                             UintIs("disconnect_peer_disconnection_count", 0),
5146                             UintIs("interrogation_complete_count", 1),
5147                             StringIs("security_mode", "Mode 4"))))),
5148       ChildrenMatch(
5149           UnorderedElementsAre(empty_requests_matcher,
5150                                connections_after_disconnect_matcher,
5151                                outgoing_matcher,
5152                                incoming_matcher_after_disconnect,
5153                                recent_conn_list_after_disconnect_matcher)));
5154 
5155   hierarchy = inspect::ReadFromVmo(inspector().DuplicateVmo());
5156   EXPECT_THAT(hierarchy.value(),
5157               ChildrenMatch(ElementsAre(conn_mgr_after_disconnect_matcher)));
5158 }
5159 
5160 // Verify that a failed incoming BR/EDR connection is reflected in inspect data
TEST_F(BrEdrConnectionManagerTest,InspectDataAfterFailedIncomingConnection)5161 TEST_F(BrEdrConnectionManagerTest, InspectDataAfterFailedIncomingConnection) {
5162   connmgr()->AttachInspect(inspector().GetRoot(), "bredr_connection_manager");
5163 
5164   const auto connection_complete_failed = testing::ConnectionCompletePacket(
5165       kTestDevAddr,
5166       kConnectionHandle,
5167       pw::bluetooth::emboss::StatusCode::CONNECTION_TIMEOUT);
5168   EXPECT_CMD_PACKET_OUT(test_device(),
5169                         testing::AcceptConnectionRequestPacket(kTestDevAddr),
5170                         &kAcceptConnectionRequestRsp,
5171                         &connection_complete_failed);
5172   test_device()->SendCommandChannelPacket(kConnectionRequest);
5173   RunUntilIdle();
5174 
5175   auto* const peer = peer_cache()->FindByAddress(kTestDevAddr);
5176   ASSERT_TRUE(peer);
5177 
5178   auto empty_requests_matcher =
5179       AllOf(NodeMatches(NameMatches("connection_requests")),
5180             ChildrenMatch(::testing::IsEmpty()));
5181 
5182   auto connections_matcher = AllOf(NodeMatches(NameMatches("connections")),
5183                                    ChildrenMatch(::testing::IsEmpty()));
5184 
5185   auto recent_conn_list_matcher =
5186       AllOf(NodeMatches(NameMatches("last_disconnected")),
5187             ChildrenMatch(::testing::IsEmpty()));
5188 
5189   auto incoming_matcher =
5190       AllOf(NodeMatches(AllOf(NameMatches("incoming"),
5191                               PropertyList(UnorderedElementsAre(
5192                                   UintIs("connection_attempts", 1),
5193                                   UintIs("failed_connections", 1),
5194                                   UintIs("successful_connections", 0))))));
5195 
5196   auto outgoing_matcher =
5197       AllOf(NodeMatches(AllOf(NameMatches("outgoing"),
5198                               PropertyList(UnorderedElementsAre(
5199                                   UintIs("connection_attempts", 0),
5200                                   UintIs("failed_connections", 0),
5201                                   UintIs("successful_connections", 0))))));
5202 
5203   auto conn_mgr_matcher = AllOf(
5204       NodeMatches(AllOf(NameMatches("bredr_connection_manager"),
5205                         PropertyList(UnorderedElementsAre(
5206                             UintIs("disconnect_acl_link_error_count", 0),
5207                             UintIs("disconnect_interrogation_failed_count", 0),
5208                             UintIs("disconnect_local_api_request_count", 0),
5209                             UintIs("disconnect_pairing_failed_count", 0),
5210                             UintIs("disconnect_peer_disconnection_count", 0),
5211                             UintIs("interrogation_complete_count", 0),
5212                             StringIs("security_mode", "Mode 4"))))),
5213       ChildrenMatch(UnorderedElementsAre(empty_requests_matcher,
5214                                          connections_matcher,
5215                                          recent_conn_list_matcher,
5216                                          incoming_matcher,
5217                                          outgoing_matcher)));
5218 
5219   auto hierarchy = inspect::ReadFromVmo(inspector().DuplicateVmo());
5220   EXPECT_THAT(hierarchy.value(), ChildrenMatch(ElementsAre(conn_mgr_matcher)));
5221 }
5222 #endif  // NINSPECT
5223 
TEST_F(BrEdrConnectionManagerTest,RoleChangeAfterInboundConnection)5224 TEST_F(BrEdrConnectionManagerTest, RoleChangeAfterInboundConnection) {
5225   EXPECT_EQ(kInvalidPeerId, connmgr()->GetPeerId(kConnectionHandle));
5226 
5227   QueueSuccessfulIncomingConn();
5228   test_device()->SendCommandChannelPacket(kConnectionRequest);
5229   RunUntilIdle();
5230   auto* peer = peer_cache()->FindByAddress(kTestDevAddr);
5231   ASSERT_TRUE(peer);
5232   EXPECT_EQ(peer->bredr()->connection_state(),
5233             Peer::ConnectionState::kInitializing);
5234 
5235   // Request an outbound connection in order to get a pointer to the existing
5236   // connection. No packets should be sent.
5237   BrEdrConnection* conn_ref = nullptr;
5238   auto callback = [&conn_ref](auto /*status*/, auto cb_conn_ref) {
5239     conn_ref = cb_conn_ref;
5240   };
5241 
5242   EXPECT_TRUE(connmgr()->Connect(peer->identifier(), callback));
5243   ASSERT_TRUE(conn_ref);
5244   EXPECT_EQ(conn_ref->link().role(),
5245             pw::bluetooth::emboss::ConnectionRole::PERIPHERAL);
5246 
5247   test_device()->SendCommandChannelPacket(testing::RoleChangePacket(
5248       kTestDevAddr, pw::bluetooth::emboss::ConnectionRole::CENTRAL));
5249   RunUntilIdle();
5250   EXPECT_EQ(conn_ref->link().role(),
5251             pw::bluetooth::emboss::ConnectionRole::CENTRAL);
5252 
5253   QueueDisconnection(kConnectionHandle);
5254 }
5255 
TEST_F(BrEdrConnectionManagerTest,RoleChangeWithFailureStatusAfterInboundConnection)5256 TEST_F(BrEdrConnectionManagerTest,
5257        RoleChangeWithFailureStatusAfterInboundConnection) {
5258   EXPECT_EQ(kInvalidPeerId, connmgr()->GetPeerId(kConnectionHandle));
5259 
5260   QueueSuccessfulIncomingConn();
5261   test_device()->SendCommandChannelPacket(kConnectionRequest);
5262   RunUntilIdle();
5263   auto* peer = peer_cache()->FindByAddress(kTestDevAddr);
5264   ASSERT_TRUE(peer);
5265   EXPECT_EQ(peer->bredr()->connection_state(),
5266             Peer::ConnectionState::kInitializing);
5267 
5268   // Request an outbound connection in order to get a pointer to the existing
5269   // connection. No packets should be sent.
5270   BrEdrConnection* conn_ref = nullptr;
5271   auto callback = [&conn_ref](auto /*status*/, auto cb_conn_ref) {
5272     conn_ref = cb_conn_ref;
5273   };
5274   EXPECT_TRUE(connmgr()->Connect(peer->identifier(), callback));
5275   ASSERT_TRUE(conn_ref);
5276   EXPECT_EQ(conn_ref->link().role(),
5277             pw::bluetooth::emboss::ConnectionRole::PERIPHERAL);
5278 
5279   test_device()->SendCommandChannelPacket(testing::RoleChangePacket(
5280       kTestDevAddr,
5281       pw::bluetooth::emboss::ConnectionRole::CENTRAL,
5282       pw::bluetooth::emboss::StatusCode::UNSPECIFIED_ERROR));
5283   RunUntilIdle();
5284   // The role should not change.
5285   EXPECT_EQ(conn_ref->link().role(),
5286             pw::bluetooth::emboss::ConnectionRole::PERIPHERAL);
5287 
5288   QueueDisconnection(kConnectionHandle);
5289 }
5290 
TEST_F(BrEdrConnectionManagerTest,RoleChangeDuringInboundConnectionProcedure)5291 TEST_F(BrEdrConnectionManagerTest, RoleChangeDuringInboundConnectionProcedure) {
5292   EXPECT_EQ(kInvalidPeerId, connmgr()->GetPeerId(kConnectionHandle));
5293 
5294   QueueSuccessfulIncomingConn(
5295       kTestDevAddr,
5296       kConnectionHandle,
5297       /*role_change=*/pw::bluetooth::emboss::ConnectionRole::CENTRAL);
5298   test_device()->SendCommandChannelPacket(kConnectionRequest);
5299   RunUntilIdle();
5300   auto* peer = peer_cache()->FindByAddress(kTestDevAddr);
5301   ASSERT_TRUE(peer);
5302   EXPECT_EQ(peer->bredr()->connection_state(),
5303             Peer::ConnectionState::kInitializing);
5304 
5305   // Request an outbound connection in order to get a pointer to the existing
5306   // connection. No packets should be sent.
5307   BrEdrConnection* conn_ref = nullptr;
5308   auto callback = [&conn_ref](auto /*status*/, auto cb_conn_ref) {
5309     conn_ref = cb_conn_ref;
5310   };
5311   EXPECT_TRUE(connmgr()->Connect(peer->identifier(), callback));
5312   ASSERT_TRUE(conn_ref);
5313   EXPECT_EQ(conn_ref->link().role(),
5314             pw::bluetooth::emboss::ConnectionRole::CENTRAL);
5315 
5316   QueueDisconnection(kConnectionHandle);
5317 }
5318 
5319 // Peer and local Secure Connections (SC) are supported and key is of SC type
TEST_F(BrEdrConnectionManagerTest,SecureConnectionsSupportedCorrectLinkKeyTypeSucceeds)5320 TEST_F(BrEdrConnectionManagerTest,
5321        SecureConnectionsSupportedCorrectLinkKeyTypeSucceeds) {
5322   const auto kReadRemoteExtended2CompleteSc = StaticByteBuffer(
5323       hci_spec::kReadRemoteExtendedFeaturesCompleteEventCode,
5324       0x0D,  // parameter_total_size (13 bytes)
5325       pw::bluetooth::emboss::StatusCode::SUCCESS,  // status
5326       0xAA,
5327       0x0B,  // connection_handle,
5328       0x02,  // page_number
5329       0x02,  // max_page_number
5330       0x00,
5331       0x01,
5332       0x00,
5333       0x00,
5334       0x00,
5335       0x00,
5336       0x00,
5337       0x00
5338       // lmp_features_page2: Secure Connections (Controller Support)
5339   );
5340   const auto kLinkKeyNotificationSc = MakeLinkKeyNotification(
5341       hci_spec::LinkKeyType::kAuthenticatedCombination256);
5342   const StaticByteBuffer kEncryptionChangeEventSc(
5343       hci_spec::kEncryptionChangeEventCode,
5344       4,     // parameter total size
5345       0x00,  // status
5346       0xAA,
5347       0x0B,  // connection handle
5348       0x02   // encryption enabled: AES-CCM for BR/EDR
5349   );
5350 
5351   FakePairingDelegate pairing_delegate(sm::IOCapability::kDisplayYesNo);
5352   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
5353 
5354   // Trigger inbound connection and respond to interrogation. LMP features are
5355   // set to support peer host and controller Secure Connections.
5356   QueueSuccessfulAccept(kTestDevAddr,
5357                         kConnectionHandle,
5358                         pw::bluetooth::emboss::ConnectionRole::CENTRAL);
5359   EXPECT_CMD_PACKET_OUT(test_device(),
5360                         kRemoteNameRequest,
5361                         &kRemoteNameRequestRsp,
5362                         &kRemoteNameRequestComplete);
5363   EXPECT_CMD_PACKET_OUT(test_device(),
5364                         kReadRemoteVersionInfo,
5365                         &kReadRemoteVersionInfoRsp,
5366                         &kRemoteVersionInfoComplete);
5367   EXPECT_CMD_PACKET_OUT(test_device(),
5368                         hci_spec::kReadRemoteSupportedFeatures,
5369                         &kReadRemoteSupportedFeaturesRsp,
5370                         &kReadRemoteSupportedFeaturesComplete);
5371   EXPECT_CMD_PACKET_OUT(test_device(),
5372                         kReadRemoteExtended1,
5373                         &kReadRemoteExtendedFeaturesRsp,
5374                         &kReadRemoteExtended1Complete);
5375   EXPECT_CMD_PACKET_OUT(test_device(),
5376                         kReadRemoteExtended2,
5377                         &kReadRemoteExtendedFeaturesRsp,
5378                         &kReadRemoteExtended2CompleteSc);
5379 
5380   test_device()->SendCommandChannelPacket(kConnectionRequest);
5381 
5382   RunUntilIdle();
5383 
5384   // Ensure that the interrogation has begun but the peer hasn't yet bonded
5385   EXPECT_EQ(6, transaction_count());
5386   auto* const peer = peer_cache()->FindByAddress(kTestDevAddr);
5387   ASSERT_TRUE(peer);
5388   ASSERT_TRUE(IsInitializing(peer));
5389   ASSERT_FALSE(peer->bredr()->bonded());
5390 
5391   // Approve pairing requests
5392   pairing_delegate.SetDisplayPasskeyCallback(
5393       [](PeerId, uint32_t, auto, auto confirm_cb) {
5394         ASSERT_TRUE(confirm_cb);
5395         confirm_cb(true);
5396       });
5397 
5398   pairing_delegate.SetCompletePairingCallback(
5399       [](PeerId, sm::Result<> status) { EXPECT_EQ(fit::ok(), status); });
5400 
5401   // Initiate pairing from the peer before interrogation completes
5402   test_device()->SendCommandChannelPacket(MakeIoCapabilityResponse(
5403       IoCapability::DISPLAY_YES_NO,
5404       AuthenticationRequirements::MITM_GENERAL_BONDING));
5405   test_device()->SendCommandChannelPacket(kIoCapabilityRequest);
5406   const auto kUserConfirmationRequest = MakeUserConfirmationRequest(kPasskey);
5407   EXPECT_CMD_PACKET_OUT(test_device(),
5408                         MakeIoCapabilityRequestReply(
5409                             IoCapability::DISPLAY_YES_NO,
5410                             AuthenticationRequirements::MITM_GENERAL_BONDING),
5411                         &kIoCapabilityRequestReplyRsp,
5412                         &kUserConfirmationRequest);
5413   EXPECT_CMD_PACKET_OUT(test_device(),
5414                         kUserConfirmationRequestReply,
5415                         &kUserConfirmationRequestReplyRsp,
5416                         &kSimplePairingCompleteSuccess,
5417                         &kLinkKeyNotificationSc);
5418   EXPECT_CMD_PACKET_OUT(test_device(),
5419                         kSetConnectionEncryption,
5420                         &kSetConnectionEncryptionRsp,
5421                         &kEncryptionChangeEventSc);
5422   EXPECT_CMD_PACKET_OUT(
5423       test_device(), kReadEncryptionKeySize, &kReadEncryptionKeySizeRsp);
5424 
5425   // Configure TestSecurityManager with bonding data so cross-transport key
5426   // derivation succeeds.
5427   sm::testing::TestSecurityManager::WeakPtr security_manager =
5428       security_manager_factory()->GetTestSm(kConnectionHandle);
5429   ASSERT_TRUE(security_manager.is_alive());
5430   sm::PairingData pairing_data;
5431   pairing_data.local_ltk = kLELtk;
5432   pairing_data.peer_ltk = kLELtk;
5433   security_manager->set_pairing_data(pairing_data);
5434   EXPECT_FALSE(peer->le());
5435 
5436   RETURN_IF_FATAL(RunUntilIdle());
5437 
5438   EXPECT_TRUE(l2cap()->IsLinkConnected(kConnectionHandle));
5439   ASSERT_TRUE(peer->bredr()->bonded());
5440   ASSERT_TRUE(peer->le());
5441   ASSERT_TRUE(peer->le()->bond_data().has_value());
5442   EXPECT_EQ(peer->le()->bond_data().value(), pairing_data);
5443   EXPECT_TRUE(security_manager->last_identity_info().has_value());
5444 
5445   QueueDisconnection(kConnectionHandle);
5446 }
5447 
5448 // Peer and local Secure Connections (SC) are supported, but key is not of SC
5449 // type
TEST_F(BrEdrConnectionManagerTest,SecureConnectionsSupportedIncorrectLinkKeyTypeFails)5450 TEST_F(BrEdrConnectionManagerTest,
5451        SecureConnectionsSupportedIncorrectLinkKeyTypeFails) {
5452   const auto kReadRemoteExtended2CompleteLktf = StaticByteBuffer(
5453       hci_spec::kReadRemoteExtendedFeaturesCompleteEventCode,
5454       0x0D,  // parameter_total_size (13 bytes)
5455       pw::bluetooth::emboss::StatusCode::SUCCESS,  // status
5456       0xAA,
5457       0x0B,  // connection_handle,
5458       0x02,  // page_number
5459       0x02,  // max_page_number
5460       0x00,
5461       0x01,
5462       0x00,
5463       0x00,
5464       0x00,
5465       0x00,
5466       0x00,
5467       0x00
5468       // lmp_features_page2: Secure Connections (Controller Support)
5469   );
5470 
5471   FakePairingDelegate pairing_delegate(sm::IOCapability::kDisplayYesNo);
5472   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
5473 
5474   // Trigger inbound connection and respond to interrogation. LMP features are
5475   // set to support peer host and controller Secure Connections.
5476   EXPECT_CMD_PACKET_OUT(test_device(),
5477                         kAcceptConnectionRequest,
5478                         &kAcceptConnectionRequestRsp,
5479                         &kConnectionComplete);
5480   EXPECT_CMD_PACKET_OUT(test_device(),
5481                         kRemoteNameRequest,
5482                         &kRemoteNameRequestRsp,
5483                         &kRemoteNameRequestComplete);
5484   EXPECT_CMD_PACKET_OUT(test_device(),
5485                         kReadRemoteVersionInfo,
5486                         &kReadRemoteVersionInfoRsp,
5487                         &kRemoteVersionInfoComplete);
5488   EXPECT_CMD_PACKET_OUT(test_device(),
5489                         hci_spec::kReadRemoteSupportedFeatures,
5490                         &kReadRemoteSupportedFeaturesRsp,
5491                         &kReadRemoteSupportedFeaturesComplete);
5492   EXPECT_CMD_PACKET_OUT(test_device(),
5493                         kReadRemoteExtended1,
5494                         &kReadRemoteExtendedFeaturesRsp,
5495                         &kReadRemoteExtended1Complete);
5496   EXPECT_CMD_PACKET_OUT(test_device(),
5497                         kReadRemoteExtended2,
5498                         &kReadRemoteExtendedFeaturesRsp,
5499                         &kReadRemoteExtended2CompleteLktf);
5500 
5501   test_device()->SendCommandChannelPacket(kConnectionRequest);
5502 
5503   RunUntilIdle();
5504 
5505   // Ensure that the interrogation has begun but the peer hasn't yet bonded
5506   EXPECT_EQ(6, transaction_count());
5507   auto* const peer = peer_cache()->FindByAddress(kTestDevAddr);
5508   ASSERT_TRUE(peer);
5509   ASSERT_TRUE(IsInitializing(peer));
5510   ASSERT_FALSE(peer->bredr()->bonded());
5511 
5512   // Approve pairing requests
5513   pairing_delegate.SetDisplayPasskeyCallback(
5514       [](PeerId, uint32_t, auto, auto confirm_cb) {
5515         ASSERT_TRUE(confirm_cb);
5516         confirm_cb(true);
5517       });
5518 
5519   pairing_delegate.SetCompletePairingCallback(
5520       [](PeerId, sm::Result<> status) { EXPECT_EQ(fit::ok(), status); });
5521 
5522   // Initiate pairing from the peer
5523   test_device()->SendCommandChannelPacket(MakeIoCapabilityResponse(
5524       IoCapability::DISPLAY_YES_NO,
5525       AuthenticationRequirements::MITM_GENERAL_BONDING));
5526   test_device()->SendCommandChannelPacket(kIoCapabilityRequest);
5527   const auto kUserConfirmationRequest = MakeUserConfirmationRequest(kPasskey);
5528   EXPECT_CMD_PACKET_OUT(test_device(),
5529                         MakeIoCapabilityRequestReply(
5530                             IoCapability::DISPLAY_YES_NO,
5531                             AuthenticationRequirements::MITM_GENERAL_BONDING),
5532                         &kIoCapabilityRequestReplyRsp,
5533                         &kUserConfirmationRequest);
5534   EXPECT_CMD_PACKET_OUT(test_device(),
5535                         kUserConfirmationRequestReply,
5536                         &kUserConfirmationRequestReplyRsp,
5537                         &kSimplePairingCompleteSuccess,
5538                         &kLinkKeyNotification);
5539 
5540   // Connection terminates because kLinkKeyNotification's key type is
5541   // kAuthenticatedCombination192. When SC is supported, key type must be of SC
5542   // type (kUnauthenticatedCombination256 or kAuthenticatedCombination256).
5543   QueueDisconnection(kConnectionHandle);
5544   RETURN_IF_FATAL(RunUntilIdle());
5545 }
5546 
5547 // Active connections that do not meeting the requirements for Secure
5548 // Connections Only mode are disconnected when the security mode is changed to
5549 // SC Only.
TEST_F(BrEdrConnectionManagerTest,SecureConnectionsOnlyDisconnectsInsufficientSecurity)5550 TEST_F(BrEdrConnectionManagerTest,
5551        SecureConnectionsOnlyDisconnectsInsufficientSecurity) {
5552   QueueSuccessfulIncomingConn();
5553   test_device()->SendCommandChannelPacket(kConnectionRequest);
5554   RunUntilIdle();
5555   EXPECT_EQ(kIncomingConnTransactions, transaction_count());
5556   auto* const peer = peer_cache()->FindByAddress(kTestDevAddr);
5557   ASSERT_TRUE(peer);
5558   ASSERT_TRUE(IsInitializing(peer));
5559   ASSERT_FALSE(peer->bonded());
5560 
5561   FakePairingDelegate pairing_delegate(sm::IOCapability::kDisplayYesNo);
5562   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
5563 
5564   // Approve pairing requests.
5565   pairing_delegate.SetDisplayPasskeyCallback(
5566       [](PeerId, uint32_t, auto, auto confirm_cb) {
5567         ASSERT_TRUE(confirm_cb);
5568         confirm_cb(true);
5569       });
5570 
5571   pairing_delegate.SetCompletePairingCallback(
5572       [](PeerId, sm::Result<> status) { EXPECT_EQ(fit::ok(), status); });
5573 
5574   QueueSuccessfulPairing();  // kAuthenticatedCombination192 default is not of
5575                              // SC type
5576 
5577   // Initialize as error to verify that |pairing_complete_cb| assigns success.
5578   hci::Result<> pairing_status = ToResult(HostError::kInsufficientSecurity);
5579   auto pairing_complete_cb = [&pairing_status](hci::Result<> status) {
5580     ASSERT_EQ(fit::ok(), status);
5581     pairing_status = status;
5582   };
5583 
5584   connmgr()->Pair(
5585       peer->identifier(), kNoSecurityRequirements, pairing_complete_cb);
5586   ASSERT_TRUE(IsInitializing(peer));
5587   ASSERT_FALSE(peer->bonded());
5588   RunUntilIdle();
5589 
5590   ASSERT_EQ(fit::ok(), pairing_status);
5591   ASSERT_TRUE(IsConnected(peer));
5592   ASSERT_TRUE(peer->bonded());
5593 
5594   // Setting Secure Connections Only mode causes connections not allowed under
5595   // this mode to be disconnected. In this case, |peer| is encrypted,
5596   // authenticated, but not SC-generated.
5597   EXPECT_CMD_PACKET_OUT(test_device(), kDisconnect);
5598   connmgr()->SetSecurityMode(BrEdrSecurityMode::SecureConnectionsOnly);
5599   RunUntilIdle();
5600   EXPECT_EQ(BrEdrSecurityMode::SecureConnectionsOnly,
5601             connmgr()->security_mode());
5602   ASSERT_TRUE(IsNotConnected(peer));
5603 }
5604 
5605 // Active connections that meet the requirements for Secure Connections Only
5606 // mode are not disconnected when the security mode is changed to SC Only.
TEST_F(BrEdrConnectionManagerTest,SecureConnectionsOnlySufficientSecuritySucceeds)5607 TEST_F(BrEdrConnectionManagerTest,
5608        SecureConnectionsOnlySufficientSecuritySucceeds) {
5609   QueueSuccessfulIncomingConn();
5610   test_device()->SendCommandChannelPacket(kConnectionRequest);
5611   RunUntilIdle();
5612   EXPECT_EQ(kIncomingConnTransactions, transaction_count());
5613   auto* const peer = peer_cache()->FindByAddress(kTestDevAddr);
5614   ASSERT_TRUE(peer);
5615   ASSERT_TRUE(IsInitializing(peer));
5616   ASSERT_FALSE(peer->bonded());
5617 
5618   FakePairingDelegate pairing_delegate(sm::IOCapability::kDisplayYesNo);
5619   connmgr()->SetPairingDelegate(pairing_delegate.GetWeakPtr());
5620 
5621   // Approve pairing requests.
5622   pairing_delegate.SetDisplayPasskeyCallback(
5623       [](PeerId, uint32_t, auto, auto confirm_cb) {
5624         ASSERT_TRUE(confirm_cb);
5625         confirm_cb(true);
5626       });
5627 
5628   pairing_delegate.SetCompletePairingCallback(
5629       [](PeerId, sm::Result<> status) { EXPECT_EQ(fit::ok(), status); });
5630 
5631   QueueSuccessfulPairing(hci_spec::LinkKeyType::kAuthenticatedCombination256);
5632 
5633   // Initialize as error to verify that |pairing_complete_cb| assigns success.
5634   hci::Result<> pairing_status = ToResult(HostError::kInsufficientSecurity);
5635   auto pairing_complete_cb = [&pairing_status](hci::Result<> status) {
5636     ASSERT_EQ(fit::ok(), status);
5637     pairing_status = status;
5638   };
5639 
5640   connmgr()->Pair(
5641       peer->identifier(), kNoSecurityRequirements, pairing_complete_cb);
5642   ASSERT_TRUE(IsInitializing(peer));
5643   ASSERT_FALSE(peer->bonded());
5644   RunUntilIdle();
5645 
5646   ASSERT_EQ(fit::ok(), pairing_status);
5647   ASSERT_TRUE(IsConnected(peer));
5648   ASSERT_TRUE(peer->bonded());
5649 
5650   // Setting Secure Connections Only mode causes connections not allowed under
5651   // this mode to be disconnected. In this case, |peer| is encrypted,
5652   // authenticated, and SC-generated.
5653   connmgr()->SetSecurityMode(BrEdrSecurityMode::SecureConnectionsOnly);
5654   RunUntilIdle();
5655   EXPECT_EQ(BrEdrSecurityMode::SecureConnectionsOnly,
5656             connmgr()->security_mode());
5657   ASSERT_TRUE(IsConnected(peer));
5658 
5659   QueueDisconnection(kConnectionHandle);
5660 }
5661 
5662 #undef COMMAND_COMPLETE_RSP
5663 #undef COMMAND_STATUS_RSP
5664 
5665 }  // namespace
5666 }  // namespace bt::gap
5667