From 4d9ebdb80f1611d2ae03ed5b59985134d03778ae Mon Sep 17 00:00:00 2001 From: Fede Luzzi Date: Tue, 20 Oct 2026 12:27:15 -0300 Subject: [PATCH] feat(mosh): TASK-MOSH-02 early UDP block detection, clean termination and test fixtures fix --- connpy/core.py | 20 +++++++-- connpy/tests/test_core.py | 72 ++++++++++++++++++++++++++++--- connpy/tests/test_grpc_layer.py | 12 ++++-- connpy/tests/test_node_service.py | 13 ++++-- 4 files changed, 100 insertions(+), 17 deletions(-) diff --git a/connpy/core.py b/connpy/core.py index 46b14e0..309ea09 100755 --- a/connpy/core.py +++ b/connpy/core.py @@ -1355,7 +1355,7 @@ class node: prompt = self.tags.get("prompt", default_prompt) if isinstance(self.tags, dict) else default_prompt password_prompt = '[p|P]assword:|[u|U]sername:' if effective_protocol != 'telnet' else '[p|P]assword:' prompt_unanchored = "|".join([t[:-1] if t.endswith("$") else t for t in prompt.split("|")]) - mosh_prompt = r"(?:(?:" + prompt_unanchored + r")\s*\[[0-9;?]*[a-zA-Z]|\[\?1049h.*)$" + mosh_prompt = r"(?:" + prompt_unanchored + r")\s*(?:\[[0-9;?]*[a-zA-Z])*$" expects = { "ssh": ['yes/no', 'refused', 'supported', 'Invalid|[u|U]sage: ssh', 'ssh-keygen.*\"', 'timeout|timed.out', 'unavailable', 'closed', password_prompt, prompt, 'suspend', pexpect.EOF, pexpect.TIMEOUT, "No route to host", "resolve hostname", "no matching", "[b|B]ad (owner|permissions)"], @@ -1384,7 +1384,7 @@ class node: r'(?:ssh|mosh): .*no matching', # 15 (error) "[b|B]ad (owner|permissions)", # 16 (error) "mosh-server:.*not found|command not found", # 17 (error) - "Did not find mosh server startup message|Nothing received from server", # 18 (error) + r"(?:Did not find mosh server startup message|(?:mosh: )?Nothing received from server on UDP port \d+\.?|Nothing received from server)", # 18 (error) "needs a UTF-8 native locale to run|requires a UTF-8 locale|locale.*not available", # 19 (error) ] @@ -1453,7 +1453,10 @@ class node: break elif results in error_indices[effective_protocol]: - child.terminate() + try: + child.terminate() + except Exception: + pass can_retry = ( results_value == pexpect.TIMEOUT and attempts != max_attempts @@ -1471,7 +1474,16 @@ class node: return val.decode() return str(val) after = "Connection timeout" if results_value == pexpect.TIMEOUT else _to_str(child.after) - return f"Connection failed code: {results}\n{_to_str(child.before).lstrip()}{after}{_to_str(child.readline())}".rstrip() + before = _to_str(child.before) + readline_val = _to_str(child.readline()) + if effective_protocol == "mosh": + after = self._logclean(after, True) + before = self._logclean(before, True) + readline_val = self._logclean(readline_val, True) + if effective_protocol == "mosh" and results == 18 and ("Nothing received from server" in after or "Nothing received from server" in before): + err_msg = after.strip() if "Nothing received from server" in after else before.strip() + return f"Connection failed code: {results}\n{err_msg} — UDP traffic is blocked or unreachable. Verify firewall rules for UDP ports (60000-61000 or mosh_udp_port)." + return f"Connection failed code: {results}\n{before.lstrip()}{after}{readline_val}".rstrip() elif results in eof_indices[effective_protocol]: if results_value == password_prompt: diff --git a/connpy/tests/test_core.py b/connpy/tests/test_core.py index ee02157..94a2329 100644 --- a/connpy/tests/test_core.py +++ b/connpy/tests/test_core.py @@ -1065,13 +1065,13 @@ class TestMoshProtocol: default_prompt = r'>$|#$|\$$|>.$|#.$|\$.$' prompt_unanchored = "|".join([t[:-1] if t.endswith("$") else t for t in default_prompt.split("|")]) - mosh_prompt_pattern = r"(?:(?:" + prompt_unanchored + r")\s*\[[0-9;?]*[a-zA-Z]|\[\?1049h.*)$" + mosh_prompt_pattern = r"(?:" + prompt_unanchored + r")\s*(?:\x1b\[[0-9;?]*[a-zA-Z])*$" - assert re.search(mosh_prompt_pattern, "\x1b[?1049h\x1b[1;1H") is not None + # Must NOT match empty alternate screen without real prompt + assert re.search(mosh_prompt_pattern, "\x1b[?1049h\x1b[1;1H") is None assert re.search(mosh_prompt_pattern, "admin@host:~$ \x1b[1;15H") is not None - # Strict: must NOT match without \x1b - assert re.search(mosh_prompt_pattern, "admin@host:~$ ") is None - assert re.search(mosh_prompt_pattern, "admin@host:~$") is None + assert re.search(mosh_prompt_pattern, "admin@host:~$ ") is not None + assert re.search(mosh_prompt_pattern, "admin@host:~$") is not None # Must not match MOTD words for word in ["supported", "unavailable", "refused", "closed", "timeout"]: assert re.search(mosh_prompt_pattern, f"MOTD: System is {word}") is None @@ -1137,3 +1137,65 @@ class TestMoshProtocol: n_ssh._spawn_child(["ssh", "10.0.0.1"], protocol="ssh") _, kwargs = mock_spawn.call_args assert kwargs.get("env") is None + + def test_mosh_prompt_rejects_bare_alternate_screen_without_prompt(self): + """mosh_prompt does not match empty alternate screen without a real remote shell prompt.""" + default_prompt = r'>$|#$|\$$|>.$|#.$|\$.$' + prompt_unanchored = "|".join([t[:-1] if t.endswith("$") else t for t in default_prompt.split("|")]) + mosh_prompt_pattern = r"(?:" + prompt_unanchored + r")\s*(?:\x1b\[[0-9;?]*[a-zA-Z])*$" + + # Bare alternate screen escape sequences without remote prompt must NOT match + assert re.search(mosh_prompt_pattern, "\x1b[?1049h\x1b[1;1H") is None + assert re.search(mosh_prompt_pattern, "\x1b[?1049h\x1b[1;24r\x1b[4l") is None + assert re.search(mosh_prompt_pattern, "\x1b[?1049h") is None + assert re.search(mosh_prompt_pattern, "\x1b[?1049h\r\n") is None + + # Real prompts with cursor sequences must match + assert re.search(mosh_prompt_pattern, "admin@host:~$ \x1b[1;15H") is not None + assert re.search(mosh_prompt_pattern, "router# ") is not None + assert re.search(mosh_prompt_pattern, "admin@host:~$ ") is not None + assert re.search(mosh_prompt_pattern, "user@host:~$ \x1b[?2004h") is not None + + def test_mosh_connect_early_udp_block_detection_terminates_child_and_explicit_error(self): + """Early UDP block detection terminates child, does not return True, and returns explicit firewall error.""" + from connpy.core import node + n = node("m1", "10.0.0.1", user="admin", protocol="mosh") + + mock_child = MagicMock() + mock_child.expect.return_value = 18 # index 18: UDP error pattern + mock_child.after = b"mosh: Nothing received from server on UDP port 60001\r\n" + mock_child.before = b"\x1b[?1049h" + mock_child.readline.return_value = b"" + + with patch("shutil.which", return_value="/usr/bin/mosh"), \ + patch("pexpect.spawn", return_value=mock_child): + res = n._connect() + + # Ensure does NOT return True + assert res is not True + assert isinstance(res, str) + + # Ensure child.terminate was called + mock_child.terminate.assert_called() + + # Verify explicit firewall error message + assert "Connection failed code: 18" in res + assert "Nothing received from server on UDP port 60001" in res + assert "UDP traffic is blocked or unreachable" in res + assert "Verify firewall rules for UDP ports" in res + assert "\x1b[?1049h" not in res # Cleaned of alternate screen escapes + + # Test with bare 'Nothing received from server on UDP port 60001' + mock_child2 = MagicMock() + mock_child2.expect.return_value = 18 + mock_child2.after = b"Nothing received from server on UDP port 60001" + mock_child2.before = b"" + mock_child2.readline.return_value = b"" + + with patch("shutil.which", return_value="/usr/bin/mosh"), \ + patch("pexpect.spawn", return_value=mock_child2): + res2 = n._connect() + assert res2 is not True + mock_child2.terminate.assert_called() + assert "Connection failed code: 18" in res2 + assert "UDP traffic is blocked or unreachable" in res2 diff --git a/connpy/tests/test_grpc_layer.py b/connpy/tests/test_grpc_layer.py index 4977f0f..874eec6 100644 --- a/connpy/tests/test_grpc_layer.py +++ b/connpy/tests/test_grpc_layer.py @@ -14,6 +14,10 @@ class MockContext: # --- UNIT TESTS (with mocks) --- +@pytest.fixture +def grpc_servicer(populated_config): + return server.NodeServicer(populated_config) + class TestNodeServicerNaming: @pytest.fixture def servicer(self, populated_config): @@ -289,9 +293,9 @@ class TestGRPCIntegration: assert reqs[1].copilot_action == "cancel" -def test_grpc_interact_node_mosh_sftp_preserves_orig_protocol(populated_config): +def test_grpc_interact_node_mosh_sftp_preserves_orig_protocol(grpc_servicer): """Test NodeServiceServicer.interact_node with sftp=True preserves _orig_protocol='mosh'.""" - servicer = server.NodeServicer(populated_config) + servicer = grpc_servicer params = { "host": "10.0.0.15", "user": "admin", @@ -305,8 +309,8 @@ def test_grpc_interact_node_mosh_sftp_preserves_orig_protocol(populated_config): connection_params_json=json.dumps(params), sftp=True ) - with patch("connpy.grpc_layer.server.node") as mock_node_cls: - from connpy.core import node as real_node + from connpy.core import node as real_node + with patch("connpy.core.node") as mock_node_cls: created_nodes = [] def fake_node_constructor(*args, **kwargs): diff --git a/connpy/tests/test_node_service.py b/connpy/tests/test_node_service.py index cc984b6..7e60e38 100644 --- a/connpy/tests/test_node_service.py +++ b/connpy/tests/test_node_service.py @@ -68,19 +68,24 @@ def test_list_nodes_case_sensitivity(populated_config): def test_connect_node_mosh_and_sftp_override(populated_config): """Test connect_node preserves mosh by default and switches to sftp while keeping _orig_protocol.""" - from unittest.mock import patch + from unittest.mock import patch, MagicMock from connpy.core import node service = NodeService(populated_config) - populated_config.connections.append({ - "id": "mosh1", + service.add_node("mosh1", { "host": "10.0.0.99", "user": "admin", "protocol": "mosh", + "port": "22", + "options": "", + "logs": "", + "tags": {}, + "jumphost": "", "type": "connection" }) - with patch.object(node, "interact", autospec=True) as mock_interact: + mock_interact = MagicMock() + with patch.object(getattr(node, "cls", node), "interact", lambda *a, **kw: mock_interact(*a, **kw)): service.connect_node("mosh1", sftp=False) node_obj = mock_interact.call_args[0][0] assert node_obj.protocol == "mosh"