diff --git a/meshterm/core/connection.py b/meshterm/core/connection.py index 59c989d..703c7fc 100644 --- a/meshterm/core/connection.py +++ b/meshterm/core/connection.py @@ -145,6 +145,16 @@ _BLE_CONNECT_ATTEMPTS = 2 #: Pause between BLE link-open attempts (seconds), giving the OS radio a beat to settle. _BLE_CONNECT_RETRY_DELAY_S = 1.0 +#: Attempts, and the wait between them, while macOS finishes a pairing it has just begun. +#: An unbonded subscribe to the companion's authenticated characteristic is what *triggers* +#: Passkey Entry there, so the very failure we catch is the signal that the OS has raised +#: its dialog — and the person now has to read a 6-digit code off the device and type it. +#: Giving up at once meant a correct PIN produced an error and only the *second* attempt +#: worked, the first having quietly done the bonding. Sized to cover a human typing a code +#: rather than a radio settling, and bounded so a cancelled dialog still fails in the end. +_BLE_MACOS_PAIRING_ATTEMPTS = 5 +_BLE_MACOS_PAIRING_DELAY_S = 6.0 + TX_POWER_MIN = 1 TX_POWER_MAX = 22 @@ -1224,8 +1234,55 @@ class MeshCoreDevice(Device): # Clear it, pair with the PIN, and retry the connect exactly once before giving up. if allow_repair and await self._pair_ble_windows(force=True): return await self._open_ble(mesh_core, allow_repair=False) + # On macOS the same rejection means the opposite thing: it is not the end of a + # pairing attempt but the *start* of one, because touching the authenticated + # characteristic is the only way to make CoreBluetooth pair at all. The OS is + # putting its Passkey dialog up as we unwind. Wait for the person to answer it. + if allow_repair and sys.platform == "darwin": + return await self._open_ble_after_macos_pairing(mesh_core, exc) raise DeviceAuthenticationError(self._ble_auth_message()) from exc + async def _open_ble_after_macos_pairing(self, mesh_core, cause: BaseException): # type: ignore[no-untyped-def] + """Re-open the link while macOS is running the Passkey dialog it just raised. + + CoreBluetooth exposes no pairing API — Apple's model is that a peripheral pairs + *implicitly* when something touches a characteristic that requires encryption. The + companion firmware puts its UART characteristic at ENC+MITM precisely so that + happens (``SECMODE_ENC_WITH_MITM`` on nRF52, ``ESP_GATT_PERM_*_ENC_MITM`` on + ESP32), so the subscribe fails with "Insufficient Authentication" *and* that + failure is what makes macOS ask for the code. The GATT operation is already dead by + then; the bond it started arrives seconds later, once a human has typed six digits. + + Failing there reported an error for a pairing that was in fact succeeding, and the + device connected on the next attempt — the first having silently done the work. So + retry rather than give up, for long enough to cover the typing. + + Args: + mesh_core: The imported ``meshcore.MeshCore`` class. + cause: The authentication failure that opened the dialog, chained onto the + final error if the pairing never completes. + + Returns: + The connected ``MeshCore`` client, or ``None`` if a later attempt opened the + transport but the peripheral never answered the identity handshake. + + Raises: + DeviceAuthenticationError: If every attempt was still refused — the dialog was + dismissed, or the code entered was wrong. + """ + for attempt in range(_BLE_MACOS_PAIRING_ATTEMPTS): + await asyncio.sleep(_BLE_MACOS_PAIRING_DELAY_S) + try: + return await self._open_ble(mesh_core, allow_repair=False) + except DeviceAuthenticationError: + _log.debug( + "BLE bond with %s not established yet (attempt %d/%d)", + self._address, + attempt + 1, + _BLE_MACOS_PAIRING_ATTEMPTS, + ) + raise DeviceAuthenticationError(self._ble_auth_message()) from cause + async def _create_ble_with_retry(self, mesh_core): # type: ignore[no-untyped-def] """Open the owned BLE client, retrying the transport-level failures that are transient. @@ -1645,6 +1702,16 @@ class MeshCoreDevice(Device): before an authenticated characteristic can be subscribed. """ where = self._address or "the selected Bluetooth device" + if sys.platform == "darwin": + # macOS collects the code itself, in its own dialog, so --ble-pin is not the + # remedy here and naming it would send the reader somewhere that cannot help. + return ( + f"{where} was not paired. macOS asks for the pairing code in its own dialog " + "rather than through MeshTerm — enter the 6-digit code shown on the device " + "(or in the MeshCore app) when it appears, and the bond is remembered for " + "next time. If no dialog appeared, check that Bluetooth is allowed for this " + "terminal in System Settings > Privacy & Security > Bluetooth." + ) if self._pin: return ( f"{where} rejected the Bluetooth PIN — it needs pairing and the PIN provided " diff --git a/tests/test_ble_pairing.py b/tests/test_ble_pairing.py index 6ee58d4..7cd3ad0 100644 --- a/tests/test_ble_pairing.py +++ b/tests/test_ble_pairing.py @@ -23,6 +23,7 @@ no radio, no real address, and no real pairing code is involved. from __future__ import annotations import asyncio +import sys import pytest @@ -200,8 +201,12 @@ def test_a_good_connect_hands_the_client_over_still_open() -> None: assert client.cx.link_open is True -def test_the_connection_is_built_from_this_device_s_own_endpoint() -> None: +def test_the_connection_is_built_from_this_device_s_own_endpoint( + monkeypatch: pytest.MonkeyPatch, +) -> None: """Address, discovered ``BLEDevice`` and PIN all reach the connection we construct.""" + # Pinned off macOS, where the PIN is deliberately withheld (see the test below). + monkeypatch.setattr(sys, "platform", "win32") _FakeMeshCore.reset("ok") sentinel = object() dev = MeshCoreDevice( @@ -221,6 +226,24 @@ def test_the_connection_is_built_from_this_device_s_own_endpoint() -> None: assert (client.default_timeout, client.auto_reconnect) == (7.5, False) +def test_the_pin_is_withheld_on_macos(monkeypatch: pytest.MonkeyPatch) -> None: + """macOS gets no PIN: handing one over is what *breaks* the connection there. + + ``BLEConnection.connect`` responds to a PIN by calling bleak's ``pair()``, and + CoreBluetooth has no pairing API — the macOS backend raises outright, whereupon the + library disconnects and re-raises. Pairing there is the OS's to run, prompted by the + unbonded subscribe, so saying nothing is what lets a protected companion bond at all. + """ + monkeypatch.setattr(sys, "platform", "darwin") + _FakeMeshCore.reset("ok") + dev = MeshCoreDevice(transport="ble", address=_ADDR, pin="000000") + + asyncio.run(dev._connect_owned_ble(_FakeMeshCore)) + + assert _FakeTransport.last.pin is None + assert dev._pin == "000000" # still remembered — it is the platform that can't use it + + def test_a_cancelled_handshake_still_closes_the_link() -> None: """A probe's ``wait_for`` expiring mid-handshake must not leak what it cancelled. diff --git a/tests/test_disconnect.py b/tests/test_disconnect.py index a884d74..e269880 100644 --- a/tests/test_disconnect.py +++ b/tests/test_disconnect.py @@ -11,6 +11,7 @@ from __future__ import annotations import asyncio import io +import sys from pathlib import Path from types import SimpleNamespace @@ -194,6 +195,10 @@ def _fake_ble_stack(monkeypatch: pytest.MonkeyPatch, *outcomes): async def test_create_ble_translates_auth_error_to_pin_guidance(monkeypatch) -> None: """A raw GATT auth rejection becomes a DeviceAuthenticationError that names the PIN fix.""" + # Pinned off macOS: there the same rejection starts an OS-run pairing and is retried + # rather than reported, and the advice is the system dialog rather than --ble-pin. + # Without this the test would assert Windows/Linux wording on the macOS CI runner. + monkeypatch.setattr(sys, "platform", "win32") # No PIN supplied -> tell the user to pass one. The subclass lets the interactive picker # catch "needs a PIN" specifically, while the CLI still catches it as DeviceCommandError. fake = _fake_ble_stack(monkeypatch, BleakGATTProtocolError("Insufficient Authentication")) @@ -302,6 +307,8 @@ async def test_create_ble_gives_up_after_the_retry(monkeypatch) -> None: async def test_create_ble_never_retries_an_auth_rejection(monkeypatch) -> None: """A PIN/bond rejection is translated on the first attempt — never looped by the retry.""" + # Off macOS, where a rejection is the *start* of an OS-run pairing and is waited on. + monkeypatch.setattr(sys, "platform", "win32") fake = _fake_ble_stack(monkeypatch, BleakGATTProtocolError("Insufficient Authentication")) dev = connection.MeshCoreDevice(transport="ble", address=_BONDED_ADDR) await _disable_windows_pairing(dev) @@ -310,6 +317,53 @@ async def test_create_ble_never_retries_an_auth_rejection(monkeypatch) -> None: assert len(fake.built) == 1 +async def test_create_ble_waits_for_macos_to_finish_pairing(monkeypatch) -> None: + """On macOS the first auth rejection is the pairing *starting*, so the connect waits. + + Touching the companion's authenticated characteristic is the only way to make + CoreBluetooth pair at all, so the rejection and the Passkey dialog are the same event. + Giving up there reported an error for a pairing that was succeeding, and the device + connected only when the user selected it a second time. + """ + monkeypatch.setattr(sys, "platform", "darwin") + monkeypatch.setattr(connection, "_BLE_MACOS_PAIRING_DELAY_S", 0) + # Refused twice while the dialog is up, then the bond lands and the subscribe works. + fake = _fake_ble_stack( + monkeypatch, + BleakGATTProtocolError("Insufficient Authentication"), + BleakGATTProtocolError("Insufficient Authentication"), + "handshake-ok", + ) + dev = connection.MeshCoreDevice(transport="ble", address=_BONDED_ADDR) + await _disable_windows_pairing(dev) + + result = await dev._create_ble(fake) + assert result is fake.built[2] # the attempt made after the bond is what the caller gets + assert len(fake.built) == 3 + assert fake.built[0].disconnect_calls == 1 # each refused link was released, not stranded + assert fake.built[1].disconnect_calls == 1 + assert fake.built[2].disconnect_calls == 0 # the live one is handed over open + + +async def test_create_ble_gives_up_when_macos_pairing_is_dismissed(monkeypatch) -> None: + """A dialog nobody answers still fails in the end, and says where the code is asked for.""" + monkeypatch.setattr(sys, "platform", "darwin") + monkeypatch.setattr(connection, "_BLE_MACOS_PAIRING_DELAY_S", 0) + refusals = [BleakGATTProtocolError("Insufficient Authentication")] * ( + connection._BLE_MACOS_PAIRING_ATTEMPTS + 1 + ) + fake = _fake_ble_stack(monkeypatch, *refusals) + dev = connection.MeshCoreDevice(transport="ble", address=_BONDED_ADDR) + await _disable_windows_pairing(dev) + + with pytest.raises(connection.DeviceAuthenticationError) as excinfo: + await dev._create_ble(fake) + assert len(fake.built) == connection._BLE_MACOS_PAIRING_ATTEMPTS + 1 # bounded, not endless + # --ble-pin cannot help on macOS: the OS collects the code, so don't send the reader there. + assert "--ble-pin" not in str(excinfo.value) + assert "System Settings" in str(excinfo.value) + + async def test_connect_reports_an_unanswered_handshake_and_closes_it(monkeypatch) -> None: """Transport up but no identity reply: a clean "not a companion", link still released.""" fake = _fake_ble_stack(monkeypatch, None)