Debian Codegraph @

tests/channels/test_att.py

raw
1 """Tests for the ATT/GATT codec."""
2
3 from __future__ import annotations
4
5 import asyncio
6 from typing import TYPE_CHECKING
7 from unittest.mock import patch
8
9 import pytest
10 from bleak import BleakError
11
12 from habluetooth.channels.att import (
13 ATT_ERR_ATTRIBUTE_NOT_FOUND,
14 ATT_ERR_INSUFFICIENT_AUTHENTICATION,
15 ATT_ERR_INSUFFICIENT_ENCRYPTION,
16 ATT_ERR_INVALID_OFFSET,
17 ATT_ERR_READ_NOT_PERMITTED,
18 ATT_ERR_REQUEST_NOT_SUPPORTED,
19 ATT_ERROR_RSP,
20 ATT_EXCHANGE_MTU_RSP,
21 ATT_FIND_INFO_REQ,
22 ATT_FIND_INFO_RSP,
23 ATT_HANDLE_VALUE_CFM,
24 ATT_HANDLE_VALUE_IND,
25 ATT_HANDLE_VALUE_NTF,
26 ATT_READ_BLOB_RSP,
27 ATT_READ_BY_GROUP_TYPE_REQ,
28 ATT_READ_BY_GROUP_TYPE_RSP,
29 ATT_READ_BY_TYPE_REQ,
30 ATT_READ_BY_TYPE_RSP,
31 ATT_READ_RSP,
32 ATT_WRITE_CMD,
33 ATT_WRITE_RSP,
34 CCCD_UUID,
35 DEFAULT_MTU,
36 ATTClient,
37 ATTError,
38 properties_to_strings,
39 uuid_from_bytes,
40 )
41
42 if TYPE_CHECKING:
43 from collections.abc import Awaitable, Callable
44
45 pytestmark = pytest.mark.asyncio
46
47
48 class FakePeer:
49 """A fake ATT peer that captures sent PDUs and auto-replies."""
50
51 def __init__(
52 self,
53 responder: Callable[[bytes], bytes | None] | None = None,
54 *,
55 escalate_security: Callable[[int], bool] | None = None,
56 ) -> None:
57 """Create the bound ATTClient and optionally script replies."""
58 self.sent: list[bytes] = []
59 self.responder = responder
60 self.client = ATTClient(self.send, escalate_security=escalate_security)
61
62 async def send(self, data: bytes) -> None:
63 """Capture an outbound PDU and feed back the scripted response."""
64 self.sent.append(bytes(data))
65 if self.responder is not None:
66 response = self.responder(bytes(data))
67 if response is not None:
68 self.client.data_received(response)
69
70
71 def _att_error(req_opcode: int, handle: int, code: int) -> bytes:
72 return (
73 bytes([ATT_ERROR_RSP, req_opcode])
74 + handle.to_bytes(2, "little")
75 + bytes([code])
76 )
77
78
79 # -- pure helpers ---------------------------------------------------------
80 async def test_uuid_from_bytes_16_bit() -> None:
81 """A 16-bit UUID expands against the Bluetooth base UUID."""
82 assert uuid_from_bytes(b"\x02\x29") == CCCD_UUID
83 assert uuid_from_bytes(b"\x0d\x18") == "0000180d-0000-1000-8000-00805f9b34fb"
84
85
86 async def test_uuid_from_bytes_128_bit() -> None:
87 """A 128-bit UUID is byte-reversed and formatted."""
88 raw = bytes.fromhex("fb349b5f8000008000100000661a0a05")
89 assert uuid_from_bytes(raw) == "050a1a66-0000-1000-8000-00805f9b34fb"
90
91
92 async def test_properties_to_strings() -> None:
93 """The property bitmask expands to bleak property names."""
94 # 0x12 sets the read and notify bits
95 assert properties_to_strings(0x12) == ["read", "notify"]
96 assert properties_to_strings(0x00) == []
97
98
99 # -- security escalation --------------------------------------------------
100 async def test_request_escalates_and_retries_on_encryption_error() -> None:
101 """An insufficient-encryption error raises security and re-sends once."""
102 attempts = 0
103
104 def responder(req: bytes) -> bytes:
105 nonlocal attempts
106 attempts += 1
107 if attempts == 1:
108 return _att_error(req[0], 0x0005, ATT_ERR_INSUFFICIENT_ENCRYPTION)
109 return bytes([ATT_READ_RSP]) + b"\x01\x02"
110
111 seen: list[int] = []
112
113 def escalate(err: int) -> bool:
114 seen.append(err)
115 return True
116
117 peer = FakePeer(responder, escalate_security=escalate)
118 assert await peer.client.read(0x0005) == b"\x01\x02"
119 assert seen == [ATT_ERR_INSUFFICIENT_ENCRYPTION]
120 assert len(peer.sent) == 2 # original request plus one retry
121
122
123 async def test_request_does_not_retry_when_escalation_declines() -> None:
124 """If security cannot be raised, the error is surfaced without a retry."""
125 peer = FakePeer(
126 lambda req: _att_error(req[0], 0x0001, ATT_ERR_INSUFFICIENT_AUTHENTICATION),
127 escalate_security=lambda _err: False,
128 )
129 with pytest.raises(ATTError) as exc_info:
130 await peer.client.read(0x0001)
131 assert exc_info.value.error_code == ATT_ERR_INSUFFICIENT_AUTHENTICATION
132 assert len(peer.sent) == 1 # not retried
133
134
135 async def test_request_escalates_at_most_once() -> None:
136 """A persistent security error is surfaced after a single retry."""
137 seen: list[int] = []
138
139 def escalate(err: int) -> bool:
140 seen.append(err)
141 return True
142
143 peer = FakePeer(
144 lambda req: _att_error(req[0], 0x0001, ATT_ERR_INSUFFICIENT_ENCRYPTION),
145 escalate_security=escalate,
146 )
147 with pytest.raises(ATTError):
148 await peer.client.read(0x0001)
149 assert len(seen) == 1 # escalated once
150 assert len(peer.sent) == 2 # original request plus one retry
151
152
153 async def test_request_without_escalation_surfaces_security_error() -> None:
154 """With no escalation hook, a security error propagates immediately."""
155 peer = FakePeer(
156 lambda req: _att_error(req[0], 0x0001, ATT_ERR_INSUFFICIENT_ENCRYPTION)
157 )
158 with pytest.raises(ATTError) as exc_info:
159 await peer.client.read(0x0001)
160 assert exc_info.value.error_code == ATT_ERR_INSUFFICIENT_ENCRYPTION
161 assert len(peer.sent) == 1
162
163
164 # -- MTU ------------------------------------------------------------------
165 async def test_exchange_mtu_negotiates_minimum() -> None:
166 """The negotiated MTU is the minimum of ours and the server's."""
167 peer = FakePeer(
168 lambda _req: bytes([ATT_EXCHANGE_MTU_RSP]) + (185).to_bytes(2, "little")
169 )
170 assert await peer.client.exchange_mtu(247) == 185
171 assert peer.client.mtu == 185
172
173
174 async def test_exchange_mtu_unsupported_keeps_default() -> None:
175 """A peer that does not support MTU exchange falls back to the default."""
176 peer = FakePeer(lambda req: _att_error(req[0], 0, ATT_ERR_REQUEST_NOT_SUPPORTED))
177 assert await peer.client.exchange_mtu(247) == DEFAULT_MTU
178 assert peer.client.mtu == DEFAULT_MTU
179
180
181 async def test_exchange_mtu_propagates_other_errors() -> None:
182 """An MTU rejection other than 'not supported' is surfaced, not swallowed."""
183 peer = FakePeer(
184 lambda req: _att_error(req[0], 0, ATT_ERR_INSUFFICIENT_AUTHENTICATION)
185 )
186 with pytest.raises(ATTError) as exc_info:
187 await peer.client.exchange_mtu(247)
188 assert exc_info.value.error_code == ATT_ERR_INSUFFICIENT_AUTHENTICATION
189
190
191 # -- reads ----------------------------------------------------------------
192 async def test_read_short_value() -> None:
193 """A short value is returned without a Read Blob follow-up."""
194 peer = FakePeer(lambda _req: bytes([ATT_READ_RSP]) + b"\x01\x02\x03")
195 assert await peer.client.read(0x0010) == b"\x01\x02\x03"
196
197
198 async def test_read_long_value_continues_with_blob() -> None:
199 """A value is read across multiple full Read Blob chunks until a short one."""
200 # With the default MTU (23) a full chunk is mtu - 1 = 22 bytes; a chunk
201 # shorter than that ends the read without an extra empty round-trip.
202 first = bytes(range(22)) # full -> blob read
203 blob_full = bytes(range(100, 122)) # full (22) -> continue
204 blob_short = b"\xaa\xbb\xcc\xdd" # short (4) -> stop
205
206 def responder(req: bytes) -> bytes:
207 if req[0] == 0x0A: # ATT_READ_REQ
208 return bytes([ATT_READ_RSP]) + first
209 offset = int.from_bytes(req[3:5], "little")
210 if offset == 22:
211 return bytes([ATT_READ_BLOB_RSP]) + blob_full
212 return bytes([ATT_READ_BLOB_RSP]) + blob_short
213
214 peer = FakePeer(responder)
215 assert await peer.client.read(0x0010) == first + blob_full + blob_short
216 # READ + two READ_BLOB; the short final chunk avoids a trailing empty read.
217 assert len(peer.sent) == 3
218
219
220 async def test_read_blob_invalid_offset_stops() -> None:
221 """An invalid-offset error during a long read ends the read cleanly."""
222 full = bytes(range(22))
223
224 def responder(req: bytes) -> bytes:
225 if req[0] == 0x0A: # ATT_READ_REQ
226 return bytes([ATT_READ_RSP]) + full
227 return _att_error(req[0], 0x10, ATT_ERR_INVALID_OFFSET)
228
229 peer = FakePeer(responder)
230 assert await peer.client.read(0x0010) == full
231
232
233 # -- writes ---------------------------------------------------------------
234 async def test_write_with_response() -> None:
235 """Write Request waits for the Write Response."""
236 peer = FakePeer(lambda _req: bytes([ATT_WRITE_RSP]))
237 await peer.client.write(0x0011, b"\x01\x00")
238 assert peer.sent[0][0] == 0x12 # ATT_WRITE_REQ
239 assert peer.sent[0][1:3] == (0x0011).to_bytes(2, "little")
240 assert peer.sent[0][3:] == b"\x01\x00"
241
242
243 async def test_write_command_has_no_response() -> None:
244 """Write Command is fire-and-forget."""
245 peer = FakePeer()
246 await peer.client.write_command(0x0011, b"\x09")
247 assert peer.sent == [bytes([ATT_WRITE_CMD]) + b"\x11\x00\x09"]
248
249
250 # -- error handling -------------------------------------------------------
251 async def test_error_response_raises_att_error() -> None:
252 """An ATT error response raises ATTError with the details."""
253 peer = FakePeer(lambda req: _att_error(req[0], 0x0010, ATT_ERR_READ_NOT_PERMITTED))
254 with pytest.raises(ATTError) as exc_info:
255 await peer.client.read(0x0010)
256 assert exc_info.value.error_code == ATT_ERR_READ_NOT_PERMITTED
257 assert exc_info.value.handle == 0x0010
258
259
260 async def test_unexpected_opcode_raises() -> None:
261 """A response with the wrong opcode raises a BleakError."""
262 peer = FakePeer(lambda _req: bytes([ATT_WRITE_RSP])) # wrong for a read
263 with pytest.raises(BleakError, match="unexpected ATT opcode"):
264 await peer.client.read(0x0010)
265
266
267 # -- notifications --------------------------------------------------------
268 async def test_notification_dispatched_to_handler() -> None:
269 """A handle value notification reaches the registered handler."""
270 peer = FakePeer()
271 received: list[bytearray] = []
272 peer.client.set_notify_handler(0x0003, received.append)
273 peer.client.data_received(
274 bytes([ATT_HANDLE_VALUE_NTF]) + (0x0003).to_bytes(2, "little") + b"\x10\x20"
275 )
276 assert received == [bytearray(b"\x10\x20")]
277
278
279 async def test_indication_dispatched_and_confirmed() -> None:
280 """An indication reaches the handler and is acknowledged."""
281 peer = FakePeer()
282 received: list[bytearray] = []
283 peer.client.set_notify_handler(0x0005, received.append)
284 peer.client.data_received(
285 bytes([ATT_HANDLE_VALUE_IND]) + (0x0005).to_bytes(2, "little") + b"\x99"
286 )
287 await asyncio.sleep(0) # let the fire-and-forget confirm run
288 assert received == [bytearray(b"\x99")]
289 assert peer.sent == [bytes([ATT_HANDLE_VALUE_CFM])]
290
291
292 async def test_remove_notify_handler() -> None:
293 """A removed handler no longer receives notifications."""
294 peer = FakePeer()
295 received: list[bytearray] = []
296 peer.client.set_notify_handler(0x0003, received.append)
297 peer.client.remove_notify_handler(0x0003)
298 peer.client.data_received(
299 bytes([ATT_HANDLE_VALUE_NTF]) + (0x0003).to_bytes(2, "little") + b"\x10"
300 )
301 assert received == []
302
303
304 async def test_data_received_empty_is_ignored() -> None:
305 """An empty inbound PDU is ignored."""
306 peer = FakePeer()
307 peer.client.data_received(b"") # must not raise
308
309
310 # -- connection loss ------------------------------------------------------
311 async def test_connection_lost_fails_pending_and_notifies() -> None:
312 """Connection loss fails the in-flight request and calls the callback."""
313 disconnects: list[Exception | None] = []
314 peer = FakePeer() # no responder: the request will hang awaiting a reply
315 client = ATTClient(peer.send, on_disconnect=disconnects.append)
316
317 task = asyncio.create_task(client.read(0x0010))
318 await asyncio.sleep(0) # let the request go out and await the response
319 err = OSError("link lost")
320 client.connection_lost(err)
321 with pytest.raises(OSError, match="link lost"):
322 await task
323 assert disconnects == [err]
324
325
326 # -- discovery primitives -------------------------------------------------
327 async def test_read_by_group_type_parses_entries() -> None:
328 """Primary-service discovery parses (handle, end, uuid) entries."""
329
330 def responder(req: bytes) -> bytes:
331 start = int.from_bytes(req[1:3], "little")
332 if start <= 0x0001:
333 return bytes([ATT_READ_BY_GROUP_TYPE_RSP, 6]) + b"\x01\x00\x05\x00\x0d\x18"
334 return _att_error(req[0], start, ATT_ERR_ATTRIBUTE_NOT_FOUND)
335
336 peer = FakePeer(responder)
337 # End the search at 0x0005 so the loop terminates on the range, not an error.
338 results = await peer.client.read_by_group_type(0x0001, 0x0005, b"\x00\x28")
339 assert results == [(0x0001, 0x0005, b"\x0d\x18")]
340 assert len(peer.sent) == 1
341
342
343 async def test_read_by_type_parses_entries() -> None:
344 """Characteristic discovery parses (handle, value) entries."""
345
346 def responder(req: bytes) -> bytes:
347 start = int.from_bytes(req[1:3], "little")
348 if start <= 0x0002:
349 return bytes([ATT_READ_BY_TYPE_RSP, 7]) + b"\x02\x00\x12\x03\x00\x37\x2a"
350 return _att_error(req[0], start, ATT_ERR_ATTRIBUTE_NOT_FOUND)
351
352 peer = FakePeer(responder)
353 # End at the entry handle so the loop terminates on the range.
354 results = await peer.client.read_by_type(0x0001, 0x0002, b"\x03\x28")
355 assert results == [(0x0002, b"\x12\x03\x00\x37\x2a")]
356 assert len(peer.sent) == 1
357
358
359 async def test_find_information_parses_16_bit() -> None:
360 """Descriptor discovery parses 16-bit UUID entries."""
361
362 def responder(req: bytes) -> bytes:
363 start = int.from_bytes(req[1:3], "little")
364 if start <= 0x0004:
365 # format 0x01 (16-bit): handle 0x0004 -> CCCD
366 return bytes([ATT_FIND_INFO_RSP, 0x01]) + b"\x04\x00\x02\x29"
367 return _att_error(req[0], start, ATT_ERR_ATTRIBUTE_NOT_FOUND)
368
369 peer = FakePeer(responder)
370 results = await peer.client.find_information(0x0004, 0x0005)
371 assert results == [(0x0004, CCCD_UUID)]
372
373
374 # -- full discovery -------------------------------------------------------
375 async def test_discover_builds_service_tree() -> None:
376 """
377 discover() walks services, characteristics and descriptors.
378
379 The service has two characteristics: the first owns a CCCD descriptor (so
380 descriptors are fetched) and the second's value handle is the service's last
381 handle (so it has no descriptor range to scan).
382 """
383
384 def responder(req: bytes) -> bytes:
385 opcode = req[0]
386 start = int.from_bytes(req[1:3], "little")
387 if opcode == ATT_READ_BY_GROUP_TYPE_REQ:
388 if start <= 0x0001:
389 # service 0x0001-0x0006, uuid 0x180D
390 return (
391 bytes([ATT_READ_BY_GROUP_TYPE_RSP, 6]) + b"\x01\x00\x06\x00\x0d\x18"
392 )
393 return _att_error(opcode, start, ATT_ERR_ATTRIBUTE_NOT_FOUND)
394 if opcode == ATT_READ_BY_TYPE_REQ:
395 if start <= 0x0002:
396 # two characteristics in one response (each 7 bytes):
397 # A: decl 0x0002, props 0x12, value 0x0003, uuid 0x2A37
398 # B: decl 0x0005, props 0x02, value 0x0006, uuid 0x2A38
399 char_a = b"\x02\x00\x12\x03\x00\x37\x2a"
400 char_b = b"\x05\x00\x02\x06\x00\x38\x2a"
401 return bytes([ATT_READ_BY_TYPE_RSP, 7]) + char_a + char_b
402 return _att_error(opcode, start, ATT_ERR_ATTRIBUTE_NOT_FOUND)
403 if opcode == ATT_FIND_INFO_REQ:
404 # Only characteristic A (value 0x0003, end 0x0004) has a descriptor.
405 if start <= 0x0004:
406 return bytes([ATT_FIND_INFO_RSP, 0x01]) + b"\x04\x00\x02\x29"
407 return _att_error(opcode, start, ATT_ERR_ATTRIBUTE_NOT_FOUND)
408 msg = f"unexpected opcode {opcode:#x}"
409 raise AssertionError(msg)
410
411 peer = FakePeer(responder)
412 services = await peer.client.discover()
413
414 assert len(services) == 1
415 svc = services[0]
416 assert svc.handle == 0x0001
417 assert svc.end_handle == 0x0006
418 assert svc.uuid == "0000180d-0000-1000-8000-00805f9b34fb"
419
420 assert len(svc.characteristics) == 2
421 char_a, char_b = svc.characteristics
422
423 assert char_a.handle == 0x0002
424 assert char_a.value_handle == 0x0003
425 assert char_a.uuid == "00002a37-0000-1000-8000-00805f9b34fb"
426 assert char_a.properties == 0x12
427 assert char_a.end_handle == 0x0004 # one before the next declaration
428 assert properties_to_strings(char_a.properties) == ["read", "notify"]
429 assert len(char_a.descriptors) == 1
430 assert char_a.descriptors[0].handle == 0x0004
431 assert char_a.descriptors[0].uuid == CCCD_UUID
432
433 # The last characteristic's value handle is the service end, so no
434 # descriptor range remains to scan.
435 assert char_b.handle == 0x0005
436 assert char_b.value_handle == 0x0006
437 assert char_b.uuid == "00002a38-0000-1000-8000-00805f9b34fb"
438 assert char_b.end_handle == 0x0006
439 assert char_b.descriptors == []
440
441
442 async def test_read_blob_propagates_other_errors() -> None:
443 """A non-offset error during a long read propagates."""
444 full = bytes(range(22))
445
446 def responder(req: bytes) -> bytes:
447 if req[0] == 0x0A: # ATT_READ_REQ
448 return bytes([ATT_READ_RSP]) + full
449 return _att_error(req[0], 0x10, ATT_ERR_READ_NOT_PERMITTED)
450
451 peer = FakePeer(responder)
452 with pytest.raises(ATTError):
453 await peer.client.read(0x0010)
454
455
456 @pytest.mark.parametrize(
457 "call",
458 [
459 lambda c: c.read_by_group_type(0x0001, 0xFFFF, b"\x00\x28"),
460 lambda c: c.read_by_type(0x0001, 0xFFFF, b"\x03\x28"),
461 lambda c: c.find_information(0x0001, 0xFFFF),
462 ],
463 )
464 async def test_discovery_propagates_non_not_found_errors(
465 call: Callable[[ATTClient], Awaitable[object]],
466 ) -> None:
467 """A non-ATTR_NOT_FOUND error aborts discovery instead of ending it."""
468 peer = FakePeer(lambda req: _att_error(req[0], 0x0001, ATT_ERR_READ_NOT_PERMITTED))
469 with pytest.raises(ATTError):
470 await call(peer.client)
471
472
473 async def test_read_by_group_type_stops_at_max_handle() -> None:
474 """An end handle of 0xFFFF ends the loop without another request."""
475 peer = FakePeer(
476 lambda _req: (
477 bytes([ATT_READ_BY_GROUP_TYPE_RSP, 6]) + b"\x01\x00\xff\xff\x0d\x18"
478 )
479 )
480 results = await peer.client.read_by_group_type(0x0001, 0xFFFF, b"\x00\x28")
481 assert results == [(0x0001, 0xFFFF, b"\x0d\x18")]
482 assert len(peer.sent) == 1
483
484
485 async def test_read_by_type_stops_at_max_handle() -> None:
486 """A handle of 0xFFFF ends the loop without another request."""
487 peer = FakePeer(
488 lambda _req: bytes([ATT_READ_BY_TYPE_RSP, 7]) + b"\xff\xff\x12\x03\x00\x37\x2a"
489 )
490 results = await peer.client.read_by_type(0x0001, 0xFFFF, b"\x03\x28")
491 assert results[0][0] == 0xFFFF
492 assert len(peer.sent) == 1
493
494
495 async def test_find_information_128_bit_and_max_handle() -> None:
496 """find_information parses 128-bit UUIDs and stops at the max handle."""
497 uuid128 = bytes.fromhex("fb349b5f8000008000100000661a0a05")
498 peer = FakePeer(
499 lambda _req: bytes([ATT_FIND_INFO_RSP, 0x02]) + b"\xff\xff" + uuid128
500 )
501 results = await peer.client.find_information(0x0001, 0xFFFF)
502 assert results == [(0xFFFF, "050a1a66-0000-1000-8000-00805f9b34fb")]
503 assert len(peer.sent) == 1
504
505
506 async def test_no_pending_request_paths() -> None:
507 """A stray response and a bare connection loss are handled safely."""
508 peer = FakePeer()
509 # A response with no in-flight request is ignored.
510 peer.client.data_received(bytes([ATT_WRITE_RSP]))
511 # Connection loss with no pending request and no callback does not raise.
512 peer.client.connection_lost(None)
513
514
515 # -- wire robustness on malformed input -----------------------------------
516 async def test_uuid_from_bytes_rejects_invalid_length() -> None:
517 """A UUID that is neither 2 nor 16 bytes is rejected, not mis-formatted."""
518 with pytest.raises(BleakError, match="invalid ATT UUID length"):
519 uuid_from_bytes(b"\x01\x02\x03\x04")
520
521
522 async def test_read_by_group_type_rejects_malformed_length() -> None:
523 """A zero/short length byte raises instead of crashing range()."""
524 peer = FakePeer(lambda _req: bytes([ATT_READ_BY_GROUP_TYPE_RSP, 0]))
525 with pytest.raises(BleakError, match="malformed read-by-group-type"):
526 await peer.client.read_by_group_type(0x0001, 0xFFFF, b"\x00\x28")
527
528
529 async def test_read_by_type_rejects_malformed_length() -> None:
530 """A zero/short length byte raises instead of crashing range()."""
531 peer = FakePeer(lambda _req: bytes([ATT_READ_BY_TYPE_RSP, 0]))
532 with pytest.raises(BleakError, match="malformed read-by-type"):
533 await peer.client.read_by_type(0x0001, 0xFFFF, b"\x03\x28")
534
535
536 async def test_find_information_rejects_invalid_format() -> None:
537 """A format byte other than 0x01/0x02 raises rather than mis-parsing."""
538 peer = FakePeer(lambda _req: bytes([ATT_FIND_INFO_RSP, 0x03]) + b"\x04\x00")
539 with pytest.raises(BleakError, match="invalid find-information format"):
540 await peer.client.find_information(0x0004, 0xFFFF)
541
542
543 async def test_indication_confirm_failure_is_logged(
544 caplog: pytest.LogCaptureFixture,
545 ) -> None:
546 """A failed indication confirmation is logged, not raised as a task error."""
547
548 async def send(data: bytes) -> None:
549 if data == bytes([ATT_HANDLE_VALUE_CFM]):
550 msg = "send failed"
551 raise OSError(msg)
552
553 client = ATTClient(send)
554 client.set_notify_handler(0x0005, lambda _v: None)
555 with caplog.at_level("DEBUG", logger="habluetooth.channels.att"):
556 client.data_received(
557 bytes([ATT_HANDLE_VALUE_IND]) + (0x0005).to_bytes(2, "little") + b"\x99"
558 )
559 # Let the confirm task run and its done-callback fire.
560 for _ in range(3):
561 await asyncio.sleep(0)
562 assert "Failed to confirm ATT indication" in caplog.text
563
564
565 async def test_request_rejects_truncated_error_response() -> None:
566 """A truncated ATT error response raises BleakError, not struct.error."""
567 # ATT_ERROR_RSP needs 5 bytes; return only 2.
568 peer = FakePeer(lambda _req: bytes([ATT_ERROR_RSP, 0x0A]))
569 with pytest.raises(BleakError, match="truncated ATT error response"):
570 await peer.client.read(0x0010)
571
572
573 async def test_discover_rejects_malformed_characteristic_declaration() -> None:
574 """A characteristic declaration shorter than 5 bytes raises BleakError."""
575
576 def responder(req: bytes) -> bytes:
577 opcode = req[0]
578 start = int.from_bytes(req[1:3], "little")
579 if opcode == ATT_READ_BY_GROUP_TYPE_REQ:
580 if start <= 0x0001:
581 return (
582 bytes([ATT_READ_BY_GROUP_TYPE_RSP, 6]) + b"\x01\x00\x05\x00\x0d\x18"
583 )
584 return _att_error(opcode, start, ATT_ERR_ATTRIBUTE_NOT_FOUND)
585 if opcode == ATT_READ_BY_TYPE_REQ:
586 # length 2 survives read_by_type's guard but leaves an empty value.
587 return bytes([ATT_READ_BY_TYPE_RSP, 2]) + b"\x02\x00"
588 msg = f"unexpected opcode {opcode:#x}"
589 raise AssertionError(msg)
590
591 peer = FakePeer(responder)
592 with pytest.raises(BleakError, match="malformed characteristic declaration"):
593 await peer.client.discover()
594
595
596 async def test_request_timeout_raises_bleak_error() -> None:
597 """A request with no reply times out as a BleakError, not TimeoutError."""
598 peer = FakePeer() # no responder: the future never resolves
599 with (
600 patch("habluetooth.channels.att.ATT_TIMEOUT", 0.01),
601 pytest.raises(BleakError, match="ATT request timed out"),
602 ):
603 await peer.client.read(0x0010)
604
605
606 async def test_notification_handler_exception_is_isolated(
607 caplog: pytest.LogCaptureFixture,
608 ) -> None:
609 """A raising notification handler is logged, not propagated to data_received."""
610
611 def bad_handler(_value: bytearray) -> None:
612 msg = "boom"
613 raise ValueError(msg)
614
615 peer = FakePeer()
616 peer.client.set_notify_handler(0x0003, bad_handler)
617 with caplog.at_level("ERROR", logger="habluetooth.channels.att"):
618 # Must not raise out of data_received.
619 peer.client.data_received(
620 bytes([ATT_HANDLE_VALUE_NTF]) + (0x0003).to_bytes(2, "little") + b"\x10"
621 )
622 assert "Error in notification handler" in caplog.text
623
624
625 async def test_indication_handler_exception_still_confirms() -> None:
626 """A raising indication handler does not block the confirmation."""
627
628 def bad_handler(_value: bytearray) -> None:
629 msg = "boom"
630 raise ValueError(msg)
631
632 peer = FakePeer()
633 peer.client.set_notify_handler(0x0005, bad_handler)
634 peer.client.data_received(
635 bytes([ATT_HANDLE_VALUE_IND]) + (0x0005).to_bytes(2, "little") + b"\x99"
636 )
637 await asyncio.sleep(0)
638 assert peer.sent == [bytes([ATT_HANDLE_VALUE_CFM])]
639
640
641 @pytest.mark.parametrize(
642 ("call", "empty_response"),
643 [
644 (
645 lambda c: c.read_by_group_type(0x0001, 0xFFFF, b"\x00\x28"),
646 bytes([ATT_READ_BY_GROUP_TYPE_RSP, 6]), # valid stride, no entries
647 ),
648 (
649 lambda c: c.read_by_type(0x0001, 0xFFFF, b"\x03\x28"),
650 bytes([ATT_READ_BY_TYPE_RSP, 7]),
651 ),
652 (
653 lambda c: c.find_information(0x0001, 0xFFFF),
654 bytes([ATT_FIND_INFO_RSP, 0x01]),
655 ),
656 ],
657 )
658 async def test_discovery_rejects_entryless_response(
659 call: Callable[[ATTClient], Awaitable[list[object]]],
660 empty_response: bytes,
661 ) -> None:
662 """An entry-less response is rejected, not treated as a silent partial stop."""
663 peer = FakePeer(lambda _req: empty_response)
664 with pytest.raises(BleakError, match="truncated entries"):
665 await call(peer.client)
666 # Exactly one request; the loop neither re-requests nor returns partial data.
667 assert len(peer.sent) == 1
668
669
670 @pytest.mark.parametrize(
671 ("call", "partial_response"),
672 [
673 (
674 lambda c: c.read_by_group_type(0x0001, 0xFFFF, b"\x00\x28"),
675 # stride 6: one full entry plus a 2 byte trailing partial.
676 bytes([ATT_READ_BY_GROUP_TYPE_RSP, 6])
677 + b"\x01\x00\x05\x00\x0f\x18"
678 + b"\x06\x00",
679 ),
680 (
681 lambda c: c.read_by_type(0x0001, 0xFFFF, b"\x03\x28"),
682 # stride 7: one full entry plus a 3 byte trailing partial.
683 bytes([ATT_READ_BY_TYPE_RSP, 7])
684 + b"\x02\x00\x02\x03\x00\x0f\x18"
685 + b"\x04\x00\x02",
686 ),
687 (
688 lambda c: c.find_information(0x0001, 0xFFFF),
689 # entry size 4: one full entry plus a 2 byte trailing partial.
690 bytes([ATT_FIND_INFO_RSP, 0x01]) + b"\x04\x00\x02\x29" + b"\x05\x00",
691 ),
692 ],
693 )
694 async def test_discovery_rejects_trailing_partial_entry(
695 call: Callable[[ATTClient], Awaitable[list[object]]],
696 partial_response: bytes,
697 ) -> None:
698 """A body that is not a whole multiple of the stride is rejected."""
699 peer = FakePeer(lambda _req: partial_response)
700 with pytest.raises(BleakError, match="truncated entries"):
701 await call(peer.client)
702 assert len(peer.sent) == 1
703
704
705 async def test_exchange_mtu_rejects_truncated_response() -> None:
706 """A truncated MTU response raises rather than negotiating off a stray byte."""
707 peer = FakePeer(lambda _req: bytes([ATT_EXCHANGE_MTU_RSP, 0x10])) # 2 bytes
708 with pytest.raises(BleakError, match="truncated ATT MTU response"):
709 await peer.client.exchange_mtu(247)
710
711
712 async def test_timeout_poisons_channel() -> None:
713 """A request timeout closes the channel so a late response can't desync it."""
714 disconnects: list[Exception | None] = []
715 peer = FakePeer() # no responder: the request times out
716 client = ATTClient(peer.send, on_disconnect=disconnects.append)
717 with (
718 patch("habluetooth.channels.att.ATT_TIMEOUT", 0.01),
719 pytest.raises(BleakError, match="timed out"),
720 ):
721 await client.read(0x0010)
722 assert len(disconnects) == 1
723
724 # The channel is poisoned: requests and write commands fail fast without
725 # sending, so a write command does not hand a PDU to a dead socket.
726 sent_before = len(peer.sent)
727 with pytest.raises(BleakError, match="ATT channel closed"):
728 await client.read(0x0011)
729 with pytest.raises(BleakError, match="ATT channel closed"):
730 await client.write_command(0x0011, b"\x01")
731 assert len(peer.sent) == sent_before
732
733 # A subsequent connection_lost does not notify a second time.
734 client.connection_lost(None)
735 assert len(disconnects) == 1
736
737
738 async def test_poisoned_channel_drops_inbound_pdus() -> None:
739 """A poisoned channel drops late notifications and skips indication confirms."""
740 received: list[bytearray] = []
741 peer = FakePeer() # no responder: the request times out
742 peer.client.set_notify_handler(0x0005, received.append)
743 with (
744 patch("habluetooth.channels.att.ATT_TIMEOUT", 0.01),
745 pytest.raises(BleakError, match="timed out"),
746 ):
747 await peer.client.read(0x0010)
748
749 sent_before = len(peer.sent)
750 # A late notification is not delivered to the subscriber.
751 peer.client.data_received(bytes([ATT_HANDLE_VALUE_NTF, 0x05, 0x00, 0xAB]))
752 assert received == []
753 # A late indication is dropped without scheduling a confirmation send.
754 peer.client.data_received(bytes([ATT_HANDLE_VALUE_IND, 0x05, 0x00, 0xAB]))
755 await asyncio.sleep(0)
756 assert received == []
757 assert len(peer.sent) == sent_before
758
759
760 async def test_write_rejects_oversized_value() -> None:
761 """A write larger than mtu - 3 is rejected (no long-write support)."""
762 peer = FakePeer()
763 with pytest.raises(BleakError, match="value too long"):
764 await peer.client.write(0x0011, bytes(21)) # default mtu 23 -> max 20
765 assert peer.sent == []
766
767
768 async def test_write_command_rejects_oversized_value() -> None:
769 """A write command larger than mtu - 3 is rejected."""
770 peer = FakePeer()
771 with pytest.raises(BleakError, match="value too long"):
772 await peer.client.write_command(0x0011, bytes(21))
773 assert peer.sent == []
774
775
776 async def test_read_caps_value_at_offset_range() -> None:
777 """An always-full long read is capped instead of overflowing the offset."""
778 full = bytes(range(22)) # a full chunk (mtu - 1) every time, never terminating
779
780 def responder(req: bytes) -> bytes:
781 if req[0] == 0x0A: # ATT_READ_REQ
782 return bytes([ATT_READ_RSP]) + full
783 return bytes([ATT_READ_BLOB_RSP]) + full
784
785 peer = FakePeer(responder)
786 with pytest.raises(BleakError, match="exceeds the 16-bit"):
787 await peer.client.read(0x0010)
788
789
790 async def test_truncated_notification_is_dropped() -> None:
791 """A notification PDU too short to carry a handle is dropped, not fabricated."""
792 peer = FakePeer()
793 received: list[bytearray] = []
794 peer.client.set_notify_handler(0x0005, received.append)
795 # opcode + a single handle byte: too short to carry a 2-byte handle.
796 peer.client.data_received(bytes([ATT_HANDLE_VALUE_NTF, 0x05]))
797 assert received == []
798
799
800 async def test_truncated_indication_is_dropped() -> None:
801 """A truncated indication is dropped and not confirmed."""
802 peer = FakePeer()
803 peer.client.data_received(bytes([ATT_HANDLE_VALUE_IND, 0x05]))
804 await asyncio.sleep(0)
805 assert peer.sent == [] # no CFM sent for a malformed PDU