Merge remote-tracking branch 'origin/main' into fix/rest-cert-tofu-17
The REST login now checks the certificate before it posts the password (#17) and then tells a web page from a refused login (#13); the two login-answer checks moved into _require_login so connect() stays within the function-length limit. #13's REST tests stand in for the switch's certificate, since connect() fetches it before the login.
This commit is contained in:
commit
586632efe0
13 files changed
+517
-75
No files matched your search
@@ -0,0 +1,44 @@
|
||||
"""cli() over REST returns the command's output, not the API's base64 of it.
|
||||
|
||||
The REST ``/cli`` endpoint answers ``{"result_base64_encoded": ...}``: the output in
|
||||
base64, ending in a NUL byte. cli() returned that string as it came.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from napalm_procurve.procurve import ProcurveDriver
|
||||
|
||||
FIXTURES = Path(__file__).parent.parent / "fixtures"
|
||||
|
||||
SHOW_SNMP_SERVER = (FIXTURES / "procurve-show-snmp-server.txt").read_text(encoding="utf-8")
|
||||
SHOW_SNMP_SERVER_REST = (FIXTURES / "procurve-rest-cli-show-snmp-server.b64").read_text().strip()
|
||||
|
||||
|
||||
def _rest_driver(resp: MagicMock) -> ProcurveDriver:
|
||||
driver = ProcurveDriver("10.0.0.40", "manager", "s3cret")
|
||||
driver._transport = "api"
|
||||
driver._api = MagicMock()
|
||||
driver._api.post.return_value = resp
|
||||
return driver
|
||||
|
||||
|
||||
def test_over_rest_cli_returns_the_decoded_output():
|
||||
resp = MagicMock(ok=True, status_code=200)
|
||||
resp.json.return_value = {
|
||||
"cmd": "show snmp-server",
|
||||
"result_base64_encoded": SHOW_SNMP_SERVER_REST,
|
||||
"status": "CCS_SUCCESS",
|
||||
}
|
||||
|
||||
out = _rest_driver(resp).cli(["show snmp-server"])
|
||||
|
||||
assert out == {"show snmp-server": SHOW_SNMP_SERVER}
|
||||
|
||||
|
||||
def test_over_rest_cli_names_a_failed_request():
|
||||
resp = MagicMock(ok=False, status_code=401)
|
||||
|
||||
assert _rest_driver(resp).cli(["show version"]) == {"show version": "Error: HTTP 401"}
|
||||
@@ -0,0 +1,156 @@
|
||||
"""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"
|
||||
FETCH_CERTIFICATE = "napalm_device_types.tls_certificates.fetch_certificate"
|
||||
|
||||
# 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),
|
||||
# The certificate is checked before the login (#17); this is the switch's own.
|
||||
patch(FETCH_CERTIFICATE, return_value=b"the switch's certificate"),
|
||||
):
|
||||
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
|
||||
@@ -0,0 +1,98 @@
|
||||
"""get_snmp_config reads the switch's communities over every transport (#10).
|
||||
|
||||
Over the REST API there is no CLI session, so the getter returned None and a
|
||||
switch managed over REST always read as "SNMP not configured". The API's
|
||||
``/cli`` endpoint runs ``show snmp-server`` and answers with the output in
|
||||
base64, which the SSH path's parser reads.
|
||||
|
||||
The fixtures are ``show snmp-server`` recorded from a ProCurve switch: as the SSH
|
||||
CLI prints it, and as the REST ``/cli`` endpoint answers it (base64, ending in a
|
||||
NUL byte); the trap receiver's address is replaced.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from napalm.base.exceptions import CommandErrorException
|
||||
|
||||
from napalm_procurve.procurve import ProcurveDriver
|
||||
|
||||
FIXTURES = Path(__file__).parent.parent / "fixtures"
|
||||
|
||||
SHOW_SNMP_SERVER = (FIXTURES / "procurve-show-snmp-server.txt").read_text(encoding="utf-8")
|
||||
SHOW_SNMP_SERVER_REST = (FIXTURES / "procurve-rest-cli-show-snmp-server.b64").read_text().strip()
|
||||
|
||||
_PUBLIC = " public Operator Restricted \n"
|
||||
assert SHOW_SNMP_SERVER.count(_PUBLIC) == 1
|
||||
#: The recording with a read-write community put in before the read-only one.
|
||||
TWO_COMMUNITIES = SHOW_SNMP_SERVER.replace(
|
||||
_PUBLIC, " private Manager Unrestricted\n" + _PUBLIC
|
||||
)
|
||||
|
||||
#: The recording with its only community removed.
|
||||
NO_COMMUNITY = SHOW_SNMP_SERVER.replace(_PUBLIC, "")
|
||||
|
||||
|
||||
def _b64(output: str) -> str:
|
||||
return base64.b64encode(output.encode()).decode()
|
||||
|
||||
|
||||
def _cli_answer(encoded: str, status: str = "CCS_SUCCESS", http: int = 200) -> MagicMock:
|
||||
resp = MagicMock(ok=200 <= http < 300, status_code=http, text="")
|
||||
resp.json.return_value = {
|
||||
"cmd": "show snmp-server",
|
||||
"result_base64_encoded": encoded,
|
||||
"status": status,
|
||||
}
|
||||
return resp
|
||||
|
||||
|
||||
def _rest_driver(resp: MagicMock) -> ProcurveDriver:
|
||||
driver = ProcurveDriver("10.0.0.40", "manager", "s3cret")
|
||||
driver._transport = "api"
|
||||
driver._api = MagicMock()
|
||||
driver._api.post.return_value = resp
|
||||
return driver
|
||||
|
||||
|
||||
def test_over_rest_the_community_is_read_through_the_cli_endpoint():
|
||||
driver = _rest_driver(_cli_answer(SHOW_SNMP_SERVER_REST))
|
||||
|
||||
config = driver.get_snmp_config()
|
||||
|
||||
assert config == {"running": True, "community": "public", "port": 161, "version": "2c"}
|
||||
driver._api.post.assert_called_once_with("cli", json={"cmd": "show snmp-server"})
|
||||
|
||||
|
||||
def test_over_rest_a_switch_without_a_community_has_no_snmp_config():
|
||||
assert _rest_driver(_cli_answer(_b64(NO_COMMUNITY))).get_snmp_config() is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"resp",
|
||||
[
|
||||
_cli_answer("", http=401),
|
||||
_cli_answer(_b64("Invalid input: snmp-server"), status="CCS_FAILURE"),
|
||||
],
|
||||
)
|
||||
def test_over_rest_a_failed_read_raises_instead_of_reading_as_no_snmp(resp):
|
||||
with pytest.raises(CommandErrorException, match="show snmp-server"):
|
||||
_rest_driver(resp).get_snmp_config()
|
||||
|
||||
|
||||
def test_over_ssh_the_read_only_community_is_preferred():
|
||||
driver = ProcurveDriver("10.0.0.40", "manager", "s3cret")
|
||||
driver._transport = "ssh"
|
||||
driver._device = MagicMock(base_prompt="swt")
|
||||
driver._device.send_command.return_value = TWO_COMMUNITIES
|
||||
|
||||
assert driver.get_snmp_config() == {
|
||||
"running": True,
|
||||
"community": "public",
|
||||
"port": 161,
|
||||
"version": "2c",
|
||||
}
|
||||
@@ -104,7 +104,7 @@ def test_the_config_fallback_checks_the_key_of_port_22():
|
||||
|
||||
def test_the_snmp_fix_over_rest_stops_at_a_changed_key():
|
||||
seen: list = []
|
||||
driver = _driver(seen, {"443": SshHostKey.of(OTHER_KEY).as_dict()}, port=443)
|
||||
driver = _driver(seen, {"22": SshHostKey.of(OTHER_KEY).as_dict()}, port=443)
|
||||
driver._transport = "api"
|
||||
driver._api = MagicMock()
|
||||
with patch(HANDLER, side_effect=_refuse) as handler:
|
||||
@@ -112,3 +112,16 @@ def test_the_snmp_fix_over_rest_stops_at_a_changed_key():
|
||||
assert result["success"] is False
|
||||
assert handler.call_count == 1
|
||||
assert "host key" in str(result)
|
||||
|
||||
|
||||
def test_the_snmp_fix_over_rest_opens_ssh_on_port_22_not_the_api_port():
|
||||
"""``port`` is the REST API's port when REST is the transport (#17)."""
|
||||
seen: list = []
|
||||
driver = _driver(seen, {"22": SshHostKey.of(SERVER_KEY).as_dict()}, port=443)
|
||||
driver._transport = "api"
|
||||
driver._api = MagicMock()
|
||||
with patch(HANDLER, return_value=_device()) as handler:
|
||||
driver.configure_snmp_agent({"community": "c0mm", "allowed_sources": []})
|
||||
assert handler.call_args.kwargs["port"] == 22
|
||||
assert handler.call_args.kwargs["ssh_strict"] is True
|
||||
assert (seen[0]["port"], seen[0]["accepted"]) == (22, True)
|
||||
Reference in new issue
Block a user