test_ssh_console_helper.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. """SSH host-console helper tests use local fake executables, never a network."""
  2. import asyncio
  3. import json
  4. import os
  5. from pathlib import Path
  6. import sys
  7. import tempfile
  8. import unittest
  9. ROOT = Path(__file__).resolve().parents[1]
  10. HELPER = ROOT / "native/stl_ssh_console_bridge.py"
  11. SSHPASS = '''#!/usr/bin/env python3
  12. import os,sys
  13. assert sys.argv[1] == '-e'
  14. assert os.environ.get('SSHPASS') == 'test-only-console-secret'
  15. assert 'STL_SOL_PASSWORD' not in os.environ
  16. os.execvp(sys.argv[2],sys.argv[2:])
  17. '''
  18. SSH = '''#!/usr/bin/env python3
  19. import os,sys,time,json
  20. from pathlib import Path
  21. Path(os.environ['SSH_ARGS']).write_text(json.dumps(sys.argv[1:]))
  22. mode=os.environ.get('SSH_MODE','normal')
  23. if mode=='changed-key':
  24. os.write(2,b'@@@@@@@@ REMOTE HOST IDENTIFICATION HAS CHANGED! @@@@@@@@\\nHost key verification failed.\\n')
  25. sys.exit(255)
  26. os.write(2,b'debug1: Authenticated to example.invalid using "password".\\n')
  27. if mode=='missing-shell':
  28. # These apparent status messages came from the remote console stdout.
  29. os.write(1,b'Authenticated to server\\nshell request accepted on channel 0\\n')
  30. time.sleep(30)
  31. sys.exit(0)
  32. os.write(1,b'[0][AMEMDIAG #]')
  33. time.sleep(0.05)
  34. os.write(2,b'debug2: shell request accep')
  35. time.sleep(0.01)
  36. os.write(2,b'ted on channel 0\\n')
  37. with Path(os.environ['SSH_INPUT']).open('ab',buffering=0) as capture:
  38. while True:
  39. data=os.read(0,8192)
  40. if not data:break
  41. capture.write(data)
  42. os.write(1,b'RX:'+data)
  43. '''
  44. class SshConsoleHelperTests(unittest.IsolatedAsyncioTestCase):
  45. async def asyncSetUp(self):
  46. self.tmp = tempfile.TemporaryDirectory()
  47. self.root = Path(self.tmp.name)
  48. for name, text in (("sshpass", SSHPASS), ("ssh", SSH)):
  49. script = self.root / name
  50. script.write_text(text)
  51. script.chmod(0o755)
  52. self.env = {**os.environ, "PATH": str(self.root) + os.pathsep + os.environ["PATH"],
  53. "STL_SOL_HOST": "example.invalid", "STL_SOL_USER": "ADMIN",
  54. "STL_SOL_PASSWORD": "test-only-console-secret", "STL_SSH_PORT": "2200",
  55. "STL_SSH_KNOWN_HOSTS": str(self.root / "data/ssh_known_hosts"),
  56. "SSH_ARGS": str(self.root / "argv.json"), "SSH_INPUT": str(self.root / "input.raw")}
  57. self.proc = None
  58. async def asyncTearDown(self):
  59. if self.proc and self.proc.returncode is None:
  60. self.proc.terminate()
  61. try:
  62. await asyncio.wait_for(self.proc.communicate(), 3)
  63. except asyncio.TimeoutError:
  64. self.proc.kill()
  65. await self.proc.communicate()
  66. self.tmp.cleanup()
  67. async def launch(self, mode="normal"):
  68. self.proc = await asyncio.create_subprocess_exec(sys.executable, str(HELPER),
  69. stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,
  70. stderr=asyncio.subprocess.PIPE, env={**self.env, "SSH_MODE": mode})
  71. self.assertEqual(json.loads(await asyncio.wait_for(self.proc.stderr.readline(), 2))["event"], "connecting")
  72. async def test_authenticated_shell_ready_preserves_bytes_and_does_not_type_automatically(self):
  73. await self.launch()
  74. state = json.loads(await asyncio.wait_for(self.proc.stderr.readline(), 2))
  75. self.assertEqual(state, {"event": "ready", "code": 0})
  76. # The fake SSH executable opens its capture file after reporting its
  77. # shell acknowledgement. Wait for that independent setup step, then
  78. # prove the helper itself has not typed any bytes.
  79. async with asyncio.timeout(2):
  80. while not (self.root / "input.raw").exists():
  81. await asyncio.sleep(.01)
  82. self.assertEqual((self.root / "input.raw").read_bytes(), b"")
  83. payload = b"help\r\x1b[A\x03"
  84. self.proc.stdin.write(payload)
  85. await self.proc.stdin.drain()
  86. output = b""
  87. async with asyncio.timeout(2):
  88. while b"RX:" + payload not in output:
  89. output += await self.proc.stdout.read(4096)
  90. self.assertEqual(output, b"[0][AMEMDIAG #]RX:" + payload)
  91. self.assertEqual((self.root / "input.raw").read_bytes(), payload)
  92. argv = json.loads((self.root / "argv.json").read_text())
  93. self.assertNotIn("test-only-console-secret", " ".join(argv))
  94. self.assertIn("StrictHostKeyChecking=accept-new", argv)
  95. self.assertIn("UserKnownHostsFile=" + str(self.root / "data/ssh_known_hosts"), argv)
  96. self.assertEqual(argv[argv.index("-p") + 1], "2200")
  97. self.proc.stdin.close()
  98. self.assertEqual(json.loads(await asyncio.wait_for(self.proc.stderr.readline(), 2))["event"], "closed")
  99. self.assertEqual(await asyncio.wait_for(self.proc.wait(), 3), 0)
  100. async def test_remote_stdout_cannot_fake_ready_without_shell_acceptance(self):
  101. await self.launch("missing-shell")
  102. with self.assertRaises(asyncio.TimeoutError):
  103. await asyncio.wait_for(self.proc.stderr.readline(), 0.15)
  104. self.proc.terminate()
  105. _, stderr = await asyncio.wait_for(self.proc.communicate(), 3)
  106. states = [json.loads(x) for x in stderr.splitlines()]
  107. self.assertNotIn("ready", [x["event"] for x in states])
  108. self.assertFalse((self.root / "input.raw").exists())
  109. async def test_changed_host_key_reports_error_and_never_reports_ready(self):
  110. await self.launch("changed-key")
  111. stdout, stderr = await asyncio.wait_for(self.proc.communicate(), 3)
  112. states = [json.loads(x) for x in stderr.splitlines()]
  113. self.assertIn({"event": "error", "code": 1011}, states)
  114. self.assertNotIn("ready", [x["event"] for x in states])
  115. self.assertEqual(stdout, b"")
  116. self.assertNotIn(b"test-only-console-secret", stderr)
  117. self.assertEqual(self.proc.returncode, 2)