Debian Codegraph @

tests/functional_tests/test_ssh_recovery.py

raw
1 """A tunnel that drops mid-session, and the connection that died with it.
2
3 Restarting `ssh` is not enough on its own -- the adapter's TCP connection ran
4 *through* the old forward -- so the recovery is both halves, and it happens
5 lazily, before the next thing that needs the database.
6 """
7
8 from __future__ import annotations
9
10 import socket
11 import sys
12 import time
13 from pathlib import Path
14 from typing import Awaitable, Callable
15
16 import pytest
17
18 from harlequin import Harlequin
19 from harlequin.components.text_modal import ErrorModal
20 from harlequin.ssh import Forward, SshTunnel
21
22 pytestmark = pytest.mark.skipif(
23 sys.platform == "win32", reason="the fake client binds on a POSIX loopback"
24 )
25
26
27 def free_port() -> int:
28 with socket.socket() as sock:
29 sock.bind(("127.0.0.1", 0))
30 return int(sock.getsockname()[1])
31
32
33 def accepts(port: int) -> bool:
34 try:
35 with socket.create_connection(("127.0.0.1", port), timeout=1):
36 return True
37 except OSError:
38 return False
39
40
41 def wait_until(predicate: Callable[[], bool], *, seconds: float = 10) -> bool:
42 deadline = time.monotonic() + seconds
43 while time.monotonic() < deadline:
44 if predicate():
45 return True
46 time.sleep(0.02)
47 return predicate()
48
49
50 def _modal_text(app: Harlequin) -> str:
51 """What the error modal on top of the stack is showing."""
52 modal = app.screen_stack[-1]
53 assert isinstance(modal, ErrorModal)
54 return modal.text
55
56
57 @pytest.fixture
58 def dropping_tunnel(drop_trigger: Path, fake_ssh_client: Path) -> SshTunnel:
59 """A tunnel whose child holds its forward until `drop_trigger` is touched."""
60 port = free_port()
61 tunnel = SshTunnel(
62 [
63 sys.executable,
64 str(fake_ssh_client),
65 "-N",
66 "-L",
67 f"{port}:db.internal:5432",
68 "web-1",
69 ],
70 forwards=(Forward(str(port), "[db.internal]:5432"),),
71 host="web-1",
72 )
73 tunnel.start()
74 return tunnel
75
76
77 @pytest.mark.asyncio
78 async def test_a_dropped_tunnel_is_reopened_before_the_next_thing_that_needs_it(
79 app: Harlequin,
80 dropping_tunnel: SshTunnel,
81 drop_trigger: Path,
82 wait_for_workers: Callable[[Harlequin], Awaitable[None]],
83 monkeypatch: pytest.MonkeyPatch,
84 ) -> None:
85 app.ssh_tunnel = dropping_tunnel
86 try:
87 async with app.run_test() as pilot:
88 await wait_for_workers(app)
89 first_connection = app.connection
90 assert first_connection is not None
91
92 drop_trigger.touch()
93 assert wait_until(lambda: dropping_tunnel.needs_restart)
94 # the child that comes back stays up
95 monkeypatch.delenv("FAKE_SSH_DROP_WHEN")
96
97 app.action_refresh_catalog()
98 await wait_for_workers(app)
99 await pilot.pause()
100
101 assert dropping_tunnel.running
102 assert accepts(dropping_tunnel.endpoints[0][1])
103 # both halves: a new session, on a forward that is open again
104 assert app.connection is not None
105 assert app.connection is not first_connection
106 finally:
107 dropping_tunnel.stop()
108
109
110 @pytest.mark.asyncio
111 async def test_a_tunnel_that_will_not_come_back_is_not_tried_twice(
112 app: Harlequin,
113 dropping_tunnel: SshTunnel,
114 drop_trigger: Path,
115 wait_for_workers: Callable[[Harlequin], Awaitable[None]],
116 monkeypatch: pytest.MonkeyPatch,
117 ) -> None:
118 app.ssh_tunnel = dropping_tunnel
119 try:
120 async with app.run_test() as pilot:
121 await wait_for_workers(app)
122 drop_trigger.touch()
123 assert wait_until(lambda: dropping_tunnel.needs_restart)
124 monkeypatch.setenv("FAKE_SSH_STDERR", "Permission denied (publickey).")
125 monkeypatch.setenv("FAKE_SSH_EXIT", "255")
126
127 app.action_refresh_catalog()
128 await wait_for_workers(app)
129 await pilot.pause()
130 assert not dropping_tunnel.needs_restart
131 # the error modal, once, quoting ssh
132 assert len(app.screen_stack) == 2
133 assert "Permission denied (publickey)." in _modal_text(app)
134 await pilot.press("escape")
135 await pilot.pause()
136
137 # and the worker aborts rather than running on the connection that
138 # died with the forward, which would raise a second modal
139 assert app._connection_for_worker() is None
140
141 app.action_refresh_catalog()
142 await wait_for_workers(app)
143 await pilot.pause()
144 assert not dropping_tunnel.running
145 assert len(app.screen_stack) == 1
146 finally:
147 dropping_tunnel.stop()