diff --git a/homeassistant/components/telegram_bot/bot.py b/homeassistant/components/telegram_bot/bot.py index 0434623b1a6e..8ee3e24f4fb9 100644 --- a/homeassistant/components/telegram_bot/bot.py +++ b/homeassistant/components/telegram_bot/bot.py @@ -7,6 +7,8 @@ import io import logging import os from pathlib import Path +import ssl +import sys from types import MappingProxyType from typing import Any, cast @@ -46,6 +48,7 @@ from homeassistant.const import ( ) from homeassistant.core import Context, HomeAssistant from homeassistant.exceptions import HomeAssistantError, ServiceValidationError +from homeassistant.helpers import issue_registry as ir from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.httpx_client import get_async_client from homeassistant.helpers.os_error import os_read_error, os_write_error @@ -110,6 +113,7 @@ ALLOWED_UPDATES = [ type TelegramBotConfigEntry = ConfigEntry[TelegramNotificationService] _RETRY_DELAY = 1 # 1 second delay between retries +_VERIFY_SSL_DEFAULT_BREAKS_IN = "2027.7.0" def _get_bot_info(bot: Bot, config_entry: TelegramBotConfigEntry) -> dict[str, Any]: @@ -647,7 +651,7 @@ class TelegramNotificationService: username=kwargs.get(TelegramBotServiceArgument.USERNAME, ""), password=kwargs.get(TelegramBotServiceArgument.PASSWORD, ""), authentication=kwargs.get(TelegramBotServiceArgument.AUTHENTICATION), - verify_ssl=kwargs.get(TelegramBotServiceArgument.VERIFY_SSL, False), + verify_ssl=kwargs.get(TelegramBotServiceArgument.VERIFY_SSL), ) media: InputMedia @@ -810,7 +814,7 @@ class TelegramNotificationService: username=kwargs.get(TelegramBotServiceArgument.USERNAME, ""), password=kwargs.get(TelegramBotServiceArgument.PASSWORD, ""), authentication=kwargs.get(TelegramBotServiceArgument.AUTHENTICATION), - verify_ssl=kwargs.get(TelegramBotServiceArgument.VERIFY_SSL, False), + verify_ssl=kwargs.get(TelegramBotServiceArgument.VERIFY_SSL), ) if file_type == TelegramBotService.SEND_PHOTO: @@ -1180,6 +1184,85 @@ def _url_origin(url: str) -> str: return "URL" +def _is_cert_verification_error( + err: BaseException, caller_exc: BaseException | None +) -> bool: + """Return whether the exception chain has an SSL certificate verification error. + + The chain stops at caller_exc, the exception the caller was handling, if any. + """ + # httpcore sets __context__ but not __cause__ on the error it wraps + exc: BaseException | None = err + while exc is not None and exc is not caller_exc: + if isinstance(exc, ssl.SSLCertVerificationError): + return True + exc = exc.__cause__ or exc.__context__ + return False + + +async def _load_url_data( + hass: HomeAssistant, + url: str, + headers: dict[str, str], + params: dict[str, Any], + verify_ssl: bool, + num_retries: int, +) -> io.BytesIO: + """Load data from a URL into a ByteIO/File container.""" + retry_num = 0 + async with get_async_client(hass, verify_ssl) as client: + while retry_num < num_retries: + try: + response = await client.get( + url, headers=headers, timeout=DEFAULT_TIMEOUT_SECONDS, **params + ) + except (httpx2.HTTPError, httpx2.InvalidURL) as err: + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="failed_to_load_url", + translation_placeholders={ + "url": _url_origin(url), + "error": str(err), + }, + ) from err + + if response.status_code != 200: + _LOGGER.warning( + "Status code %s (retry #%s) loading %s", + response.status_code, + retry_num + 1, + url, + ) + else: + data = io.BytesIO(response.content) + if data.read(): + data.seek(0) + data.name = url + _LOGGER.debug("file downloaded: %s", url) + return data + _LOGGER.warning("Empty data (retry #%s) in %s)", retry_num + 1, url) + retry_num += 1 + if retry_num < num_retries: + # Add a sleep to allow other async operations to proceed + await asyncio.sleep(_RETRY_DELAY) + + # A 200 with data returns early, so a final 200 means an empty body + if response.status_code == 200: + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="failed_to_load_url_empty", + translation_placeholders={"url": _url_origin(url)}, + ) + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="failed_to_load_url_status", + translation_placeholders={ + "url": _url_origin(url), + "status_code": str(response.status_code), + }, + ) + + async def load_data( hass: HomeAssistant, url: str | None, @@ -1187,7 +1270,7 @@ async def load_data( username: str, password: str, authentication: str | None, - verify_ssl: bool, + verify_ssl: bool | None, num_retries: int = 5, ) -> io.BytesIO: """Load data into ByteIO/File container from a source.""" @@ -1203,59 +1286,43 @@ async def load_data( elif authentication == HTTP_BASIC_AUTHENTICATION: params["auth"] = httpx2.BasicAuth(username, password) - retry_num = 0 - async with get_async_client(hass, verify_ssl) as client: - while retry_num < num_retries: - try: - response = await client.get( - url, headers=headers, timeout=DEFAULT_TIMEOUT_SECONDS, **params - ) - except (httpx2.HTTPError, httpx2.InvalidURL) as err: - raise HomeAssistantError( - translation_domain=DOMAIN, - translation_key="failed_to_load_url", - translation_placeholders={ - "url": _url_origin(url), - "error": str(err), - }, - ) from err - - if response.status_code != 200: - _LOGGER.warning( - "Status code %s (retry #%s) loading %s", - response.status_code, - retry_num + 1, - url, - ) - else: - data = io.BytesIO(response.content) - if data.read(): - data.seek(0) - data.name = url - _LOGGER.debug("file downloaded: %s", url) - return data - _LOGGER.warning("Empty data (retry #%s) in %s)", retry_num + 1, url) - retry_num += 1 - if retry_num < num_retries: - # Add a sleep to allow other async operations to proceed - await asyncio.sleep(_RETRY_DELAY) - - # A 200 with data returns early, so a final 200 means an empty body - if response.status_code == 200: - raise HomeAssistantError( - translation_domain=DOMAIN, - translation_key="failed_to_load_url_empty", - translation_placeholders={"url": _url_origin(url)}, - ) - raise HomeAssistantError( - translation_domain=DOMAIN, - translation_key="failed_to_load_url_status", - translation_placeholders={ - "url": _url_origin(url), - "status_code": str(response.status_code), - }, + if verify_ssl is not None: + return await _load_url_data( + hass, url, headers, params, verify_ssl, num_retries ) - elif filepath is not None: + # Deprecated fallback to an unverified download when verify_ssl is not set + caller_exc = sys.exception() + try: + return await _load_url_data(hass, url, headers, params, True, num_retries) + except HomeAssistantError as err: + if not _is_cert_verification_error(err, caller_exc): + raise + origin = _url_origin(url) + issue_id = f"deprecated_verify_ssl_default_{origin}" + # Non-persistent issues are restored inactive after a restart + if ( + issue := ir.async_get(hass).async_get_issue(DOMAIN, issue_id) + ) is None or not issue.active: + _LOGGER.warning( + "The SSL certificate of %s could not be verified, downloading " + "without verification because verify_ssl is not set. This will " + "fail from Home Assistant %s", + origin, + _VERIFY_SSL_DEFAULT_BREAKS_IN, + ) + ir.async_create_issue( + hass, + DOMAIN, + issue_id, + breaks_in_ha_version=_VERIFY_SSL_DEFAULT_BREAKS_IN, + is_fixable=False, + is_persistent=False, + severity=ir.IssueSeverity.WARNING, + translation_key="deprecated_verify_ssl_default", + translation_placeholders={"url": origin}, + ) + return await _load_url_data(hass, url, headers, params, False, num_retries) + if filepath is not None: if hass.config.is_allowed_path(filepath): return await hass.async_add_executor_job(_read_file_as_bytesio, filepath) @@ -1263,12 +1330,11 @@ async def load_data( translation_domain=DOMAIN, translation_key="allowlist_external_dirs_error", ) - else: - raise ServiceValidationError( - translation_domain=DOMAIN, - translation_key="missing_input", - translation_placeholders={"field": "URL or File"}, - ) + raise ServiceValidationError( + translation_domain=DOMAIN, + translation_key="missing_input", + translation_placeholders={"field": "URL or File"}, + ) def _validate_credentials_input( diff --git a/homeassistant/components/telegram_bot/quality_scale.yaml b/homeassistant/components/telegram_bot/quality_scale.yaml index 2b5c959b6cc0..7d11f35dc968 100644 --- a/homeassistant/components/telegram_bot/quality_scale.yaml +++ b/homeassistant/components/telegram_bot/quality_scale.yaml @@ -85,9 +85,7 @@ rules: exception-translations: done icon-translations: done reconfiguration-flow: done - repair-issues: - status: exempt - comment: Integration does not raise repair issues. + repair-issues: done stale-devices: status: exempt comment: only one device per entry, is deleted with the entry. diff --git a/homeassistant/components/telegram_bot/strings.json b/homeassistant/components/telegram_bot/strings.json index 757f2a8b5039..1db0cdb3dc37 100644 --- a/homeassistant/components/telegram_bot/strings.json +++ b/homeassistant/components/telegram_bot/strings.json @@ -238,6 +238,12 @@ "message": "Failed to set up the Telegram bot." } }, + "issues": { + "deprecated_verify_ssl_default": { + "description": "A Telegram bot action tried to download a file from {url}, but the SSL certificate of that server could not be verified.\n\nThe action does not set the **Verify SSL** option, so Home Assistant tried the download again without verifying the certificate. This fallback will be removed in a future release, and the action will then fail.\n\nTo resolve this, fix the SSL certificate of the server. Without verification, anyone who can intercept the connection can pretend to be the server, read the credentials set in the action and replace the file. If you accept that risk, for example for a server on your own network, set `verify_ssl: false` in the actions that download from it instead (under **URL options** in the UI). Then restart Home Assistant to clear this issue.", + "title": "Telegram bot action downloads from a server with an unverified SSL certificate" + } + }, "options": { "step": { "init": { diff --git a/tests/components/telegram_bot/test_telegram_bot.py b/tests/components/telegram_bot/test_telegram_bot.py index 33380dc13a40..93c8416abc10 100644 --- a/tests/components/telegram_bot/test_telegram_bot.py +++ b/tests/components/telegram_bot/test_telegram_bot.py @@ -1,13 +1,25 @@ """Tests for the telegram_bot component.""" +import asyncio import base64 +from collections.abc import AsyncGenerator, Callable +from datetime import timedelta import errno import io +from ipaddress import ip_address import os from pathlib import Path +import ssl from typing import Any from unittest.mock import AsyncMock, MagicMock, mock_open, patch +from aiohttp import web +from aiohttp.test_utils import TestServer +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.x509.oid import NameOID +import httpcore2 import httpx2 import pytest from pytest_homeassistant.common import ( @@ -33,6 +45,7 @@ from telegram.error import ( TimedOut, ) +from homeassistant.components.telegram_bot import bot as telegram_bot from homeassistant.components.telegram_bot.bot import ( ALLOWED_UPDATES, _read_file_as_bytesio, @@ -68,7 +81,8 @@ from homeassistant.core import ( ServiceResponse, ) from homeassistant.exceptions import HomeAssistantError, ServiceValidationError -from homeassistant.helpers import entity_registry as er +from homeassistant.helpers import entity_registry as er, issue_registry as ir +from homeassistant.helpers.httpx_client import get_async_client from homeassistant.util import dt as dt_util, json as json_util from homeassistant.util.file import write_utf8_file @@ -1852,6 +1866,529 @@ async def test_send_video_url_error( assert err.value.translation_placeholders == translation_placeholders +URL_SERVICE_PARAMS = [ + pytest.param(TelegramBotService.SEND_PHOTO, {}, "send_photo", id="send_photo"), + pytest.param( + TelegramBotService.SEND_STICKER, {}, "send_sticker", id="send_sticker" + ), + pytest.param( + TelegramBotService.SEND_ANIMATION, {}, "send_animation", id="send_animation" + ), + pytest.param(TelegramBotService.SEND_VIDEO, {}, "send_video", id="send_video"), + pytest.param(TelegramBotService.SEND_VOICE, {}, "send_voice", id="send_voice"), + pytest.param( + TelegramBotService.SEND_DOCUMENT, {}, "send_document", id="send_document" + ), + pytest.param( + TelegramBotService.EDIT_MESSAGE_MEDIA, + { + TelegramBotServiceArgument.MEDIA_TYPE: InputMediaType.PHOTO, + TelegramBotServiceArgument.MESSAGE_ID: 12345, + TelegramBotServiceArgument.CHAT_ID: 123456, + }, + "edit_message_media", + id="edit_message_media", + ), +] +CERT_URL = "https://user:secret@self-signed.mock:8443/image.jpg?token=secret" +CERT_ORIGIN = "https://self-signed.mock:8443" +CERT_ISSUE_ID = f"deprecated_verify_ssl_default_{CERT_ORIGIN}" + + +def _cert_verify_error() -> httpx2.ConnectError: + """Return a certificate failure with the exception chain that httpx2 raises.""" + ssl_err = ssl.SSLCertVerificationError( + 1, + "[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: " + "self-signed certificate (_ssl.c:1081)", + ) + core_err = httpcore2.ConnectError(str(ssl_err)) + core_err.__context__ = ssl_err + err = httpx2.ConnectError(str(core_err)) + err.__cause__ = core_err + return err + + +@pytest.mark.parametrize(("service", "service_data", "bot_method"), URL_SERVICE_PARAMS) +@pytest.mark.parametrize( + ("verify_ssl_data", "expected_verify_ssl"), + [ + pytest.param({}, True, id="verify_ssl_left_out"), + pytest.param( + {TelegramBotServiceArgument.VERIFY_SSL: True}, True, id="verify_ssl_true" + ), + pytest.param( + {TelegramBotServiceArgument.VERIFY_SSL: False}, + False, + id="verify_ssl_false", + ), + ], +) +@pytest.mark.usefixtures("mock_external_calls") +async def test_url_verify_ssl( + hass: HomeAssistant, + mock_broadcast_config_entry: MockConfigEntry, + issue_registry: ir.IssueRegistry, + service: str, + service_data: dict[str, Any], + bot_method: str, + verify_ssl_data: dict[str, Any], + expected_verify_ssl: bool, +) -> None: + """Test a URL download uses verify_ssl, and verifies when it is left out.""" + mock_broadcast_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_broadcast_config_entry.entry_id) + await hass.async_block_till_done() + + with ( + patch( + "homeassistant.components.telegram_bot.bot.get_async_client", + wraps=get_async_client, + ) as mock_client, + patch( + "homeassistant.components.telegram_bot.bot.httpx2.AsyncClient.get", + return_value=AsyncMock(status_code=200, content=b"mock content"), + ) as mock_get, + patch( + "homeassistant.components.telegram_bot.bot.Bot.edit_message_media", + AsyncMock(return_value=True), + ), + ): + await hass.services.async_call( + DOMAIN, + service, + {TelegramBotServiceArgument.URL: CERT_URL} | service_data | verify_ssl_data, + blocking=True, + ) + getattr(telegram_bot.Bot, bot_method).assert_called_once() + + assert [call.args[1] for call in mock_client.call_args_list] == [ + expected_verify_ssl + ] + mock_get.assert_called_once() + assert not issue_registry.issues + + +@pytest.mark.parametrize(("service", "service_data", "bot_method"), URL_SERVICE_PARAMS) +@pytest.mark.usefixtures("mock_external_calls") +async def test_url_verify_ssl_left_out_cert_error( + hass: HomeAssistant, + mock_broadcast_config_entry: MockConfigEntry, + issue_registry: ir.IssueRegistry, + caplog: pytest.LogCaptureFixture, + service: str, + service_data: dict[str, Any], + bot_method: str, +) -> None: + """Test a certificate failure retries without verification and creates an issue.""" + mock_broadcast_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_broadcast_config_entry.entry_id) + await hass.async_block_till_done() + + with ( + patch( + "homeassistant.components.telegram_bot.bot.get_async_client", + wraps=get_async_client, + ) as mock_client, + patch( + "homeassistant.components.telegram_bot.bot.httpx2.AsyncClient.get", + side_effect=[ + _cert_verify_error(), + AsyncMock(status_code=200, content=b"mock content"), + _cert_verify_error(), + AsyncMock(status_code=200, content=b"mock content"), + ], + ) as mock_get, + patch( + "homeassistant.components.telegram_bot.bot.Bot.edit_message_media", + AsyncMock(return_value=True), + ), + ): + await hass.services.async_call( + DOMAIN, + service, + {TelegramBotServiceArgument.URL: CERT_URL} | service_data, + blocking=True, + ) + assert ( + f"The SSL certificate of {CERT_ORIGIN} could not be verified" in caplog.text + ) + caplog.clear() + # The warning is logged only once per issue + await hass.services.async_call( + DOMAIN, + service, + {TelegramBotServiceArgument.URL: CERT_URL} | service_data, + blocking=True, + ) + assert getattr(telegram_bot.Bot, bot_method).call_count == 2 + + assert "could not be verified" not in caplog.text + assert [call.args[1] for call in mock_client.call_args_list] == [ + True, + False, + True, + False, + ] + assert mock_get.call_count == 4 + assert len(issue_registry.issues) == 1 + issue = issue_registry.async_get_issue(DOMAIN, CERT_ISSUE_ID) + assert issue is not None + assert issue.translation_key == "deprecated_verify_ssl_default" + assert issue.translation_placeholders == {"url": CERT_ORIGIN} + assert issue.severity == ir.IssueSeverity.WARNING + assert issue.breaks_in_ha_version == "2027.7.0" + assert not issue.is_fixable + assert not issue.is_persistent + + +@pytest.mark.usefixtures("mock_external_calls") +async def test_url_verify_ssl_left_out_cert_error_unverified_fails( + hass: HomeAssistant, + mock_broadcast_config_entry: MockConfigEntry, + issue_registry: ir.IssueRegistry, +) -> None: + """Test the error of the unverified download is raised after a certificate failure.""" + mock_broadcast_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_broadcast_config_entry.entry_id) + await hass.async_block_till_done() + + with ( + patch( + "homeassistant.components.telegram_bot.bot.get_async_client", + wraps=get_async_client, + ) as mock_client, + patch( + "homeassistant.components.telegram_bot.bot.httpx2.AsyncClient.get", + side_effect=[_cert_verify_error(), httpx2.ConnectError("Connection reset")], + ), + pytest.raises(HomeAssistantError) as err, + ): + await hass.services.async_call( + DOMAIN, + TelegramBotService.SEND_PHOTO, + {TelegramBotServiceArgument.URL: CERT_URL}, + blocking=True, + ) + + assert [call.args[1] for call in mock_client.call_args_list] == [True, False] + assert err.value.translation_key == "failed_to_load_url" + assert err.value.translation_placeholders == { + "url": CERT_ORIGIN, + "error": "Connection reset", + } + assert issue_registry.async_get_issue(DOMAIN, CERT_ISSUE_ID) + + +@pytest.mark.parametrize( + ("verify_ssl_data", "get_kwargs", "translation_key"), + [ + pytest.param( + {}, + {"side_effect": httpx2.ConnectError("Connection refused")}, + "failed_to_load_url", + id="left_out_connect_error", + ), + pytest.param( + {}, + {"return_value": AsyncMock(status_code=404, content=b"")}, + "failed_to_load_url_status", + id="left_out_status_code", + ), + pytest.param( + {TelegramBotServiceArgument.VERIFY_SSL: True}, + {"side_effect": _cert_verify_error()}, + "failed_to_load_url", + id="true_cert_error", + ), + ], +) +@pytest.mark.usefixtures("mock_external_calls") +async def test_url_verify_ssl_no_unverified_retry( + hass: HomeAssistant, + mock_broadcast_config_entry: MockConfigEntry, + issue_registry: ir.IssueRegistry, + verify_ssl_data: dict[str, Any], + get_kwargs: dict[str, Any], + translation_key: str, +) -> None: + """Test other failures, or a set verify_ssl, do not retry without verification.""" + mock_broadcast_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_broadcast_config_entry.entry_id) + await hass.async_block_till_done() + + with ( + patch( + "homeassistant.components.telegram_bot.bot.get_async_client", + wraps=get_async_client, + ) as mock_client, + patch( + "homeassistant.components.telegram_bot.bot.httpx2.AsyncClient.get", + **get_kwargs, + ), + patch("homeassistant.components.telegram_bot.bot._RETRY_DELAY", 0), + pytest.raises(HomeAssistantError) as err, + ): + await hass.services.async_call( + DOMAIN, + TelegramBotService.SEND_PHOTO, + {TelegramBotServiceArgument.URL: CERT_URL} | verify_ssl_data, + blocking=True, + ) + + assert [call.args[1] for call in mock_client.call_args_list] == [True] + assert err.value.translation_key == translation_key + assert not issue_registry.issues + + +@pytest.mark.usefixtures("mock_external_calls") +async def test_url_verify_ssl_left_out_caller_cert_error( + hass: HomeAssistant, + mock_broadcast_config_entry: MockConfigEntry, + issue_registry: ir.IssueRegistry, +) -> None: + """Test a certificate error the caller is handling is not taken as the cause.""" + mock_broadcast_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_broadcast_config_entry.entry_id) + await hass.async_block_till_done() + + with ( + patch( + "homeassistant.components.telegram_bot.bot.get_async_client", + wraps=get_async_client, + ) as mock_client, + patch( + "homeassistant.components.telegram_bot.bot.httpx2.AsyncClient.get", + return_value=AsyncMock(status_code=404, content=b""), + ), + patch("homeassistant.components.telegram_bot.bot._RETRY_DELAY", 0), + ): + try: + raise _cert_verify_error() + except httpx2.ConnectError: + with pytest.raises(HomeAssistantError) as err: + await hass.services.async_call( + DOMAIN, + TelegramBotService.SEND_PHOTO, + {TelegramBotServiceArgument.URL: CERT_URL}, + blocking=True, + ) + + assert err.value.translation_key == "failed_to_load_url_status" + assert [call.args[1] for call in mock_client.call_args_list] == [True] + assert not issue_registry.issues + + +@pytest.mark.usefixtures("mock_external_calls") +async def test_url_verify_ssl_left_out_cert_error_restored_issue( + hass: HomeAssistant, + hass_storage: dict[str, Any], + mock_broadcast_config_entry: MockConfigEntry, + issue_registry: ir.IssueRegistry, + caplog: pytest.LogCaptureFixture, +) -> None: + """Test the warning is logged again for an issue restored inactive after a restart.""" + hass_storage[ir.STORAGE_KEY] = { + "version": ir.STORAGE_VERSION_MAJOR, + "minor_version": ir.STORAGE_VERSION_MINOR, + "data": { + "issues": [ + { + "config_entry_id": None, + "config_subentry_id": None, + "created": "2026-01-01T00:00:00+00:00", + "dismissed_version": None, + "domain": DOMAIN, + "is_persistent": False, + "issue_id": CERT_ISSUE_ID, + } + ] + }, + } + await issue_registry.async_load() + issue = issue_registry.async_get_issue(DOMAIN, CERT_ISSUE_ID) + assert issue is not None + assert not issue.active + + mock_broadcast_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_broadcast_config_entry.entry_id) + await hass.async_block_till_done() + + with patch( + "homeassistant.components.telegram_bot.bot.httpx2.AsyncClient.get", + side_effect=[ + _cert_verify_error(), + AsyncMock(status_code=200, content=b"mock content"), + ], + ): + await hass.services.async_call( + DOMAIN, + TelegramBotService.SEND_PHOTO, + {TelegramBotServiceArgument.URL: CERT_URL}, + blocking=True, + ) + + assert f"The SSL certificate of {CERT_ORIGIN} could not be verified" in caplog.text + issue = issue_registry.async_get_issue(DOMAIN, CERT_ISSUE_ID) + assert issue is not None + assert issue.active + + +@pytest.fixture +async def self_signed_server( + hass: HomeAssistant, + aiohttp_server: Callable[[], TestServer], + tmp_path: Path, + socket_enabled: None, +) -> AsyncGenerator[str]: + """Serve a file over loopback TLS with a self-signed certificate.""" + key = ec.generate_private_key(ec.SECP256R1()) + name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "Telegram bot test")]) + now = dt_util.utcnow() + certificate = ( + x509.CertificateBuilder() + .subject_name(name) + .issuer_name(name) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - timedelta(days=1)) + .not_valid_after(now + timedelta(days=1)) + .add_extension( + x509.SubjectAlternativeName([x509.IPAddress(ip_address("127.0.0.1"))]), + critical=False, + ) + .sign(key, hashes.SHA256()) + ) + cert_path = tmp_path / "server.pem" + cert_path.write_bytes(certificate.public_bytes(serialization.Encoding.PEM)) + key_path = tmp_path / "server.key" + key_path.write_bytes( + key.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ) + ) + server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + server_context.load_cert_chain(cert_path, key_path) + + async def handle(request: web.Request) -> web.Response: + return web.Response(body=b"mock content") + + app = web.Application() + app.router.add_get("/photo.jpg", handle) + server = await aiohttp_server(app, ssl=server_context) + + loop = asyncio.get_running_loop() + original_handler = loop.get_exception_handler() + + def exception_handler( + loop: asyncio.AbstractEventLoop, context: dict[str, Any] + ) -> None: + # A client rejecting the certificate can reset the server's TLS handshake + if context.get( + "message" + ) == "Error on transport creation for incoming connection" and isinstance( + context.get("exception"), (ConnectionResetError, ssl.SSLError) + ): + return + assert original_handler is not None + original_handler(loop, context) + + loop.set_exception_handler(exception_handler) + try: + yield f"https://127.0.0.1:{server.port}/photo.jpg" + finally: + await hass.async_block_till_done() + loop.set_exception_handler(original_handler) + + +@pytest.mark.usefixtures("mock_external_calls") +async def test_url_verify_ssl_left_out_self_signed_server( + hass: HomeAssistant, + mock_broadcast_config_entry: MockConfigEntry, + issue_registry: ir.IssueRegistry, + self_signed_server: str, +) -> None: + """Test the unverified retry with the exception chain of a real TLS connection.""" + mock_broadcast_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_broadcast_config_entry.entry_id) + await hass.async_block_till_done() + + with pytest.raises(HomeAssistantError) as err: + await hass.services.async_call( + DOMAIN, + TelegramBotService.SEND_PHOTO, + { + TelegramBotServiceArgument.URL: self_signed_server, + TelegramBotServiceArgument.VERIFY_SSL: True, + }, + blocking=True, + ) + assert err.value.translation_key == "failed_to_load_url" + assert not issue_registry.issues + + await hass.services.async_call( + DOMAIN, + TelegramBotService.SEND_PHOTO, + {TelegramBotServiceArgument.URL: self_signed_server}, + blocking=True, + ) + + telegram_bot.Bot.send_photo.assert_called_once() + origin = self_signed_server.removesuffix("/photo.jpg") + issue = issue_registry.async_get_issue( + DOMAIN, f"deprecated_verify_ssl_default_{origin}" + ) + assert issue is not None + assert issue.translation_placeholders == {"url": origin} + + +@pytest.mark.usefixtures("mock_external_calls") +async def test_send_media_group_cert_error( + hass: HomeAssistant, + mock_broadcast_config_entry: MockConfigEntry, + issue_registry: ir.IssueRegistry, +) -> None: + """Test send_media_group verifies by default without an unverified retry.""" + mock_broadcast_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_broadcast_config_entry.entry_id) + await hass.async_block_till_done() + + with ( + patch( + "homeassistant.components.telegram_bot.bot.get_async_client", + wraps=get_async_client, + ) as mock_client, + patch( + "homeassistant.components.telegram_bot.bot.httpx2.AsyncClient.get", + side_effect=_cert_verify_error(), + ), + pytest.raises(HomeAssistantError) as err, + ): + await hass.services.async_call( + DOMAIN, + TelegramBotService.SEND_MEDIA_GROUP, + { + TelegramBotServiceArgument.MEDIA: [ + { + TelegramBotServiceArgument.MEDIA_TYPE: InputMediaType.PHOTO, + TelegramBotServiceArgument.URL: CERT_URL, + }, + { + TelegramBotServiceArgument.MEDIA_TYPE: InputMediaType.PHOTO, + TelegramBotServiceArgument.URL: CERT_URL, + }, + ], + }, + blocking=True, + ) + + assert [call.args[1] for call in mock_client.call_args_list] == [True] + assert err.value.translation_key == "failed_to_load_url" + assert not issue_registry.issues + + async def test_set_message_reaction( hass: HomeAssistant, mock_broadcast_config_entry: MockConfigEntry,