Fix System Bridge pairing and media URL follow-ups (#194991)

This commit is contained in:
Aidan Timson
2026-11-29 10:33:59 +00:00
committed by GitHub
parent 8d51f5b169
commit f6ee5a338d
6 changed files with 55 additions and 20 deletions
@@ -63,14 +63,20 @@ async def async_get_key_client(hass: HomeAssistant) -> KeyClient:
"""
return KeyClient(
id=await instance_id.async_get(hass),
name=hass.config.location_name,
# System Bridge turns a blank name away
name=hass.config.location_name.strip() or "Home Assistant",
kind="home-assistant",
)
def _pairing_code(text: str) -> str:
"""Return the pairing code from what was entered, the code or its link."""
return URL(text).query.get("pair") or text
"""Return the pairing code from what was entered, the code or its link.
System Bridge takes the code in any case and grouped with dashes or
spaces, so it's normalised the same way.
"""
code = URL(text).query.get("pair") or text
return code.upper().replace("-", "").replace(" ", "")
async def _async_pair(hass: HomeAssistant, data: dict[str, Any], code: str) -> str:
@@ -94,16 +100,16 @@ async def _validate_input(
hass: HomeAssistant,
data: dict[str, Any],
*,
paired_keys: dict[str, str] | None = None,
paired_keys: dict[tuple[str, str, str], str] | None = None,
) -> dict[str, str]:
"""Validate the user input allows us to connect.
Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user.
With paired_keys, the token field takes a key, or a pairing code that is
traded for one. Each key is kept against its code, as a code works once and
a retry after a failed connection needs the same key. Without paired_keys,
the stored key or old token is used as it is, and setup swaps an old token
later.
traded for one. Each key is kept against its host, port and code, as a code
works once and a retry after a failed connection needs the same key, but
only for the computer that gave it. Without paired_keys, the stored key or
old token is used as it is, and setup swaps an old token later.
"""
session = async_get_clientsession(hass)
version = Version(data[CONF_HOST], data[CONF_PORT], "", session=session)
@@ -120,9 +126,10 @@ async def _validate_input(
key = data[CONF_TOKEN].strip()
if paired_keys is not None and not is_client_key(key):
code = _pairing_code(key)
if code not in paired_keys:
paired_keys[code] = await _async_pair(hass, data, code)
key = paired_keys[code]
target = (data[CONF_HOST], data[CONF_PORT], code)
if target not in paired_keys:
paired_keys[target] = await _async_pair(hass, data, code)
key = paired_keys[target]
websocket_client = WebSocketClient(
data[CONF_HOST],
@@ -175,7 +182,7 @@ async def _async_get_info(
hass: HomeAssistant,
user_input: dict[str, Any],
*,
paired_keys: dict[str, str] | None = None,
paired_keys: dict[tuple[str, str, str], str] | None = None,
) -> tuple[dict[str, str], dict[str, str] | None]:
errors = {}
@@ -212,7 +219,7 @@ class SystemBridgeConfigFlow(
def __init__(self) -> None:
"""Initialize flow."""
self._input: dict[str, Any] = {}
self._paired_keys: dict[str, str] = {}
self._paired_keys: dict[tuple[str, str, str], str] = {}
@override
async def async_step_user(
@@ -164,6 +164,7 @@ async def _async_build_file_url(
AuthenticationException,
BadRequestException,
ConnectionErrorException,
TimeoutError,
) as exception:
raise Unresolvable(
translation_domain=DOMAIN,
@@ -402,7 +402,7 @@
"message": "No media player named {name}"
},
"media_url_failed": {
"message": "System Bridge couldn't make a link to {path}"
"message": "System Bridge couldn't create a link for {path}"
},
"no_data_received": {
"message": "No data received from {host}"
@@ -38,6 +38,7 @@ FIXTURE_NEW_KEY = (
# The shared token System Bridge used before each client had its own key
FIXTURE_OLD_TOKEN = "abc-123-def-456-ghi"
FIXTURE_PAIRING_CODE = "MZXW6YTBOI4DQNZXGQ2DGMBQGE3TSNBR"
FIXTURE_PAIRING_CODE_GROUPED = "mzxw-6ytb-oi4d-qnzx gq2d-gmbq-ge3t-snbr"
FIXTURE_AUTH_INPUT = {
CONF_TOKEN: FIXTURE_KEY,
@@ -19,6 +19,7 @@ from systembridgeconnector.models.modules import ModulesData
from systembridgeconnector.models.system_control import PowerState, PowerStateEvent
from homeassistant import config_entries
from homeassistant.components.system_bridge.config_flow import async_get_key_client
from homeassistant.components.system_bridge.const import DOMAIN
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_TOKEN, STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
@@ -31,6 +32,7 @@ from . import (
FIXTURE_NEW_KEY,
FIXTURE_OLD_TOKEN,
FIXTURE_PAIRING_CODE,
FIXTURE_PAIRING_CODE_GROUPED,
FIXTURE_USER_INPUT,
FIXTURE_UUID,
FIXTURE_ZEROCONF,
@@ -127,6 +129,7 @@ async def test_user_flow(hass: HomeAssistant) -> None:
"entered",
[
pytest.param(FIXTURE_PAIRING_CODE, id="code"),
pytest.param(FIXTURE_PAIRING_CODE_GROUPED, id="grouped"),
pytest.param(
f"http://test-bridge.local:9170/?ip=127.0.0.1&pair={FIXTURE_PAIRING_CODE}",
id="link",
@@ -196,10 +199,19 @@ async def test_user_flow_pairing_failed(
assert result["type"] is FlowResultType.CREATE_ENTRY
@pytest.mark.parametrize(
("retry_input", "pair_calls"),
[
pytest.param({}, 1, id="same"),
pytest.param({CONF_TOKEN: FIXTURE_PAIRING_CODE_GROUPED}, 1, id="grouped"),
pytest.param({CONF_HOST: "127.0.0.2"}, 2, id="other_host"),
pytest.param({CONF_PORT: "9171"}, 2, id="other_port"),
],
)
async def test_user_flow_pairing_kept_after_failed_connection(
hass: HomeAssistant,
hass: HomeAssistant, retry_input: dict[str, str], pair_calls: int
) -> None:
"""Test a retry reuses the key from a used pairing code."""
"""Test a retry reuses the key from a used pairing code, on the same computer."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
@@ -222,13 +234,22 @@ async def test_user_flow_pairing_kept_after_failed_connection(
with _patch_success():
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input
result["flow_id"], {**user_input, **retry_input}
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == FIXTURE_USER_INPUT
mock_pair.assert_called_once()
assert result["data"][CONF_TOKEN] == FIXTURE_KEY
assert mock_pair.call_count == pair_calls
async def test_key_client_blank_location_name(hass: HomeAssistant) -> None:
"""Test a blank location name still gives System Bridge a client name."""
hass.config.location_name = " "
client = await async_get_key_client(hass)
assert client.name == "Home Assistant"
async def test_reauth_pairing_kept_after_failed_connection(
@@ -188,7 +188,12 @@ async def test_file_url_signed_by_system_bridge(
@pytest.mark.parametrize(
"side_effect",
[AuthenticationException, BadRequestException, ConnectionErrorException],
[
AuthenticationException,
BadRequestException,
ConnectionErrorException,
TimeoutError,
],
)
async def test_file_url_failed(
hass: HomeAssistant,