mirror of
https://github.com/home-assistant/core.git
synced 2026-12-04 20:59:22 -04:00
Sign System Bridge media file URLs instead of sending the token (#191835)
This commit is contained in:
@@ -25,6 +25,9 @@ AUDIO_MIN_VERSION: Final = (5, 16, 0)
|
||||
# Backends before 5.23.0 list players without their controls or details
|
||||
PLAYER_DETAILS_MIN_VERSION: Final = (5, 23, 0)
|
||||
|
||||
# Backends before 5.25.0 only accept the API token in media file URLs
|
||||
SIGNED_MEDIA_URL_MIN_VERSION: Final = (5, 25, 0)
|
||||
|
||||
AUDIO_OUTPUT: Final = "output"
|
||||
AUDIO_INPUT: Final = "input"
|
||||
|
||||
|
||||
@@ -2,9 +2,12 @@
|
||||
|
||||
from typing import override
|
||||
|
||||
from packaging.version import parse as parse_version
|
||||
from systembridgeconnector.helpers import media_file_url
|
||||
from systembridgeconnector.models.media_directories import MediaDirectory
|
||||
from systembridgeconnector.models.media_files import MediaFile, MediaFiles
|
||||
from systembridgeconnector.models.media_get_files import MediaGetFiles
|
||||
from yarl import URL
|
||||
|
||||
from homeassistant.components.media_player import BrowseError, MediaClass
|
||||
from homeassistant.components.media_source import (
|
||||
@@ -20,7 +23,7 @@ from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_TOKEN
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from .const import DOMAIN
|
||||
from .const import DOMAIN, SIGNED_MEDIA_URL_MIN_VERSION
|
||||
from .coordinator import SystemBridgeConfigEntry
|
||||
|
||||
|
||||
@@ -71,11 +74,8 @@ class SystemBridgeSource(MediaSource):
|
||||
"""Resolve media to a url."""
|
||||
entry_id, path, mime_type = item.identifier.split("~~", 2)
|
||||
entry = _get_loaded_entry(self.hass, entry_id, Unresolvable)
|
||||
path_split = path.split("/", 1)
|
||||
return PlayMedia(
|
||||
f"{_build_base_url(entry)}&base={path_split[0]}&path={path_split[1]}",
|
||||
mime_type,
|
||||
)
|
||||
base, file_path = path.split("/", 1)
|
||||
return PlayMedia(_build_file_url(entry, base, file_path), mime_type)
|
||||
|
||||
@override
|
||||
async def async_browse_media(
|
||||
@@ -138,13 +138,28 @@ class SystemBridgeSource(MediaSource):
|
||||
)
|
||||
|
||||
|
||||
def _build_base_url(
|
||||
entry: SystemBridgeConfigEntry,
|
||||
) -> str:
|
||||
"""Build base url for System Bridge media."""
|
||||
return (
|
||||
f"http://{entry.data[CONF_HOST]}:{entry.data[CONF_PORT]}"
|
||||
f"/api/media/file/data?token={entry.data[CONF_TOKEN]}"
|
||||
def _build_file_url(entry: SystemBridgeConfigEntry, base: str, path: str) -> str:
|
||||
"""Build the URL for a System Bridge media file."""
|
||||
host = entry.data[CONF_HOST]
|
||||
port = entry.data[CONF_PORT]
|
||||
token = entry.data[CONF_TOKEN]
|
||||
system = entry.runtime_data.data.system
|
||||
if (
|
||||
system is not None
|
||||
and system.version is not None
|
||||
and parse_version(system.version).release >= SIGNED_MEDIA_URL_MIN_VERSION
|
||||
):
|
||||
# The URL goes to players such as cast devices, so it's signed for
|
||||
# this file rather than carrying the API token
|
||||
return media_file_url(host, port, token, base, path)
|
||||
return str(
|
||||
URL.build(
|
||||
scheme="http",
|
||||
host=host,
|
||||
port=int(port),
|
||||
path="/api/media/file/data",
|
||||
query={"token": token, "base": base, "path": path},
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -1,9 +1,18 @@
|
||||
"""Test the System Bridge integration."""
|
||||
|
||||
from collections.abc import Generator
|
||||
from dataclasses import replace
|
||||
from datetime import timedelta
|
||||
import hashlib
|
||||
import hmac
|
||||
from unittest.mock import MagicMock, patch
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
import pytest
|
||||
from pytest_homeassistant.common import MockConfigEntry
|
||||
from syrupy.assertion import SnapshotAssertion
|
||||
from syrupy.filters import paths
|
||||
from systembridgeconnector.models.fixtures.modules.system import FIXTURE_SYSTEM
|
||||
|
||||
from homeassistant.components.media_player import BrowseError
|
||||
from homeassistant.components.media_source import (
|
||||
@@ -15,8 +24,12 @@ from homeassistant.components.media_source import (
|
||||
)
|
||||
from homeassistant.components.system_bridge.const import DOMAIN
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.const import CONF_TOKEN
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.setup import async_setup_component
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
from . import FIXTURE_USER_INPUT
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
@@ -140,6 +153,50 @@ async def test_file(
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def signed_url_backend(mock_websocket_client: MagicMock) -> Generator[None]:
|
||||
"""Report a backend that accepts signed media URLs."""
|
||||
system = replace(FIXTURE_SYSTEM, version="5.25.0")
|
||||
mock_websocket_client.get_data.return_value = replace(
|
||||
mock_websocket_client.get_data.return_value, system=system
|
||||
)
|
||||
with patch("tests.components.system_bridge.FIXTURE_SYSTEM", system):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("signed_url_backend")
|
||||
async def test_file_signed_url(
|
||||
hass: HomeAssistant,
|
||||
init_integration: MockConfigEntry,
|
||||
) -> None:
|
||||
"""Test hosts that accept signed URLs get one, without the API token."""
|
||||
earliest = int((dt_util.utcnow() + timedelta(hours=24)).timestamp())
|
||||
resolved = await async_resolve_media(
|
||||
hass,
|
||||
f"{URI_SCHEME}{DOMAIN}/{init_integration.entry_id}~~documents/my file.txt~~text/plain",
|
||||
None,
|
||||
)
|
||||
latest = int((dt_util.utcnow() + timedelta(hours=24)).timestamp())
|
||||
|
||||
url = urlparse(resolved.url)
|
||||
query = parse_qs(url.query)
|
||||
assert f"{url.scheme}://{url.netloc}{url.path}" == (
|
||||
"http://127.0.0.1:9170/api/media/file/data"
|
||||
)
|
||||
assert "token" not in query
|
||||
assert query["base"] == ["documents"]
|
||||
assert query["path"] == ["my file.txt"]
|
||||
[expires] = query["expires"]
|
||||
assert earliest <= int(expires) <= latest
|
||||
assert query["sig"] == [
|
||||
hmac.new(
|
||||
FIXTURE_USER_INPUT[CONF_TOKEN].encode(),
|
||||
f"documents\nmy file.txt\n{expires}".encode(),
|
||||
hashlib.sha256,
|
||||
).hexdigest()
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"entry_id",
|
||||
[
|
||||
|
||||
Reference in New Issue
Block a user