diff --git a/homeassistant/components/imap/__init__.py b/homeassistant/components/imap/__init__.py index c2369935d5fc..fba1dbfde901 100644 --- a/homeassistant/components/imap/__init__.py +++ b/homeassistant/components/imap/__init__.py @@ -51,7 +51,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ImapConfigEntry) -> bool raise ConfigEntryAuthFailed from err except InvalidFolder as err: raise ConfigEntryError("Selected mailbox folder is invalid.") from err - except (TimeoutError, AioImapException) as err: + except (OSError, AioImapException) as err: raise ConfigEntryNotReady from err coordinator_class: type[ diff --git a/homeassistant/components/imap/config_flow.py b/homeassistant/components/imap/config_flow.py index 25567b29731e..0e7015a8982c 100644 --- a/homeassistant/components/imap/config_flow.py +++ b/homeassistant/components/imap/config_flow.py @@ -42,6 +42,7 @@ from .const import ( DEFAULT_MAX_MESSAGE_SIZE, DEFAULT_PORT, DOMAIN, + INVALID_COMMAND_CHARS, MAX_MESSAGE_SIZE_LIMIT, MESSAGE_DATA_OPTIONS, ) @@ -109,7 +110,18 @@ async def validate_input( hass: HomeAssistant, user_input: dict[str, Any] ) -> dict[str, str]: """Validate user input.""" - errors = {} + if errors := { + key: "invalid_characters" + for key in ( + CONF_USERNAME, + CONF_PASSWORD, + CONF_FOLDER, + CONF_SEARCH, + CONF_CHARSET, + ) + if INVALID_COMMAND_CHARS.search(user_input[key]) + }: + return errors try: imap_client = await connect_to_server(user_input) @@ -123,13 +135,8 @@ async def validate_input( except InvalidFolder: errors[CONF_FOLDER] = "invalid_folder" except ssl.SSLError: - # The aioimaplib library 1.0.1 does not raise an - # ssl.SSLError correctly, but is logged. - # See - # https://github.com/bamthomas/aioimaplib/issues/91 - # This handler supplies a better error message. errors["base"] = "ssl_error" - except TimeoutError, AioImapException, ConnectionRefusedError: + except OSError, AioImapException: errors["base"] = "cannot_connect" else: if result != "OK": diff --git a/homeassistant/components/imap/const.py b/homeassistant/components/imap/const.py index a341a2a55e79..632b7017d6d8 100644 --- a/homeassistant/components/imap/const.py +++ b/homeassistant/components/imap/const.py @@ -1,5 +1,6 @@ """Constants for the imap integration.""" +import re from typing import Final DOMAIN: Final = "imap" @@ -21,3 +22,6 @@ DEFAULT_MAX_MESSAGE_SIZE = 2048 MESSAGE_DATA_OPTIONS: Final = ["text", "headers"] MAX_MESSAGE_SIZE_LIMIT: Final = 30000 + +# aioimaplib raises a ValueError for command arguments containing these +INVALID_COMMAND_CHARS: Final = re.compile(r"[\x00\r\n]") diff --git a/homeassistant/components/imap/coordinator.py b/homeassistant/components/imap/coordinator.py index 9f22a7bccdf3..4453bed706ad 100644 --- a/homeassistant/components/imap/coordinator.py +++ b/homeassistant/components/imap/coordinator.py @@ -445,7 +445,7 @@ class ImapPollingDataUpdateCoordinator(ImapDataUpdateCoordinator): except ( AioImapException, UpdateFailed, - TimeoutError, + OSError, ) as ex: await self._cleanup() self.async_set_update_error(ex) @@ -525,7 +525,7 @@ class ImapPushDataUpdateCoordinator(ImapDataUpdateCoordinator): except ( UpdateFailed, AioImapException, - TimeoutError, + OSError, ) as ex: await self._cleanup() self.async_set_update_error(ex) diff --git a/homeassistant/components/imap/manifest.json b/homeassistant/components/imap/manifest.json index 914206944389..eaef4b80ff25 100644 --- a/homeassistant/components/imap/manifest.json +++ b/homeassistant/components/imap/manifest.json @@ -8,5 +8,5 @@ "integration_type": "service", "iot_class": "cloud_push", "loggers": ["aioimaplib"], - "requirements": ["aioimaplib==2.0.1"] + "requirements": ["aioimaplib==2.0.3"] } diff --git a/homeassistant/components/imap/services.py b/homeassistant/components/imap/services.py index 66ab116f208e..49d1ba304854 100644 --- a/homeassistant/components/imap/services.py +++ b/homeassistant/components/imap/services.py @@ -20,7 +20,7 @@ from homeassistant.core import ( from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers import config_validation as cv -from .const import DOMAIN +from .const import DOMAIN, INVALID_COMMAND_CHARS from .coordinator import ImapMessage, connect_to_server, get_parts from .errors import InvalidAuth, InvalidFolder @@ -32,10 +32,19 @@ CONF_PART = "part" CONF_UID = "uid" CONF_TARGET_FOLDER = "target_folder" + +def _command_argument(value: Any) -> str: + """Validate a string that is passed as an IMAP command argument.""" + command_argument = cv.string(value) + if INVALID_COMMAND_CHARS.search(command_argument): + raise probatio.Invalid("NUL, CR and LF characters are not allowed") + return command_argument + + _SERVICE_UID_SCHEMA = probatio.Schema( { probatio.Required(CONF_ENTRY): cv.string, - probatio.Required(CONF_UID): cv.string, + probatio.Required(CONF_UID): _command_argument, } ) @@ -43,7 +52,7 @@ SERVICE_SEEN_SCHEMA = _SERVICE_UID_SCHEMA SERVICE_MOVE_SCHEMA = _SERVICE_UID_SCHEMA.extend( { probatio.Optional(CONF_SEEN): cv.boolean, - probatio.Required(CONF_TARGET_FOLDER): cv.string, + probatio.Required(CONF_TARGET_FOLDER): _command_argument, } ) SERVICE_DELETE_SCHEMA = _SERVICE_UID_SCHEMA @@ -75,7 +84,7 @@ async def async_get_imap_client(hass: HomeAssistant, entry_id: str) -> IMAP4_SSL raise ServiceValidationError( translation_domain=DOMAIN, translation_key="invalid_folder" ) from exc - except (TimeoutError, AioImapException) as exc: + except (OSError, AioImapException) as exc: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="imap_server_fail", diff --git a/homeassistant/components/imap/strings.json b/homeassistant/components/imap/strings.json index f0bd31025e90..5b299675c85e 100644 --- a/homeassistant/components/imap/strings.json +++ b/homeassistant/components/imap/strings.json @@ -6,6 +6,7 @@ "error": { "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", "invalid_auth": "[%key:common::config_flow::error::invalid_auth%]", + "invalid_characters": "NUL, CR and LF characters are not allowed", "invalid_charset": "The specified charset is not supported", "invalid_folder": "The selected folder is invalid", "invalid_search": "The selected search is invalid", @@ -95,6 +96,7 @@ "already_configured": "An entry with these folder and search options already exists.", "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", "invalid_auth": "[%key:common::config_flow::error::invalid_auth%]", + "invalid_characters": "[%key:component::imap::config::error::invalid_characters%]", "invalid_charset": "[%key:component::imap::config::error::invalid_charset%]", "invalid_folder": "[%key:component::imap::config::error::invalid_folder%]", "invalid_search": "[%key:component::imap::config::error::invalid_search%]" diff --git a/requirements_all.txt b/requirements_all.txt index aa24f7b0ee0d..85ccbefee198 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -310,7 +310,7 @@ aiohttp_sse==2.2.0 aiohue==4.9.0 # homeassistant.components.imap -aioimaplib==2.0.1 +aioimaplib==2.0.3 # homeassistant.components.immich aioimmich==0.18.0 diff --git a/tests/components/imap/test_config_flow.py b/tests/components/imap/test_config_flow.py index d6b5865da8d8..86801f0dc4e7 100644 --- a/tests/components/imap/test_config_flow.py +++ b/tests/components/imap/test_config_flow.py @@ -2,6 +2,7 @@ from collections.abc import Generator from contextlib import contextmanager +import socket import ssl from unittest.mock import AsyncMock, patch @@ -143,7 +144,10 @@ async def test_form_invalid_auth(hass: HomeAssistant) -> None: [ (TimeoutError, "cannot_connect"), (AioImapException(""), "cannot_connect"), + (ConnectionRefusedError, "cannot_connect"), + (socket.gaierror, "cannot_connect"), (ssl.SSLError, "ssl_error"), + (ssl.SSLCertVerificationError, "ssl_error"), ], ) async def test_form_cannot_connect( @@ -261,6 +265,42 @@ async def test_form_invalid_search(hass: HomeAssistant) -> None: assert result3["type"] is FlowResultType.CREATE_ENTRY +@pytest.mark.parametrize( + "key", [CONF_USERNAME, CONF_PASSWORD, CONF_FOLDER, CONF_SEARCH, CONF_CHARSET] +) +@pytest.mark.parametrize( + "value", + ["INBOX\x00", "INBOX\r", "INBOX\nA001 LOGOUT"], + ids=["NUL", "CR", "LF"], +) +async def test_form_invalid_characters( + hass: HomeAssistant, key: str, value: str +) -> None: + """Test we reject input that aioimaplib refuses to send to the server.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": config_entries.SOURCE_USER} + ) + + with patch( + "homeassistant.components.imap.config_flow.connect_to_server" + ) as mock_client: + result2 = await hass.config_entries.flow.async_configure( + result["flow_id"], {**MOCK_CONFIG, key: value} + ) + + mock_client.assert_not_called() + assert result2["type"] is FlowResultType.FORM + assert result2["errors"] == {key: "invalid_characters"} + + with _patch_imap_success(): + result3 = await hass.config_entries.flow.async_configure( + result["flow_id"], MOCK_CONFIG + ) + await hass.async_block_till_done() + + assert result3["type"] is FlowResultType.CREATE_ENTRY + + async def test_reauth_success(hass: HomeAssistant, mock_setup_entry: AsyncMock) -> None: """Test we can reauth.""" entry = MockConfigEntry( @@ -620,6 +660,36 @@ async def test_options_flow_when_connection_fails( assert assert_result is FlowResultType.FORM +@pytest.mark.parametrize("key", [CONF_FOLDER, CONF_SEARCH]) +async def test_options_form_invalid_characters(hass: HomeAssistant, key: str) -> None: + """Test the options flow rejects input that aioimaplib refuses to send.""" + entry = MockConfigEntry(domain=DOMAIN, data=MOCK_CONFIG) + entry.add_to_hass(hass) + await hass.config_entries.async_setup(entry.entry_id) + + result = await hass.config_entries.options.async_init(entry.entry_id) + + with patch( + "homeassistant.components.imap.config_flow.connect_to_server" + ) as mock_client: + result2 = await hass.config_entries.options.async_configure( + result["flow_id"], {**MOCK_OPTIONS, key: "INBOX\r\nA001 LOGOUT"} + ) + + mock_client.assert_not_called() + assert result2["type"] is FlowResultType.FORM + assert result2["errors"] == {key: "invalid_characters"} + assert entry.data == MOCK_CONFIG + + with _patch_imap_success(): + result3 = await hass.config_entries.options.async_configure( + result["flow_id"], MOCK_OPTIONS + ) + await hass.async_block_till_done() + + assert result3["type"] is FlowResultType.CREATE_ENTRY + + @pytest.mark.parametrize("cipher_list", ["python_default", "modern", "intermediate"]) @pytest.mark.parametrize("verify_ssl", [False, True]) async def test_config_flow_with_cipherlist_and_ssl_verify( diff --git a/tests/components/imap/test_init.py b/tests/components/imap/test_init.py index 27f8c52d56a8..28d22287f8b1 100644 --- a/tests/components/imap/test_init.py +++ b/tests/components/imap/test_init.py @@ -3,16 +3,20 @@ import asyncio from base64 import b64decode from datetime import datetime, timedelta, timezone +import socket +import ssl from typing import Any from unittest.mock import AsyncMock, MagicMock, call, patch from aioimaplib import AUTH, NONAUTH, SELECTED, AioImapException, Response +import probatio import pytest from homeassistant.components.imap import DOMAIN from homeassistant.components.imap.const import CONF_CHARSET from homeassistant.components.imap.errors import InvalidAuth, InvalidFolder from homeassistant.components.sensor import SensorStateClass +from homeassistant.config_entries import ConfigEntryState from homeassistant.const import STATE_UNAVAILABLE from homeassistant.core import HomeAssistant from homeassistant.exceptions import ServiceValidationError @@ -108,6 +112,37 @@ async def test_entry_startup_fails( assert await hass.config_entries.async_setup(config_entry.entry_id) is False +@pytest.mark.parametrize( + "exc", + [ + TimeoutError, + AioImapException("Something went wrong"), + ConnectionRefusedError, + socket.gaierror, + ssl.SSLError, + ], + ids=[ + "TimeoutError", + "AioImapException", + "ConnectionRefusedError", + "gaierror", + "SSLError", + ], +) +async def test_entry_startup_connection_error( + hass: HomeAssistant, + mock_imap_protocol: MagicMock, + exc: Exception, +) -> None: + """Test setup is retried when the imap server can not be reached.""" + mock_imap_protocol.wait_hello_from_server.side_effect = exc + config_entry = MockConfigEntry(domain=DOMAIN, data=MOCK_CONFIG) + config_entry.add_to_hass(hass) + + assert await hass.config_entries.async_setup(config_entry.entry_id) is False + assert config_entry.state is ConfigEntryState.SETUP_RETRY + + @pytest.mark.parametrize("imap_search", [TEST_SEARCH_RESPONSE]) @pytest.mark.parametrize( ("imap_fetch", "valid_date", "parts"), @@ -557,6 +592,63 @@ async def test_lost_connection_with_imap_push( assert "Canceling IDLE wait for imap.server.com" in caplog.text +@pytest.mark.parametrize("imap_has_capability", [True, False], ids=["push", "poll"]) +@pytest.mark.parametrize( + "exc", + [ConnectionRefusedError, socket.gaierror, ssl.SSLError], + ids=["ConnectionRefusedError", "gaierror", "SSLError"], +) +async def test_reconnect_after_connection_error( + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + mock_imap_protocol: MagicMock, + exc: Exception, +) -> None: + """Test we keep reconnecting after a connection error.""" + mock_imap_protocol.idle_start.return_value = asyncio.Future() + config_entry = MockConfigEntry(domain=DOMAIN, data=MOCK_CONFIG) + config_entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + now = utcnow() + + state = hass.states.get("sensor.imap_email_email_com_messages") + assert state is not None + assert state.state == "0" + + # Lose the connection and fail to reconnect + mock_imap_protocol.noop.side_effect = AioImapException("Connection lost") + mock_imap_protocol.wait_server_push.side_effect = AioImapException( + "Connection lost" + ) + mock_imap_protocol.wait_hello_from_server.side_effect = exc + for _ in range(4): + now += timedelta(seconds=15) + async_fire_time_changed(hass, now) + await hass.async_block_till_done() + + assert mock_imap_protocol.wait_hello_from_server.call_count >= 2 + state = hass.states.get("sensor.imap_email_email_com_messages") + assert state is not None + assert state.state == STATE_UNAVAILABLE + + # The server is reachable again + mock_imap_protocol.noop.side_effect = None + mock_imap_protocol.wait_server_push.side_effect = None + mock_imap_protocol.wait_hello_from_server.side_effect = None + mock_imap_protocol.protocol.state = NONAUTH + for _ in range(2): + now += timedelta(seconds=15) + async_fire_time_changed(hass, now) + await hass.async_block_till_done() + + state = hass.states.get("sensor.imap_email_email_com_messages") + assert state is not None + assert state.state == "0" + assert "Unexpected error" not in caplog.text + assert "Error doing job" not in caplog.text + + @pytest.mark.parametrize("imap_has_capability", [True], ids=["push"]) async def test_fetch_number_of_messages( hass: HomeAssistant, @@ -1024,15 +1116,25 @@ async def test_services( assert exc.value.translation_key == "invalid_entry" # Test processing imap client failures - exceptions = { - "invalid_auth": {"exc": InvalidAuth(), "translation_placeholders": None}, - "invalid_folder": {"exc": InvalidFolder(), "translation_placeholders": None}, - "imap_server_fail": { - "exc": AioImapException("Bla"), - "translation_placeholders": {"error": "Bla"}, - }, - } - for translation_key, attrs in exceptions.items(): + exceptions = [ + ("invalid_auth", {"exc": InvalidAuth(), "translation_placeholders": None}), + ("invalid_folder", {"exc": InvalidFolder(), "translation_placeholders": None}), + ( + "imap_server_fail", + { + "exc": AioImapException("Bla"), + "translation_placeholders": {"error": "Bla"}, + }, + ), + ( + "imap_server_fail", + { + "exc": ConnectionRefusedError("Bla"), + "translation_placeholders": {"error": "Bla"}, + }, + ), + ] + for translation_key, attrs in exceptions: with patch( "homeassistant.components.imap.services.connect_to_server", side_effect=attrs["exc"], @@ -1101,6 +1203,38 @@ async def test_services( assert exc.value.translation_placeholders == {"error": "Bla"} +@pytest.mark.parametrize( + ("service", "data"), + [ + pytest.param("seen", {"uid": "1\r\nA001 LOGOUT"}, id="seen_uid"), + pytest.param("delete", {"uid": "1\x00"}, id="delete_uid"), + pytest.param( + "move", + {"uid": "1", "target_folder": "Trash\nA001 LOGOUT"}, + id="move_target_folder", + ), + ], +) +async def test_services_invalid_characters( + hass: HomeAssistant, + mock_imap_protocol: MagicMock, + service: str, + data: dict[str, str], +) -> None: + """Test service arguments that aioimaplib refuses to send are rejected.""" + config_entry = MockConfigEntry(domain=DOMAIN, data=MOCK_CONFIG) + config_entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + with pytest.raises(probatio.Invalid): + await hass.services.async_call( + DOMAIN, service, {"entry": config_entry.entry_id, **data}, blocking=True + ) + mock_imap_protocol.store.assert_not_called() + mock_imap_protocol.copy.assert_not_called() + + @pytest.mark.parametrize( "imap_fetch", [