"""SSH host-console helper tests use local fake executables, never a network.""" import asyncio import json import os from pathlib import Path import sys import tempfile import unittest ROOT = Path(__file__).resolve().parents[1] HELPER = ROOT / "native/stl_ssh_console_bridge.py" SSHPASS = '''#!/usr/bin/env python3 import os,sys assert sys.argv[1] == '-e' assert os.environ.get('SSHPASS') == 'test-only-console-secret' assert 'STL_SOL_PASSWORD' not in os.environ os.execvp(sys.argv[2],sys.argv[2:]) ''' SSH = '''#!/usr/bin/env python3 import os,sys,time,json from pathlib import Path Path(os.environ['SSH_ARGS']).write_text(json.dumps(sys.argv[1:])) mode=os.environ.get('SSH_MODE','normal') if mode=='changed-key': os.write(2,b'@@@@@@@@ REMOTE HOST IDENTIFICATION HAS CHANGED! @@@@@@@@\\nHost key verification failed.\\n') sys.exit(255) os.write(2,b'debug1: Authenticated to example.invalid using "password".\\n') if mode=='missing-shell': # These apparent status messages came from the remote console stdout. os.write(1,b'Authenticated to server\\nshell request accepted on channel 0\\n') time.sleep(30) sys.exit(0) os.write(1,b'[0][AMEMDIAG #]') time.sleep(0.05) os.write(2,b'debug2: shell request accep') time.sleep(0.01) os.write(2,b'ted on channel 0\\n') with Path(os.environ['SSH_INPUT']).open('ab',buffering=0) as capture: while True: data=os.read(0,8192) if not data:break capture.write(data) os.write(1,b'RX:'+data) ''' class SshConsoleHelperTests(unittest.IsolatedAsyncioTestCase): async def asyncSetUp(self): self.tmp = tempfile.TemporaryDirectory() self.root = Path(self.tmp.name) for name, text in (("sshpass", SSHPASS), ("ssh", SSH)): script = self.root / name script.write_text(text) script.chmod(0o755) self.env = {**os.environ, "PATH": str(self.root) + os.pathsep + os.environ["PATH"], "STL_SOL_HOST": "example.invalid", "STL_SOL_USER": "ADMIN", "STL_SOL_PASSWORD": "test-only-console-secret", "STL_SSH_PORT": "2200", "STL_SSH_KNOWN_HOSTS": str(self.root / "data/ssh_known_hosts"), "SSH_ARGS": str(self.root / "argv.json"), "SSH_INPUT": str(self.root / "input.raw")} self.proc = None async def asyncTearDown(self): if self.proc and self.proc.returncode is None: self.proc.terminate() try: await asyncio.wait_for(self.proc.communicate(), 3) except asyncio.TimeoutError: self.proc.kill() await self.proc.communicate() self.tmp.cleanup() async def launch(self, mode="normal"): self.proc = await asyncio.create_subprocess_exec(sys.executable, str(HELPER), stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env={**self.env, "SSH_MODE": mode}) self.assertEqual(json.loads(await asyncio.wait_for(self.proc.stderr.readline(), 2))["event"], "connecting") async def test_authenticated_shell_ready_preserves_bytes_and_does_not_type_automatically(self): await self.launch() state = json.loads(await asyncio.wait_for(self.proc.stderr.readline(), 2)) self.assertEqual(state, {"event": "ready", "code": 0}) # The fake SSH executable opens its capture file after reporting its # shell acknowledgement. Wait for that independent setup step, then # prove the helper itself has not typed any bytes. async with asyncio.timeout(2): while not (self.root / "input.raw").exists(): await asyncio.sleep(.01) self.assertEqual((self.root / "input.raw").read_bytes(), b"") payload = b"help\r\x1b[A\x03" self.proc.stdin.write(payload) await self.proc.stdin.drain() output = b"" async with asyncio.timeout(2): while b"RX:" + payload not in output: output += await self.proc.stdout.read(4096) self.assertEqual(output, b"[0][AMEMDIAG #]RX:" + payload) self.assertEqual((self.root / "input.raw").read_bytes(), payload) argv = json.loads((self.root / "argv.json").read_text()) self.assertNotIn("test-only-console-secret", " ".join(argv)) self.assertIn("StrictHostKeyChecking=accept-new", argv) self.assertIn("UserKnownHostsFile=" + str(self.root / "data/ssh_known_hosts"), argv) self.assertEqual(argv[argv.index("-p") + 1], "2200") self.proc.stdin.close() self.assertEqual(json.loads(await asyncio.wait_for(self.proc.stderr.readline(), 2))["event"], "closed") self.assertEqual(await asyncio.wait_for(self.proc.wait(), 3), 0) async def test_remote_stdout_cannot_fake_ready_without_shell_acceptance(self): await self.launch("missing-shell") with self.assertRaises(asyncio.TimeoutError): await asyncio.wait_for(self.proc.stderr.readline(), 0.15) self.proc.terminate() _, stderr = await asyncio.wait_for(self.proc.communicate(), 3) states = [json.loads(x) for x in stderr.splitlines()] self.assertNotIn("ready", [x["event"] for x in states]) self.assertFalse((self.root / "input.raw").exists()) async def test_changed_host_key_reports_error_and_never_reports_ready(self): await self.launch("changed-key") stdout, stderr = await asyncio.wait_for(self.proc.communicate(), 3) states = [json.loads(x) for x in stderr.splitlines()] self.assertIn({"event": "error", "code": 1011}, states) self.assertNotIn("ready", [x["event"] for x in states]) self.assertEqual(stdout, b"") self.assertNotIn(b"test-only-console-secret", stderr) self.assertEqual(self.proc.returncode, 2)