fix(connect): name a full switch and a web page, not a bad password

A switch whose Telnet sessions were all taken, and a REST API answering
the login with the web UI's HTML page, were both reported as an
authentication failure, which sent the operator after the password. The
Telnet login now keeps the switch's greeting in an in-memory session log
and reports a full switch as a connection error; an HTML answer to the
REST login says so. An SSH attempt records netmiko's underlying error
instead of "timed out" when it was not a timeout.

Session log objects need netmiko 4.3.0, which becomes the floor.

Closes #13
This commit is contained in:
Christian Manivong committed 2026-11-01 21:48:56 +01:00
1 parent 874e25a1ce
commit ee49948b2b
7 files changed
+233 -12

No files matched your search

+151
View File
@@ -0,0 +1,151 @@
"""A failed connection names what the switch actually said (#13).
A switch whose Telnet sessions are all taken, a REST API that answers with the
web UI's HTML page, and an SSH key exchange that found no common algorithm were
all reported as a wrong password or a timeout, which sends the operator after
the credentials instead of the session table.
"""
from __future__ import annotations
from unittest.mock import MagicMock, patch
import paramiko
import pytest
from napalm.base.exceptions import ConnectAuthError, ConnectionException
from netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutException
from napalm_procurve.api_client import ProcurveApiClient
from napalm_procurve.procurve import ProcurveDriver
HANDLER = "napalm_procurve.procurve.ConnectHandler"
PROBE = "napalm_procurve.procurve.ProcurveApiClient.probe"
# What a ProCurve 2520G prints instead of a login prompt when every session is taken.
NO_FREE_SESSION = "Sorry, the maximum number of telnet sessions are active. Try again later.\r\n"
def _telnet_refused(greeting: str):
def connect(**kwargs):
if kwargs["device_type"] != ProcurveDriver.NETMIKO_DEVICE_TYPE_TELNET:
raise OSError("no route to host")
kwargs["session_log"].write(greeting)
raise NetmikoAuthenticationException(f"Login failed: {kwargs['host']}")
return connect
def _open(connect, **optional_args) -> ConnectionException:
driver = ProcurveDriver("10.0.0.40", "manager", "s3cret", optional_args=optional_args)
with patch(PROBE, return_value=(None, None)), patch(HANDLER, side_effect=connect):
with pytest.raises(ConnectionException) as exc_info:
driver.open()
return exc_info.value
# --- Telnet -----------------------------------------------------------------
def test_no_free_telnet_session_is_a_connection_error_not_a_wrong_password():
error = _open(_telnet_refused(NO_FREE_SESSION))
msg = str(error)
assert "Authentication failed" not in msg
assert "telnet: the switch has no free session (maximum number of telnet sessions" in msg
def test_a_refused_telnet_login_is_still_an_authentication_failure():
error = _open(_telnet_refused("Password: \r\nInvalid password\r\n"))
assert "Authentication failed for 10.0.0.40 via telnet" in str(error)
def test_the_telnet_transcript_records_what_the_switch_sent_not_the_password():
sessions: list = []
def connect(**kwargs):
sessions.append(kwargs["session_log"])
return MagicMock()
driver = ProcurveDriver("10.0.0.40", "manager", "s3cret", optional_args={"transport": "telnet"})
with patch(HANDLER, side_effect=connect):
driver.open()
assert sessions[0].record_writes is False
# --- SSH --------------------------------------------------------------------
def _wrapped(cause: Exception) -> NetmikoTimeoutException:
"""What netmiko raises: its own exception, the paramiko or socket error as context."""
exc = NetmikoTimeoutException("A paramiko SSHException occurred during connection creation")
exc.__context__ = cause
return exc
def test_an_ssh_key_exchange_failure_is_named_not_reported_as_a_timeout():
no_kex = paramiko.ssh_exception.IncompatiblePeer(
"Incompatible ssh peer (no acceptable kex algorithm)"
)
def connect(**kwargs):
if kwargs["device_type"] == ProcurveDriver.NETMIKO_DEVICE_TYPE_TELNET:
raise OSError("no route to host")
raise _wrapped(no_kex)
msg = str(_open(connect))
assert "ssh: Incompatible ssh peer (no acceptable kex algorithm)" in msg
assert "ssh: timed out" not in msg
def test_an_ssh_timeout_is_still_reported_as_one():
def connect(**kwargs):
if kwargs["device_type"] == ProcurveDriver.NETMIKO_DEVICE_TYPE_TELNET:
raise OSError("no route to host")
raise _wrapped(TimeoutError("timed out"))
assert "ssh: timed out" in str(_open(connect))
# --- REST -------------------------------------------------------------------
def _client_answering(status: int, content_type: str) -> ProcurveApiClient:
client = ProcurveApiClient("10.0.0.40", "manager", "s3cret")
client.setup("v7", "https")
response = MagicMock(status_code=status, headers={"Content-Type": content_type})
session = MagicMock()
session.post.return_value = response
session.headers = {}
with patch("napalm_procurve.api_client.requests.Session", return_value=session):
client.connect()
return client
def test_a_web_page_instead_of_a_rest_answer_is_not_a_login_failure():
with pytest.raises(ConnectionException) as exc_info:
_client_answering(200, "text/html; charset=utf-8")
assert not isinstance(exc_info.value, ConnectAuthError)
assert str(exc_info.value) == (
"REST API on 10.0.0.40 answered with a web page instead of JSON (HTTP 200)"
)
def test_a_refused_rest_login_is_still_an_authentication_failure():
with pytest.raises(ConnectAuthError, match=r"REST API login failed \(HTTP 401\)"):
_client_answering(401, "application/json")
def test_the_transcript_keeps_the_greeting_not_the_whole_session():
from napalm_procurve.connect_reasons import TelnetTranscript
transcript = TelnetTranscript()
transcript.write(NO_FREE_SESSION)
for _ in range(1000):
transcript.write("show running-config output\r\n" * 10)
assert transcript.no_free_session
assert len(transcript.text) < 10_000