diff --git a/homeassistant/components/media_player/entity.py b/homeassistant/components/media_player/entity.py index 93e2721e5ee2..7b4c8097e139 100644 --- a/homeassistant/components/media_player/entity.py +++ b/homeassistant/components/media_player/entity.py @@ -2,7 +2,6 @@ import asyncio import collections -from contextlib import suppress import datetime as dt import functools as ft from functools import lru_cache @@ -873,28 +872,39 @@ def _image_response_appears_complete( return True +def _url_host(url: str) -> str: + """Return the host of url for logging, leaving out credentials and path.""" + try: + return URL(url).host or "" + except ValueError: + return "" + + async def async_fetch_image( logger: logging.Logger, hass: HomeAssistant, url: str ) -> tuple[bytes | None, str | None]: """Retrieve an image.""" - content, content_type = (None, None) websession = async_get_clientsession(hass) - with suppress(TimeoutError): - response = await websession.get(url, timeout=_FETCH_TIMEOUT) - if response.status == HTTPStatus.OK: - body = await response.read() - if _image_response_appears_complete(response, body): - content = body - if content_type := response.headers.get(CONTENT_TYPE): - content_type = content_type.split(";")[0] + try: + async with websession.get(url, timeout=_FETCH_TIMEOUT) as response: + if response.status != HTTPStatus.OK: + reason = f"HTTP {response.status}" + else: + body = await response.read() + if _image_response_appears_complete(response, body): + content_type = response.headers.get(CONTENT_TYPE) + return body, content_type.split(";")[0] if content_type else None + reason = ( + f"truncated response, {len(body)} of " + f"{response.headers.get(CONTENT_LENGTH)} bytes" + ) + detail = reason + except (TimeoutError, aiohttp.ClientError) as err: + # The exception text can contain the full URL, so it is only logged at + # debug level, next to the URL itself. + reason = type(err).__name__ + detail = str(err) or reason - if content is None: - url_parts = URL(url) - if url_parts.user is not None: - url_parts = url_parts.with_user("xxxx") - if url_parts.password is not None: - url_parts = url_parts.with_password("xxxxxxxx") - url = str(url_parts) - logger.warning("Error retrieving proxied image from %s", url) - - return content, content_type + logger.warning("Error retrieving proxied image from %s: %s", _url_host(url), reason) + logger.debug("Error retrieving proxied image from %s: %s", url, detail) + return None, None diff --git a/tests/components/demo/test_media_player.py b/tests/components/demo/test_media_player.py index 73c24cc4072f..138c357e5363 100644 --- a/tests/components/demo/test_media_player.py +++ b/tests/components/demo/test_media_player.py @@ -513,7 +513,7 @@ async def test_media_image_proxy( fake_picture_data = "test.test" class MockResponse: - """Test response.""" + """Test response, usable as an async context manager.""" def __init__(self) -> None: """Test response init.""" @@ -527,10 +527,18 @@ async def test_media_image_proxy( async def release(self): """Test response release.""" + async def __aenter__(self): + """Enter the response context.""" + return self + + async def __aexit__(self, exc_type, exc, tb): + """Release the response on exit.""" + await self.release() + class MockWebsession: """Test websession.""" - async def get(self, url, **kwargs): + def get(self, url, **kwargs): """Test websession get.""" return MockResponse() diff --git a/tests/components/media_player/test_init.py b/tests/components/media_player/test_init.py index 03262bfabea9..caef60c43763 100644 --- a/tests/components/media_player/test_init.py +++ b/tests/components/media_player/test_init.py @@ -1,8 +1,11 @@ """Test the base functions of the media player.""" from http import HTTPStatus +import logging +from typing import Any from unittest.mock import patch +import aiohttp from aiohttp import hdrs import probatio import pytest @@ -21,6 +24,7 @@ from homeassistant.components.media_player import ( MediaPlayerServiceArgument, SearchMedia, SearchMediaQuery, + entity as media_player_entity, ) from homeassistant.components.media_player.const import DATA_COMPONENT from homeassistant.components.websocket_api import TYPE_RESULT @@ -209,14 +213,72 @@ async def test_get_image_http_missing_image( assert resp.status == HTTPStatus.NOT_FOUND -async def test_get_image_http_log_credentials_redacted( +_CREDENTIALS_URL = "http://usr51:s3cr3t99@example.com/default.jpg" + + +@pytest.mark.parametrize( + ("url", "mock_kwargs", "warning_reason", "debug_detail"), + [ + pytest.param( + _CREDENTIALS_URL, + {"exc": TimeoutError()}, + "TimeoutError", + "TimeoutError", + id="timeout", + ), + pytest.param( + _CREDENTIALS_URL, + # InvalidUrlClientError stringifies to the offending URL itself + {"exc": aiohttp.InvalidUrlClientError(_CREDENTIALS_URL)}, + "InvalidUrlClientError", + _CREDENTIALS_URL, + id="exception_text_contains_url", + ), + pytest.param( + _CREDENTIALS_URL, + {"exc": aiohttp.ClientPayloadError("incomplete chunked read")}, + "ClientPayloadError", + "incomplete chunked read", + id="client_payload_error", + ), + pytest.param( + _CREDENTIALS_URL, + {"exc": aiohttp.ClientConnectionError("connection reset")}, + "ClientConnectionError", + "connection reset", + id="client_connection_error", + ), + pytest.param( + _CREDENTIALS_URL, + {"status": HTTPStatus.NOT_FOUND}, + "HTTP 404", + "HTTP 404", + id="http_status", + ), + pytest.param( + _CREDENTIALS_URL, + { + "content": b"hello-world", + "headers": {"Content-Type": "image/jpeg", "Content-Length": "9999"}, + }, + "truncated response, 11 of 9999 bytes", + "truncated response, 11 of 9999 bytes", + id="truncated_response", + ), + ], +) +async def test_get_image_http_fetch_failure_logging( hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator, aioclient_mock: AiohttpClientMocker, caplog: pytest.LogCaptureFixture, + url: str, + mock_kwargs: dict[str, Any], + warning_reason: str, + debug_detail: str, ) -> None: - """Test credentials are redacted when logging url when fetching image.""" - url = "http://vi:pass@example.com/default.jpg" + """Test a failed fetch logs only the host at warning and the URL at debug.""" + caplog.set_level(logging.DEBUG) with patch( "homeassistant.components.demo.media_player.DemoYoutubePlayer.media_image_url", url, @@ -229,18 +291,31 @@ async def test_get_image_http_log_credentials_redacted( state = hass.states.get("media_player.bedroom") assert "entity_picture_local" not in state.attributes - aioclient_mock.get(url, exc=TimeoutError()) - + aioclient_mock.get(url, **mock_kwargs) client = await hass_client_no_auth() - resp = await client.get(state.attributes["entity_picture"]) assert resp.status == HTTPStatus.NOT_FOUND - assert f"Error retrieving proxied image from {url}" not in caplog.text + warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING] assert ( - "Error retrieving proxied image from " - f"{url.replace('pass', 'xxxxxxxx').replace('vi', 'xxxx')}" - ) in caplog.text + f"Error retrieving proxied image from example.com: {warning_reason}" in warnings + ) + assert not any("s3cr3t99" in message for message in warnings) + debug = [r.getMessage() for r in caplog.records if r.levelno == logging.DEBUG] + assert f"Error retrieving proxied image from {url}: {debug_detail}" in debug + + +@pytest.mark.parametrize( + ("url", "expected"), + [ + pytest.param("http://vi:pass@example.com/image.jpg", "example.com", id="host"), + pytest.param("/local/image.jpg", "", id="no_host"), + pytest.param("http://[invalid", "", id="invalid_url"), + ], +) +def test_url_host(url: str, expected: str) -> None: + """Test the host logged for a failed fetch, including unparsable URLs.""" + assert media_player_entity._url_host(url) == expected async def test_get_image_http_truncated_response(