diff --git a/homeassistant/components/ipp/config_flow.py b/homeassistant/components/ipp/config_flow.py index ae2ae4bb7a777e..ff48e019757626 100644 --- a/homeassistant/components/ipp/config_flow.py +++ b/homeassistant/components/ipp/config_flow.py @@ -7,11 +7,13 @@ from pyipp import ( IPP, IPPConnectionError, + IPPConnectionTLSError, IPPConnectionUpgradeRequired, IPPError, IPPParseError, IPPResponseError, IPPVersionNotSupportedError, + Printer, ) from homeassistant.config_entries import ConfigFlow, ConfigFlowResult @@ -28,8 +30,8 @@ from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo -from .const import CONF_BASE_PATH, CONF_SERIAL, DOMAIN, REQUEST_TIMEOUT -from .coordinator import IPPConfigEntry +from .const import CONF_BASE_PATH, CONF_LEGACY_TLS, CONF_SERIAL, DOMAIN, REQUEST_TIMEOUT +from .coordinator import IPPConfigEntry, ipp_ssl_context _LOGGER = logging.getLogger(__name__) @@ -44,25 +46,98 @@ ) -async def validate_input(hass: HomeAssistant, data: dict) -> dict[str, Any]: - """Validate the user input allows us to connect. +# OpenSSL reasons with a more specific message than "tls_error". +_TLS_ERROR_KEYS = ( + ("CERTIFICATE_VERIFY_FAILED", "tls_certificate"), + ("WRONG_VERSION_NUMBER", "tls_not_offered"), + ("RECORD_LAYER_FAILURE", "tls_not_offered"), + ("PACKET_LENGTH_TOO_LONG", "tls_not_offered"), + ("HANDSHAKE_FAILURE", "tls_unsupported"), + ("PROTOCOL_VERSION", "tls_unsupported"), + ("INSUFFICIENT_SECURITY", "tls_unsupported"), + ("NO_PROTOCOLS_AVAILABLE", "tls_unsupported"), + ("UNSUPPORTED_PROTOCOL", "tls_unsupported"), + ("NO_CIPHERS_AVAILABLE", "tls_unsupported"), +) - Data has the keys from DATA_SCHEMA with values provided by the user. - """ - session = async_get_clientsession(hass) + +# Failures the older cipher suites can fix. The intermediate profile does not +# allow older TLS versions, and insufficient_security means the printer wants +# stronger suites, so neither is among them. +_LEGACY_CIPHER_REASONS = ("HANDSHAKE_FAILURE", "NO_CIPHERS_AVAILABLE") + + +def _legacy_ciphers_may_help(reason: str) -> bool: + """Return whether the older cipher suites may fix a failed handshake.""" + return any(code in reason for code in _LEGACY_CIPHER_REASONS) + + +def _tls_reason_key(reason: str) -> str: + """Return the translation key for an OpenSSL failure reason.""" + for code, key in _TLS_ERROR_KEYS: + if code in reason: + return key + return "tls_error" + + +def _tls_error_key(err: IPPConnectionTLSError, verify_ssl: bool = False) -> str: + """Return the translation key for a failed TLS handshake.""" + _LOGGER.debug("TLS connection to printer failed: %s", err.reason, exc_info=err) + if verify_ssl and _legacy_ciphers_may_help(err.reason): + # The older cipher suites are only tried without verification + return "tls_unsupported_verify_ssl" + return _tls_reason_key(err.reason) + + +async def _async_get_printer( + hass: HomeAssistant, data: dict, legacy_tls: bool +) -> Printer: + """Connect to the printer and return its attributes.""" ipp = IPP( host=data[CONF_HOST], port=data[CONF_PORT], base_path=data[CONF_BASE_PATH], tls=data[CONF_SSL], verify_ssl=data[CONF_VERIFY_SSL], - session=session, + ssl_context=ipp_ssl_context(data[CONF_VERIFY_SSL], legacy_tls), + session=async_get_clientsession(hass), request_timeout=REQUEST_TIMEOUT, ) + return await ipp.printer() - printer = await ipp.printer() - return {CONF_SERIAL: printer.info.serial, CONF_UUID: printer.info.uuid} +async def validate_input(hass: HomeAssistant, data: dict) -> dict[str, Any]: + """Validate the user input allows us to connect. + + Data has the keys from DATA_SCHEMA with values provided by the user. A + printer that rejects the TLS handshake is tried again with the older cipher + suites of the intermediate profile, but only without certificate + verification. With it, a forged handshake failure could otherwise make us + store a weaker profile for a printer that does not need it. + """ + legacy_tls = False + try: + printer = await _async_get_printer(hass, data, legacy_tls) + except IPPConnectionTLSError as err: + if data[CONF_VERIFY_SSL] or not _legacy_ciphers_may_help(err.reason): + raise + _LOGGER.debug( + "Printer rejected the TLS handshake (%s), retrying with older cipher" + " suites", + err.reason, + ) + legacy_tls = True + printer = await _async_get_printer(hass, data, legacy_tls) + + return { + CONF_SERIAL: printer.info.serial, + CONF_UUID: printer.info.uuid, + CONF_LEGACY_TLS: legacy_tls, + } + + +# Connection settings a stored entry must share with the validated endpoint +_CONNECTION_KEYS = (CONF_PORT, CONF_BASE_PATH, CONF_SSL, CONF_VERIFY_SSL) class IPPFlowHandler(ConfigFlow, domain=DOMAIN): @@ -86,6 +161,10 @@ async def async_step_user( info = await validate_input(self.hass, user_input) except IPPConnectionUpgradeRequired: return self._show_setup_form({"base": "connection_upgrade"}) + except IPPConnectionTLSError as err: + return self._show_setup_form( + {"base": _tls_error_key(err, user_input[CONF_VERIFY_SSL])} + ) except IPPConnectionError, IPPResponseError: _LOGGER.debug("IPP Connection/Response Error", exc_info=True) return self._show_setup_form({"base": "cannot_connect"}) @@ -98,6 +177,7 @@ async def async_step_user( _LOGGER.debug("IPP Error", exc_info=True) return self.async_abort(reason="ipp_error") + user_input[CONF_LEGACY_TLS] = info[CONF_LEGACY_TLS] unique_id = user_input[CONF_UUID] = info[CONF_UUID] if not unique_id and info[CONF_SERIAL]: @@ -110,7 +190,12 @@ async def async_step_user( _LOGGER.debug("Unable to determine unique id from IPP response") await self.async_set_unique_id(unique_id) - self._abort_if_unique_id_configured(updates={CONF_HOST: user_input[CONF_HOST]}) + self._abort_if_unique_id_configured( + updates={ + CONF_HOST: user_input[CONF_HOST], + **self._legacy_tls_update(user_input), + } + ) return self.async_create_entry(title=user_input[CONF_HOST], data=user_input) @@ -155,6 +240,8 @@ async def async_step_zeroconf( info = await validate_input(self.hass, self.discovery_info) except IPPConnectionUpgradeRequired: return self.async_abort(reason="connection_upgrade") + except IPPConnectionTLSError as err: + return self.async_abort(reason=_tls_error_key(err)) except IPPConnectionError, IPPResponseError: _LOGGER.debug("IPP Connection/Response Error", exc_info=True) return self.async_abort(reason="cannot_connect") @@ -167,6 +254,8 @@ async def async_step_zeroconf( _LOGGER.debug("IPP Error", exc_info=True) return self.async_abort(reason="ipp_error") + self.discovery_info[CONF_LEGACY_TLS] = info[CONF_LEGACY_TLS] + if not unique_id and info[CONF_UUID]: _LOGGER.debug( "Printer UUID is missing from discovery info. Falling back to IPP UUID" @@ -198,6 +287,7 @@ async def _async_set_unique_id_and_abort_if_already_configured( updates={ CONF_HOST: self.discovery_info[CONF_HOST], CONF_NAME: self.discovery_info[CONF_NAME], + **self._legacy_tls_update(self.discovery_info), }, ) @@ -229,6 +319,8 @@ async def async_step_reconfigure( info = await validate_input(self.hass, user_input) except IPPConnectionUpgradeRequired: errors["base"] = "connection_upgrade" + except IPPConnectionTLSError as err: + errors["base"] = _tls_error_key(err, user_input[CONF_VERIFY_SSL]) except IPPConnectionError, IPPResponseError: _LOGGER.debug("IPP Connection/Response Error", exc_info=True) errors["base"] = "cannot_connect" @@ -242,7 +334,11 @@ async def async_step_reconfigure( return self.async_abort(reason="different_device") return self.async_update_reload_and_abort( reconfigure_entry, - data_updates={**user_input, CONF_UUID: info[CONF_UUID]}, + data_updates={ + **user_input, + CONF_UUID: info[CONF_UUID], + CONF_LEGACY_TLS: info[CONF_LEGACY_TLS], + }, ) return self.async_show_form( @@ -253,6 +349,23 @@ async def async_step_reconfigure( errors=errors, ) + def _legacy_tls_update(self, data: dict[str, Any]) -> dict[str, bool]: + """Return the update that keeps a configured printer reachable. + + Only applies to an entry with the connection settings that were + validated, and only ever turns the older cipher suites on. + """ + if not data.get(CONF_LEGACY_TLS) or self.unique_id is None: + return {} + entry = self.hass.config_entries.async_entry_for_domain_unique_id( + DOMAIN, self.unique_id + ) + if entry is None or any( + entry.data.get(key) != data[key] for key in _CONNECTION_KEYS + ): + return {} + return {CONF_LEGACY_TLS: True} + def _is_same_printer(self, entry: IPPConfigEntry, info: dict[str, Any]) -> bool: """Return whether the printer info belongs to the config entry.""" if entry.unique_id == (info[CONF_UUID] or info[CONF_SERIAL]): diff --git a/homeassistant/components/ipp/const.py b/homeassistant/components/ipp/const.py index d1ad3e73fc8f9a..6aca4605587e83 100644 --- a/homeassistant/components/ipp/const.py +++ b/homeassistant/components/ipp/const.py @@ -19,5 +19,7 @@ # Config Keys CONF_BASE_PATH = "base_path" +# The printer needs the older cipher suites of the intermediate TLS profile +CONF_LEGACY_TLS = "legacy_tls" CONF_SERIAL = "serial" CONF_TLS = "tls" diff --git a/homeassistant/components/ipp/coordinator.py b/homeassistant/components/ipp/coordinator.py index 414f27aca62c97..7950f6ea085093 100644 --- a/homeassistant/components/ipp/coordinator.py +++ b/homeassistant/components/ipp/coordinator.py @@ -2,6 +2,7 @@ from datetime import timedelta import logging +from ssl import SSLContext from typing import override from pyipp import IPP, IPPConnectionError, IPPError, Printer as IPPPrinter @@ -15,8 +16,14 @@ UpdateFailed, UpdateFailedUnreachable, ) +from homeassistant.util.ssl import ( + SSL_ALPN_HTTP11, + SSLCipherList, + client_context, + client_context_no_verify, +) -from .const import CONF_BASE_PATH, DOMAIN, REQUEST_TIMEOUT +from .const import CONF_BASE_PATH, CONF_LEGACY_TLS, DOMAIN, REQUEST_TIMEOUT SCAN_INTERVAL = timedelta(seconds=60) @@ -25,6 +32,22 @@ type IPPConfigEntry = ConfigEntry[IPPDataUpdateCoordinator] +def ipp_ssl_context(verify_ssl: bool, legacy_tls: bool) -> SSLContext | None: + """Return the SSL context for talking to a printer over IPPS. + + Some printers only offer TLS_RSA_* cipher suites, which Python's default + client context leaves out. For those, use the intermediate profile, which + still prefers ECDHE suites but falls back to them. Other printers keep the + default context, so a printer that prefers static RSA keeps forward + secrecy. + """ + if not legacy_tls: + return None + if verify_ssl: + return client_context(SSLCipherList.INTERMEDIATE, SSL_ALPN_HTTP11) + return client_context_no_verify(SSLCipherList.INTERMEDIATE, SSL_ALPN_HTTP11) + + class IPPDataUpdateCoordinator(DataUpdateCoordinator[IPPPrinter]): """Class to manage fetching IPP data from single endpoint.""" @@ -39,6 +62,10 @@ def __init__(self, hass: HomeAssistant, config_entry: IPPConfigEntry) -> None: base_path=config_entry.data[CONF_BASE_PATH], tls=config_entry.data[CONF_SSL], verify_ssl=config_entry.data[CONF_VERIFY_SSL], + ssl_context=ipp_ssl_context( + config_entry.data[CONF_VERIFY_SSL], + config_entry.data.get(CONF_LEGACY_TLS, False), + ), session=async_get_clientsession(hass, config_entry.data[CONF_VERIFY_SSL]), request_timeout=REQUEST_TIMEOUT, ) diff --git a/homeassistant/components/ipp/manifest.json b/homeassistant/components/ipp/manifest.json index 11d06c6c5832a4..7d95c5c3ba25fe 100644 --- a/homeassistant/components/ipp/manifest.json +++ b/homeassistant/components/ipp/manifest.json @@ -9,6 +9,6 @@ "integration_type": "device", "iot_class": "local_polling", "loggers": ["deepmerge", "pyipp"], - "requirements": ["aioipp==0.21.2"], + "requirements": ["aioipp==0.22.0"], "zeroconf": ["_ipps._tcp.local.", "_ipp._tcp.local."] } diff --git a/homeassistant/components/ipp/strings.json b/homeassistant/components/ipp/strings.json index a14445cbe1df86..2121d358438d95 100644 --- a/homeassistant/components/ipp/strings.json +++ b/homeassistant/components/ipp/strings.json @@ -8,13 +8,22 @@ "ipp_error": "Encountered IPP error.", "ipp_version_error": "IPP version not supported by printer.", "parse_error": "Failed to parse response from printer.", + "tls_certificate": "The printer's certificate could not be verified.", + "tls_error": "The secure (TLS) connection to the printer failed.", + "tls_not_offered": "The printer did not answer with TLS on the discovered port.", + "tls_unsupported": "The printer rejected the secure connection. It may not support any of the TLS versions or cipher suites that Home Assistant offers.", "unique_id_required": "Device missing unique identification required for discovery." }, "error": { "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", "connection_upgrade": "Failed to connect to printer. Please try again with SSL/TLS option checked.", "ipp_error": "[%key:component::ipp::config::abort::ipp_error%]", - "ipp_version_error": "[%key:component::ipp::config::abort::ipp_version_error%]" + "ipp_version_error": "[%key:component::ipp::config::abort::ipp_version_error%]", + "tls_certificate": "The printer's certificate could not be verified. If the printer uses a self-signed certificate, uncheck the option to verify the SSL certificate.", + "tls_error": "[%key:component::ipp::config::abort::tls_error%]", + "tls_not_offered": "The printer did not answer with TLS on this port. Uncheck the SSL/TLS option, or check the port.", + "tls_unsupported": "[%key:component::ipp::config::abort::tls_unsupported%]", + "tls_unsupported_verify_ssl": "The printer rejected the secure connection. If it only supports older TLS cipher suites, uncheck the option to verify the SSL certificate to set it up." }, "flow_title": "{name}", "step": { diff --git a/requirements_all.txt b/requirements_all.txt index 7a278508b616be..94aeb645369687 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -338,7 +338,7 @@ aioimmich==0.18.0 aioindiallsky==0.1.8 # homeassistant.components.ipp -aioipp==0.21.2 +aioipp==0.22.0 # homeassistant.components.apache_kafka aiokafka==0.10.0 diff --git a/tests/components/ipp/test_config_flow.py b/tests/components/ipp/test_config_flow.py index 10a73681c2dcaf..7de734033c3ccb 100644 --- a/tests/components/ipp/test_config_flow.py +++ b/tests/components/ipp/test_config_flow.py @@ -7,6 +7,7 @@ from pyipp import ( IPPConnectionError, + IPPConnectionTLSError, IPPConnectionUpgradeRequired, IPPError, IPPParseError, @@ -17,7 +18,7 @@ import pytest from pytest_homeassistant.common import MockConfigEntry, load_fixture -from homeassistant.components.ipp.const import CONF_BASE_PATH, DOMAIN +from homeassistant.components.ipp.const import CONF_BASE_PATH, CONF_LEGACY_TLS, DOMAIN from homeassistant.config_entries import SOURCE_USER, SOURCE_ZEROCONF from homeassistant.const import ( CONF_HOST, @@ -30,6 +31,11 @@ from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from homeassistant.helpers import device_registry as dr +from homeassistant.util.ssl import ( + SSL_ALPN_HTTP11, + SSLCipherList, + client_context_no_verify, +) from . import ( MOCK_USER_INPUT, @@ -174,6 +180,337 @@ async def test_zeroconf_connection_upgrade_required( assert result["reason"] == "connection_upgrade" +TLS_ERRORS = [ + pytest.param("SSLV3_ALERT_HANDSHAKE_FAILURE", "tls_unsupported", 2, id="handshake"), + pytest.param("TLSV1_ALERT_PROTOCOL_VERSION", "tls_unsupported", 1, id="version"), + pytest.param( + "TLSV1_ALERT_INSUFFICIENT_SECURITY", + "tls_unsupported", + 1, + id="insufficient_security", + ), + pytest.param("WRONG_VERSION_NUMBER", "tls_not_offered", 1, id="not_tls"), + pytest.param( + "CERTIFICATE_VERIFY_FAILED: self-signed certificate", + "tls_certificate", + 1, + id="certificate", + ), + pytest.param("connection reset during handshake", "tls_error", 1, id="other"), +] + + +@pytest.mark.parametrize(("reason", "error", "attempts"), TLS_ERRORS) +async def test_user_tls_error( + hass: HomeAssistant, + mock_ipp_config_flow: MagicMock, + reason: str, + error: str, + attempts: int, +) -> None: + """Test we explain a failed TLS handshake on the user form.""" + mock_ipp_config_flow.printer.side_effect = IPPConnectionTLSError( + f"TLS handshake with IPP server failed: {reason}", reason=reason + ) + + user_input = {**MOCK_USER_INPUT, CONF_SSL: True} + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input=user_input + ) + + assert result["step_id"] == "user" + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {"base": error} + # Only a rejected handshake is retried with the older cipher suites. + assert mock_ipp_config_flow.printer.call_count == attempts + + mock_ipp_config_flow.printer.side_effect = None + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input=user_input + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["result"].unique_id == "cfe92100-67c4-11d4-a45f-f8d027761251" + assert result["data"][CONF_LEGACY_TLS] is False + + +@pytest.mark.parametrize(("reason", "error", "attempts"), TLS_ERRORS) +async def test_zeroconf_tls_error( + hass: HomeAssistant, + mock_ipp_config_flow: MagicMock, + reason: str, + error: str, + attempts: int, +) -> None: + """Test we abort the zeroconf flow with an explanation of the TLS failure.""" + mock_ipp_config_flow.printer.side_effect = IPPConnectionTLSError( + f"TLS handshake with IPP server failed: {reason}", reason=reason + ) + + discovery_info = dataclasses.replace(MOCK_ZEROCONF_IPPS_SERVICE_INFO) + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": SOURCE_ZEROCONF}, + data=discovery_info, + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == error + assert mock_ipp_config_flow.printer.call_count == attempts + + +HANDSHAKE_FAILURE = IPPConnectionTLSError( + "TLS handshake with IPP server failed: SSLV3_ALERT_HANDSHAKE_FAILURE", + reason="SSLV3_ALERT_HANDSHAKE_FAILURE", +) + + +async def test_user_flow_legacy_tls_fallback( + hass: HomeAssistant, + mock_printer: Printer, +) -> None: + """Test a rejected handshake is retried with the older cipher suites.""" + with patch( + "homeassistant.components.ipp.config_flow.IPP", autospec=True + ) as ipp_class: + ipp_class.return_value.printer.side_effect = [HANDSHAKE_FAILURE, mock_printer] + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={**MOCK_USER_INPUT, CONF_SSL: True, CONF_VERIFY_SSL: False}, + ) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["result"].unique_id == "cfe92100-67c4-11d4-a45f-f8d027761251" + assert result["data"][CONF_LEGACY_TLS] is True + first, second = ipp_class.call_args_list + assert first.kwargs["ssl_context"] is None + assert second.kwargs["ssl_context"] is client_context_no_verify( + SSLCipherList.INTERMEDIATE, SSL_ALPN_HTTP11 + ) + + +async def test_user_flow_no_legacy_tls_fallback_when_verifying( + hass: HomeAssistant, + mock_ipp_config_flow: MagicMock, + mock_printer: Printer, +) -> None: + """Test the older cipher suites are not tried with certificate verification.""" + mock_ipp_config_flow.printer.side_effect = HANDSHAKE_FAILURE + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={**MOCK_USER_INPUT, CONF_SSL: True, CONF_VERIFY_SSL: True}, + ) + + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {"base": "tls_unsupported_verify_ssl"} + assert mock_ipp_config_flow.printer.call_count == 1 + + # Following the advice and turning verification off sets the printer up + mock_ipp_config_flow.printer.side_effect = [HANDSHAKE_FAILURE, mock_printer] + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={**MOCK_USER_INPUT, CONF_SSL: True, CONF_VERIFY_SSL: False}, + ) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["result"].unique_id == "cfe92100-67c4-11d4-a45f-f8d027761251" + assert result["data"][CONF_LEGACY_TLS] is True + + +async def test_user_flow_protocol_version_not_retried_when_verifying( + hass: HomeAssistant, + mock_ipp_config_flow: MagicMock, + mock_printer: Printer, +) -> None: + """Test a TLS version mismatch does not suggest turning verification off.""" + mock_ipp_config_flow.printer.side_effect = IPPConnectionTLSError( + "TLS handshake with IPP server failed: TLSV1_ALERT_PROTOCOL_VERSION", + reason="TLSV1_ALERT_PROTOCOL_VERSION", + ) + user_input = {**MOCK_USER_INPUT, CONF_SSL: True, CONF_VERIFY_SSL: True} + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input=user_input + ) + + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {"base": "tls_unsupported"} + assert mock_ipp_config_flow.printer.call_count == 1 + + mock_ipp_config_flow.printer.side_effect = [mock_printer] + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input=user_input + ) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["result"].unique_id == "cfe92100-67c4-11d4-a45f-f8d027761251" + assert result["data"][CONF_LEGACY_TLS] is False + + +async def test_zeroconf_legacy_tls_fallback( + hass: HomeAssistant, + mock_ipp_config_flow: MagicMock, + mock_printer: Printer, +) -> None: + """Test a discovered printer that needs older cipher suites is remembered.""" + mock_ipp_config_flow.printer.side_effect = [HANDSHAKE_FAILURE, mock_printer] + + discovery_info = dataclasses.replace(MOCK_ZEROCONF_IPPS_SERVICE_INFO) + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": SOURCE_ZEROCONF}, + data=discovery_info, + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "zeroconf_confirm" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={} + ) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["result"].unique_id == "cfe92100-67c4-11d4-a45f-f8d027761251" + assert result["data"][CONF_LEGACY_TLS] is True + + +IPPS_ENTRY_SETTINGS = { + CONF_PORT: 631, + CONF_BASE_PATH: "/ipp/print", + CONF_SSL: True, + CONF_VERIFY_SSL: False, +} + + +async def test_user_existing_entry_needs_legacy_tls( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_ipp_config_flow: MagicMock, + mock_printer: Printer, +) -> None: + """Test a configured printer that now needs older cipher suites keeps working.""" + mock_config_entry.add_to_hass(hass) + hass.config_entries.async_update_entry( + mock_config_entry, data={**mock_config_entry.data, **IPPS_ENTRY_SETTINGS} + ) + original = dict(mock_config_entry.data) + mock_ipp_config_flow.printer.side_effect = [HANDSHAKE_FAILURE, mock_printer] + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={ + **MOCK_USER_INPUT, + **IPPS_ENTRY_SETTINGS, + CONF_HOST: "192.168.1.40", + }, + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + assert mock_config_entry.data == { + **original, + CONF_HOST: "192.168.1.40", + CONF_LEGACY_TLS: True, + } + + +async def test_user_existing_entry_other_endpoint_needs_legacy_tls( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_ipp_config_flow: MagicMock, + mock_printer: Printer, +) -> None: + """Test the flag is not applied to an entry with other connection settings.""" + mock_config_entry.add_to_hass(hass) + hass.config_entries.async_update_entry( + mock_config_entry, data={**mock_config_entry.data, **IPPS_ENTRY_SETTINGS} + ) + original = dict(mock_config_entry.data) + mock_ipp_config_flow.printer.side_effect = [HANDSHAKE_FAILURE, mock_printer] + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={**MOCK_USER_INPUT, **IPPS_ENTRY_SETTINGS, CONF_PORT: 443}, + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + assert mock_config_entry.data == original + + +async def test_zeroconf_existing_entry_needs_legacy_tls( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_ipp_config_flow: MagicMock, + mock_printer: Printer, +) -> None: + """Test a rediscovered printer that now needs older cipher suites keeps working.""" + mock_config_entry.add_to_hass(hass) + hass.config_entries.async_update_entry( + mock_config_entry, data={**mock_config_entry.data, **IPPS_ENTRY_SETTINGS} + ) + original = dict(mock_config_entry.data) + mock_ipp_config_flow.printer.side_effect = [HANDSHAKE_FAILURE, mock_printer] + + discovery_info = dataclasses.replace( + MOCK_ZEROCONF_IPPS_SERVICE_INFO, ip_address=ip_address("1.2.3.9") + ) + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": SOURCE_ZEROCONF}, + data=discovery_info, + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + assert mock_config_entry.data == { + **original, + CONF_HOST: "1.2.3.9", + CONF_NAME: "EPSON XP-6000 Series", + CONF_LEGACY_TLS: True, + } + + +async def test_user_existing_entry_keeps_legacy_tls( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_ipp_config_flow: MagicMock, +) -> None: + """Test re-adding a printer without the fallback leaves the flag alone.""" + mock_config_entry.add_to_hass(hass) + hass.config_entries.async_update_entry( + mock_config_entry, data={**mock_config_entry.data, CONF_LEGACY_TLS: True} + ) + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input=MOCK_USER_INPUT + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + assert mock_config_entry.data[CONF_LEGACY_TLS] is True + + async def test_user_parse_error( hass: HomeAssistant, mock_ipp_config_flow: MagicMock, @@ -615,6 +952,7 @@ async def test_reconfigure_flow( assert mock_config_entry.data == { **RECONFIGURE_INPUT, CONF_UUID: "cfe92100-67c4-11d4-a45f-f8d027761251", + CONF_LEGACY_TLS: False, } @@ -665,6 +1003,36 @@ async def test_reconfigure_zeroconf_uuid_matching_device_serial( assert mock_config_entry.data[CONF_HOST] == "192.168.1.32" +async def test_reconfigure_flow_tls_error( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_ipp_config_flow: MagicMock, +) -> None: + """Test the reconfigure flow explains a TLS failure and can recover.""" + mock_config_entry.add_to_hass(hass) + mock_ipp_config_flow.printer.side_effect = IPPConnectionTLSError( + "TLS handshake with IPP server failed: WRONG_VERSION_NUMBER", + reason="WRONG_VERSION_NUMBER", + ) + + result = await mock_config_entry.start_reconfigure_flow(hass) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input=RECONFIGURE_INPUT + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "reconfigure" + assert result["errors"] == {"base": "tls_not_offered"} + + mock_ipp_config_flow.printer.side_effect = None + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input=RECONFIGURE_INPUT + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reconfigure_successful" + + @pytest.mark.parametrize( ("side_effect", "error"), [ diff --git a/tests/components/ipp/test_init.py b/tests/components/ipp/test_init.py index f329e23442977d..6c3dac4fbb69a2 100644 --- a/tests/components/ipp/test_init.py +++ b/tests/components/ipp/test_init.py @@ -1,6 +1,7 @@ """Tests for the IPP integration.""" import logging +from ssl import SSLContext from unittest.mock import AsyncMock, MagicMock, patch from freezegun.api import FrozenDateTimeFactory @@ -13,14 +14,20 @@ import pytest from pytest_homeassistant.common import MockConfigEntry, async_fire_time_changed -from homeassistant.components.ipp.const import REQUEST_TIMEOUT +from homeassistant.components.ipp.const import CONF_LEGACY_TLS, REQUEST_TIMEOUT from homeassistant.components.ipp.coordinator import ( SCAN_INTERVAL, IPPDataUpdateCoordinator, ) from homeassistant.config_entries import ConfigEntryState -from homeassistant.const import STATE_UNAVAILABLE +from homeassistant.const import CONF_VERIFY_SSL, STATE_UNAVAILABLE from homeassistant.core import HomeAssistant +from homeassistant.util.ssl import ( + SSL_ALPN_HTTP11, + SSLCipherList, + client_context, + client_context_no_verify, +) @patch( @@ -66,6 +73,39 @@ async def test_request_timeout( assert coordinator.ipp.request_timeout == REQUEST_TIMEOUT +@pytest.mark.parametrize( + ("data", "context"), + [ + pytest.param({}, None, id="default"), + pytest.param( + {CONF_LEGACY_TLS: True}, + client_context(SSLCipherList.INTERMEDIATE, SSL_ALPN_HTTP11), + id="legacy_verify", + ), + pytest.param( + {CONF_LEGACY_TLS: True, CONF_VERIFY_SSL: False}, + client_context_no_verify(SSLCipherList.INTERMEDIATE, SSL_ALPN_HTTP11), + id="legacy_no_verify", + ), + ], +) +async def test_ssl_context( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + data: dict[str, bool], + context: SSLContext | None, +) -> None: + """Test only printers that need it get the older cipher suites.""" + mock_config_entry.add_to_hass(hass) + hass.config_entries.async_update_entry( + mock_config_entry, data={**mock_config_entry.data, **data} + ) + + coordinator = IPPDataUpdateCoordinator(hass, mock_config_entry) + + assert coordinator.ipp.ssl_context is context + + @pytest.mark.parametrize( ("exc", "level"), [