xref: /aosp_15_r20/external/pigweed/pw_bluetooth_sapphire/host/att/bearer_test.cc (revision 61c4878ac05f98d0ceed94b57d316916de578985)
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/att/bearer.h"
18 
19 #include "pw_bluetooth_sapphire/internal/host/l2cap/mock_channel_test.h"
20 #include "pw_bluetooth_sapphire/internal/host/testing/test_helpers.h"
21 
22 namespace bt::att {
23 namespace {
24 
25 constexpr OpCode kTestRequest = kFindInformationRequest;
26 constexpr OpCode kTestResponse = kFindInformationResponse;
27 constexpr OpCode kTestRequest2 = kExchangeMTURequest;
28 constexpr OpCode kTestResponse2 = kExchangeMTUResponse;
29 constexpr OpCode kTestRequest3 = kFindByTypeValueRequest;
30 constexpr OpCode kTestResponse3 = kFindByTypeValueResponse;
31 
32 constexpr OpCode kTestCommand = kWriteCommand;
33 
NopHandler(Bearer::TransactionId,const PacketReader &)34 void NopHandler(Bearer::TransactionId /*unused*/,
35                 const PacketReader& /*unused*/) {}
36 
37 class BearerTest : public l2cap::testing::MockChannelTest {
38  public:
39   BearerTest() = default;
40   ~BearerTest() override = default;
41 
42  protected:
SetUp()43   void SetUp() override {
44     ChannelOptions options(l2cap::kATTChannelId);
45     bearer_ =
46         Bearer::Create(CreateFakeChannel(options)->GetWeakPtr(), dispatcher());
47   }
48 
TearDown()49   void TearDown() override { bearer_ = nullptr; }
50 
bearer() const51   Bearer* bearer() const { return bearer_.get(); }
fake_att_chan() const52   l2cap::testing::FakeChannel::WeakPtr fake_att_chan() const {
53     return fake_chan();
54   }
55 
DeleteBearer()56   void DeleteBearer() { bearer_ = nullptr; }
57 
58  private:
59   std::unique_ptr<Bearer> bearer_;
60 
61   BT_DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(BearerTest);
62 };
63 
TEST_F(BearerTest,CreateFailsToActivate)64 TEST_F(BearerTest, CreateFailsToActivate) {
65   ChannelOptions options(l2cap::kATTChannelId);
66   auto fake_chan = CreateFakeChannel(options);
67   fake_chan->set_activate_fails(true);
68 
69   EXPECT_FALSE(Bearer::Create(fake_chan->GetWeakPtr(), dispatcher()));
70 }
71 
TEST_F(BearerTest,CreateUsesLEMaxMTUAsPreferredMTU)72 TEST_F(BearerTest, CreateUsesLEMaxMTUAsPreferredMTU) {
73   EXPECT_EQ(kLEMaxMTU, bearer()->preferred_mtu());
74 }
75 
TEST_F(BearerTest,ShutDown)76 TEST_F(BearerTest, ShutDown) {
77   ASSERT_TRUE(bearer()->is_open());
78   ASSERT_FALSE(fake_att_chan()->link_error());
79 
80   // Verify that shutting down an open bearer notifies the closed callback.
81   bool called = false;
82   auto cb = [&called] { called = true; };
83 
84   bearer()->set_closed_callback(cb);
85   bearer()->ShutDown();
86   EXPECT_TRUE(called);
87   EXPECT_FALSE(bearer()->is_open());
88 
89   // Bearer should also signal a link error over the channel.
90   EXPECT_TRUE(fake_att_chan()->link_error());
91 
92   // ShutDown() on a closed bearer does nothing.
93   bearer()->ShutDown();
94   EXPECT_FALSE(bearer()->is_open());
95 }
96 
TEST_F(BearerTest,StartTransactionErrorClosed)97 TEST_F(BearerTest, StartTransactionErrorClosed) {
98   bearer()->ShutDown();
99   ASSERT_FALSE(bearer()->is_open());
100 
101   bool received_error = false;
102   Bearer::TransactionCallback cb =
103       [&received_error](Bearer::TransactionResult result) {
104         if (result.is_error()) {
105           received_error = true;
106         }
107       };
108   bearer()->StartTransaction(NewBuffer(kTestRequest), std::move(cb));
109   EXPECT_TRUE(received_error);
110 }
111 
TEST_F(BearerTest,StartTransactionInvalidPacket)112 TEST_F(BearerTest, StartTransactionInvalidPacket) {
113   auto cb = [](Bearer::TransactionResult) { FAIL(); };
114 
115   // Empty
116   EXPECT_DEATH_IF_SUPPORTED(
117       bearer()->StartTransaction(std::make_unique<BufferView>(), cb),
118       "bad length");
119 
120   // Exceeds MTU.
121   bearer()->set_mtu(1);
122   EXPECT_DEATH_IF_SUPPORTED(
123       bearer()->StartTransaction(NewBuffer(kTestRequest, 2), cb), "bad length");
124 }
125 
TEST_F(BearerTest,StartTransactionWrongMethodType)126 TEST_F(BearerTest, StartTransactionWrongMethodType) {
127   auto cb = [](Bearer::TransactionResult) { FAIL(); };
128 
129   // Command
130   EXPECT_DEATH_IF_SUPPORTED(
131       bearer()->StartTransaction(NewBuffer(kWriteCommand), cb),
132       "callback was provided");
133 
134   // Notification
135   EXPECT_DEATH_IF_SUPPORTED(
136       bearer()->StartTransaction(NewBuffer(kNotification), cb),
137       "callback was provided");
138 }
139 
TEST_F(BearerTest,RequestTimeout)140 TEST_F(BearerTest, RequestTimeout) {
141   // We expect the channel to be closed and the pending transaction to end in an
142   // error.
143   bool closed = false;
144   bool err_cb_called = false;
145   bearer()->set_closed_callback([&closed] { closed = true; });
146 
147   auto cb = [&err_cb_called](Bearer::TransactionResult result) {
148     if (result.is_ok()) {
149       return;
150     }
151     const auto& [error, handle] = result.error_value();
152     EXPECT_EQ(Error(HostError::kTimedOut), error);
153     EXPECT_EQ(0, handle);
154 
155     err_cb_called = true;
156   };
157 
158   ASSERT_FALSE(fake_att_chan()->link_error());
159   MutableByteBufferPtr request = NewBuffer(kTestRequest);
160   EXPECT_PACKET_OUT(*request);
161   bearer()->StartTransaction(std::move(request), cb);
162 
163   RunFor(kTransactionTimeout);
164 
165   EXPECT_TRUE(closed);
166   EXPECT_TRUE(err_cb_called);
167   EXPECT_TRUE(fake_att_chan()->link_error());
168 }
169 
170 // Queue many requests but make sure that FakeChannel only receives one.
TEST_F(BearerTest,RequestTimeoutMany)171 TEST_F(BearerTest, RequestTimeoutMany) {
172   constexpr unsigned int kTransactionCount = 2;
173   unsigned int chan_count = 0;
174   auto chan_cb = [&chan_count](auto cb_packet) {
175     chan_count++;
176     // This should only be called once and for the first request.
177     EXPECT_EQ(kTestRequest, (*cb_packet)[0]);
178   };
179   fake_chan()->SetSendCallback(chan_cb, dispatcher());
180 
181   bool closed = false;
182   unsigned int err_cb_count = 0u;
183 
184   bearer()->set_closed_callback([&closed] { closed = true; });
185 
186   auto cb = [&err_cb_count](Bearer::TransactionResult result) {
187     if (result.is_ok()) {
188       return;
189     }
190     const auto& [error, handle] = result.error_value();
191     EXPECT_EQ(Error(HostError::kTimedOut), error);
192     EXPECT_EQ(0, handle);
193 
194     err_cb_count++;
195   };
196 
197   bearer()->StartTransaction(NewBuffer(kTestRequest, 'T', 'e', 's', 't'), cb);
198   bearer()->StartTransaction(NewBuffer(kTestRequest2, 'T', 'e', 's', 't'), cb);
199 
200   RunUntilIdle();
201 
202   // The first indication should have been sent and the second one queued.
203   EXPECT_EQ(1u, chan_count);
204 
205   EXPECT_FALSE(closed);
206   EXPECT_EQ(0u, err_cb_count);
207 
208   // Make the request timeout.
209   RunFor(kTransactionTimeout);
210 
211   EXPECT_TRUE(closed);
212   EXPECT_EQ(kTransactionCount, err_cb_count);
213 }
214 
TEST_F(BearerTest,IndicationTimeout)215 TEST_F(BearerTest, IndicationTimeout) {
216   // We expect the channel to be closed and the pending transaction to end in an
217   // error.
218   bool closed = false;
219   bool err_cb_called = false;
220 
221   bearer()->set_closed_callback([&closed] { closed = true; });
222 
223   auto cb = [&err_cb_called](Bearer::TransactionResult result) {
224     if (result.is_ok()) {
225       return;
226     }
227     const auto& [error, handle] = result.error_value();
228     EXPECT_EQ(Error(HostError::kTimedOut), error);
229     EXPECT_EQ(0, handle);
230 
231     err_cb_called = true;
232   };
233   MutableByteBufferPtr request = NewBuffer(kIndication, 'T', 'e', 's', 't');
234   EXPECT_PACKET_OUT(*request);
235   bearer()->StartTransaction(std::move(request), cb);
236 
237   RunFor(kTransactionTimeout);
238 
239   EXPECT_TRUE(closed);
240   EXPECT_TRUE(err_cb_called);
241 }
242 
243 // Queue many indications but make sure that FakeChannel only receives one.
TEST_F(BearerTest,IndicationTimeoutMany)244 TEST_F(BearerTest, IndicationTimeoutMany) {
245   constexpr unsigned int kTransactionCount = 2;
246   constexpr uint8_t kIndValue1 = 1;
247   constexpr uint8_t kIndValue2 = 2;
248 
249   unsigned int chan_count = 0;
250   auto chan_cb = [kIndValue1, &chan_count](auto cb_packet) {
251     chan_count++;
252     // This should only be called once and for the first request.
253     EXPECT_EQ(kIndValue1, (*cb_packet)[1]);
254   };
255   fake_chan()->SetSendCallback(chan_cb, dispatcher());
256 
257   bool closed = false;
258   unsigned int err_cb_count = 0u;
259 
260   bearer()->set_closed_callback([&closed] { closed = true; });
261 
262   auto cb = [&err_cb_count](Bearer::TransactionResult result) {
263     if (result.is_ok()) {
264       return;
265     }
266     const auto& [error, handle] = result.error_value();
267     EXPECT_EQ(Error(HostError::kTimedOut), error);
268     EXPECT_EQ(0, handle);
269 
270     err_cb_count++;
271   };
272 
273   bearer()->StartTransaction(NewBuffer(kIndication, kIndValue1), cb);
274   bearer()->StartTransaction(NewBuffer(kIndication, kIndValue2), cb);
275 
276   RunUntilIdle();
277 
278   // The first indication should have been sent and the second one queued.
279   EXPECT_EQ(1u, chan_count);
280 
281   EXPECT_FALSE(closed);
282   EXPECT_EQ(0u, err_cb_count);
283 
284   // Make the request timeout.
285   RunFor(kTransactionTimeout);
286 
287   EXPECT_TRUE(closed);
288   EXPECT_EQ(kTransactionCount, err_cb_count);
289 }
290 
TEST_F(BearerTest,ReceiveEmptyPacket)291 TEST_F(BearerTest, ReceiveEmptyPacket) {
292   bool closed = false;
293   bearer()->set_closed_callback([&closed] { closed = true; });
294 
295   fake_chan()->Receive(BufferView());
296 
297   RunUntilIdle();
298   EXPECT_TRUE(closed);
299 }
300 
TEST_F(BearerTest,ReceiveResponseWithoutRequest)301 TEST_F(BearerTest, ReceiveResponseWithoutRequest) {
302   bool closed = false;
303   bearer()->set_closed_callback([&closed] { closed = true; });
304 
305   fake_chan()->Receive(StaticByteBuffer(kTestResponse));
306 
307   RunUntilIdle();
308   EXPECT_TRUE(closed);
309 }
310 
TEST_F(BearerTest,ReceiveConfirmationWithoutIndication)311 TEST_F(BearerTest, ReceiveConfirmationWithoutIndication) {
312   bool closed = false;
313   bearer()->set_closed_callback([&closed] { closed = true; });
314 
315   fake_chan()->Receive(StaticByteBuffer(kConfirmation));
316 
317   RunUntilIdle();
318   EXPECT_TRUE(closed);
319 }
320 
TEST_F(BearerTest,SendRequestWrongResponse)321 TEST_F(BearerTest, SendRequestWrongResponse) {
322   unsigned int count = 0;
323   auto chan_cb = [this, &count](auto cb_packet) {
324     count++;
325     // This should only be called once and for the first request.
326     EXPECT_EQ(kTestRequest, (*cb_packet)[0]);
327 
328     // Send back the wrong response.
329     fake_chan()->Receive(StaticByteBuffer(kTestResponse2));
330   };
331   fake_chan()->SetSendCallback(chan_cb, dispatcher());
332 
333   bool err_cb_called = false;
334   bool closed = false;
335 
336   bearer()->set_closed_callback([&closed] { closed = true; });
337 
338   auto cb = [&err_cb_called](Bearer::TransactionResult result) {
339     if (result.is_ok()) {
340       return;
341     }
342     const auto& [error, handle] = result.error_value();
343     EXPECT_EQ(Error(HostError::kFailed), error);
344     EXPECT_EQ(0, handle);
345 
346     err_cb_called = true;
347   };
348   bearer()->StartTransaction(NewBuffer(kTestRequest), cb);
349 
350   RunUntilIdle();
351   EXPECT_TRUE(closed);
352   EXPECT_TRUE(err_cb_called);
353   EXPECT_EQ(1u, count);
354 }
355 
TEST_F(BearerTest,SendRequestErrorResponseTooShort)356 TEST_F(BearerTest, SendRequestErrorResponseTooShort) {
357   StaticByteBuffer malformed_error_rsp(
358       // Opcode: error response
359       kErrorResponse,
360 
361       // Parameters are too short (by 1 byte). Contents are unimportant, as the
362       // PDU should be rejected.
363       1,
364       2,
365       3);
366 
367   bool chan_cb_called = false;
368   auto chan_cb = [this, &chan_cb_called, &malformed_error_rsp](auto cb_packet) {
369     ASSERT_FALSE(chan_cb_called);
370     EXPECT_EQ(kTestRequest, (*cb_packet)[0]);
371 
372     chan_cb_called = true;
373     fake_chan()->Receive(malformed_error_rsp);
374   };
375   fake_chan()->SetSendCallback(chan_cb, dispatcher());
376 
377   bool err_cb_called = false;
378   bool closed = false;
379 
380   bearer()->set_closed_callback([&closed] { closed = true; });
381 
382   auto cb = [&err_cb_called](Bearer::TransactionResult result) {
383     if (result.is_ok()) {
384       return;
385     }
386     const auto& [error, handle] = result.error_value();
387     EXPECT_EQ(Error(HostError::kFailed), error);
388     EXPECT_EQ(0, handle);
389 
390     err_cb_called = true;
391   };
392   bearer()->StartTransaction(NewBuffer(kTestRequest), cb);
393 
394   RunUntilIdle();
395   EXPECT_TRUE(closed);
396   EXPECT_TRUE(err_cb_called);
397   EXPECT_TRUE(chan_cb_called);
398 }
399 
TEST_F(BearerTest,SendRequestErrorResponseTooLong)400 TEST_F(BearerTest, SendRequestErrorResponseTooLong) {
401   StaticByteBuffer malformed_error_rsp(
402       // Opcode: error response
403       kErrorResponse,
404 
405       // Parameters are too long (by 1 byte). Contents are unimportant, as the
406       // PDU should be rejected.
407       1,
408       2,
409       3,
410       4,
411       5);
412 
413   bool chan_cb_called = false;
414   auto chan_cb = [this, &chan_cb_called, &malformed_error_rsp](auto cb_packet) {
415     ASSERT_FALSE(chan_cb_called);
416     EXPECT_EQ(kTestRequest, (*cb_packet)[0]);
417 
418     chan_cb_called = true;
419     fake_chan()->Receive(malformed_error_rsp);
420   };
421   fake_chan()->SetSendCallback(chan_cb, dispatcher());
422 
423   bool err_cb_called = false;
424   bool closed = false;
425 
426   bearer()->set_closed_callback([&closed] { closed = true; });
427 
428   auto cb = [&err_cb_called](Bearer::TransactionResult result) {
429     if (result.is_ok()) {
430       return;
431     }
432     const auto& [error, handle] = result.error_value();
433     EXPECT_EQ(Error(HostError::kFailed), error);
434     EXPECT_EQ(0, handle);
435 
436     err_cb_called = true;
437   };
438   bearer()->StartTransaction(NewBuffer(kTestRequest), cb);
439 
440   RunUntilIdle();
441   EXPECT_TRUE(closed);
442   EXPECT_TRUE(err_cb_called);
443   EXPECT_TRUE(chan_cb_called);
444 }
445 
TEST_F(BearerTest,SendRequestErrorResponseWrongOpCode)446 TEST_F(BearerTest, SendRequestErrorResponseWrongOpCode) {
447   StaticByteBuffer error_rsp(
448       // Opcode: error response
449       kErrorResponse,
450 
451       // request opcode: non-matching opcode in error response
452       kTestRequest2,
453 
454       // handle, should be ignored
455       0x00,
456       0x00,
457 
458       // error code:
459       ErrorCode::kRequestNotSupported);
460 
461   bool chan_cb_called = false;
462   auto chan_cb = [this, &chan_cb_called, &error_rsp](auto cb_packet) {
463     ASSERT_FALSE(chan_cb_called);
464     EXPECT_EQ(kTestRequest, (*cb_packet)[0]);
465 
466     chan_cb_called = true;
467     fake_chan()->Receive(error_rsp);
468   };
469   fake_chan()->SetSendCallback(chan_cb, dispatcher());
470 
471   bool err_cb_called = false;
472   bool closed = false;
473 
474   bearer()->set_closed_callback([&closed] { closed = true; });
475 
476   auto cb = [&err_cb_called](Bearer::TransactionResult result) {
477     if (result.is_ok()) {
478       return;
479     }
480     const auto& [error, handle] = result.error_value();
481     EXPECT_EQ(Error(HostError::kFailed), error);
482     EXPECT_EQ(0, handle);
483 
484     err_cb_called = true;
485   };
486   bearer()->StartTransaction(NewBuffer(kTestRequest), cb);
487 
488   RunUntilIdle();
489   EXPECT_TRUE(closed);
490   EXPECT_TRUE(err_cb_called);
491   EXPECT_TRUE(chan_cb_called);
492 }
493 
TEST_F(BearerTest,SendRequestErrorResponse)494 TEST_F(BearerTest, SendRequestErrorResponse) {
495   StaticByteBuffer error_rsp(
496       // Opcode: error response
497       kErrorResponse,
498 
499       // request opcode
500       kTestRequest,
501 
502       // handle (0x0001)
503       0x01,
504       0x00,
505 
506       // error code:
507       ErrorCode::kRequestNotSupported);
508 
509   bool chan_cb_called = false;
510   auto chan_cb = [this, &chan_cb_called, &error_rsp](auto cb_packet) {
511     ASSERT_FALSE(chan_cb_called);
512     EXPECT_EQ(kTestRequest, (*cb_packet)[0]);
513 
514     chan_cb_called = true;
515     fake_chan()->Receive(error_rsp);
516   };
517   fake_chan()->SetSendCallback(chan_cb, dispatcher());
518 
519   bool err_cb_called = false;
520   auto cb = [&err_cb_called](Bearer::TransactionResult result) {
521     if (result.is_ok()) {
522       return;
523     }
524     const auto& [error, handle] = result.error_value();
525     EXPECT_EQ(Error(ErrorCode::kRequestNotSupported), error);
526     EXPECT_EQ(0x0001, handle);
527 
528     err_cb_called = true;
529   };
530   bearer()->StartTransaction(NewBuffer(kTestRequest), cb);
531 
532   RunUntilIdle();
533   EXPECT_TRUE(err_cb_called);
534   EXPECT_TRUE(chan_cb_called);
535 
536   // The channel should remain open
537   EXPECT_TRUE(bearer()->is_open());
538 }
539 
TEST_F(BearerTest,SendRequestSuccess)540 TEST_F(BearerTest, SendRequestSuccess) {
541   StaticByteBuffer response(kTestResponse, 'T', 'e', 's', 't');
542 
543   bool chan_cb_called = false;
544   auto chan_cb = [this, &chan_cb_called, &response](auto cb_packet) {
545     ASSERT_FALSE(chan_cb_called);
546     EXPECT_EQ(kTestRequest, (*cb_packet)[0]);
547 
548     chan_cb_called = true;
549     fake_chan()->Receive(response);
550   };
551   fake_chan()->SetSendCallback(chan_cb, dispatcher());
552 
553   bool cb_called = false;
554   auto cb = [&cb_called, &response](Bearer::TransactionResult result) {
555     ASSERT_FALSE(cb_called);
556     if (result.is_error()) {
557       return;
558     }
559 
560     cb_called = true;
561     EXPECT_TRUE(ContainersEqual(response, result.value().data()));
562   };
563   bearer()->StartTransaction(NewBuffer(kTestRequest), cb);
564 
565   RunUntilIdle();
566   EXPECT_TRUE(chan_cb_called);
567   EXPECT_TRUE(cb_called);
568 
569   // The channel should remain open
570   EXPECT_TRUE(bearer()->is_open());
571 }
572 
573 // Closing the L2CAP channel while ATT requests have been queued will cause the
574 // error callbacks to be called. The code should fail gracefully if one of these
575 // callbacks deletes the attribute bearer.
TEST_F(BearerTest,CloseChannelAndDeleteBearerWhileRequestsArePending)576 TEST_F(BearerTest, CloseChannelAndDeleteBearerWhileRequestsArePending) {
577   // We expect the callback to be called 3 times since we queue 3 transactions
578   // below.
579   constexpr size_t kExpectedCount = 3;
580 
581   size_t cb_error_count = 0;
582   auto cb = [this, &cb_error_count](Bearer::TransactionResult result) {
583     if (result.is_ok()) {
584       return;
585     }
586     cb_error_count++;
587 
588     // Delete the bearer on the first callback. The remaining callbacks should
589     // still run gracefully.
590     DeleteBearer();
591   };
592 
593   MutableByteBufferPtr kRequest0 = NewBuffer(kTestRequest);
594   EXPECT_PACKET_OUT(*kRequest0);
595   bearer()->StartTransaction(std::move(kRequest0), cb);
596 
597   MutableByteBufferPtr kRequest1 = NewBuffer(kTestRequest);
598   EXPECT_PACKET_OUT(*kRequest1);
599   bearer()->StartTransaction(std::move(kRequest1), cb);
600 
601   MutableByteBufferPtr kRequest2 = NewBuffer(kTestRequest);
602   EXPECT_PACKET_OUT(*kRequest2);
603   bearer()->StartTransaction(std::move(kRequest2), cb);
604 
605   fake_chan()->Close();
606   EXPECT_EQ(kExpectedCount, cb_error_count);
607 }
608 
TEST_F(BearerTest,SendManyRequests)609 TEST_F(BearerTest, SendManyRequests) {
610   const StaticByteBuffer response1(kTestResponse, 'f', 'o', 'o');
611   const StaticByteBuffer response2(kErrorResponse,
612 
613                                    // request opcode
614                                    kTestRequest2,
615 
616                                    // handle (0x0001)
617                                    0x01,
618                                    0x00,
619 
620                                    // error code:
621                                    ErrorCode::kRequestNotSupported);
622   const StaticByteBuffer response3(kTestResponse3, 'b', 'a', 'r');
623 
624   auto chan_cb = [&, this](auto cb_packet) {
625     OpCode opcode = (*cb_packet)[0];
626 
627     if (opcode == kTestRequest) {
628       fake_chan()->Receive(response1);
629     } else if (opcode == kTestRequest2) {
630       fake_chan()->Receive(response2);
631     } else if (opcode == kTestRequest3) {
632       fake_chan()->Receive(response3);
633     }
634   };
635   fake_chan()->SetSendCallback(chan_cb, dispatcher());
636 
637   bool called_1 = false, called_2 = false, called_3 = false;
638 
639   // We expect each callback to be called in the order that we send the
640   // corresponding request.
641   auto callback1 = [&called_1, &called_2, &called_3, &response1](
642                        Bearer::TransactionResult result) {
643     EXPECT_FALSE(called_2);
644     EXPECT_FALSE(called_3);
645     called_1 = true;
646 
647     // First request should've succeeded
648     ASSERT_EQ(fit::ok(), result);
649     EXPECT_TRUE(ContainersEqual(response1, result.value().data()));
650   };
651   bearer()->StartTransaction(NewBuffer(kTestRequest), callback1);
652 
653   auto callback2 =
654       [&called_1, &called_2, &called_3](Bearer::TransactionResult result) {
655         EXPECT_TRUE(called_1);
656         EXPECT_FALSE(called_3);
657         called_2 = true;
658 
659         // Second request should've failed
660         ASSERT_EQ(fit::failed(), result);
661         const auto& [error, handle] = result.error_value();
662         EXPECT_EQ(Error(ErrorCode::kRequestNotSupported), error);
663         EXPECT_EQ(0x0001, handle);
664       };
665   bearer()->StartTransaction(NewBuffer(kTestRequest2), callback2);
666 
667   auto callback3 = [&called_1, &called_2, &called_3, &response3](
668                        Bearer::TransactionResult result) {
669     EXPECT_TRUE(called_1);
670     EXPECT_TRUE(called_2);
671     called_3 = true;
672 
673     // Third request should've succeeded
674     ASSERT_EQ(fit::ok(), result);
675     EXPECT_TRUE(ContainersEqual(response3, result.value().data()));
676   };
677   bearer()->StartTransaction(NewBuffer(kTestRequest3), callback3);
678 
679   RunUntilIdle();
680 
681   EXPECT_TRUE(bearer()->is_open());
682 }
683 
684 // An indication transaction can only fail in a circumstance that would shut
685 // down the bearer (e.g. a transaction timeout or an empty PDU). Otherwise,
686 // Bearer will only complete an indication transaction when it receives a
687 // confirmation PDU.
688 //
689 // NOTE: Bearer only looks at the opcode of a PDU and ignores the payload, so a
690 // malformed confirmation payload is not considered an error at this layer.
TEST_F(BearerTest,SendIndicationSuccess)691 TEST_F(BearerTest, SendIndicationSuccess) {
692   // Even though this is a malformed confirmation PDU it will not be rejected by
693   // Bearer.
694   StaticByteBuffer conf(kConfirmation, 'T', 'e', 's', 't');
695 
696   bool chan_cb_called = false;
697   auto chan_cb = [this, &chan_cb_called, &conf](auto cb_packet) {
698     ASSERT_FALSE(chan_cb_called);
699     EXPECT_EQ(kIndication, (*cb_packet)[0]);
700 
701     chan_cb_called = true;
702     fake_chan()->Receive(conf);
703   };
704   fake_chan()->SetSendCallback(chan_cb, dispatcher());
705 
706   bool cb_called = false;
707   auto cb = [&cb_called, &conf](Bearer::TransactionResult result) {
708     ASSERT_FALSE(cb_called);
709 
710     cb_called = true;
711     EXPECT_TRUE(ContainersEqual(conf, result.value().data()));
712   };
713   bearer()->StartTransaction(NewBuffer(kIndication), cb);
714 
715   RunUntilIdle();
716   EXPECT_TRUE(chan_cb_called);
717   EXPECT_TRUE(cb_called);
718 
719   // The channel should remain open
720   EXPECT_TRUE(bearer()->is_open());
721 }
722 
TEST_F(BearerTest,SendWithoutResponseErrorClosed)723 TEST_F(BearerTest, SendWithoutResponseErrorClosed) {
724   bearer()->ShutDown();
725   ASSERT_FALSE(bearer()->is_open());
726 
727   EXPECT_FALSE(bearer()->SendWithoutResponse(NewBuffer(kTestCommand)));
728 }
729 
TEST_F(BearerTest,SendWithoutResponseInvalidPacket)730 TEST_F(BearerTest, SendWithoutResponseInvalidPacket) {
731   // Empty
732   EXPECT_DEATH_IF_SUPPORTED(
733       [[maybe_unused]] auto _ =
734           bearer()->SendWithoutResponse(std::make_unique<BufferView>()),
735       "bad length");
736 
737   // Exceeds MTU
738   bearer()->set_mtu(1);
739   EXPECT_DEATH_IF_SUPPORTED(
740       [[maybe_unused]] auto _ =
741           bearer()->SendWithoutResponse(NewBuffer(kTestCommand, 2)),
742       "bad length");
743 }
744 
TEST_F(BearerTest,SendWithoutResponseWrongMethodType)745 TEST_F(BearerTest, SendWithoutResponseWrongMethodType) {
746   EXPECT_DEATH_IF_SUPPORTED(
747       [[maybe_unused]] auto _ =
748           bearer()->SendWithoutResponse(NewBuffer(kTestRequest)),
749       "requires callback");
750   EXPECT_DEATH_IF_SUPPORTED(
751       [[maybe_unused]] auto _ =
752           bearer()->SendWithoutResponse(NewBuffer(kTestResponse)),
753       "unsupported opcode");
754   EXPECT_DEATH_IF_SUPPORTED(
755       [[maybe_unused]] auto _ =
756           bearer()->SendWithoutResponse(NewBuffer(kIndication)),
757       "requires callback");
758 }
759 
TEST_F(BearerTest,SendWithoutResponseCorrectMethodType)760 TEST_F(BearerTest, SendWithoutResponseCorrectMethodType) {
761   MutableByteBufferPtr request_0 = NewBuffer(kNotification);
762   EXPECT_PACKET_OUT(*request_0);
763   EXPECT_TRUE(bearer()->SendWithoutResponse(std::move(request_0)));
764   MutableByteBufferPtr request_1 = NewBuffer(kTestCommand);
765   EXPECT_PACKET_OUT(*request_1);
766   EXPECT_TRUE(bearer()->SendWithoutResponse(std::move(request_1)));
767   MutableByteBufferPtr request_2 = NewBuffer(kTestRequest | kCommandFlag);
768   EXPECT_PACKET_OUT(*request_2);
769   EXPECT_TRUE(bearer()->SendWithoutResponse(std::move(request_2)));
770 
771   // Any opcode is accepted as long as it has the command flag set.
772   auto request_3 = NewBuffer(kInvalidOpCode | kCommandFlag);
773   EXPECT_PACKET_OUT(*request_3);
774   EXPECT_TRUE(bearer()->SendWithoutResponse(std::move(request_3)));
775 }
776 
TEST_F(BearerTest,SendWithoutResponseMany)777 TEST_F(BearerTest, SendWithoutResponseMany) {
778   // Everything should go through without any flow control.
779   constexpr unsigned int kExpectedCount = 10;
780   unsigned int chan_cb_count = 0u;
781 
782   auto chan_cb = [&chan_cb_count](auto cb_packet) {
783     OpCode opcode = (*cb_packet)[0];
784     EXPECT_TRUE(kCommandFlag & opcode || opcode == kIndication);
785 
786     chan_cb_count++;
787   };
788   fake_chan()->SetSendCallback(chan_cb, dispatcher());
789 
790   for (OpCode opcode = 0; opcode < kExpectedCount; opcode++) {
791     // Everything
792     EXPECT_TRUE(
793         bearer()->SendWithoutResponse(NewBuffer(opcode | kCommandFlag)));
794   }
795 
796   RunUntilIdle();
797   EXPECT_EQ(kExpectedCount, chan_cb_count);
798 }
799 
TEST_F(BearerTest,RegisterHandlerErrorClosed)800 TEST_F(BearerTest, RegisterHandlerErrorClosed) {
801   bearer()->ShutDown();
802   EXPECT_FALSE(bearer()->is_open());
803   EXPECT_EQ(Bearer::kInvalidHandlerId,
804             bearer()->RegisterHandler(kWriteRequest, NopHandler));
805   EXPECT_EQ(Bearer::kInvalidHandlerId,
806             bearer()->RegisterHandler(kIndication, NopHandler));
807 }
808 
TEST_F(BearerTest,RegisterHandlerErrorAlreadyRegistered)809 TEST_F(BearerTest, RegisterHandlerErrorAlreadyRegistered) {
810   EXPECT_NE(Bearer::kInvalidHandlerId,
811             bearer()->RegisterHandler(kIndication, NopHandler));
812   EXPECT_EQ(Bearer::kInvalidHandlerId,
813             bearer()->RegisterHandler(kIndication, NopHandler));
814 }
815 
TEST_F(BearerTest,UnregisterHandler)816 TEST_F(BearerTest, UnregisterHandler) {
817   auto id0 = bearer()->RegisterHandler(kNotification, NopHandler);
818   EXPECT_NE(Bearer::kInvalidHandlerId, id0);
819 
820   bearer()->UnregisterHandler(id0);
821 
822   // It should be possible to register new handlers for the same opcodes.
823   id0 = bearer()->RegisterHandler(kNotification, NopHandler);
824   EXPECT_NE(Bearer::kInvalidHandlerId, id0);
825 }
826 
TEST_F(BearerTest,RemoteTransactionNoHandler)827 TEST_F(BearerTest, RemoteTransactionNoHandler) {
828   StaticByteBuffer error_rsp(
829       // opcode
830       kErrorResponse,
831 
832       // request opcode
833       kTestRequest,
834 
835       // handle
836       0x00,
837       0x00,
838 
839       // error code
840       ErrorCode::kRequestNotSupported);
841 
842   bool received_error_rsp = false;
843   auto chan_cb = [&received_error_rsp, &error_rsp](auto packet) {
844     received_error_rsp = true;
845     EXPECT_TRUE(ContainersEqual(error_rsp, *packet));
846   };
847   fake_chan()->SetSendCallback(chan_cb, dispatcher());
848   fake_chan()->Receive(StaticByteBuffer(kTestRequest));
849 
850   RunUntilIdle();
851   EXPECT_TRUE(received_error_rsp);
852 }
853 
TEST_F(BearerTest,RemoteTransactionSeqProtocolError)854 TEST_F(BearerTest, RemoteTransactionSeqProtocolError) {
855   int request_count = 0;
856   auto handler = [&request_count](auto, const PacketReader& packet) {
857     EXPECT_EQ(kTestRequest, packet.opcode());
858     EXPECT_EQ(0u, packet.payload_size());
859 
860     request_count++;
861   };
862 
863   bearer()->RegisterHandler(kTestRequest, handler);
864   fake_chan()->Receive(StaticByteBuffer(kTestRequest));
865 
866   RunUntilIdle();
867   ASSERT_EQ(1, request_count);
868 
869   // Receiving a second request before sending a response should close the
870   // bearer.
871   bool closed = false;
872   bearer()->set_closed_callback([&closed] { closed = true; });
873 
874   fake_chan()->Receive(StaticByteBuffer(kTestRequest));
875 
876   RunUntilIdle();
877   EXPECT_TRUE(closed);
878   EXPECT_EQ(1, request_count);
879   EXPECT_FALSE(bearer()->is_open());
880 }
881 
TEST_F(BearerTest,RemoteIndicationSeqProtocolError)882 TEST_F(BearerTest, RemoteIndicationSeqProtocolError) {
883   int ind_count = 0;
884   auto handler = [&ind_count](auto, const PacketReader& packet) {
885     EXPECT_EQ(kIndication, packet.opcode());
886     EXPECT_EQ(0u, packet.payload_size());
887 
888     ind_count++;
889   };
890 
891   bearer()->RegisterHandler(kIndication, handler);
892   fake_chan()->Receive(StaticByteBuffer(kIndication));
893 
894   RunUntilIdle();
895   ASSERT_EQ(1, ind_count);
896 
897   // Receiving a second indication before sending a confirmation should close
898   // the bearer.
899   bool closed = false;
900   bearer()->set_closed_callback([&closed] { closed = true; });
901 
902   fake_chan()->Receive(StaticByteBuffer(kIndication));
903 
904   RunUntilIdle();
905   EXPECT_TRUE(closed);
906   EXPECT_EQ(1, ind_count);
907   EXPECT_FALSE(bearer()->is_open());
908 }
909 
TEST_F(BearerTest,ReplyInvalidPacket)910 TEST_F(BearerTest, ReplyInvalidPacket) {
911   // Empty
912   EXPECT_FALSE(bearer()->Reply(0, std::make_unique<BufferView>()));
913 
914   // Exceeds MTU.
915   bearer()->set_mtu(1);
916   EXPECT_FALSE(bearer()->Reply(0, NewBuffer(kTestRequest, 2)));
917 }
918 
TEST_F(BearerTest,ReplyInvalidId)919 TEST_F(BearerTest, ReplyInvalidId) {
920   EXPECT_FALSE(
921       bearer()->Reply(Bearer::kInvalidTransactionId, NewBuffer(kTestResponse)));
922 
923   // The ID is valid but doesn't correspond to an active transaction.
924   EXPECT_FALSE(bearer()->Reply(1u, NewBuffer(kTestResponse)));
925 }
926 
TEST_F(BearerTest,ReplyWrongOpCode)927 TEST_F(BearerTest, ReplyWrongOpCode) {
928   Bearer::TransactionId id;
929   bool handler_called = false;
930   auto handler = [&id, &handler_called](auto cb_id,
931                                         const PacketReader& packet) {
932     EXPECT_EQ(kTestRequest, packet.opcode());
933     EXPECT_EQ(0u, packet.payload_size());
934 
935     handler_called = true;
936     id = cb_id;
937   };
938 
939   bearer()->RegisterHandler(kTestRequest, handler);
940   fake_chan()->Receive(StaticByteBuffer(kTestRequest));
941 
942   RunUntilIdle();
943   ASSERT_TRUE(handler_called);
944 
945   EXPECT_FALSE(bearer()->Reply(id, NewBuffer(kTestResponse2)));
946 }
947 
TEST_F(BearerTest,ReplyToIndicationWrongOpCode)948 TEST_F(BearerTest, ReplyToIndicationWrongOpCode) {
949   Bearer::TransactionId id;
950   bool handler_called = false;
951   auto handler = [&id, &handler_called](auto cb_id,
952                                         const PacketReader& packet) {
953     EXPECT_EQ(kIndication, packet.opcode());
954     EXPECT_EQ(0u, packet.payload_size());
955 
956     handler_called = true;
957     id = cb_id;
958   };
959 
960   bearer()->RegisterHandler(kIndication, handler);
961   fake_chan()->Receive(StaticByteBuffer(kIndication));
962 
963   RunUntilIdle();
964   ASSERT_TRUE(handler_called);
965 
966   EXPECT_FALSE(bearer()->Reply(id, NewBuffer(kTestResponse)));
967 }
968 
TEST_F(BearerTest,ReplyWithResponse)969 TEST_F(BearerTest, ReplyWithResponse) {
970   bool response_sent = false;
971   auto chan_cb = [&response_sent](auto packet) {
972     response_sent = true;
973 
974     EXPECT_EQ(kTestResponse, (*packet)[0]);
975   };
976   fake_chan()->SetSendCallback(chan_cb, dispatcher());
977 
978   Bearer::TransactionId id;
979   bool handler_called = false;
980   auto handler = [&id, &handler_called](auto cb_id,
981                                         const PacketReader& packet) {
982     EXPECT_EQ(kTestRequest, packet.opcode());
983     EXPECT_EQ(0u, packet.payload_size());
984 
985     handler_called = true;
986     id = cb_id;
987   };
988 
989   bearer()->RegisterHandler(kTestRequest, handler);
990   fake_chan()->Receive(StaticByteBuffer(kTestRequest));
991 
992   RunUntilIdle();
993   ASSERT_TRUE(handler_called);
994 
995   EXPECT_TRUE(bearer()->Reply(id, NewBuffer(kTestResponse)));
996 
997   // The transaction is marked as complete.
998   EXPECT_FALSE(bearer()->Reply(id, NewBuffer(kTestResponse)));
999   EXPECT_FALSE(bearer()->ReplyWithError(id, 0, ErrorCode::kUnlikelyError));
1000 
1001   RunUntilIdle();
1002   EXPECT_TRUE(response_sent);
1003 }
1004 
TEST_F(BearerTest,IndicationConfirmation)1005 TEST_F(BearerTest, IndicationConfirmation) {
1006   bool conf_sent = false;
1007   auto chan_cb = [&conf_sent](auto packet) {
1008     conf_sent = true;
1009     EXPECT_EQ(kConfirmation, (*packet)[0]);
1010   };
1011   fake_chan()->SetSendCallback(chan_cb, dispatcher());
1012 
1013   Bearer::TransactionId id;
1014   bool handler_called = false;
1015   auto handler = [&id, &handler_called](auto cb_id,
1016                                         const PacketReader& packet) {
1017     EXPECT_EQ(kIndication, packet.opcode());
1018     EXPECT_EQ(0u, packet.payload_size());
1019 
1020     handler_called = true;
1021     id = cb_id;
1022   };
1023 
1024   bearer()->RegisterHandler(kIndication, handler);
1025   fake_chan()->Receive(StaticByteBuffer(kIndication));
1026 
1027   RunUntilIdle();
1028   ASSERT_TRUE(handler_called);
1029 
1030   EXPECT_TRUE(bearer()->Reply(id, NewBuffer(kConfirmation)));
1031 
1032   // The transaction is marked as complete.
1033   EXPECT_FALSE(bearer()->Reply(id, NewBuffer(kConfirmation)));
1034 
1035   RunUntilIdle();
1036   EXPECT_TRUE(conf_sent);
1037 }
1038 
TEST_F(BearerTest,ReplyWithErrorInvalidId)1039 TEST_F(BearerTest, ReplyWithErrorInvalidId) {
1040   EXPECT_FALSE(bearer()->ReplyWithError(0, 0, ErrorCode::kUnlikelyError));
1041 }
1042 
TEST_F(BearerTest,IndicationReplyWithError)1043 TEST_F(BearerTest, IndicationReplyWithError) {
1044   Bearer::TransactionId id;
1045   bool handler_called = false;
1046   auto handler = [&id, &handler_called](auto cb_id,
1047                                         const PacketReader& packet) {
1048     EXPECT_EQ(kIndication, packet.opcode());
1049     EXPECT_EQ(0u, packet.payload_size());
1050 
1051     handler_called = true;
1052     id = cb_id;
1053   };
1054 
1055   bearer()->RegisterHandler(kIndication, handler);
1056   fake_chan()->Receive(StaticByteBuffer(kIndication));
1057 
1058   RunUntilIdle();
1059   ASSERT_TRUE(handler_called);
1060 
1061   // Cannot reply to an indication with error.
1062   EXPECT_FALSE(bearer()->ReplyWithError(id, 0, ErrorCode::kUnlikelyError));
1063 }
1064 
TEST_F(BearerTest,ReplyWithError)1065 TEST_F(BearerTest, ReplyWithError) {
1066   bool response_sent = false;
1067   auto chan_cb = [&response_sent](auto packet) {
1068     response_sent = true;
1069 
1070     // The error response that we send below
1071     StaticByteBuffer expected(
1072         kErrorResponse, kTestRequest, 0x00, 0x00, ErrorCode::kUnlikelyError);
1073     EXPECT_TRUE(ContainersEqual(expected, *packet));
1074   };
1075   fake_chan()->SetSendCallback(chan_cb, dispatcher());
1076 
1077   Bearer::TransactionId id;
1078   bool handler_called = false;
1079   auto handler = [&id, &handler_called](auto cb_id,
1080                                         const PacketReader& packet) {
1081     EXPECT_EQ(kTestRequest, packet.opcode());
1082     EXPECT_EQ(0u, packet.payload_size());
1083 
1084     handler_called = true;
1085     id = cb_id;
1086   };
1087 
1088   bearer()->RegisterHandler(kTestRequest, handler);
1089   fake_chan()->Receive(StaticByteBuffer(kTestRequest));
1090 
1091   RunUntilIdle();
1092   ASSERT_TRUE(handler_called);
1093 
1094   EXPECT_TRUE(bearer()->ReplyWithError(id, 0, ErrorCode::kUnlikelyError));
1095 
1096   // The transaction is marked as complete.
1097   EXPECT_FALSE(bearer()->Reply(id, NewBuffer(kTestResponse)));
1098   EXPECT_FALSE(bearer()->ReplyWithError(id, 0, ErrorCode::kUnlikelyError));
1099 
1100   RunUntilIdle();
1101   EXPECT_TRUE(response_sent);
1102 }
1103 
1104 // Requests and indications have independent flow control
TEST_F(BearerTest,RequestAndIndication)1105 TEST_F(BearerTest, RequestAndIndication) {
1106   Bearer::TransactionId req_id, ind_id;
1107 
1108   int req_count = 0;
1109   int ind_count = 0;
1110   auto req_handler = [&req_id, &req_count](auto id, const auto& packet) {
1111     EXPECT_EQ(kTestRequest, packet.opcode());
1112     EXPECT_EQ(0u, packet.payload_size());
1113 
1114     req_count++;
1115     req_id = id;
1116   };
1117   auto ind_handler = [&ind_id, &ind_count](auto id, const auto& packet) {
1118     EXPECT_EQ(kIndication, packet.opcode());
1119     EXPECT_EQ(0u, packet.payload_size());
1120 
1121     ind_count++;
1122     ind_id = id;
1123   };
1124 
1125   bearer()->RegisterHandler(kTestRequest, req_handler);
1126   bearer()->RegisterHandler(kIndication, ind_handler);
1127 
1128   fake_chan()->Receive(StaticByteBuffer(kTestRequest));
1129   fake_chan()->Receive(StaticByteBuffer(kIndication));
1130 
1131   RunUntilIdle();
1132   EXPECT_EQ(1, req_count);
1133   ASSERT_EQ(1, ind_count);
1134 
1135   // Opcodes for the wrong transaction should be rejected.
1136   EXPECT_FALSE(bearer()->Reply(ind_id, NewBuffer(kTestResponse)));
1137   EXPECT_FALSE(bearer()->Reply(req_id, NewBuffer(kConfirmation)));
1138 
1139   // It should be possible to end two distinct transactions.
1140   MutableByteBufferPtr reply_0 = NewBuffer(kTestResponse);
1141   EXPECT_PACKET_OUT(*reply_0);
1142   EXPECT_TRUE(bearer()->Reply(req_id, std::move(reply_0)));
1143   MutableByteBufferPtr reply_1 = NewBuffer(kConfirmation);
1144   EXPECT_PACKET_OUT(*reply_1);
1145   EXPECT_TRUE(bearer()->Reply(ind_id, std::move(reply_1)));
1146 }
1147 
1148 // Test receipt of non-transactional PDUs.
TEST_F(BearerTest,RemotePDUWithoutResponse)1149 TEST_F(BearerTest, RemotePDUWithoutResponse) {
1150   int cmd_count = 0;
1151   auto cmd_handler = [&cmd_count](auto tid, const auto& packet) {
1152     EXPECT_EQ(Bearer::kInvalidTransactionId, tid);
1153     EXPECT_EQ(kWriteCommand, packet.opcode());
1154     cmd_count++;
1155   };
1156   bearer()->RegisterHandler(kWriteCommand, cmd_handler);
1157 
1158   int not_count = 0;
1159   auto not_handler = [&not_count](auto tid, const auto& packet) {
1160     EXPECT_EQ(Bearer::kInvalidTransactionId, tid);
1161     EXPECT_EQ(kNotification, packet.opcode());
1162     not_count++;
1163   };
1164   bearer()->RegisterHandler(kNotification, not_handler);
1165 
1166   fake_chan()->Receive(StaticByteBuffer(kTestCommand));
1167   fake_chan()->Receive(StaticByteBuffer(kNotification));
1168 
1169   RunUntilIdle();
1170   EXPECT_EQ(1, cmd_count);
1171   EXPECT_EQ(1, not_count);
1172 }
1173 
1174 // Verify proper operation if a transaction callback frees the bearer
TEST_F(BearerTest,ResponseShutsDownBearer)1175 TEST_F(BearerTest, ResponseShutsDownBearer) {
1176   StaticByteBuffer response(kTestResponse, 'T', 'e', 's', 't');
1177 
1178   bool chan_cb_called = false;
1179   auto chan_cb = [this, &chan_cb_called, &response](auto cb_packet) {
1180     ASSERT_FALSE(chan_cb_called);
1181     EXPECT_EQ(kTestRequest, (*cb_packet)[0]);
1182 
1183     chan_cb_called = true;
1184     fake_chan()->Receive(response);
1185   };
1186   fake_chan()->SetSendCallback(chan_cb, dispatcher());
1187 
1188   bool cb_called = false;
1189   auto cb = [this, &cb_called, &response](Bearer::TransactionResult result) {
1190     ASSERT_FALSE(cb_called);
1191     if (result.is_error()) {
1192       return;
1193     }
1194 
1195     cb_called = true;
1196     EXPECT_TRUE(ContainersEqual(response, result.value().data()));
1197     DeleteBearer();
1198   };
1199   bearer()->StartTransaction(NewBuffer(kTestRequest), cb);
1200 
1201   RunUntilIdle();
1202   EXPECT_TRUE(chan_cb_called);
1203   EXPECT_TRUE(cb_called);
1204 }
1205 
1206 // Verify proper operation if a transaction error callback frees the bearer
TEST_F(BearerTest,ErrorResponseShutsDownBearer)1207 TEST_F(BearerTest, ErrorResponseShutsDownBearer) {
1208   StaticByteBuffer error_rsp(
1209       // Opcode: error response
1210       kErrorResponse,
1211 
1212       // request opcode
1213       kTestRequest,
1214 
1215       // handle (0x0001)
1216       0x01,
1217       0x00,
1218 
1219       // error code:
1220       ErrorCode::kRequestNotSupported);
1221 
1222   bool chan_cb_called = false;
1223   auto chan_cb = [this, &chan_cb_called, &error_rsp](auto cb_packet) {
1224     ASSERT_FALSE(chan_cb_called);
1225     EXPECT_EQ(kTestRequest, (*cb_packet)[0]);
1226 
1227     chan_cb_called = true;
1228     fake_chan()->Receive(error_rsp);
1229   };
1230   fake_chan()->SetSendCallback(chan_cb, dispatcher());
1231 
1232   bool err_cb_called = false;
1233   auto cb = [this, &err_cb_called](Bearer::TransactionResult result) {
1234     if (result.is_ok()) {
1235       return;
1236     }
1237     const auto& [error, handle] = result.error_value();
1238     EXPECT_EQ(Error(ErrorCode::kRequestNotSupported), error);
1239     EXPECT_EQ(0x0001, handle);
1240 
1241     err_cb_called = true;
1242     DeleteBearer();
1243   };
1244   bearer()->StartTransaction(NewBuffer(kTestRequest), cb);
1245 
1246   RunUntilIdle();
1247   EXPECT_TRUE(err_cb_called);
1248   EXPECT_TRUE(chan_cb_called);
1249 }
1250 
1251 class BearerTestSecurity : public BearerTest {
1252  protected:
SetUp()1253   void SetUp() override {
1254     BearerTest::SetUp();
1255 
1256     fake_chan()->SetSecurityCallback(
1257         [this](hci_spec::ConnectionHandle,
1258                sm::SecurityLevel level,
1259                sm::ResultFunction<> callback) {
1260           security_request_count_++;
1261           requested_security_level_ = level;
1262 
1263           ASSERT_FALSE(security_responder_)
1264               << "Security request received while one was pending";
1265           security_responder_ = std::move(callback);
1266         },
1267         dispatcher());
1268   }
1269 
1270   // Sets up the fake channel to send an error response to all packets it
1271   // receives.
SetUpErrorResponder(ErrorCode ecode,Handle handle=1)1272   void SetUpErrorResponder(ErrorCode ecode, Handle handle = 1) {
1273     fake_chan()->SetSendCallback(
1274         [this, ecode, handle](auto) {
1275           att_request_count_++;
1276           fake_chan()->Receive(StaticByteBuffer(
1277               kErrorResponse,  // opcode (Error Response)
1278               kTestRequest,    // request opcode
1279               LowerBits(handle),
1280               UpperBits(handle),  // handle
1281               ecode               // error code
1282               ));
1283         },
1284         dispatcher());
1285   }
1286 
1287   // Sets up the fake channel to respond with the given |response| opcode to all
1288   // requests that it receives. The PDU contains no additional payload as it is
1289   // not needed for this test fixture.
SetUpResponder()1290   void SetUpResponder() {
1291     fake_chan()->SetSendCallback(
1292         [this](auto) {
1293           att_request_count_++;
1294           fake_chan()->Receive(StaticByteBuffer(kTestResponse));
1295         },
1296         dispatcher());
1297   }
1298 
1299   // Resolves the currently pending security request.
ResolvePendingSecurityRequest(sm::Result<> status)1300   void ResolvePendingSecurityRequest(sm::Result<> status) {
1301     ASSERT_TRUE(security_responder_);
1302 
1303     if (status.is_ok()) {
1304       fake_chan()->set_security(sm::SecurityProperties(
1305           requested_security_level_, 16, /*secure_connections=*/false));
1306     }
1307 
1308     // Clear the responder before invoking it.
1309     auto f = std::move(security_responder_);
1310     f(status);
1311   }
1312 
SendRequest()1313   void SendRequest() {
1314     bearer()->StartTransaction(NewBuffer(kTestRequest), [this](auto result) {
1315       if (result.is_ok()) {
1316         request_success_count_++;
1317         last_request_status_ = fit::ok();
1318       } else {
1319         request_error_count_++;
1320         last_request_status_ = fit::error(result.error_value().first);
1321       }
1322     });
1323   }
1324 
last_request_status() const1325   const Result<>& last_request_status() const { return last_request_status_; }
request_success_count() const1326   size_t request_success_count() const { return request_success_count_; }
request_error_count() const1327   size_t request_error_count() const { return request_error_count_; }
att_request_count() const1328   size_t att_request_count() const { return att_request_count_; }
1329 
security_request_count() const1330   size_t security_request_count() const { return security_request_count_; }
requested_security_level() const1331   sm::SecurityLevel requested_security_level() const {
1332     return requested_security_level_;
1333   }
1334 
1335  private:
1336   Result<> last_request_status_ = fit::ok();
1337   size_t request_success_count_ = 0u;
1338   size_t request_error_count_ = 0u;
1339 
1340   size_t att_request_count_ = 0u;
1341   sm::SecurityLevel requested_security_level_ = sm::SecurityLevel::kNoSecurity;
1342   size_t security_request_count_ = 0u;
1343 
1344   sm::ResultFunction<> security_responder_;
1345 };
1346 
TEST_F(BearerTestSecurity,SecurityUpgradeAfterInsufficientAuthentication)1347 TEST_F(BearerTestSecurity, SecurityUpgradeAfterInsufficientAuthentication) {
1348   // Configure the endpoint to respond with an authentication error.
1349   SetUpErrorResponder(ErrorCode::kInsufficientAuthentication);
1350   SendRequest();
1351   RunUntilIdle();
1352 
1353   // At this stage the remote device should have received the request and
1354   // responded with "Insufficient Authentication". Since the link was not
1355   // encrypted, the Bearer should have requested a security upgrade without
1356   // requiring MITM protection.
1357   EXPECT_EQ(1u, att_request_count());
1358   EXPECT_EQ(1u, security_request_count());
1359   EXPECT_EQ(sm::SecurityLevel::kEncrypted, requested_security_level());
1360 
1361   // The request should be still unresolved.
1362   EXPECT_EQ(0u, request_success_count());
1363   EXPECT_EQ(0u, request_error_count());
1364 
1365   // Configure the endpoint to respond with success and notify the Bearer of the
1366   // security upgrade. The Bearer should re-send the request.
1367   SetUpResponder();
1368   ResolvePendingSecurityRequest(fit::ok());
1369   RunUntilIdle();
1370 
1371   // We should have received the same request again.
1372   EXPECT_EQ(2u, att_request_count());
1373   EXPECT_EQ(1u, security_request_count());
1374   EXPECT_EQ(1u, request_success_count());
1375   EXPECT_EQ(0u, request_error_count());
1376 }
1377 
TEST_F(BearerTestSecurity,SecurityUpgradeWithMitmAfterInsufficientAuthentication)1378 TEST_F(BearerTestSecurity,
1379        SecurityUpgradeWithMitmAfterInsufficientAuthentication) {
1380   // Configure the channel to be already encrypted.
1381   fake_chan()->set_security(sm::SecurityProperties(
1382       sm::SecurityLevel::kEncrypted, 16, /*secure_connections=*/false));
1383 
1384   // Configure the endpoint to respond with an authentication error.
1385   SetUpErrorResponder(ErrorCode::kInsufficientAuthentication);
1386   SendRequest();
1387   RunUntilIdle();
1388 
1389   // At this stage the remote device should have received the request and
1390   // responded with "Insufficient Authentication". Since the link was already
1391   // encrypted, the Bearer should have requested a security upgrade with MITM
1392   // protection.
1393   EXPECT_EQ(1u, att_request_count());
1394   EXPECT_EQ(1u, security_request_count());
1395   EXPECT_EQ(sm::SecurityLevel::kAuthenticated, requested_security_level());
1396 
1397   // The request should be still unresolved.
1398   EXPECT_EQ(0u, request_success_count());
1399   EXPECT_EQ(0u, request_error_count());
1400 
1401   // Configure the endpoint to respond with success and notify the Bearer of the
1402   // security upgrade. The Bearer should re-send the request.
1403   SetUpResponder();
1404   ResolvePendingSecurityRequest(fit::ok());
1405   RunUntilIdle();
1406 
1407   // We should have received the same request again.
1408   EXPECT_EQ(2u, att_request_count());
1409   EXPECT_EQ(1u, security_request_count());
1410   EXPECT_EQ(1u, request_success_count());
1411   EXPECT_EQ(0u, request_error_count());
1412   EXPECT_EQ(fit::ok(), last_request_status());
1413 }
1414 
TEST_F(BearerTestSecurity,SecurityUpgradeFailsAfterAuthError)1415 TEST_F(BearerTestSecurity, SecurityUpgradeFailsAfterAuthError) {
1416   // Configure the endpoint to respond with an authentication error.
1417   SetUpErrorResponder(ErrorCode::kInsufficientAuthentication);
1418   SendRequest();
1419   RunUntilIdle();
1420 
1421   // At this stage the remote device should have received the request and
1422   // responded with "Insufficient Authentication". Since the link was not
1423   // encrypted, the Bearer should have requested a security upgrade without
1424   // requiring MITM protection.
1425   EXPECT_EQ(1u, att_request_count());
1426   EXPECT_EQ(1u, security_request_count());
1427   EXPECT_EQ(sm::SecurityLevel::kEncrypted, requested_security_level());
1428 
1429   // The request should be still unresolved.
1430   EXPECT_EQ(0u, request_success_count());
1431   EXPECT_EQ(0u, request_error_count());
1432 
1433   // Configure the endpoint to respond with success and notify the Bearer of the
1434   // security upgrade. The Bearer should re-send the request.
1435   SetUpResponder();
1436   ResolvePendingSecurityRequest(ToResult(HostError::kFailed));
1437   RunUntilIdle();
1438 
1439   // The request should not have been retried and failed with the original
1440   // error.
1441   EXPECT_EQ(1u, att_request_count());
1442   EXPECT_EQ(1u, security_request_count());
1443   EXPECT_EQ(0u, request_success_count());
1444   EXPECT_EQ(1u, request_error_count());
1445   EXPECT_EQ(ToResult(ErrorCode::kInsufficientAuthentication),
1446             last_request_status());
1447 }
1448 
TEST_F(BearerTestSecurity,NoSecurityUpgradeIfAlreadyRetried)1449 TEST_F(BearerTestSecurity, NoSecurityUpgradeIfAlreadyRetried) {
1450   // Configure the endpoint to respond with an authentication error.
1451   SetUpErrorResponder(ErrorCode::kInsufficientAuthentication);
1452   SendRequest();
1453   RunUntilIdle();
1454 
1455   // At this stage the remote device should have received the request and
1456   // responded with "Insufficient Authentication". Since the link was not
1457   // encrypted, the Bearer should have requested a security upgrade without
1458   // requiring MITM protection.
1459   EXPECT_EQ(1u, att_request_count());
1460   EXPECT_EQ(1u, security_request_count());
1461   EXPECT_EQ(sm::SecurityLevel::kEncrypted, requested_security_level());
1462 
1463   // The request should be still unresolved.
1464   EXPECT_EQ(0u, request_success_count());
1465   EXPECT_EQ(0u, request_error_count());
1466 
1467   // Resolve the pending security request with success while the channel is
1468   // configured to respond with "Insufficient Authentication". The Bearer should
1469   // re-send the request.
1470   ResolvePendingSecurityRequest(fit::ok());
1471   RunUntilIdle();
1472 
1473   // The request should have been retried once. The "Insufficient
1474   // Authentication" error received while the link is encrypted should result in
1475   // a second security request at the next security level.
1476   EXPECT_EQ(2u, att_request_count());
1477   EXPECT_EQ(2u, security_request_count());
1478   EXPECT_EQ(0u, request_success_count());
1479   EXPECT_EQ(0u, request_error_count());
1480 
1481   // Resolve the pending security request with success while the channel is
1482   // configured to respond with "Insufficient Authentication. The Bearer should
1483   // retry the request one last time.
1484   ResolvePendingSecurityRequest(fit::ok());
1485   RunUntilIdle();
1486 
1487   // The request should have failed without retrying the request a third time as
1488   // the highest security level has been reached.
1489   EXPECT_EQ(3u, att_request_count());
1490   EXPECT_EQ(2u, security_request_count());
1491   EXPECT_EQ(0u, request_success_count());
1492   EXPECT_EQ(1u, request_error_count());
1493   EXPECT_EQ(ToResult(ErrorCode::kInsufficientAuthentication),
1494             last_request_status());
1495 }
1496 
TEST_F(BearerTestSecurity,NoSecurityUpgradeIfChannelAlreadyEncrypted)1497 TEST_F(BearerTestSecurity, NoSecurityUpgradeIfChannelAlreadyEncrypted) {
1498   // Configure the channel to be already encrypted.
1499   fake_chan()->set_security(sm::SecurityProperties(
1500       sm::SecurityLevel::kEncrypted, 16, /*secure_connections=*/false));
1501 
1502   // Configure the endpoint to respond with an encryption error.
1503   SetUpErrorResponder(ErrorCode::kInsufficientEncryption);
1504   SendRequest();
1505   RunUntilIdle();
1506 
1507   // No security upgrade should have been requested since the channel was
1508   // sufficiently encrypted.
1509   EXPECT_EQ(1u, att_request_count());
1510   EXPECT_EQ(0u, security_request_count());
1511   EXPECT_EQ(0u, request_success_count());
1512   EXPECT_EQ(1u, request_error_count());
1513   EXPECT_EQ(ToResult(ErrorCode::kInsufficientEncryption),
1514             last_request_status());
1515 }
1516 
TEST_F(BearerTestSecurity,NoSecurityUpgradeIfChannelAlreadyEncryptedWithMitm)1517 TEST_F(BearerTestSecurity, NoSecurityUpgradeIfChannelAlreadyEncryptedWithMitm) {
1518   // Configure the channel to be already encrypted with MITM protection
1519   fake_chan()->set_security(sm::SecurityProperties(
1520       sm::SecurityLevel::kAuthenticated, 16, /*secure_connections=*/false));
1521 
1522   // Configure the endpoint to respond with an authentication error.
1523   SetUpErrorResponder(ErrorCode::kInsufficientAuthentication);
1524   SendRequest();
1525   RunUntilIdle();
1526 
1527   // No security upgrade should have been requested since the channel was
1528   // sufficiently encrypted.
1529   EXPECT_EQ(1u, att_request_count());
1530   EXPECT_EQ(0u, security_request_count());
1531   EXPECT_EQ(0u, request_success_count());
1532   EXPECT_EQ(1u, request_error_count());
1533   EXPECT_EQ(ToResult(ErrorCode::kInsufficientAuthentication),
1534             last_request_status());
1535 }
1536 
1537 }  // namespace
1538 }  // namespace bt::att
1539