Files
napalm-windows/tests/test_transport.py
T
Christian Manivong 0bbeebb7a7 feat(repairs): SFC, DISM and Defender runs through HostRepairMixin (NetOrk/netork#2899)
verify_system_files (sfc /verifyonly), check_component_store (DISM
/ScanHealth /English), update_antimalware_signatures (Update-MpSignature)
and scan_antimalware (Start-MpScan, quick or full), each one bounded PSRP
call streamed line by line through PsrpTransport.run_streaming. Native
tools run as a process read in their own encoding (sfc: UTF-16), and NULs
of UTF-16 read byte by byte are dropped. The exit code decides; a missing
tool or Defender says it is not available. sfc /scannow and DISM
/RestoreHealth stay undefined until a real host was tested.

tools/harvest.py --runs records the runs' output.
2026-12-01 12:49:37 +01:00

302 lines
10 KiB
Python

"""Unit tests for the PSRP transport.
pypsrp is patched out at the module boundary: these tests pin down how the
transport configures it and how its failures reach the driver, not pypsrp itself.
"""
from __future__ import annotations
from unittest.mock import patch
import pytest
import requests
from napalm.base.exceptions import ConnectionClosedException, ConnectionException
from pypsrp.complex_objects import PSInvocationState
from pypsrp.exceptions import AuthenticationError, WinRMError, WinRMTransportError
from napalm_windows.transport import PowerShellError, PsrpTransport
def _transport(**overrides):
kwargs = {
"port": 5986,
"ssl": True,
"cert_validation": True,
"auth": "negotiate",
"timeout": 60,
}
kwargs.update(overrides)
return PsrpTransport("win01", "admin", "secret", **kwargs)
@pytest.fixture()
def psrp():
"""Patch WSMan, RunspacePool and PowerShell as the transport sees them."""
with (
patch("napalm_windows.transport.WSMan") as wsman,
patch("napalm_windows.transport.RunspacePool") as pool,
patch("napalm_windows.transport.PowerShell") as ps,
):
yield {"wsman": wsman, "pool": pool, "ps": ps}
class TestOpen:
def test_passes_connection_settings_to_wsman(self, psrp):
_transport(port=5985, ssl=False, cert_validation=False, auth="ntlm").open()
kwargs = psrp["wsman"].call_args.kwargs
assert psrp["wsman"].call_args.args == ("win01",)
assert kwargs["port"] == 5985
assert kwargs["ssl"] is False
assert kwargs["cert_validation"] is False
assert kwargs["auth"] == "ntlm"
assert kwargs["username"] == "admin"
assert kwargs["password"] == "secret" # noqa: S105
def test_opens_one_runspace_pool_on_the_connection(self, psrp):
_transport().open()
psrp["pool"].assert_called_once_with(psrp["wsman"].return_value)
psrp["pool"].return_value.open.assert_called_once_with()
def test_authentication_failure_is_a_connection_exception(self, psrp):
psrp["pool"].return_value.open.side_effect = AuthenticationError("bad creds")
with pytest.raises(ConnectionException, match="Authentication failed"):
_transport().open()
def test_http_401_is_an_authentication_failure(self, psrp):
psrp["pool"].return_value.open.side_effect = WinRMTransportError(
"http", 401, "Unauthorized"
)
with pytest.raises(ConnectionException, match="Authentication failed"):
_transport().open()
def test_unreachable_host_is_a_connection_exception(self, psrp):
psrp["pool"].return_value.open.side_effect = requests.ConnectionError("refused")
with pytest.raises(ConnectionException, match="win01:5986"):
_transport().open()
def test_is_open_only_after_open(self, psrp):
t = _transport()
assert t.is_open is False
t.open()
assert t.is_open is True
class TestRun:
def test_returns_output_objects_joined_by_newline(self, psrp):
psrp["ps"].return_value.invoke.return_value = ['{"a":', "1}"]
psrp["ps"].return_value.had_errors = False
t = _transport()
t.open()
assert t.run("Get-Thing") == '{"a":\n1}'
psrp["ps"].return_value.add_script.assert_called_once_with("Get-Thing")
def test_none_objects_are_skipped(self, psrp):
psrp["ps"].return_value.invoke.return_value = [None, "x", None]
psrp["ps"].return_value.had_errors = False
t = _transport()
t.open()
assert t.run("Get-Thing") == "x"
def test_error_stream_raises_powershell_error_with_its_text(self, psrp):
psrp["ps"].return_value.invoke.return_value = []
psrp["ps"].return_value.had_errors = True
psrp["ps"].return_value.streams.error = [
"Cannot find any service with service name 'nope'."
]
t = _transport()
t.open()
with pytest.raises(PowerShellError, match="service name 'nope'"):
t.run("Start-Service nope")
def test_run_before_open_raises_connection_closed(self):
with pytest.raises(ConnectionClosedException):
_transport().run("Get-Thing")
class TestRunLast:
"""A script that may take WinRM down with it: a restart, a shutdown."""
def test_a_finished_script_is_true(self, psrp):
psrp["ps"].return_value.invoke.return_value = []
psrp["ps"].return_value.had_errors = False
t = _transport()
t.open()
assert t.run_last("Restart-Computer") is True
psrp["ps"].return_value.add_script.assert_called_once_with("Restart-Computer")
assert t.is_open is True
def test_the_error_stream_still_raises_powershell_error(self, psrp):
psrp["ps"].return_value.invoke.return_value = []
psrp["ps"].return_value.had_errors = True
psrp["ps"].return_value.streams.error = ["other users logged on"]
t = _transport()
t.open()
with pytest.raises(PowerShellError, match="other users logged on"):
t.run_last("Restart-Computer")
@pytest.mark.parametrize(
"error",
[
requests.ConnectionError("connection reset by peer"),
requests.ReadTimeout("read timed out"),
WinRMTransportError("http", 503, "Service Unavailable"),
WinRMError("the shell was terminated"),
ConnectionResetError(104, "Connection reset by peer"),
],
)
def test_a_connection_that_breaks_is_false_and_closed(self, psrp, error):
psrp["ps"].return_value.invoke.side_effect = error
t = _transport()
t.open()
assert t.run_last("Restart-Computer") is False
assert t.is_open is False
def test_run_last_before_open_raises_connection_closed(self):
with pytest.raises(ConnectionClosedException):
_transport().run_last("Restart-Computer")
class _Pipeline:
"""A PowerShell pipeline whose output arrives over several polls, as pypsrp's
``begin_invoke``/``poll_invoke`` deliver a long-running script's."""
def __init__(self, batches, *, errors=(), never_ends=False):
self.batches = [list(b) for b in batches]
self.output: list = []
self.state = PSInvocationState.NOT_STARTED
self.had_errors = bool(errors)
self.streams = type("Streams", (), {"error": list(errors)})()
self.never_ends = never_ends
self.polls: list = []
self.stopped = False
self.script = None
def add_script(self, script):
self.script = script
def begin_invoke(self):
self.state = PSInvocationState.RUNNING
def poll_invoke(self, timeout=None):
self.polls.append(timeout)
if self.batches:
self.output.extend(self.batches.pop(0))
if not self.batches and not self.never_ends:
self.state = PSInvocationState.COMPLETED
def stop(self):
self.stopped = True
self.state = PSInvocationState.STOPPED
class TestRunStreaming:
"""A long-running script: each output line reaches the caller as the host prints it."""
def _open(self, psrp, pipeline, **overrides):
psrp["ps"].return_value = pipeline
t = _transport(**overrides)
t.open()
return t
def test_each_output_object_reaches_the_caller_as_it_arrives(self, psrp):
pipeline = _Pipeline([["one"], [], ["two", None, "three"]])
t = self._open(psrp, pipeline)
seen: list[str] = []
out = t.run_streaming("sfc", seen.append, limit=60)
assert seen == ["one", "two", "three"]
assert out == ["one", "two", "three"]
assert pipeline.script == "sfc"
def test_each_poll_waits_less_than_a_read_of_the_connection(self, psrp):
pipeline = _Pipeline([["a"], ["b"]])
t = self._open(psrp, pipeline, timeout=60)
t.run_streaming("x", lambda _line: None, limit=600)
assert pipeline.polls and all(0 < p < 60 for p in pipeline.polls)
def test_a_short_connection_timeout_still_polls(self, psrp):
pipeline = _Pipeline([["a"]])
t = self._open(psrp, pipeline, timeout=5)
t.run_streaming("x", lambda _line: None, limit=600)
assert pipeline.polls == [2]
def test_the_error_stream_raises_after_the_output_was_passed_on(self, psrp):
pipeline = _Pipeline([["started"]], errors=["Access is denied."])
t = self._open(psrp, pipeline)
seen: list[str] = []
with pytest.raises(PowerShellError, match="Access is denied"):
t.run_streaming("x", seen.append, limit=60)
assert seen == ["started"]
def test_a_script_past_its_limit_is_stopped(self, psrp):
pipeline = _Pipeline([["working"]], never_ends=True)
t = self._open(psrp, pipeline)
clock = iter([0.0, 10.0, 70.0, 130.0])
with (
patch("napalm_windows.transport.time.monotonic", lambda: next(clock)),
pytest.raises(TimeoutError, match="60 seconds"),
):
t.run_streaming("x", lambda _line: None, limit=60)
assert pipeline.stopped is True
def test_stopping_a_pipeline_that_ended_meanwhile_still_times_out(self, psrp):
pipeline = _Pipeline([["working"]], never_ends=True)
pipeline.stop = lambda: (_ for _ in ()).throw(RuntimeError("not running"))
t = self._open(psrp, pipeline)
clock = iter([0.0, 61.0])
with (
patch("napalm_windows.transport.time.monotonic", lambda: next(clock)),
pytest.raises(TimeoutError),
):
t.run_streaming("x", lambda _line: None, limit=60)
def test_before_open_raises_connection_closed(self):
with pytest.raises(ConnectionClosedException):
_transport().run_streaming("x", lambda _line: None, limit=60)
class TestClose:
def test_close_closes_pool_and_connection(self, psrp):
t = _transport()
t.open()
t.close()
psrp["pool"].return_value.close.assert_called_once_with()
psrp["wsman"].return_value.close.assert_called_once_with()
assert t.is_open is False
def test_close_swallows_errors_from_a_dead_connection(self, psrp):
psrp["pool"].return_value.close.side_effect = requests.ConnectionError("gone")
t = _transport()
t.open()
t.close()
assert t.is_open is False
def test_close_without_open_is_a_no_op(self):
_transport().close()
def test_transport_does_not_print_password_in_repr():
assert "secret" not in repr(_transport())