| 1 |
"""Tests for the kernel/L2CAP GATT client backend.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import asyncio |
| 6 |
import logging |
| 7 |
from contextlib import contextmanager |
| 8 |
from typing import TYPE_CHECKING |
| 9 |
from unittest.mock import patch |
| 10 |
|
| 11 |
import pytest |
| 12 |
from bleak import BleakError |
| 13 |
from bleak.backends.device import BLEDevice |
| 14 |
|
| 15 |
from habluetooth.channels.att import ( |
| 16 |
ATT_ERR_INSUFFICIENT_AUTHENTICATION, |
| 17 |
ATT_ERR_INSUFFICIENT_ENCRYPTION, |
| 18 |
) |
| 19 |
from habluetooth.channels.bluez import ( |
| 20 |
AuthenticationFailed, |
| 21 |
LongTermKey, |
| 22 |
NewLongTermKey, |
| 23 |
UserConfirmationRequest, |
| 24 |
UserPasskeyRequest, |
| 25 |
) |
| 26 |
from habluetooth.channels.l2cap import ( |
| 27 |
BT_SECURITY_HIGH, |
| 28 |
BT_SECURITY_LOW, |
| 29 |
BT_SECURITY_MEDIUM, |
| 30 |
) |
| 31 |
from habluetooth.client_mgmt import HaMgmtClient, MgmtClientData |
| 32 |
from habluetooth.const import BDADDR_LE_RANDOM |
| 33 |
|
| 34 |
if TYPE_CHECKING: |
| 35 |
from collections.abc import Callable, Generator |
| 36 |
|
| 37 |
from bleak.backends.characteristic import BleakGATTCharacteristic |
| 38 |
|
| 39 |
_CHAR_UUID = "00002a37-0000-1000-8000-00805f9b34fb" |
| 40 |
_SERVICE_UUID = "0000180d-0000-1000-8000-00805f9b34fb" |
| 41 |
_CCCD_DESC_UUID = "00002902-0000-1000-8000-00805f9b34fb" |
| 42 |
|
| 43 |
pytestmark = pytest.mark.asyncio |
| 44 |
|
| 45 |
_ADAPTER = "00:11:22:33:44:55" |
| 46 |
_PEER = "AA:BB:CC:DD:EE:FF" |
| 47 |
|
| 48 |
# Opcodes used to build server responses. |
| 49 |
_ERROR_RSP = 0x01 |
| 50 |
_MTU_RSP = 0x03 |
| 51 |
_FIND_INFO_RSP = 0x05 |
| 52 |
_READ_BY_TYPE_RSP = 0x09 |
| 53 |
_READ_RSP = 0x0B |
| 54 |
_READ_BY_GROUP_TYPE_RSP = 0x11 |
| 55 |
_WRITE_RSP = 0x13 |
| 56 |
_NTF = 0x1B |
| 57 |
_ERR_ATTRIBUTE_NOT_FOUND = 0x0A |
| 58 |
|
| 59 |
# Discovered layout: heart-rate service 0x180D with one characteristic 0x2A37 |
| 60 |
# (value handle 0x0003) and, when present, a CCCD at 0x0004. |
| 61 |
_CHAR_READ_NOTIFY = 0x12 |
| 62 |
_VALUE = b"\x01\x02\x03" |
| 63 |
|
| 64 |
|
| 65 |
def _error(req_opcode: int, handle: int, code: int) -> bytes: |
| 66 |
return ( |
| 67 |
bytes([_ERROR_RSP, req_opcode]) + handle.to_bytes(2, "little") + bytes([code]) |
| 68 |
) |
| 69 |
|
| 70 |
|
| 71 |
def make_responder( |
| 72 |
char_props: int = _CHAR_READ_NOTIFY, |
| 73 |
*, |
| 74 |
has_cccd: bool = True, |
| 75 |
fail_write: bool = False, |
| 76 |
) -> Callable[[bytes], bytes | None]: |
| 77 |
"""Build a minimal ATT server for one service/characteristic.""" |
| 78 |
svc_end = 0x0004 if has_cccd else 0x0003 |
| 79 |
|
| 80 |
def services(req: bytes) -> bytes: # READ_BY_GROUP_TYPE_REQ |
| 81 |
if int.from_bytes(req[1:3], "little") > 0x0001: |
| 82 |
return _error(0x10, 0x0001, _ERR_ATTRIBUTE_NOT_FOUND) |
| 83 |
entry = ( |
| 84 |
(0x0001).to_bytes(2, "little") |
| 85 |
+ svc_end.to_bytes(2, "little") |
| 86 |
+ (0x180D).to_bytes(2, "little") |
| 87 |
) |
| 88 |
return bytes([_READ_BY_GROUP_TYPE_RSP, len(entry)]) + entry |
| 89 |
|
| 90 |
def characteristics(req: bytes) -> bytes: # READ_BY_TYPE_REQ |
| 91 |
if int.from_bytes(req[1:3], "little") > 0x0002: |
| 92 |
return _error(0x08, 0x0002, _ERR_ATTRIBUTE_NOT_FOUND) |
| 93 |
value = ( |
| 94 |
bytes([char_props]) |
| 95 |
+ (0x0003).to_bytes(2, "little") |
| 96 |
+ (0x2A37).to_bytes(2, "little") |
| 97 |
) |
| 98 |
entry = (0x0002).to_bytes(2, "little") + value |
| 99 |
return bytes([_READ_BY_TYPE_RSP, len(entry)]) + entry |
| 100 |
|
| 101 |
def descriptors(req: bytes) -> bytes: # FIND_INFORMATION_REQ |
| 102 |
if int.from_bytes(req[1:3], "little") > 0x0004: |
| 103 |
return _error(0x04, 0x0004, _ERR_ATTRIBUTE_NOT_FOUND) |
| 104 |
entry = (0x0004).to_bytes(2, "little") + (0x2902).to_bytes(2, "little") |
| 105 |
return bytes([_FIND_INFO_RSP, 0x01]) + entry |
| 106 |
|
| 107 |
write_rsp = ( |
| 108 |
_error(0x12, 0x0004, 0x03) if fail_write else bytes([_WRITE_RSP]) |
| 109 |
) # WRITE_REQ: an error (write not permitted) or success |
| 110 |
handlers: dict[int, Callable[[bytes], bytes | None]] = { |
| 111 |
0x02: lambda _req: bytes([_MTU_RSP]) + (247).to_bytes(2, "little"), |
| 112 |
0x10: services, |
| 113 |
0x08: characteristics, |
| 114 |
0x04: descriptors, |
| 115 |
0x0A: lambda _req: bytes([_READ_RSP]) + _VALUE, # READ_REQ |
| 116 |
0x12: lambda _req: write_rsp, |
| 117 |
0x52: lambda _req: None, # WRITE_CMD (no response) |
| 118 |
} |
| 119 |
|
| 120 |
def responder(req: bytes) -> bytes | None: |
| 121 |
if (handler := handlers.get(req[0])) is None: |
| 122 |
msg = f"unexpected request opcode 0x{req[0]:02x}" |
| 123 |
raise AssertionError(msg) |
| 124 |
return handler(req) |
| 125 |
|
| 126 |
return responder |
| 127 |
|
| 128 |
|
| 129 |
class FakeTransport: |
| 130 |
"""Stand-in for L2CAPSocket that answers ATT PDUs from a responder.""" |
| 131 |
|
| 132 |
def __init__( |
| 133 |
self, |
| 134 |
responder: Callable[[bytes], bytes | None], |
| 135 |
on_data: Callable[[bytes], None], |
| 136 |
on_close: Callable[[Exception | None], None], |
| 137 |
) -> None: |
| 138 |
self._responder = responder |
| 139 |
self._on_data = on_data |
| 140 |
self._on_close = on_close |
| 141 |
self.sent: list[bytes] = [] |
| 142 |
self.closed = False |
| 143 |
self.security_level = BT_SECURITY_LOW |
| 144 |
self.security_requests: list[int] = [] |
| 145 |
|
| 146 |
def set_security_level(self, level: int) -> bool: |
| 147 |
"""Raise the tracked security level, never lowering it.""" |
| 148 |
self.security_requests.append(level) |
| 149 |
if level <= self.security_level: |
| 150 |
return False |
| 151 |
self.security_level = level |
| 152 |
return True |
| 153 |
|
| 154 |
async def send(self, data: bytes) -> None: |
| 155 |
self.sent.append(bytes(data)) |
| 156 |
if (resp := self._responder(bytes(data))) is not None: |
| 157 |
self._on_data(resp) |
| 158 |
|
| 159 |
def close(self) -> None: |
| 160 |
self.closed = True |
| 161 |
|
| 162 |
def inject(self, data: bytes) -> None: |
| 163 |
"""Simulate a server-initiated PDU (e.g. a notification).""" |
| 164 |
self._on_data(data) |
| 165 |
|
| 166 |
def drop(self, exc: Exception | None = None) -> None: |
| 167 |
"""Simulate an unexpected transport failure.""" |
| 168 |
self._on_close(exc) |
| 169 |
|
| 170 |
|
| 171 |
class FakeScanner: |
| 172 |
"""Minimal scanner exposing the connecting() pause context manager.""" |
| 173 |
|
| 174 |
def __init__(self) -> None: |
| 175 |
self.connecting_calls = 0 |
| 176 |
|
| 177 |
@contextmanager |
| 178 |
def connecting(self) -> Generator[None, None, None]: |
| 179 |
self.connecting_calls += 1 |
| 180 |
yield |
| 181 |
|
| 182 |
|
| 183 |
def _ble_device() -> BLEDevice: |
| 184 |
return BLEDevice( |
| 185 |
_PEER, |
| 186 |
"test-device", |
| 187 |
{"source": _ADAPTER, "address_type": BDADDR_LE_RANDOM}, |
| 188 |
) |
| 189 |
|
| 190 |
|
| 191 |
@contextmanager |
| 192 |
def _patch_transport( |
| 193 |
responder: Callable[[bytes], bytes | None], |
| 194 |
holder: dict[str, FakeTransport], |
| 195 |
) -> Generator[None, None, None]: |
| 196 |
async def fake_create_connection( |
| 197 |
*, |
| 198 |
on_data: Callable[[bytes], None], |
| 199 |
on_close: Callable[[Exception | None], None], |
| 200 |
**_kwargs: object, |
| 201 |
) -> FakeTransport: |
| 202 |
transport = FakeTransport(responder, on_data, on_close) |
| 203 |
holder["transport"] = transport |
| 204 |
return transport |
| 205 |
|
| 206 |
with patch( |
| 207 |
"habluetooth.client_mgmt.L2CAPSocket.create_connection", |
| 208 |
fake_create_connection, |
| 209 |
): |
| 210 |
yield |
| 211 |
|
| 212 |
|
| 213 |
def _make_client( |
| 214 |
disconnected_callback: Callable[[], None] | None = None, |
| 215 |
) -> tuple[HaMgmtClient, FakeScanner]: |
| 216 |
scanner = FakeScanner() |
| 217 |
client = HaMgmtClient( |
| 218 |
_ble_device(), |
| 219 |
client_data=MgmtClientData(adapter_address=_ADAPTER, scanner=scanner), |
| 220 |
timeout=5.0, |
| 221 |
disconnected_callback=disconnected_callback, |
| 222 |
) |
| 223 |
return client, scanner |
| 224 |
|
| 225 |
|
| 226 |
async def _connect( |
| 227 |
holder: dict[str, FakeTransport], |
| 228 |
responder: Callable[[bytes], bytes | None] | None = None, |
| 229 |
disconnected_callback: Callable[[], None] | None = None, |
| 230 |
) -> tuple[HaMgmtClient, FakeScanner]: |
| 231 |
client, scanner = _make_client(disconnected_callback) |
| 232 |
with _patch_transport(responder or make_responder(), holder): |
| 233 |
await client.connect(False) |
| 234 |
return client, scanner |
| 235 |
|
| 236 |
|
| 237 |
def _char(client: HaMgmtClient) -> BleakGATTCharacteristic: |
| 238 |
"""Return the discovered 0x2A37 characteristic (asserts it was discovered).""" |
| 239 |
assert client.services is not None |
| 240 |
char = client.services.get_characteristic(_CHAR_UUID) |
| 241 |
assert char is not None |
| 242 |
return char |
| 243 |
|
| 244 |
|
| 245 |
# -- connect / discover --------------------------------------------------- |
| 246 |
async def test_connect_discovers_services() -> None: |
| 247 |
"""Connect opens the channel, exchanges MTU, and builds the GATT tree.""" |
| 248 |
holder: dict[str, FakeTransport] = {} |
| 249 |
client, scanner = await _connect(holder) |
| 250 |
assert client.is_connected is True |
| 251 |
assert client.mtu_size == 247 |
| 252 |
assert scanner.connecting_calls == 1 |
| 253 |
services = client.services |
| 254 |
assert services is not None |
| 255 |
assert services.get_service(_SERVICE_UUID) is not None |
| 256 |
char = _char(client) |
| 257 |
assert char.handle == 0x0003 # value handle drives operations |
| 258 |
assert "notify" in char.properties |
| 259 |
assert char.get_descriptor(_CCCD_DESC_UUID) is not None |
| 260 |
assert char.max_write_without_response_size == 244 # MTU 247 - 3 |
| 261 |
|
| 262 |
|
| 263 |
async def test_connect_rejects_when_already_connected() -> None: |
| 264 |
"""A second connect on a live client raises rather than re-linking.""" |
| 265 |
holder: dict[str, FakeTransport] = {} |
| 266 |
client, _scanner = await _connect(holder) |
| 267 |
with pytest.raises(BleakError, match="already connected"): |
| 268 |
await client.connect(False) |
| 269 |
|
| 270 |
|
| 271 |
async def test_connect_pair_true_without_mgmt_skips_bond() -> None: |
| 272 |
"""connect(pair=True) with no mgmt wired still connects, skipping the bond.""" |
| 273 |
holder: dict[str, FakeTransport] = {} |
| 274 |
client, _scanner = _make_client() # no mgmt wired |
| 275 |
with _patch_transport(make_responder(), holder): |
| 276 |
await client.connect(True) |
| 277 |
assert client.is_connected is True |
| 278 |
|
| 279 |
|
| 280 |
async def test_connect_failure_tears_down() -> None: |
| 281 |
"""A transport failure during connect leaves the client disconnected.""" |
| 282 |
client, _scanner = _make_client() |
| 283 |
|
| 284 |
async def boom(**_kwargs: object) -> FakeTransport: |
| 285 |
raise OSError(113, "No route to host") |
| 286 |
|
| 287 |
with ( |
| 288 |
patch("habluetooth.client_mgmt.L2CAPSocket.create_connection", boom), |
| 289 |
pytest.raises(OSError, match="No route to host"), |
| 290 |
): |
| 291 |
await client.connect(False) |
| 292 |
assert client.is_connected is False |
| 293 |
assert client.mtu_size == 23 |
| 294 |
|
| 295 |
|
| 296 |
# -- GATT operations ------------------------------------------------------ |
| 297 |
async def test_read_gatt_char() -> None: |
| 298 |
"""Reading a characteristic returns the value as a bytearray.""" |
| 299 |
holder: dict[str, FakeTransport] = {} |
| 300 |
client, _scanner = await _connect(holder) |
| 301 |
assert await client.read_gatt_char(_char(client)) == bytearray(_VALUE) |
| 302 |
|
| 303 |
|
| 304 |
async def test_read_gatt_descriptor() -> None: |
| 305 |
"""Reading a descriptor returns the value as a bytearray.""" |
| 306 |
holder: dict[str, FakeTransport] = {} |
| 307 |
client, _scanner = await _connect(holder) |
| 308 |
cccd = _char(client).get_descriptor(_CCCD_DESC_UUID) |
| 309 |
assert cccd is not None |
| 310 |
assert await client.read_gatt_descriptor(cccd) == bytearray(_VALUE) |
| 311 |
|
| 312 |
|
| 313 |
async def test_write_gatt_char_with_response() -> None: |
| 314 |
"""A write with response uses a Write Request.""" |
| 315 |
holder: dict[str, FakeTransport] = {} |
| 316 |
client, _scanner = await _connect(holder) |
| 317 |
await client.write_gatt_char(_char(client), b"\xaa", response=True) |
| 318 |
assert holder["transport"].sent[-1] == b"\x12\x03\x00\xaa" # WRITE_REQ |
| 319 |
|
| 320 |
|
| 321 |
async def test_write_gatt_char_without_response() -> None: |
| 322 |
"""A write without response uses a Write Command (no reply expected).""" |
| 323 |
holder: dict[str, FakeTransport] = {} |
| 324 |
client, _scanner = await _connect(holder) |
| 325 |
await client.write_gatt_char(_char(client), b"\xbb", response=False) |
| 326 |
assert holder["transport"].sent[-1] == b"\x52\x03\x00\xbb" # WRITE_CMD |
| 327 |
|
| 328 |
|
| 329 |
async def test_write_gatt_descriptor() -> None: |
| 330 |
"""Writing a descriptor uses a Write Request against its handle.""" |
| 331 |
holder: dict[str, FakeTransport] = {} |
| 332 |
client, _scanner = await _connect(holder) |
| 333 |
cccd = _char(client).get_descriptor(_CCCD_DESC_UUID) |
| 334 |
assert cccd is not None |
| 335 |
await client.write_gatt_descriptor(cccd, b"\x01\x00") |
| 336 |
assert holder["transport"].sent[-1] == b"\x12\x04\x00\x01\x00" |
| 337 |
|
| 338 |
|
| 339 |
# -- security escalation -------------------------------------------------- |
| 340 |
async def test_read_escalates_security_then_succeeds() -> None: |
| 341 |
"""A read rejected for encryption raises link security and retries once.""" |
| 342 |
holder: dict[str, FakeTransport] = {} |
| 343 |
base = make_responder() |
| 344 |
attempts = 0 |
| 345 |
|
| 346 |
def responder(req: bytes) -> bytes | None: |
| 347 |
nonlocal attempts |
| 348 |
if req[0] == 0x0A: # READ_REQ |
| 349 |
attempts += 1 |
| 350 |
if attempts == 1: |
| 351 |
handle = int.from_bytes(req[1:3], "little") |
| 352 |
return _error(0x0A, handle, ATT_ERR_INSUFFICIENT_ENCRYPTION) |
| 353 |
return base(req) |
| 354 |
|
| 355 |
client, _scanner = await _connect(holder, responder) |
| 356 |
assert await client.read_gatt_char(_char(client)) == bytearray(_VALUE) |
| 357 |
assert holder["transport"].security_requests == [BT_SECURITY_MEDIUM] |
| 358 |
assert holder["transport"].security_level == BT_SECURITY_MEDIUM |
| 359 |
|
| 360 |
|
| 361 |
async def test_escalate_security_steps_up_on_authentication() -> None: |
| 362 |
"""Insufficient authentication steps the level up one, capped at HIGH.""" |
| 363 |
client, _scanner = _make_client() |
| 364 |
transport = FakeTransport(make_responder(), lambda _d: None, lambda _e: None) |
| 365 |
transport.security_level = BT_SECURITY_MEDIUM |
| 366 |
client._sock = transport # type: ignore[assignment] |
| 367 |
assert client._escalate_security(ATT_ERR_INSUFFICIENT_AUTHENTICATION) is True |
| 368 |
assert transport.security_level == BT_SECURITY_HIGH |
| 369 |
# The kernel exposes nothing above HIGH, so a further step declines. |
| 370 |
assert client._escalate_security(ATT_ERR_INSUFFICIENT_AUTHENTICATION) is False |
| 371 |
assert transport.security_level == BT_SECURITY_HIGH |
| 372 |
|
| 373 |
|
| 374 |
async def test_escalate_security_declines_when_already_encrypted() -> None: |
| 375 |
"""An encryption error at MEDIUM cannot be satisfied by encryption again.""" |
| 376 |
client, _scanner = _make_client() |
| 377 |
transport = FakeTransport(make_responder(), lambda _d: None, lambda _e: None) |
| 378 |
transport.security_level = BT_SECURITY_MEDIUM |
| 379 |
client._sock = transport # type: ignore[assignment] |
| 380 |
assert client._escalate_security(ATT_ERR_INSUFFICIENT_ENCRYPTION) is False |
| 381 |
assert transport.security_level == BT_SECURITY_MEDIUM |
| 382 |
|
| 383 |
|
| 384 |
# -- notifications -------------------------------------------------------- |
| 385 |
async def test_start_notify_writes_cccd_and_routes() -> None: |
| 386 |
"""start_notify writes the notify CCCD and delivers inbound notifications.""" |
| 387 |
holder: dict[str, FakeTransport] = {} |
| 388 |
client, _scanner = await _connect(holder) |
| 389 |
received: list[bytearray] = [] |
| 390 |
await client.start_notify(_char(client), received.append) |
| 391 |
assert holder["transport"].sent[-1] == b"\x12\x04\x00\x01\x00" # CCCD notify |
| 392 |
holder["transport"].inject(bytes([_NTF]) + (0x0003).to_bytes(2, "little") + b"\x09") |
| 393 |
assert received == [bytearray(b"\x09")] |
| 394 |
|
| 395 |
|
| 396 |
async def test_start_notify_uses_indicate_when_only_indicate() -> None: |
| 397 |
"""An indicate-only characteristic gets the indicate CCCD value.""" |
| 398 |
holder: dict[str, FakeTransport] = {} |
| 399 |
client, _scanner = await _connect(holder, make_responder(0x20)) # indicate only |
| 400 |
await client.start_notify(_char(client), lambda _d: None) |
| 401 |
assert holder["transport"].sent[-1] == b"\x12\x04\x00\x02\x00" # CCCD indicate |
| 402 |
|
| 403 |
|
| 404 |
async def test_start_notify_rejects_unsupported_characteristic() -> None: |
| 405 |
"""A characteristic without notify/indicate cannot be subscribed.""" |
| 406 |
holder: dict[str, FakeTransport] = {} |
| 407 |
client, _scanner = await _connect(holder, make_responder(0x02)) # read only |
| 408 |
with pytest.raises(BleakError, match="notify or indicate"): |
| 409 |
await client.start_notify(_char(client), lambda _d: None) |
| 410 |
|
| 411 |
|
| 412 |
async def test_start_notify_rejects_missing_cccd() -> None: |
| 413 |
"""A notifying characteristic with no CCCD descriptor is rejected.""" |
| 414 |
holder: dict[str, FakeTransport] = {} |
| 415 |
client, _scanner = await _connect(holder, make_responder(has_cccd=False)) |
| 416 |
with pytest.raises(BleakError, match="client configuration descriptor"): |
| 417 |
await client.start_notify(_char(client), lambda _d: None) |
| 418 |
|
| 419 |
|
| 420 |
async def test_stop_notify_clears_cccd_and_handler() -> None: |
| 421 |
"""stop_notify clears the CCCD and stops routing notifications.""" |
| 422 |
holder: dict[str, FakeTransport] = {} |
| 423 |
client, _scanner = await _connect(holder) |
| 424 |
char = _char(client) |
| 425 |
received: list[bytearray] = [] |
| 426 |
await client.start_notify(char, received.append) |
| 427 |
await client.stop_notify(char) |
| 428 |
assert holder["transport"].sent[-1] == b"\x12\x04\x00\x00\x00" # CCCD off |
| 429 |
holder["transport"].inject(bytes([_NTF]) + (0x0003).to_bytes(2, "little") + b"\x09") |
| 430 |
assert received == [] # handler removed, notification dropped |
| 431 |
|
| 432 |
|
| 433 |
async def test_start_notify_unwinds_handler_on_cccd_write_failure() -> None: |
| 434 |
"""If the CCCD write fails, no notify handler is left registered.""" |
| 435 |
holder: dict[str, FakeTransport] = {} |
| 436 |
client, _scanner = await _connect(holder, make_responder(fail_write=True)) |
| 437 |
char = _char(client) |
| 438 |
received: list[bytearray] = [] |
| 439 |
with pytest.raises(BleakError): |
| 440 |
await client.start_notify(char, received.append) |
| 441 |
# The handler was unwound, so a stray notification is not delivered. |
| 442 |
holder["transport"].inject(bytes([_NTF]) + (0x0003).to_bytes(2, "little") + b"\x09") |
| 443 |
assert received == [] |
| 444 |
|
| 445 |
|
| 446 |
async def test_stop_notify_drops_handler_when_cccd_write_fails() -> None: |
| 447 |
"""A failed CCCD-off write still drops the handler, then surfaces the error.""" |
| 448 |
holder: dict[str, FakeTransport] = {} |
| 449 |
fail = {"on": False} |
| 450 |
base = make_responder() |
| 451 |
|
| 452 |
def responder(req: bytes) -> bytes | None: |
| 453 |
if req[0] == 0x12 and fail["on"]: # WRITE_REQ |
| 454 |
return _error(0x12, int.from_bytes(req[1:3], "little"), 0x03) |
| 455 |
return base(req) |
| 456 |
|
| 457 |
client, _scanner = await _connect(holder, responder) |
| 458 |
char = _char(client) |
| 459 |
received: list[bytearray] = [] |
| 460 |
await client.start_notify(char, received.append) |
| 461 |
ntf = bytes([_NTF]) + (0x0003).to_bytes(2, "little") + b"\x09" |
| 462 |
holder["transport"].inject(ntf) |
| 463 |
assert received == [bytearray(b"\x09")] # handler is live |
| 464 |
fail["on"] = True |
| 465 |
with pytest.raises(BleakError): |
| 466 |
await client.stop_notify(char) |
| 467 |
holder["transport"].inject(ntf) |
| 468 |
assert received == [bytearray(b"\x09")] # handler dropped despite the failure |
| 469 |
|
| 470 |
|
| 471 |
async def test_stop_notify_without_cccd_only_drops_handler() -> None: |
| 472 |
"""stop_notify on a characteristic with no CCCD just drops the handler.""" |
| 473 |
holder: dict[str, FakeTransport] = {} |
| 474 |
client, _scanner = await _connect(holder, make_responder(has_cccd=False)) |
| 475 |
char = _char(client) |
| 476 |
before = len(holder["transport"].sent) |
| 477 |
await client.stop_notify(char) |
| 478 |
assert len(holder["transport"].sent) == before # no CCCD write attempted |
| 479 |
|
| 480 |
|
| 481 |
# -- disconnect / teardown ------------------------------------------------ |
| 482 |
async def test_disconnect_closes_transport() -> None: |
| 483 |
"""Disconnect closes the socket and reports not connected.""" |
| 484 |
holder: dict[str, FakeTransport] = {} |
| 485 |
client, _scanner = await _connect(holder) |
| 486 |
await client.disconnect() |
| 487 |
assert holder["transport"].closed is True |
| 488 |
assert client.is_connected is False |
| 489 |
|
| 490 |
|
| 491 |
async def test_connection_register_callbacks_fire() -> None: |
| 492 |
"""The client reports connect/disconnect to the scanner's slot callbacks.""" |
| 493 |
holder: dict[str, FakeTransport] = {} |
| 494 |
registered: list[str] = [] |
| 495 |
unregistered: list[str] = [] |
| 496 |
client = HaMgmtClient( |
| 497 |
_ble_device(), |
| 498 |
client_data=MgmtClientData( |
| 499 |
adapter_address=_ADAPTER, |
| 500 |
scanner=FakeScanner(), |
| 501 |
register_connection=registered.append, |
| 502 |
unregister_connection=unregistered.append, |
| 503 |
), |
| 504 |
timeout=5.0, |
| 505 |
) |
| 506 |
with _patch_transport(make_responder(), holder): |
| 507 |
await client.connect(False) |
| 508 |
assert registered == [_PEER] |
| 509 |
assert unregistered == [] |
| 510 |
await client.disconnect() |
| 511 |
assert unregistered == [_PEER] |
| 512 |
|
| 513 |
|
| 514 |
async def test_register_callback_failure_does_not_break_connect() -> None: |
| 515 |
"""A raising slot register callback is swallowed; the connection survives.""" |
| 516 |
holder: dict[str, FakeTransport] = {} |
| 517 |
|
| 518 |
def boom(_address: str) -> None: |
| 519 |
msg = "bookkeeping broke" |
| 520 |
raise RuntimeError(msg) |
| 521 |
|
| 522 |
client = HaMgmtClient( |
| 523 |
_ble_device(), |
| 524 |
client_data=MgmtClientData( |
| 525 |
adapter_address=_ADAPTER, |
| 526 |
scanner=FakeScanner(), |
| 527 |
register_connection=boom, |
| 528 |
), |
| 529 |
timeout=5.0, |
| 530 |
) |
| 531 |
with _patch_transport(make_responder(), holder): |
| 532 |
await client.connect(False) |
| 533 |
assert client.is_connected is True |
| 534 |
|
| 535 |
|
| 536 |
async def test_unregister_callback_failure_still_fires_disconnect() -> None: |
| 537 |
"""A raising slot unregister callback does not block the disconnect callback.""" |
| 538 |
holder: dict[str, FakeTransport] = {} |
| 539 |
fired: list[bool] = [] |
| 540 |
|
| 541 |
def boom(_address: str) -> None: |
| 542 |
msg = "bookkeeping broke" |
| 543 |
raise RuntimeError(msg) |
| 544 |
|
| 545 |
client = HaMgmtClient( |
| 546 |
_ble_device(), |
| 547 |
client_data=MgmtClientData( |
| 548 |
adapter_address=_ADAPTER, |
| 549 |
scanner=FakeScanner(), |
| 550 |
unregister_connection=boom, |
| 551 |
), |
| 552 |
timeout=5.0, |
| 553 |
disconnected_callback=lambda: fired.append(True), |
| 554 |
) |
| 555 |
with _patch_transport(make_responder(), holder): |
| 556 |
await client.connect(False) |
| 557 |
holder["transport"].drop(OSError("reset")) |
| 558 |
assert fired == [True] |
| 559 |
assert client.is_connected is False |
| 560 |
|
| 561 |
|
| 562 |
async def test_disconnect_fires_disconnected_callback() -> None: |
| 563 |
"""A deliberate disconnect fires the callback, matching the BlueZ backend.""" |
| 564 |
holder: dict[str, FakeTransport] = {} |
| 565 |
fired: list[bool] = [] |
| 566 |
client, _scanner = await _connect( |
| 567 |
holder, disconnected_callback=lambda: fired.append(True) |
| 568 |
) |
| 569 |
await client.disconnect() |
| 570 |
assert fired == [True] |
| 571 |
|
| 572 |
|
| 573 |
async def test_unexpected_drop_fires_disconnected_callback() -> None: |
| 574 |
"""A transport drop tears down the client and fires the bleak callback.""" |
| 575 |
holder: dict[str, FakeTransport] = {} |
| 576 |
fired: list[bool] = [] |
| 577 |
client, _scanner = await _connect( |
| 578 |
holder, disconnected_callback=lambda: fired.append(True) |
| 579 |
) |
| 580 |
holder["transport"].drop(OSError("reset")) |
| 581 |
assert fired == [True] |
| 582 |
assert client.is_connected is False |
| 583 |
|
| 584 |
|
| 585 |
async def test_unexpected_drop_logs_cause( |
| 586 |
caplog: pytest.LogCaptureFixture, |
| 587 |
) -> None: |
| 588 |
"""An unexpected drop logs the originating cause for diagnosability.""" |
| 589 |
holder: dict[str, FakeTransport] = {} |
| 590 |
_client, _scanner = await _connect(holder) |
| 591 |
with caplog.at_level(logging.DEBUG, logger="habluetooth.client_mgmt"): |
| 592 |
holder["transport"].drop(OSError("connection reset by peer")) |
| 593 |
assert "channel lost" in caplog.text |
| 594 |
assert "connection reset by peer" in caplog.text |
| 595 |
|
| 596 |
|
| 597 |
async def test_operations_raise_after_disconnect() -> None: |
| 598 |
"""GATT operations on a disconnected client raise a BleakError.""" |
| 599 |
holder: dict[str, FakeTransport] = {} |
| 600 |
client, _scanner = await _connect(holder) |
| 601 |
char = _char(client) |
| 602 |
await client.disconnect() |
| 603 |
with pytest.raises(BleakError, match="not connected"): |
| 604 |
await client.read_gatt_char(char) |
| 605 |
|
| 606 |
|
| 607 |
class FakeMgmt: |
| 608 |
"""Records the pairing/bond mgmt commands the client issues.""" |
| 609 |
|
| 610 |
def __init__( |
| 611 |
self, *, pair_ok: bool = True, load_ok: bool = True, unpair_ok: bool = True |
| 612 |
) -> None: |
| 613 |
self.pair_ok = pair_ok |
| 614 |
self.load_ok = load_ok |
| 615 |
self.unpair_ok = unpair_ok |
| 616 |
self.paired: list[tuple[int, str, int]] = [] |
| 617 |
self.unpaired: list[tuple[int, str]] = [] |
| 618 |
self.loaded: list[tuple[int, list[LongTermKey]]] = [] |
| 619 |
self.confirmations: list[tuple[int, str, int, bool]] = [] |
| 620 |
self.confirm_raises = False |
| 621 |
self.event_to_emit: object | None = None # delivered during pair_device |
| 622 |
self._handlers: dict[tuple[int, str], Callable[[object], None]] = {} |
| 623 |
|
| 624 |
async def user_confirmation_reply( |
| 625 |
self, idx: int, address: str, address_type: int, *, accept: bool = True |
| 626 |
) -> bool: |
| 627 |
if self.confirm_raises: |
| 628 |
msg = "reply failed" |
| 629 |
raise OSError(msg) |
| 630 |
self.confirmations.append((idx, address, address_type, accept)) |
| 631 |
return True |
| 632 |
|
| 633 |
def register_pairing_handler( |
| 634 |
self, idx: int, address: str, handler: Callable[[object], None] |
| 635 |
) -> Callable[[], None]: |
| 636 |
self._handlers[(idx, address)] = handler |
| 637 |
|
| 638 |
def _unregister() -> None: |
| 639 |
self._handlers.pop((idx, address), None) |
| 640 |
|
| 641 |
return _unregister |
| 642 |
|
| 643 |
async def pair_device( |
| 644 |
self, idx: int, address: str, address_type: int, *_a: object |
| 645 |
) -> bool: |
| 646 |
self.paired.append((idx, address, address_type)) |
| 647 |
if self.event_to_emit is not None: |
| 648 |
# Simulate the kernel pushing a pairing event during pairing. |
| 649 |
self._handlers[(idx, address)](self.event_to_emit) |
| 650 |
return self.pair_ok |
| 651 |
|
| 652 |
async def unpair_device( |
| 653 |
self, idx: int, address: str, address_type: int, **_k: object |
| 654 |
) -> bool: |
| 655 |
self.unpaired.append((idx, address)) |
| 656 |
return self.unpair_ok |
| 657 |
|
| 658 |
async def load_long_term_keys(self, idx: int, keys: list[LongTermKey]) -> bool: |
| 659 |
self.loaded.append((idx, list(keys))) |
| 660 |
return self.load_ok |
| 661 |
|
| 662 |
|
| 663 |
class _Store: |
| 664 |
"""An in-memory per-adapter long-term-key store for tests.""" |
| 665 |
|
| 666 |
def __init__(self, keys: list[LongTermKey] | None = None) -> None: |
| 667 |
self.keys: list[LongTermKey] = list(keys or []) |
| 668 |
|
| 669 |
def all(self) -> list[LongTermKey]: |
| 670 |
return list(self.keys) |
| 671 |
|
| 672 |
def add(self, key: LongTermKey) -> None: |
| 673 |
self.keys.append(key) |
| 674 |
|
| 675 |
def forget(self, address: str) -> None: |
| 676 |
self.keys = [key for key in self.keys if key.address != address] |
| 677 |
|
| 678 |
|
| 679 |
def _ltk(address: str = _PEER) -> LongTermKey: |
| 680 |
return LongTermKey( |
| 681 |
address, BDADDR_LE_RANDOM, 0x05, False, 16, 0x1234, bytes(8), bytes(16) |
| 682 |
) |
| 683 |
|
| 684 |
|
| 685 |
def _make_pairing_client( |
| 686 |
mgmt: FakeMgmt, |
| 687 |
store: _Store | None, |
| 688 |
*, |
| 689 |
adapter_idx: int | None = 0, |
| 690 |
) -> HaMgmtClient: |
| 691 |
return HaMgmtClient( |
| 692 |
_ble_device(), |
| 693 |
client_data=MgmtClientData( |
| 694 |
adapter_address=_ADAPTER, |
| 695 |
scanner=FakeScanner(), |
| 696 |
adapter_idx=adapter_idx, |
| 697 |
mgmt=mgmt, # type: ignore[arg-type] |
| 698 |
get_long_term_keys=store.all if store else None, |
| 699 |
add_long_term_key=store.add if store else None, |
| 700 |
forget_long_term_keys=store.forget if store else None, |
| 701 |
), |
| 702 |
timeout=5.0, |
| 703 |
) |
| 704 |
|
| 705 |
|
| 706 |
async def test_pair_captures_long_term_key() -> None: |
| 707 |
"""pair() issues PAIR_DEVICE and persists the captured key.""" |
| 708 |
mgmt = FakeMgmt() |
| 709 |
mgmt.event_to_emit = NewLongTermKey(1, _ltk()) |
| 710 |
store = _Store() |
| 711 |
client = _make_pairing_client(mgmt, store) |
| 712 |
await client.pair() |
| 713 |
assert mgmt.paired == [(0, _PEER, BDADDR_LE_RANDOM)] |
| 714 |
assert store.keys == [_ltk()] |
| 715 |
|
| 716 |
|
| 717 |
async def test_pair_ignores_zero_store_hint() -> None: |
| 718 |
"""A key the kernel asks not to persist (store_hint 0) is not stored.""" |
| 719 |
mgmt = FakeMgmt() |
| 720 |
mgmt.event_to_emit = NewLongTermKey(0, _ltk()) |
| 721 |
store = _Store() |
| 722 |
client = _make_pairing_client(mgmt, store) |
| 723 |
await client.pair() |
| 724 |
assert store.keys == [] |
| 725 |
|
| 726 |
|
| 727 |
async def test_pair_ignores_non_key_event() -> None: |
| 728 |
"""An AUTHENTICATION_FAILED event during pairing stores no key.""" |
| 729 |
mgmt = FakeMgmt(pair_ok=False) |
| 730 |
mgmt.event_to_emit = AuthenticationFailed(_PEER, BDADDR_LE_RANDOM, 0x05) |
| 731 |
store = _Store() |
| 732 |
client = _make_pairing_client(mgmt, store) |
| 733 |
with pytest.raises(BleakError, match="pairing failed"): |
| 734 |
await client.pair() |
| 735 |
assert store.keys == [] |
| 736 |
|
| 737 |
|
| 738 |
async def test_pair_warns_when_no_store_wired( |
| 739 |
caplog: pytest.LogCaptureFixture, |
| 740 |
) -> None: |
| 741 |
"""A captured key with no store wired is logged, not silently dropped.""" |
| 742 |
mgmt = FakeMgmt() |
| 743 |
mgmt.event_to_emit = NewLongTermKey(1, _ltk()) |
| 744 |
client = _make_pairing_client(mgmt, None) |
| 745 |
with caplog.at_level("WARNING", logger="habluetooth.client_mgmt"): |
| 746 |
await client.pair() |
| 747 |
assert "no key store" in caplog.text |
| 748 |
|
| 749 |
|
| 750 |
async def test_pair_failure_raises() -> None: |
| 751 |
"""A failed PAIR_DEVICE raises and captures no key.""" |
| 752 |
mgmt = FakeMgmt(pair_ok=False) |
| 753 |
store = _Store() |
| 754 |
client = _make_pairing_client(mgmt, store) |
| 755 |
with pytest.raises(BleakError, match="pairing failed"): |
| 756 |
await client.pair() |
| 757 |
assert store.keys == [] |
| 758 |
|
| 759 |
|
| 760 |
async def test_pair_requires_mgmt() -> None: |
| 761 |
"""Without the mgmt socket, pairing raises a clear error.""" |
| 762 |
client, _scanner = _make_client() # no mgmt/adapter_idx wired |
| 763 |
with pytest.raises(BleakError, match="requires the management socket"): |
| 764 |
await client.pair() |
| 765 |
with pytest.raises(BleakError, match="requires the management socket"): |
| 766 |
await client.unpair() |
| 767 |
|
| 768 |
|
| 769 |
async def test_pair_auto_confirms_just_works() -> None: |
| 770 |
"""A just-works confirm (confirm_hint set) is accepted so the bond proceeds.""" |
| 771 |
mgmt = FakeMgmt() |
| 772 |
mgmt.event_to_emit = UserConfirmationRequest(_PEER, BDADDR_LE_RANDOM, 1, 0) |
| 773 |
client = _make_pairing_client(mgmt, _Store()) |
| 774 |
await client.pair() |
| 775 |
# Let the scheduled reply task run. |
| 776 |
await asyncio.gather(*client._pairing_tasks) |
| 777 |
assert mgmt.confirmations == [(0, _PEER, BDADDR_LE_RANDOM, True)] |
| 778 |
|
| 779 |
|
| 780 |
async def test_pair_rejects_numeric_comparison() -> None: |
| 781 |
"""A real numeric comparison (confirm_hint 0) is rejected, not blindly confirmed.""" |
| 782 |
mgmt = FakeMgmt() |
| 783 |
mgmt.event_to_emit = UserConfirmationRequest(_PEER, BDADDR_LE_RANDOM, 0, 123456) |
| 784 |
client = _make_pairing_client(mgmt, _Store()) |
| 785 |
await client.pair() |
| 786 |
await asyncio.gather(*client._pairing_tasks) |
| 787 |
assert mgmt.confirmations == [(0, _PEER, BDADDR_LE_RANDOM, False)] |
| 788 |
|
| 789 |
|
| 790 |
async def test_pair_logs_failed_confirmation_reply( |
| 791 |
caplog: pytest.LogCaptureFixture, |
| 792 |
) -> None: |
| 793 |
"""A confirmation reply that fails to send is logged, not lost.""" |
| 794 |
mgmt = FakeMgmt() |
| 795 |
mgmt.confirm_raises = True |
| 796 |
mgmt.event_to_emit = UserConfirmationRequest(_PEER, BDADDR_LE_RANDOM, 0, 123456) |
| 797 |
client = _make_pairing_client(mgmt, _Store()) |
| 798 |
with caplog.at_level(logging.DEBUG, logger="habluetooth.client_mgmt"): |
| 799 |
await client.pair() |
| 800 |
await asyncio.gather(*client._pairing_tasks, return_exceptions=True) |
| 801 |
assert "pairing reply task failed" in caplog.text |
| 802 |
|
| 803 |
|
| 804 |
async def test_pair_ignores_passkey_request() -> None: |
| 805 |
"""A passkey request, unsatisfiable with NoInputNoOutput, is simply ignored.""" |
| 806 |
mgmt = FakeMgmt() |
| 807 |
mgmt.event_to_emit = UserPasskeyRequest(_PEER, BDADDR_LE_RANDOM) |
| 808 |
client = _make_pairing_client(mgmt, _Store()) |
| 809 |
await client.pair() # completes; the event is not acted on |
| 810 |
assert mgmt.confirmations == [] |
| 811 |
|
| 812 |
|
| 813 |
async def test_pair_fails_fast_on_auth_failed() -> None: |
| 814 |
"""An AUTH_FAILED event ends pairing before the mgmt command resolves.""" |
| 815 |
|
| 816 |
class _BlockingPairMgmt: |
| 817 |
"""A mgmt stand-in whose pair_device blocks until released.""" |
| 818 |
|
| 819 |
def __init__(self) -> None: |
| 820 |
self.started = asyncio.Event() |
| 821 |
self._release = asyncio.Event() |
| 822 |
self._handlers: dict[tuple[int, str], Callable[[object], None]] = {} |
| 823 |
|
| 824 |
def register_pairing_handler( |
| 825 |
self, idx: int, address: str, handler: Callable[[object], None] |
| 826 |
) -> Callable[[], None]: |
| 827 |
self._handlers[(idx, address)] = handler |
| 828 |
|
| 829 |
def _unregister() -> None: |
| 830 |
self._handlers.pop((idx, address), None) |
| 831 |
|
| 832 |
return _unregister |
| 833 |
|
| 834 |
async def pair_device( |
| 835 |
self, idx: int, address: str, address_type: int, *_a: object |
| 836 |
) -> bool: |
| 837 |
self.started.set() |
| 838 |
await self._release.wait() # never released in this test |
| 839 |
return True |
| 840 |
|
| 841 |
def deliver(self, idx: int, address: str, event: object) -> None: |
| 842 |
self._handlers[(idx, address)](event) |
| 843 |
|
| 844 |
mgmt = _BlockingPairMgmt() |
| 845 |
client = _make_pairing_client(mgmt, _Store()) # type: ignore[arg-type] |
| 846 |
task = asyncio.create_task(client.pair()) |
| 847 |
await mgmt.started.wait() |
| 848 |
mgmt.deliver(0, _PEER, AuthenticationFailed(_PEER, BDADDR_LE_RANDOM, 0x05)) |
| 849 |
with pytest.raises(BleakError, match="auth status 0x05"): |
| 850 |
await task |
| 851 |
|
| 852 |
|
| 853 |
async def test_connect_pair_true_bonds_when_mgmt_wired() -> None: |
| 854 |
"""connect(pair=True) with mgmt wired bonds as part of connecting.""" |
| 855 |
holder: dict[str, FakeTransport] = {} |
| 856 |
mgmt = FakeMgmt() |
| 857 |
mgmt.event_to_emit = NewLongTermKey(1, _ltk()) |
| 858 |
store = _Store() |
| 859 |
client = _make_pairing_client(mgmt, store) |
| 860 |
with _patch_transport(make_responder(), holder): |
| 861 |
await client.connect(True) |
| 862 |
assert client.is_connected is True |
| 863 |
assert mgmt.paired == [(0, _PEER, BDADDR_LE_RANDOM)] |
| 864 |
assert store.keys == [_ltk()] |
| 865 |
|
| 866 |
|
| 867 |
async def test_connect_pair_true_skips_rebond_when_already_bonded() -> None: |
| 868 |
"""connect(pair=True) on an already-bonded peer does not re-pair.""" |
| 869 |
holder: dict[str, FakeTransport] = {} |
| 870 |
mgmt = FakeMgmt() |
| 871 |
store = _Store([_ltk()]) # already bonded |
| 872 |
client = _make_pairing_client(mgmt, store) |
| 873 |
with _patch_transport(make_responder(), holder): |
| 874 |
await client.connect(True) |
| 875 |
assert client.is_connected is True |
| 876 |
assert mgmt.paired == [] # no redundant PAIR_DEVICE that would fail the connect |
| 877 |
|
| 878 |
|
| 879 |
async def test_connect_encrypts_proactively_for_bonded_peer() -> None: |
| 880 |
"""A reconnect with a stored key opens the socket at MEDIUM up front.""" |
| 881 |
captured: dict[str, int] = {} |
| 882 |
mgmt = FakeMgmt() |
| 883 |
store = _Store([_ltk()]) # a bond already exists for this peer |
| 884 |
client = _make_pairing_client(mgmt, store) |
| 885 |
base = make_responder() |
| 886 |
|
| 887 |
async def fake_create_connection( |
| 888 |
*, |
| 889 |
on_data: Callable[[bytes], None], |
| 890 |
on_close: Callable[[Exception | None], None], |
| 891 |
security_level: int, |
| 892 |
**_kwargs: object, |
| 893 |
) -> FakeTransport: |
| 894 |
captured["security_level"] = security_level |
| 895 |
transport = FakeTransport(base, on_data, on_close) |
| 896 |
transport.security_level = security_level |
| 897 |
return transport |
| 898 |
|
| 899 |
with patch( |
| 900 |
"habluetooth.client_mgmt.L2CAPSocket.create_connection", fake_create_connection |
| 901 |
): |
| 902 |
await client.connect(False) |
| 903 |
assert captured["security_level"] == BT_SECURITY_MEDIUM |
| 904 |
|
| 905 |
|
| 906 |
async def test_connect_unbonded_opens_low_security() -> None: |
| 907 |
"""With no stored key, the socket opens at LOW and escalates on demand.""" |
| 908 |
captured: dict[str, int] = {} |
| 909 |
mgmt = FakeMgmt() |
| 910 |
client = _make_pairing_client(mgmt, _Store()) # empty store |
| 911 |
base = make_responder() |
| 912 |
|
| 913 |
async def fake_create_connection( |
| 914 |
*, |
| 915 |
on_data: Callable[[bytes], None], |
| 916 |
on_close: Callable[[Exception | None], None], |
| 917 |
security_level: int, |
| 918 |
**_kwargs: object, |
| 919 |
) -> FakeTransport: |
| 920 |
captured["security_level"] = security_level |
| 921 |
return FakeTransport(base, on_data, on_close) |
| 922 |
|
| 923 |
with patch( |
| 924 |
"habluetooth.client_mgmt.L2CAPSocket.create_connection", fake_create_connection |
| 925 |
): |
| 926 |
await client.connect(False) |
| 927 |
assert captured["security_level"] == BT_SECURITY_LOW |
| 928 |
|
| 929 |
|
| 930 |
async def test_unpair_removes_bond() -> None: |
| 931 |
"""unpair() issues UNPAIR_DEVICE and forgets the stored key.""" |
| 932 |
mgmt = FakeMgmt() |
| 933 |
store = _Store([_ltk()]) |
| 934 |
client = _make_pairing_client(mgmt, store) |
| 935 |
await client.unpair() |
| 936 |
assert mgmt.unpaired == [(0, _PEER)] |
| 937 |
assert store.keys == [] |
| 938 |
|
| 939 |
|
| 940 |
async def test_unpair_without_store() -> None: |
| 941 |
"""unpair() works when no key store was wired.""" |
| 942 |
mgmt = FakeMgmt() |
| 943 |
client = _make_pairing_client(mgmt, None) |
| 944 |
await client.unpair() |
| 945 |
assert mgmt.unpaired == [(0, _PEER)] |
| 946 |
|
| 947 |
|
| 948 |
async def test_unpair_failure_keeps_stored_key() -> None: |
| 949 |
"""A failed UNPAIR_DEVICE raises and leaves the stored key in place.""" |
| 950 |
mgmt = FakeMgmt(unpair_ok=False) |
| 951 |
store = _Store([_ltk()]) |
| 952 |
client = _make_pairing_client(mgmt, store) |
| 953 |
with pytest.raises(BleakError, match="unpair failed"): |
| 954 |
await client.unpair() |
| 955 |
assert store.keys == [_ltk()] # not desynced from the controller |
| 956 |
|
| 957 |
|
| 958 |
async def test_connect_restores_all_adapter_bonds() -> None: |
| 959 |
"""connect() reloads every stored key (LOAD replaces the whole list).""" |
| 960 |
holder: dict[str, FakeTransport] = {} |
| 961 |
mgmt = FakeMgmt() |
| 962 |
other = LongTermKey( |
| 963 |
"11:22:33:44:55:66", |
| 964 |
BDADDR_LE_RANDOM, |
| 965 |
0x05, |
| 966 |
True, |
| 967 |
16, |
| 968 |
0x9999, |
| 969 |
bytes(8), |
| 970 |
bytes(16), |
| 971 |
) |
| 972 |
store = _Store([_ltk(), other]) |
| 973 |
client = _make_pairing_client(mgmt, store) |
| 974 |
with _patch_transport(make_responder(), holder): |
| 975 |
await client.connect(False) |
| 976 |
# All keys are sent, not just the connecting peer's, so other bonds survive. |
| 977 |
assert mgmt.loaded == [(0, [_ltk(), other])] |
| 978 |
|
| 979 |
|
| 980 |
async def test_connect_warns_when_restore_fails( |
| 981 |
caplog: pytest.LogCaptureFixture, |
| 982 |
) -> None: |
| 983 |
"""A failed key restore is logged rather than silently proceeding.""" |
| 984 |
holder: dict[str, FakeTransport] = {} |
| 985 |
mgmt = FakeMgmt(load_ok=False) |
| 986 |
store = _Store([_ltk()]) |
| 987 |
client = _make_pairing_client(mgmt, store) |
| 988 |
with ( |
| 989 |
_patch_transport(make_responder(), holder), |
| 990 |
caplog.at_level("WARNING", logger="habluetooth.client_mgmt"), |
| 991 |
): |
| 992 |
await client.connect(False) |
| 993 |
assert "failed to restore" in caplog.text |
| 994 |
|
| 995 |
|
| 996 |
async def test_connect_without_bond_loads_nothing() -> None: |
| 997 |
"""connect() does not load keys when nothing is bonded on the adapter.""" |
| 998 |
holder: dict[str, FakeTransport] = {} |
| 999 |
mgmt = FakeMgmt() |
| 1000 |
client = _make_pairing_client(mgmt, _Store()) |
| 1001 |
with _patch_transport(make_responder(), holder): |
| 1002 |
await client.connect(False) |
| 1003 |
assert mgmt.loaded == [] |
| 1004 |
|
| 1005 |
|
| 1006 |
async def test_mtu_size_default_before_connect() -> None: |
| 1007 |
"""Before connect the MTU reports the ATT default.""" |
| 1008 |
client, _scanner = _make_client() |
| 1009 |
assert client.mtu_size == 23 |
| 1010 |
|
| 1011 |
|
| 1012 |
async def test_address_type_falls_back_to_public_when_missing() -> None: |
| 1013 |
"""A device without an address_type in details defaults to LE public.""" |
| 1014 |
scanner = FakeScanner() |
| 1015 |
device = BLEDevice(_PEER, "test-device", {"source": _ADAPTER}) # no address_type |
| 1016 |
client = HaMgmtClient( |
| 1017 |
device, |
| 1018 |
client_data=MgmtClientData(adapter_address=_ADAPTER, scanner=scanner), |
| 1019 |
timeout=5.0, |
| 1020 |
) |
| 1021 |
assert client._address_type == 0x01 # BDADDR_LE_PUBLIC |