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