From 447b8bc1f08daa56937e3d89f5c8bba3b9897912 Mon Sep 17 00:00:00 2001 From: Brian Egge Date: Sat, 28 Nov 2026 07:12:09 -0500 Subject: [PATCH 01/11] Show the TLS failure reason in the IPP config flow Co-Authored-By: Claude Opus 5.5 --- homeassistant/components/ipp/config_flow.py | 22 +++++- homeassistant/components/ipp/strings.json | 4 +- tests/components/ipp/test_config_flow.py | 80 +++++++++++++++++++++ 3 files changed, 104 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/ipp/config_flow.py b/homeassistant/components/ipp/config_flow.py index ae2ae4bb7a777e..0911ce736bb44a 100644 --- a/homeassistant/components/ipp/config_flow.py +++ b/homeassistant/components/ipp/config_flow.py @@ -7,6 +7,7 @@ from pyipp import ( IPP, IPPConnectionError, + IPPConnectionTLSError, IPPConnectionUpgradeRequired, IPPError, IPPParseError, @@ -86,6 +87,9 @@ 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: + _LOGGER.debug("IPP TLS Error", exc_info=True) + return self._show_setup_form({"base": "tls_error"}, {"error": err.reason}) except IPPConnectionError, IPPResponseError: _LOGGER.debug("IPP Connection/Response Error", exc_info=True) return self._show_setup_form({"base": "cannot_connect"}) @@ -155,6 +159,11 @@ 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: + _LOGGER.debug("IPP TLS Error", exc_info=True) + return self.async_abort( + reason="tls_error", description_placeholders={"error": err.reason} + ) except IPPConnectionError, IPPResponseError: _LOGGER.debug("IPP Connection/Response Error", exc_info=True) return self.async_abort(reason="cannot_connect") @@ -222,6 +231,7 @@ async def async_step_reconfigure( ) -> ConfigFlowResult: """Handle reconfiguration of an IPP printer.""" errors: dict[str, str] = {} + placeholders: dict[str, str] = {} reconfigure_entry = self._get_reconfigure_entry() if user_input is not None: @@ -229,6 +239,10 @@ async def async_step_reconfigure( info = await validate_input(self.hass, user_input) except IPPConnectionUpgradeRequired: errors["base"] = "connection_upgrade" + except IPPConnectionTLSError as err: + _LOGGER.debug("IPP TLS Error", exc_info=True) + errors["base"] = "tls_error" + placeholders["error"] = err.reason except IPPConnectionError, IPPResponseError: _LOGGER.debug("IPP Connection/Response Error", exc_info=True) errors["base"] = "cannot_connect" @@ -251,6 +265,7 @@ async def async_step_reconfigure( DATA_SCHEMA, user_input or reconfigure_entry.data ), errors=errors, + description_placeholders=placeholders, ) def _is_same_printer(self, entry: IPPConfigEntry, info: dict[str, Any]) -> bool: @@ -266,10 +281,15 @@ def _is_same_printer(self, entry: IPPConfigEntry, info: dict[str, Any]) -> bool: ) ) - def _show_setup_form(self, errors: dict | None = None) -> ConfigFlowResult: + def _show_setup_form( + self, + errors: dict | None = None, + placeholders: dict[str, str] | None = None, + ) -> ConfigFlowResult: """Show the setup form to the user.""" return self.async_show_form( step_id="user", data_schema=DATA_SCHEMA, errors=errors or {}, + description_placeholders=placeholders, ) diff --git a/homeassistant/components/ipp/strings.json b/homeassistant/components/ipp/strings.json index a14445cbe1df86..7728952caf3ae9 100644 --- a/homeassistant/components/ipp/strings.json +++ b/homeassistant/components/ipp/strings.json @@ -8,13 +8,15 @@ "ipp_error": "Encountered IPP error.", "ipp_version_error": "IPP version not supported by printer.", "parse_error": "Failed to parse response from printer.", + "tls_error": "The secure (TLS) connection to the printer failed: {error}", "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_error": "[%key:component::ipp::config::abort::tls_error%]" }, "flow_title": "{name}", "step": { diff --git a/tests/components/ipp/test_config_flow.py b/tests/components/ipp/test_config_flow.py index 10a73681c2dcaf..c89dd81d75c8da 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, @@ -174,6 +175,62 @@ async def test_zeroconf_connection_upgrade_required( assert result["reason"] == "connection_upgrade" +async def test_user_tls_error( + hass: HomeAssistant, + mock_ipp_config_flow: MagicMock, +) -> None: + """Test we show the TLS failure reason on the user form.""" + mock_ipp_config_flow.printer.side_effect = IPPConnectionTLSError( + "TLS handshake with IPP server failed: SSLV3_ALERT_HANDSHAKE_FAILURE", + reason="SSLV3_ALERT_HANDSHAKE_FAILURE", + ) + + 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": "tls_error"} + assert result["description_placeholders"] == { + "error": "SSLV3_ALERT_HANDSHAKE_FAILURE" + } + + 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 + + +async def test_zeroconf_tls_error( + hass: HomeAssistant, + mock_ipp_config_flow: MagicMock, +) -> None: + """Test we abort the zeroconf flow with the TLS failure reason.""" + mock_ipp_config_flow.printer.side_effect = IPPConnectionTLSError( + "TLS handshake with IPP server failed: SSLV3_ALERT_HANDSHAKE_FAILURE", + reason="SSLV3_ALERT_HANDSHAKE_FAILURE", + ) + + 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"] == "tls_error" + assert result["description_placeholders"] == { + "error": "SSLV3_ALERT_HANDSHAKE_FAILURE" + } + + async def test_user_parse_error( hass: HomeAssistant, mock_ipp_config_flow: MagicMock, @@ -665,6 +722,29 @@ 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 shows the TLS failure reason.""" + 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_error"} + assert result["description_placeholders"] == {"error": "WRONG_VERSION_NUMBER"} + + @pytest.mark.parametrize( ("side_effect", "error"), [ From cada57e7e774e0601d8d2c5c5886e57e2132b456 Mon Sep 17 00:00:00 2001 From: Brian Egge Date: Mon, 30 Nov 2026 11:53:38 -0500 Subject: [PATCH 02/11] Offer the intermediate cipher list to IPPS printers Co-Authored-By: Claude Opus 5.5 --- homeassistant/components/ipp/config_flow.py | 3 ++- homeassistant/components/ipp/coordinator.py | 19 ++++++++++++++++ tests/components/ipp/test_config_flow.py | 24 +++++++++++++++++++++ tests/components/ipp/test_init.py | 24 ++++++++++++++++++++- 4 files changed, 68 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/ipp/config_flow.py b/homeassistant/components/ipp/config_flow.py index 0911ce736bb44a..a562f48cce8004 100644 --- a/homeassistant/components/ipp/config_flow.py +++ b/homeassistant/components/ipp/config_flow.py @@ -30,7 +30,7 @@ from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo from .const import CONF_BASE_PATH, CONF_SERIAL, DOMAIN, REQUEST_TIMEOUT -from .coordinator import IPPConfigEntry +from .coordinator import IPPConfigEntry, ipp_ssl_context _LOGGER = logging.getLogger(__name__) @@ -57,6 +57,7 @@ async def validate_input(hass: HomeAssistant, data: dict) -> dict[str, Any]: base_path=data[CONF_BASE_PATH], tls=data[CONF_SSL], verify_ssl=data[CONF_VERIFY_SSL], + ssl_context=ipp_ssl_context(data[CONF_VERIFY_SSL]), session=session, request_timeout=REQUEST_TIMEOUT, ) diff --git a/homeassistant/components/ipp/coordinator.py b/homeassistant/components/ipp/coordinator.py index 414f27aca62c97..30ffb9e4f1cea3 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,6 +16,11 @@ UpdateFailed, UpdateFailedUnreachable, ) +from homeassistant.util.ssl import ( + SSLCipherList, + client_context, + client_context_no_verify, +) from .const import CONF_BASE_PATH, DOMAIN, REQUEST_TIMEOUT @@ -25,6 +31,18 @@ type IPPConfigEntry = ConfigEntry[IPPDataUpdateCoordinator] +def ipp_ssl_context(verify_ssl: bool) -> SSLContext: + """Return the SSL context for talking to a printer over IPPS. + + Many printers only offer TLS_RSA_* cipher suites, which Python's default + client context leaves out. The intermediate profile still prefers ECDHE + suites but falls back to those. + """ + if verify_ssl: + return client_context(SSLCipherList.INTERMEDIATE) + return client_context_no_verify(SSLCipherList.INTERMEDIATE) + + class IPPDataUpdateCoordinator(DataUpdateCoordinator[IPPPrinter]): """Class to manage fetching IPP data from single endpoint.""" @@ -39,6 +57,7 @@ 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]), session=async_get_clientsession(hass, config_entry.data[CONF_VERIFY_SSL]), request_timeout=REQUEST_TIMEOUT, ) diff --git a/tests/components/ipp/test_config_flow.py b/tests/components/ipp/test_config_flow.py index c89dd81d75c8da..78e17d56a08e0c 100644 --- a/tests/components/ipp/test_config_flow.py +++ b/tests/components/ipp/test_config_flow.py @@ -31,6 +31,7 @@ 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 SSLCipherList, client_context_no_verify from . import ( MOCK_USER_INPUT, @@ -231,6 +232,29 @@ async def test_zeroconf_tls_error( } +async def test_user_flow_ssl_context( + hass: HomeAssistant, + mock_printer: Printer, +) -> None: + """Test the user flow offers the intermediate cipher list over IPPS.""" + with patch( + "homeassistant.components.ipp.config_flow.IPP", autospec=True + ) as ipp_class: + ipp_class.return_value.printer.return_value = 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 ipp_class.call_args.kwargs["ssl_context"] is client_context_no_verify( + SSLCipherList.INTERMEDIATE + ) + + async def test_user_parse_error( hass: HomeAssistant, mock_ipp_config_flow: MagicMock, diff --git a/tests/components/ipp/test_init.py b/tests/components/ipp/test_init.py index f329e23442977d..eb8143070f6705 100644 --- a/tests/components/ipp/test_init.py +++ b/tests/components/ipp/test_init.py @@ -19,8 +19,13 @@ 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 ( + SSLCipherList, + client_context, + client_context_no_verify, +) @patch( @@ -66,6 +71,23 @@ async def test_request_timeout( assert coordinator.ipp.request_timeout == REQUEST_TIMEOUT +async def test_ssl_context( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """Test IPPS uses the intermediate cipher list, verified or not.""" + mock_config_entry.add_to_hass(hass) + coordinator = IPPDataUpdateCoordinator(hass, mock_config_entry) + assert coordinator.ipp.ssl_context is client_context(SSLCipherList.INTERMEDIATE) + + hass.config_entries.async_update_entry( + mock_config_entry, data={**mock_config_entry.data, CONF_VERIFY_SSL: False} + ) + coordinator = IPPDataUpdateCoordinator(hass, mock_config_entry) + assert coordinator.ipp.ssl_context is client_context_no_verify( + SSLCipherList.INTERMEDIATE + ) + + @pytest.mark.parametrize( ("exc", "level"), [ From 0e929c75012053e26e1257ce9f635472d55fc0be Mon Sep 17 00:00:00 2001 From: Brian Egge Date: Mon, 30 Nov 2026 12:09:52 -0500 Subject: [PATCH 03/11] Bump aioipp to 0.22.0 Co-Authored-By: Claude Opus 5.5 --- homeassistant/components/ipp/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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/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 From a1c3e143ab15d5a81231ad8678ad15c0c8826dd6 Mon Sep 17 00:00:00 2001 From: Brian Egge Date: Mon, 30 Nov 2026 13:21:49 -0500 Subject: [PATCH 04/11] Explain TLS failures with translated messages and negotiate HTTP/1.1 Map OpenSSL's reason to tls_unsupported, tls_not_offered or tls_certificate (tls_error otherwise) instead of showing the raw code, and log the code at debug level. Use SSL_ALPN_HTTP11 like the shared HTTP client. Config flow tests now finish the flow after an error and assert the unique ID. Co-Authored-By: Claude Opus 5.5 --- homeassistant/components/ipp/config_flow.py | 45 +++++++++------ homeassistant/components/ipp/coordinator.py | 5 +- homeassistant/components/ipp/strings.json | 10 +++- tests/components/ipp/test_config_flow.py | 62 ++++++++++++++------- tests/components/ipp/test_init.py | 7 ++- 5 files changed, 87 insertions(+), 42 deletions(-) diff --git a/homeassistant/components/ipp/config_flow.py b/homeassistant/components/ipp/config_flow.py index a562f48cce8004..61e790ae6c2732 100644 --- a/homeassistant/components/ipp/config_flow.py +++ b/homeassistant/components/ipp/config_flow.py @@ -45,6 +45,30 @@ ) +# 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"), +) + + +def _tls_error_key(err: IPPConnectionTLSError) -> str: + """Return the translation key for a failed TLS handshake.""" + _LOGGER.debug("TLS connection to printer failed: %s", err.reason, exc_info=err) + for reason, key in _TLS_ERROR_KEYS: + if reason in err.reason: + return key + return "tls_error" + + async def validate_input(hass: HomeAssistant, data: dict) -> dict[str, Any]: """Validate the user input allows us to connect. @@ -89,8 +113,7 @@ async def async_step_user( except IPPConnectionUpgradeRequired: return self._show_setup_form({"base": "connection_upgrade"}) except IPPConnectionTLSError as err: - _LOGGER.debug("IPP TLS Error", exc_info=True) - return self._show_setup_form({"base": "tls_error"}, {"error": err.reason}) + return self._show_setup_form({"base": _tls_error_key(err)}) except IPPConnectionError, IPPResponseError: _LOGGER.debug("IPP Connection/Response Error", exc_info=True) return self._show_setup_form({"base": "cannot_connect"}) @@ -161,10 +184,7 @@ async def async_step_zeroconf( except IPPConnectionUpgradeRequired: return self.async_abort(reason="connection_upgrade") except IPPConnectionTLSError as err: - _LOGGER.debug("IPP TLS Error", exc_info=True) - return self.async_abort( - reason="tls_error", description_placeholders={"error": err.reason} - ) + 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") @@ -232,7 +252,6 @@ async def async_step_reconfigure( ) -> ConfigFlowResult: """Handle reconfiguration of an IPP printer.""" errors: dict[str, str] = {} - placeholders: dict[str, str] = {} reconfigure_entry = self._get_reconfigure_entry() if user_input is not None: @@ -241,9 +260,7 @@ async def async_step_reconfigure( except IPPConnectionUpgradeRequired: errors["base"] = "connection_upgrade" except IPPConnectionTLSError as err: - _LOGGER.debug("IPP TLS Error", exc_info=True) - errors["base"] = "tls_error" - placeholders["error"] = err.reason + errors["base"] = _tls_error_key(err) except IPPConnectionError, IPPResponseError: _LOGGER.debug("IPP Connection/Response Error", exc_info=True) errors["base"] = "cannot_connect" @@ -266,7 +283,6 @@ async def async_step_reconfigure( DATA_SCHEMA, user_input or reconfigure_entry.data ), errors=errors, - description_placeholders=placeholders, ) def _is_same_printer(self, entry: IPPConfigEntry, info: dict[str, Any]) -> bool: @@ -282,15 +298,10 @@ def _is_same_printer(self, entry: IPPConfigEntry, info: dict[str, Any]) -> bool: ) ) - def _show_setup_form( - self, - errors: dict | None = None, - placeholders: dict[str, str] | None = None, - ) -> ConfigFlowResult: + def _show_setup_form(self, errors: dict | None = None) -> ConfigFlowResult: """Show the setup form to the user.""" return self.async_show_form( step_id="user", data_schema=DATA_SCHEMA, errors=errors or {}, - description_placeholders=placeholders, ) diff --git a/homeassistant/components/ipp/coordinator.py b/homeassistant/components/ipp/coordinator.py index 30ffb9e4f1cea3..f5be437052210c 100644 --- a/homeassistant/components/ipp/coordinator.py +++ b/homeassistant/components/ipp/coordinator.py @@ -17,6 +17,7 @@ UpdateFailedUnreachable, ) from homeassistant.util.ssl import ( + SSL_ALPN_HTTP11, SSLCipherList, client_context, client_context_no_verify, @@ -39,8 +40,8 @@ def ipp_ssl_context(verify_ssl: bool) -> SSLContext: suites but falls back to those. """ if verify_ssl: - return client_context(SSLCipherList.INTERMEDIATE) - return client_context_no_verify(SSLCipherList.INTERMEDIATE) + return client_context(SSLCipherList.INTERMEDIATE, SSL_ALPN_HTTP11) + return client_context_no_verify(SSLCipherList.INTERMEDIATE, SSL_ALPN_HTTP11) class IPPDataUpdateCoordinator(DataUpdateCoordinator[IPPPrinter]): diff --git a/homeassistant/components/ipp/strings.json b/homeassistant/components/ipp/strings.json index 7728952caf3ae9..11c63950aa147f 100644 --- a/homeassistant/components/ipp/strings.json +++ b/homeassistant/components/ipp/strings.json @@ -8,7 +8,10 @@ "ipp_error": "Encountered IPP error.", "ipp_version_error": "IPP version not supported by printer.", "parse_error": "Failed to parse response from printer.", - "tls_error": "The secure (TLS) connection to the printer failed: {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": "The secure (TLS) connection to the printer failed.", + "tls_not_offered": "The printer did not answer with TLS on this port. Uncheck the SSL/TLS option, or check the port.", + "tls_unsupported": "The printer does 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": { @@ -16,7 +19,10 @@ "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%]", - "tls_error": "[%key:component::ipp::config::abort::tls_error%]" + "tls_certificate": "[%key:component::ipp::config::abort::tls_certificate%]", + "tls_error": "[%key:component::ipp::config::abort::tls_error%]", + "tls_not_offered": "[%key:component::ipp::config::abort::tls_not_offered%]", + "tls_unsupported": "[%key:component::ipp::config::abort::tls_unsupported%]" }, "flow_title": "{name}", "step": { diff --git a/tests/components/ipp/test_config_flow.py b/tests/components/ipp/test_config_flow.py index 78e17d56a08e0c..98e55ea26ba1bd 100644 --- a/tests/components/ipp/test_config_flow.py +++ b/tests/components/ipp/test_config_flow.py @@ -31,7 +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 SSLCipherList, client_context_no_verify +from homeassistant.util.ssl import ( + SSL_ALPN_HTTP11, + SSLCipherList, + client_context_no_verify, +) from . import ( MOCK_USER_INPUT, @@ -176,14 +180,29 @@ async def test_zeroconf_connection_upgrade_required( assert result["reason"] == "connection_upgrade" +TLS_ERRORS = [ + pytest.param("SSLV3_ALERT_HANDSHAKE_FAILURE", "tls_unsupported", id="handshake"), + pytest.param("TLSV1_ALERT_PROTOCOL_VERSION", "tls_unsupported", id="version"), + pytest.param("WRONG_VERSION_NUMBER", "tls_not_offered", id="not_tls"), + pytest.param( + "CERTIFICATE_VERIFY_FAILED: self-signed certificate", + "tls_certificate", + id="certificate", + ), + pytest.param("connection reset during handshake", "tls_error", id="other"), +] + + +@pytest.mark.parametrize(("reason", "error"), TLS_ERRORS) async def test_user_tls_error( hass: HomeAssistant, mock_ipp_config_flow: MagicMock, + reason: str, + error: str, ) -> None: - """Test we show the TLS failure reason on the user form.""" + """Test we explain a failed TLS handshake on the user form.""" mock_ipp_config_flow.printer.side_effect = IPPConnectionTLSError( - "TLS handshake with IPP server failed: SSLV3_ALERT_HANDSHAKE_FAILURE", - reason="SSLV3_ALERT_HANDSHAKE_FAILURE", + f"TLS handshake with IPP server failed: {reason}", reason=reason ) user_input = {**MOCK_USER_INPUT, CONF_SSL: True} @@ -196,26 +215,26 @@ async def test_user_tls_error( assert result["step_id"] == "user" assert result["type"] is FlowResultType.FORM - assert result["errors"] == {"base": "tls_error"} - assert result["description_placeholders"] == { - "error": "SSLV3_ALERT_HANDSHAKE_FAILURE" - } + assert result["errors"] == {"base": error} 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" +@pytest.mark.parametrize(("reason", "error"), TLS_ERRORS) async def test_zeroconf_tls_error( hass: HomeAssistant, mock_ipp_config_flow: MagicMock, + reason: str, + error: str, ) -> None: - """Test we abort the zeroconf flow with the TLS failure reason.""" + """Test we abort the zeroconf flow with an explanation of the TLS failure.""" mock_ipp_config_flow.printer.side_effect = IPPConnectionTLSError( - "TLS handshake with IPP server failed: SSLV3_ALERT_HANDSHAKE_FAILURE", - reason="SSLV3_ALERT_HANDSHAKE_FAILURE", + f"TLS handshake with IPP server failed: {reason}", reason=reason ) discovery_info = dataclasses.replace(MOCK_ZEROCONF_IPPS_SERVICE_INFO) @@ -226,10 +245,7 @@ async def test_zeroconf_tls_error( ) assert result["type"] is FlowResultType.ABORT - assert result["reason"] == "tls_error" - assert result["description_placeholders"] == { - "error": "SSLV3_ALERT_HANDSHAKE_FAILURE" - } + assert result["reason"] == error async def test_user_flow_ssl_context( @@ -250,8 +266,9 @@ async def test_user_flow_ssl_context( ) assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["result"].unique_id == "cfe92100-67c4-11d4-a45f-f8d027761251" assert ipp_class.call_args.kwargs["ssl_context"] is client_context_no_verify( - SSLCipherList.INTERMEDIATE + SSLCipherList.INTERMEDIATE, SSL_ALPN_HTTP11 ) @@ -751,7 +768,7 @@ async def test_reconfigure_flow_tls_error( mock_config_entry: MockConfigEntry, mock_ipp_config_flow: MagicMock, ) -> None: - """Test the reconfigure flow shows the TLS failure reason.""" + """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", @@ -765,8 +782,15 @@ async def test_reconfigure_flow_tls_error( assert result["type"] is FlowResultType.FORM assert result["step_id"] == "reconfigure" - assert result["errors"] == {"base": "tls_error"} - assert result["description_placeholders"] == {"error": "WRONG_VERSION_NUMBER"} + 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( diff --git a/tests/components/ipp/test_init.py b/tests/components/ipp/test_init.py index eb8143070f6705..6270f883037681 100644 --- a/tests/components/ipp/test_init.py +++ b/tests/components/ipp/test_init.py @@ -22,6 +22,7 @@ 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, @@ -77,14 +78,16 @@ async def test_ssl_context( """Test IPPS uses the intermediate cipher list, verified or not.""" mock_config_entry.add_to_hass(hass) coordinator = IPPDataUpdateCoordinator(hass, mock_config_entry) - assert coordinator.ipp.ssl_context is client_context(SSLCipherList.INTERMEDIATE) + assert coordinator.ipp.ssl_context is client_context( + SSLCipherList.INTERMEDIATE, SSL_ALPN_HTTP11 + ) hass.config_entries.async_update_entry( mock_config_entry, data={**mock_config_entry.data, CONF_VERIFY_SSL: False} ) coordinator = IPPDataUpdateCoordinator(hass, mock_config_entry) assert coordinator.ipp.ssl_context is client_context_no_verify( - SSLCipherList.INTERMEDIATE + SSLCipherList.INTERMEDIATE, SSL_ALPN_HTTP11 ) From 8fef3c76e88548e95335c7385fcf18897cff3dd5 Mon Sep 17 00:00:00 2001 From: Brian Egge Date: Mon, 30 Nov 2026 13:34:34 -0500 Subject: [PATCH 05/11] Keep TLS abort messages neutral and hedge the handshake failure cause Zeroconf aborts can't show the connection form, so only the form errors tell the user what to change. A handshake_failure alert can also come from SNI or client-certificate requirements, so describe a version or cipher mismatch as likely rather than certain. Co-Authored-By: Claude Opus 5.5 --- homeassistant/components/ipp/strings.json | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/homeassistant/components/ipp/strings.json b/homeassistant/components/ipp/strings.json index 11c63950aa147f..51d78025092647 100644 --- a/homeassistant/components/ipp/strings.json +++ b/homeassistant/components/ipp/strings.json @@ -8,10 +8,10 @@ "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. If the printer uses a self-signed certificate, uncheck the option to verify the SSL certificate.", + "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 this port. Uncheck the SSL/TLS option, or check the port.", - "tls_unsupported": "The printer does not support any of the TLS versions or cipher suites that Home Assistant offers.", + "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": { @@ -19,9 +19,9 @@ "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%]", - "tls_certificate": "[%key:component::ipp::config::abort::tls_certificate%]", + "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": "[%key:component::ipp::config::abort::tls_not_offered%]", + "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%]" }, "flow_title": "{name}", From 73faf8f8e73b3148cf5f113d156c2a29195ba53d Mon Sep 17 00:00:00 2001 From: Brian Egge Date: Mon, 30 Nov 2026 14:34:24 -0500 Subject: [PATCH 06/11] Use the older cipher suites only for printers that need them A TLS 1.2 printer may choose its own cipher order, so offering the intermediate profile to every printer could move one that supports ECDHE but prefers static RSA onto a suite without forward secrecy. Connect with the default context first. Only when the printer rejects the handshake, retry with the intermediate profile and record legacy_tls on the entry; the coordinator uses the intermediate profile only for those entries. Existing entries keep the default context. Co-Authored-By: Claude Opus 5.5 --- homeassistant/components/ipp/config_flow.py | 68 +++++++++++++----- homeassistant/components/ipp/const.py | 2 + homeassistant/components/ipp/coordinator.py | 19 +++-- tests/components/ipp/test_config_flow.py | 77 +++++++++++++++++++-- tests/components/ipp/test_init.py | 39 +++++++---- 5 files changed, 164 insertions(+), 41 deletions(-) diff --git a/homeassistant/components/ipp/config_flow.py b/homeassistant/components/ipp/config_flow.py index 61e790ae6c2732..df92a0f3e46c70 100644 --- a/homeassistant/components/ipp/config_flow.py +++ b/homeassistant/components/ipp/config_flow.py @@ -13,6 +13,7 @@ IPPParseError, IPPResponseError, IPPVersionNotSupportedError, + Printer, ) from homeassistant.config_entries import ConfigFlow, ConfigFlowResult @@ -29,7 +30,7 @@ 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 .const import CONF_BASE_PATH, CONF_LEGACY_TLS, CONF_SERIAL, DOMAIN, REQUEST_TIMEOUT from .coordinator import IPPConfigEntry, ipp_ssl_context _LOGGER = logging.getLogger(__name__) @@ -60,35 +61,63 @@ ) -def _tls_error_key(err: IPPConnectionTLSError) -> str: - """Return the translation key for a failed TLS handshake.""" - _LOGGER.debug("TLS connection to printer failed: %s", err.reason, exc_info=err) - for reason, key in _TLS_ERROR_KEYS: - if reason in err.reason: +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" -async def validate_input(hass: HomeAssistant, data: dict) -> dict[str, Any]: - """Validate the user input allows us to connect. +def _tls_error_key(err: IPPConnectionTLSError) -> str: + """Return the translation key for a failed TLS handshake.""" + _LOGGER.debug("TLS connection to printer failed: %s", err.reason, exc_info=err) + return _tls_reason_key(err.reason) - Data has the keys from DATA_SCHEMA with values provided by the user. - """ - session = async_get_clientsession(hass) + +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], - ssl_context=ipp_ssl_context(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. + """ + legacy_tls = False + try: + printer = await _async_get_printer(hass, data, legacy_tls) + except IPPConnectionTLSError as err: + if _tls_reason_key(err.reason) != "tls_unsupported": + 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, + } class IPPFlowHandler(ConfigFlow, domain=DOMAIN): @@ -126,6 +155,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]: @@ -197,6 +227,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" @@ -274,7 +306,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( 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 f5be437052210c..7950f6ea085093 100644 --- a/homeassistant/components/ipp/coordinator.py +++ b/homeassistant/components/ipp/coordinator.py @@ -23,7 +23,7 @@ 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) @@ -32,13 +32,17 @@ type IPPConfigEntry = ConfigEntry[IPPDataUpdateCoordinator] -def ipp_ssl_context(verify_ssl: bool) -> SSLContext: +def ipp_ssl_context(verify_ssl: bool, legacy_tls: bool) -> SSLContext | None: """Return the SSL context for talking to a printer over IPPS. - Many printers only offer TLS_RSA_* cipher suites, which Python's default - client context leaves out. The intermediate profile still prefers ECDHE - suites but falls back to those. + 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) @@ -58,7 +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]), + 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/tests/components/ipp/test_config_flow.py b/tests/components/ipp/test_config_flow.py index 98e55ea26ba1bd..5a46d3c5b32f80 100644 --- a/tests/components/ipp/test_config_flow.py +++ b/tests/components/ipp/test_config_flow.py @@ -3,6 +3,7 @@ import dataclasses from ipaddress import ip_address import json +from ssl import SSLContext from unittest.mock import MagicMock, patch from pyipp import ( @@ -18,7 +19,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, @@ -34,6 +35,7 @@ from homeassistant.util.ssl import ( SSL_ALPN_HTTP11, SSLCipherList, + client_context, client_context_no_verify, ) @@ -216,6 +218,10 @@ async def test_user_tls_error( 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 == ( + 2 if error == "tls_unsupported" else 1 + ) mock_ipp_config_flow.printer.side_effect = None result = await hass.config_entries.flow.async_configure( @@ -223,6 +229,7 @@ async def test_user_tls_error( ) 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"), TLS_ERRORS) @@ -248,29 +255,84 @@ async def test_zeroconf_tls_error( assert result["reason"] == error -async def test_user_flow_ssl_context( +HANDSHAKE_FAILURE = IPPConnectionTLSError( + "TLS handshake with IPP server failed: SSLV3_ALERT_HANDSHAKE_FAILURE", + reason="SSLV3_ALERT_HANDSHAKE_FAILURE", +) + + +@pytest.mark.parametrize( + ("verify_ssl", "context"), + [ + pytest.param( + False, + client_context_no_verify(SSLCipherList.INTERMEDIATE, SSL_ALPN_HTTP11), + id="no_verify", + ), + pytest.param( + True, + client_context(SSLCipherList.INTERMEDIATE, SSL_ALPN_HTTP11), + id="verify", + ), + ], +) +async def test_user_flow_legacy_tls_fallback( hass: HomeAssistant, mock_printer: Printer, + *, + verify_ssl: bool, + context: SSLContext, ) -> None: - """Test the user flow offers the intermediate cipher list over IPPS.""" + """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.return_value = mock_printer + 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}, + user_input={ + **MOCK_USER_INPUT, + CONF_SSL: True, + CONF_VERIFY_SSL: verify_ssl, + }, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["result"].unique_id == "cfe92100-67c4-11d4-a45f-f8d027761251" - assert ipp_class.call_args.kwargs["ssl_context"] is client_context_no_verify( - SSLCipherList.INTERMEDIATE, SSL_ALPN_HTTP11 + 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 context + + +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 + async def test_user_parse_error( hass: HomeAssistant, @@ -713,6 +775,7 @@ async def test_reconfigure_flow( assert mock_config_entry.data == { **RECONFIGURE_INPUT, CONF_UUID: "cfe92100-67c4-11d4-a45f-f8d027761251", + CONF_LEGACY_TLS: False, } diff --git a/tests/components/ipp/test_init.py b/tests/components/ipp/test_init.py index 6270f883037681..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,7 +14,7 @@ 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, @@ -72,23 +73,37 @@ 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 + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + data: dict[str, bool], + context: SSLContext | None, ) -> None: - """Test IPPS uses the intermediate cipher list, verified or not.""" + """Test only printers that need it get the older cipher suites.""" mock_config_entry.add_to_hass(hass) - coordinator = IPPDataUpdateCoordinator(hass, mock_config_entry) - assert coordinator.ipp.ssl_context is client_context( - SSLCipherList.INTERMEDIATE, SSL_ALPN_HTTP11 - ) - hass.config_entries.async_update_entry( - mock_config_entry, data={**mock_config_entry.data, CONF_VERIFY_SSL: False} + mock_config_entry, data={**mock_config_entry.data, **data} ) + coordinator = IPPDataUpdateCoordinator(hass, mock_config_entry) - assert coordinator.ipp.ssl_context is client_context_no_verify( - SSLCipherList.INTERMEDIATE, SSL_ALPN_HTTP11 - ) + + assert coordinator.ipp.ssl_context is context @pytest.mark.parametrize( From 2191307548f7611796d7730ba22dceaca55abd99 Mon Sep 17 00:00:00 2001 From: Brian Egge Date: Mon, 30 Nov 2026 14:52:41 -0500 Subject: [PATCH 07/11] Carry the legacy TLS flag to an existing entry and parametrize attempts When the user or zeroconf step finds a configured printer that now needs the older cipher suites, set legacy_tls along with the new host. The flag is only ever turned on, which is safe: it is ignored without TLS and the intermediate profile still prefers ECDHE. Expected connection attempts in the TLS error tests are now a parameter. Co-Authored-By: Claude Opus 5.5 --- homeassistant/components/ipp/config_flow.py | 19 ++++- tests/components/ipp/test_config_flow.py | 92 +++++++++++++++++++-- 2 files changed, 101 insertions(+), 10 deletions(-) diff --git a/homeassistant/components/ipp/config_flow.py b/homeassistant/components/ipp/config_flow.py index df92a0f3e46c70..3b45354c9b7f8d 100644 --- a/homeassistant/components/ipp/config_flow.py +++ b/homeassistant/components/ipp/config_flow.py @@ -120,6 +120,17 @@ async def validate_input(hass: HomeAssistant, data: dict) -> dict[str, Any]: } +def _legacy_tls_update(data: dict[str, Any]) -> dict[str, bool]: + """Return the entry update that keeps a moved printer reachable. + + Only ever turns the older cipher suites on: they are ignored without TLS + and still prefer ECDHE, so setting the flag cannot break an entry. + """ + if data.get(CONF_LEGACY_TLS): + return {CONF_LEGACY_TLS: True} + return {} + + class IPPFlowHandler(ConfigFlow, domain=DOMAIN): """Handle an IPP config flow.""" @@ -168,7 +179,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], + **_legacy_tls_update(user_input), + } + ) return self.async_create_entry(title=user_input[CONF_HOST], data=user_input) @@ -260,6 +276,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], + **_legacy_tls_update(self.discovery_info), }, ) diff --git a/tests/components/ipp/test_config_flow.py b/tests/components/ipp/test_config_flow.py index 5a46d3c5b32f80..4b9655d40fa482 100644 --- a/tests/components/ipp/test_config_flow.py +++ b/tests/components/ipp/test_config_flow.py @@ -183,24 +183,26 @@ async def test_zeroconf_connection_upgrade_required( TLS_ERRORS = [ - pytest.param("SSLV3_ALERT_HANDSHAKE_FAILURE", "tls_unsupported", id="handshake"), - pytest.param("TLSV1_ALERT_PROTOCOL_VERSION", "tls_unsupported", id="version"), - pytest.param("WRONG_VERSION_NUMBER", "tls_not_offered", id="not_tls"), + pytest.param("SSLV3_ALERT_HANDSHAKE_FAILURE", "tls_unsupported", 2, id="handshake"), + pytest.param("TLSV1_ALERT_PROTOCOL_VERSION", "tls_unsupported", 2, id="version"), + 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", id="other"), + pytest.param("connection reset during handshake", "tls_error", 1, id="other"), ] -@pytest.mark.parametrize(("reason", "error"), TLS_ERRORS) +@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( @@ -219,9 +221,7 @@ async def test_user_tls_error( 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 == ( - 2 if error == "tls_unsupported" else 1 - ) + 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( @@ -232,12 +232,13 @@ async def test_user_tls_error( assert result["data"][CONF_LEGACY_TLS] is False -@pytest.mark.parametrize(("reason", "error"), TLS_ERRORS) +@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( @@ -253,6 +254,7 @@ async def test_zeroconf_tls_error( assert result["type"] is FlowResultType.ABORT assert result["reason"] == error + assert mock_ipp_config_flow.printer.call_count == attempts HANDSHAKE_FAILURE = IPPConnectionTLSError( @@ -334,6 +336,78 @@ async def test_zeroconf_legacy_tls_fallback( assert result["data"][CONF_LEGACY_TLS] is True +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) + 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, CONF_HOST: "192.168.1.40", CONF_SSL: True}, + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + assert mock_config_entry.data[CONF_HOST] == "192.168.1.40" + assert mock_config_entry.data[CONF_LEGACY_TLS] is True + + +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) + 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[CONF_HOST] == "1.2.3.9" + assert mock_config_entry.data[CONF_LEGACY_TLS] is 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, From 84626f81900bd9d9a6db372bf694207e281f09ae Mon Sep 17 00:00:00 2001 From: Brian Egge Date: Mon, 30 Nov 2026 14:54:56 -0500 Subject: [PATCH 08/11] Only fall back to older cipher suites without certificate verification With verification on, a forged handshake failure from an on-path attacker could make the flow store the weaker profile for a printer that supports ECDHE. Without verification such an attacker could intercept the connection anyway, so the fallback gives nothing away. With verification on, a legacy-only printer now gets an error that explains it can be set up with verification turned off. Co-Authored-By: Claude Opus 5.5 --- homeassistant/components/ipp/config_flow.py | 20 +++++-- homeassistant/components/ipp/strings.json | 3 +- tests/components/ipp/test_config_flow.py | 62 ++++++++++++--------- 3 files changed, 52 insertions(+), 33 deletions(-) diff --git a/homeassistant/components/ipp/config_flow.py b/homeassistant/components/ipp/config_flow.py index 3b45354c9b7f8d..5805aaff513f8b 100644 --- a/homeassistant/components/ipp/config_flow.py +++ b/homeassistant/components/ipp/config_flow.py @@ -69,10 +69,14 @@ def _tls_reason_key(reason: str) -> str: return "tls_error" -def _tls_error_key(err: IPPConnectionTLSError) -> str: +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) - return _tls_reason_key(err.reason) + key = _tls_reason_key(err.reason) + if key == "tls_unsupported" and verify_ssl: + # The older cipher suites are only tried without verification + return "tls_unsupported_verify_ssl" + return key async def _async_get_printer( @@ -97,13 +101,15 @@ async def validate_input(hass: HomeAssistant, data: dict) -> dict[str, Any]: 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. + 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 _tls_reason_key(err.reason) != "tls_unsupported": + if data[CONF_VERIFY_SSL] or _tls_reason_key(err.reason) != "tls_unsupported": raise _LOGGER.debug( "Printer rejected the TLS handshake (%s), retrying with older cipher" @@ -153,7 +159,9 @@ async def async_step_user( except IPPConnectionUpgradeRequired: return self._show_setup_form({"base": "connection_upgrade"}) except IPPConnectionTLSError as err: - return self._show_setup_form({"base": _tls_error_key(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"}) @@ -309,7 +317,7 @@ async def async_step_reconfigure( except IPPConnectionUpgradeRequired: errors["base"] = "connection_upgrade" except IPPConnectionTLSError as err: - errors["base"] = _tls_error_key(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" diff --git a/homeassistant/components/ipp/strings.json b/homeassistant/components/ipp/strings.json index 51d78025092647..2121d358438d95 100644 --- a/homeassistant/components/ipp/strings.json +++ b/homeassistant/components/ipp/strings.json @@ -22,7 +22,8 @@ "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": "[%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/tests/components/ipp/test_config_flow.py b/tests/components/ipp/test_config_flow.py index 4b9655d40fa482..f85ff2a64e8cdd 100644 --- a/tests/components/ipp/test_config_flow.py +++ b/tests/components/ipp/test_config_flow.py @@ -3,7 +3,6 @@ import dataclasses from ipaddress import ip_address import json -from ssl import SSLContext from unittest.mock import MagicMock, patch from pyipp import ( @@ -35,7 +34,6 @@ from homeassistant.util.ssl import ( SSL_ALPN_HTTP11, SSLCipherList, - client_context, client_context_no_verify, ) @@ -263,27 +261,9 @@ async def test_zeroconf_tls_error( ) -@pytest.mark.parametrize( - ("verify_ssl", "context"), - [ - pytest.param( - False, - client_context_no_verify(SSLCipherList.INTERMEDIATE, SSL_ALPN_HTTP11), - id="no_verify", - ), - pytest.param( - True, - client_context(SSLCipherList.INTERMEDIATE, SSL_ALPN_HTTP11), - id="verify", - ), - ], -) async def test_user_flow_legacy_tls_fallback( hass: HomeAssistant, mock_printer: Printer, - *, - verify_ssl: bool, - context: SSLContext, ) -> None: """Test a rejected handshake is retried with the older cipher suites.""" with patch( @@ -295,11 +275,7 @@ async def test_user_flow_legacy_tls_fallback( ) result = await hass.config_entries.flow.async_configure( result["flow_id"], - user_input={ - **MOCK_USER_INPUT, - CONF_SSL: True, - CONF_VERIFY_SSL: verify_ssl, - }, + user_input={**MOCK_USER_INPUT, CONF_SSL: True, CONF_VERIFY_SSL: False}, ) assert result["type"] is FlowResultType.CREATE_ENTRY @@ -307,7 +283,41 @@ async def test_user_flow_legacy_tls_fallback( 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 context + 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_zeroconf_legacy_tls_fallback( From 75170bd5966829c27ad76f3401ff3b36dcd119f5 Mon Sep 17 00:00:00 2001 From: Brian Egge Date: Mon, 30 Nov 2026 15:11:33 -0500 Subject: [PATCH 09/11] Apply legacy_tls only to an entry with the validated connection settings The duplicate-entry paths keep the stored port, path, TLS and verification settings, so only set the flag when those match the endpoint that needed the fallback. Otherwise the entry is left as it was apart from the host, and the user can reconfigure. Co-Authored-By: Claude Opus 5.5 --- homeassistant/components/ipp/config_flow.py | 32 +++++++---- tests/components/ipp/test_config_flow.py | 64 +++++++++++++++++++-- 2 files changed, 80 insertions(+), 16 deletions(-) diff --git a/homeassistant/components/ipp/config_flow.py b/homeassistant/components/ipp/config_flow.py index 5805aaff513f8b..74ea4fbb522a11 100644 --- a/homeassistant/components/ipp/config_flow.py +++ b/homeassistant/components/ipp/config_flow.py @@ -126,15 +126,8 @@ async def validate_input(hass: HomeAssistant, data: dict) -> dict[str, Any]: } -def _legacy_tls_update(data: dict[str, Any]) -> dict[str, bool]: - """Return the entry update that keeps a moved printer reachable. - - Only ever turns the older cipher suites on: they are ignored without TLS - and still prefer ECDHE, so setting the flag cannot break an entry. - """ - if data.get(CONF_LEGACY_TLS): - return {CONF_LEGACY_TLS: True} - return {} +# 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): @@ -190,7 +183,7 @@ async def async_step_user( self._abort_if_unique_id_configured( updates={ CONF_HOST: user_input[CONF_HOST], - **_legacy_tls_update(user_input), + **self._legacy_tls_update(user_input), } ) @@ -284,7 +277,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], - **_legacy_tls_update(self.discovery_info), + **self._legacy_tls_update(self.discovery_info), }, ) @@ -346,6 +339,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/tests/components/ipp/test_config_flow.py b/tests/components/ipp/test_config_flow.py index f85ff2a64e8cdd..823af6ef74cb4f 100644 --- a/tests/components/ipp/test_config_flow.py +++ b/tests/components/ipp/test_config_flow.py @@ -346,6 +346,14 @@ async def test_zeroconf_legacy_tls_fallback( 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, @@ -354,6 +362,10 @@ async def test_user_existing_entry_needs_legacy_tls( ) -> 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( @@ -361,13 +373,47 @@ async def test_user_existing_entry_needs_legacy_tls( ) result = await hass.config_entries.flow.async_configure( result["flow_id"], - user_input={**MOCK_USER_INPUT, CONF_HOST: "192.168.1.40", CONF_SSL: True}, + 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[CONF_HOST] == "192.168.1.40" - assert mock_config_entry.data[CONF_LEGACY_TLS] is True + 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( @@ -378,6 +424,10 @@ async def test_zeroconf_existing_entry_needs_legacy_tls( ) -> 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( @@ -391,8 +441,12 @@ async def test_zeroconf_existing_entry_needs_legacy_tls( assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" - assert mock_config_entry.data[CONF_HOST] == "1.2.3.9" - assert mock_config_entry.data[CONF_LEGACY_TLS] is True + 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( From 42efb2b53457d7ec57fd65441b65af84e8b337a4 Mon Sep 17 00:00:00 2001 From: Brian Egge Date: Mon, 30 Nov 2026 15:25:44 -0500 Subject: [PATCH 10/11] Do not retry or suggest skipping verification for TLS version errors The intermediate profile does not allow older TLS versions, so only cipher-related handshake failures are retried with it or answered with the advice to turn verification off. Version errors keep the tls_unsupported message. Co-Authored-By: Claude Opus 5.5 --- homeassistant/components/ipp/config_flow.py | 21 ++++++++++--- tests/components/ipp/test_config_flow.py | 35 ++++++++++++++++++++- 2 files changed, 51 insertions(+), 5 deletions(-) diff --git a/homeassistant/components/ipp/config_flow.py b/homeassistant/components/ipp/config_flow.py index 74ea4fbb522a11..38dbc9bd4d519a 100644 --- a/homeassistant/components/ipp/config_flow.py +++ b/homeassistant/components/ipp/config_flow.py @@ -61,6 +61,20 @@ ) +# Failures the older cipher suites can fix. The intermediate profile does not +# allow older TLS versions, so protocol version failures are not among them. +_LEGACY_CIPHER_REASONS = ( + "HANDSHAKE_FAILURE", + "INSUFFICIENT_SECURITY", + "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: @@ -72,11 +86,10 @@ def _tls_reason_key(reason: str) -> str: 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) - key = _tls_reason_key(err.reason) - if key == "tls_unsupported" and verify_ssl: + 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 key + return _tls_reason_key(err.reason) async def _async_get_printer( @@ -109,7 +122,7 @@ async def validate_input(hass: HomeAssistant, data: dict) -> dict[str, Any]: try: printer = await _async_get_printer(hass, data, legacy_tls) except IPPConnectionTLSError as err: - if data[CONF_VERIFY_SSL] or _tls_reason_key(err.reason) != "tls_unsupported": + 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" diff --git a/tests/components/ipp/test_config_flow.py b/tests/components/ipp/test_config_flow.py index 823af6ef74cb4f..475757821a9d90 100644 --- a/tests/components/ipp/test_config_flow.py +++ b/tests/components/ipp/test_config_flow.py @@ -182,7 +182,7 @@ async def test_zeroconf_connection_upgrade_required( TLS_ERRORS = [ pytest.param("SSLV3_ALERT_HANDSHAKE_FAILURE", "tls_unsupported", 2, id="handshake"), - pytest.param("TLSV1_ALERT_PROTOCOL_VERSION", "tls_unsupported", 2, id="version"), + pytest.param("TLSV1_ALERT_PROTOCOL_VERSION", "tls_unsupported", 1, id="version"), pytest.param("WRONG_VERSION_NUMBER", "tls_not_offered", 1, id="not_tls"), pytest.param( "CERTIFICATE_VERIFY_FAILED: self-signed certificate", @@ -320,6 +320,39 @@ async def test_user_flow_no_legacy_tls_fallback_when_verifying( 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, From 4999e1ded7f6034adf802efc64a2bc556653ca81 Mon Sep 17 00:00:00 2001 From: Brian Egge Date: Mon, 30 Nov 2026 15:42:36 -0500 Subject: [PATCH 11/11] Do not treat insufficient_security as fixable by older cipher suites That alert means the printer wants stronger suites, so neither the retry nor the advice to turn verification off can help. It keeps the tls_unsupported message. Co-Authored-By: Claude Opus 5.5 --- homeassistant/components/ipp/config_flow.py | 9 +++------ tests/components/ipp/test_config_flow.py | 6 ++++++ 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/homeassistant/components/ipp/config_flow.py b/homeassistant/components/ipp/config_flow.py index 38dbc9bd4d519a..ff48e019757626 100644 --- a/homeassistant/components/ipp/config_flow.py +++ b/homeassistant/components/ipp/config_flow.py @@ -62,12 +62,9 @@ # Failures the older cipher suites can fix. The intermediate profile does not -# allow older TLS versions, so protocol version failures are not among them. -_LEGACY_CIPHER_REASONS = ( - "HANDSHAKE_FAILURE", - "INSUFFICIENT_SECURITY", - "NO_CIPHERS_AVAILABLE", -) +# 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: diff --git a/tests/components/ipp/test_config_flow.py b/tests/components/ipp/test_config_flow.py index 475757821a9d90..7de734033c3ccb 100644 --- a/tests/components/ipp/test_config_flow.py +++ b/tests/components/ipp/test_config_flow.py @@ -183,6 +183,12 @@ async def test_zeroconf_connection_upgrade_required( 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",