Debian Codegraph @

tests/unit_tests/test_ssh.py

raw
1 """The `ssh` child's lifetime, and the one thing Harlequin parses: `ssh -G`.
2
3 No SSH server, and no `ssh` binary except in the one test that asks a real
4 client whether it accepts the argv. Everything else hands `SshTunnel` the fake
5 client in `tests/data/unit_tests/ssh/ssh`.
6 """
7
8 from __future__ import annotations
9
10 import json
11 import os
12 import shutil
13 import socket
14 import subprocess
15 import sys
16 import threading
17 from pathlib import Path
18 from typing import Callable, Iterator, Sequence
19 from unittest.mock import MagicMock
20
21 import click
22 import pytest
23 from click.testing import CliRunner, Result
24
25 from harlequin.cli import build_cli as harlequin_cli
26 from harlequin.config import DEFAULT_SSH_TIMEOUT, SSH_KEYS, take_ssh_keys
27 from harlequin.exception import HarlequinConfigError, HarlequinSshError
28 from harlequin.hsql.cli import build_cli as hsql_cli
29 from harlequin.hsql.diagnostics import ExitCode
30 from harlequin.ssh import (
31 DEFAULT_TIMEOUT,
32 KEEPALIVE_COUNT,
33 KEEPALIVE_SECONDS,
34 Forward,
35 SshOptions,
36 SshTunnel,
37 _client_path,
38 build_argv,
39 build_tunnel,
40 parse_config,
41 resolve_config,
42 )
43 from tests.tunnels import ssh_child_exited
44 from tests.waiting import accepts, free_port, on_a_free_port, settle, wait_until
45
46 FAKE_SSH = Path(__file__).parent.parent / "data" / "unit_tests" / "ssh" / "ssh"
47
48 posix_only = pytest.mark.skipif(
49 os.name == "nt", reason="a Python script is not an executable on Windows"
50 )
51
52
53 @pytest.fixture
54 def listener() -> Iterator[int]:
55 """A port already bound by something that is not Harlequin's tunnel."""
56 with socket.socket() as sock:
57 sock.bind(("127.0.0.1", 0))
58 sock.listen(8)
59 yield int(sock.getsockname()[1])
60
61
62 def child_tunnel(*ports: int, **kwargs: object) -> SshTunnel:
63 """A tunnel whose `ssh` is the fake one, run through this interpreter."""
64 specs = [f"{port}:remote:5439" for port in ports]
65 argv: list[str] = [sys.executable, str(FAKE_SSH), "-N"]
66 for spec in specs:
67 argv += ["-L", spec]
68 argv.append("redshift_prod")
69 forwards = tuple(Forward(str(port), "[remote]:5439") for port in ports)
70 return SshTunnel(argv, forwards=forwards, host="redshift_prod", **kwargs) # type: ignore[arg-type]
71
72
73 def started_tunnel(
74 *, before_start: Callable[[SshTunnel], None] | None = None, **kwargs: object
75 ) -> SshTunnel:
76 """A tunnel whose child is up, on a port it won the race for.
77
78 Its port is `tunnel.endpoints[0][1]`. `before_start` is for what a caller
79 has to set while the tunnel is still cold, since a retry builds a new one.
80 """
81
82 def start(port: int) -> SshTunnel:
83 tunnel = child_tunnel(port, **kwargs)
84 if before_start is not None:
85 before_start(tunnel)
86 tunnel.start()
87 return tunnel
88
89 return on_a_free_port(start, retry_on=ssh_child_exited)
90
91
92 # the argv, which is the whole of what Harlequin says to ssh
93
94
95 def test_the_argv_forwards_nothing_it_was_not_given() -> None:
96 assert build_argv("redshift_prod") == [
97 "ssh",
98 "-N",
99 "-o",
100 "ExitOnForwardFailure=yes",
101 "redshift_prod",
102 ]
103
104
105 def test_forwards_reach_the_argv_unchanged_and_in_order() -> None:
106 specs = ["15439:one.internal:5439", "[::1]:15440:two.internal:5440"]
107 argv = build_argv("tco@web-1", specs)
108 assert argv[-1] == "tco@web-1"
109 assert [argv[i + 1] for i, arg in enumerate(argv) if arg == "-L"] == specs
110
111
112 def test_batch_mode_is_ssh_s_own_option_and_the_only_one_added() -> None:
113 argv = build_argv("web-1", batch_mode=True)
114 assert "BatchMode=yes" in argv
115 assert [argv[i + 1] for i, arg in enumerate(argv) if arg == "-o"] == [
116 "ExitOnForwardFailure=yes",
117 "BatchMode=yes",
118 ]
119
120
121 @pytest.mark.parametrize(
122 "host", ["user@web-1", "ssh://tco@web-1:2222", "redshift_prod", "10.0.0.4"]
123 )
124 def test_the_destination_is_not_parsed(host: str) -> None:
125 assert build_argv(host)[-1] == host
126
127
128 @pytest.mark.parametrize(
129 "kwargs",
130 [
131 {"host": "-oProxyCommand=touch /tmp/pwned"},
132 {"host": "web-1", "forwards": ["-oProxyCommand=touch /tmp/pwned"]},
133 ],
134 )
135 def test_a_value_ssh_would_read_as_an_option_is_refused(kwargs: dict) -> None:
136 with pytest.raises(HarlequinSshError, match="dash"):
137 build_argv(**kwargs)
138
139
140 @pytest.mark.parametrize(
141 "host",
142 [
143 "web-1`touch /tmp/pwned`",
144 "web-1$(touch /tmp/pwned)",
145 "tco\ntouch /tmp/pwned@web-1",
146 "web-1;touch /tmp/pwned",
147 "web-1 --lol",
148 "web\\-1",
149 ],
150 )
151 def test_a_value_a_proxycommand_would_expand_is_refused(host: str) -> None:
152 """A destination reaches the user's own ssh config as %h, %r and %p.
153
154 A `ProxyCommand` there runs them through a shell, and the destination can
155 come from a config file discovered in the working directory.
156 """
157 with pytest.raises(HarlequinSshError, match="ProxyCommand"):
158 build_argv(host)
159 with pytest.raises(HarlequinSshError, match="ProxyCommand"):
160 build_argv("web-1", [f"15439:{host}:5432"])
161
162
163 @pytest.mark.parametrize(
164 "value",
165 ["tco@web-1", "ssh://tco@web-1:2222", "10.0.0.4", "redshift_prod", "web-1.a.b"],
166 )
167 def test_an_ordinary_destination_is_not_refused(value: str) -> None:
168 assert build_argv(value)[-1] == value
169
170
171 @posix_only
172 def test_the_client_is_resolved_against_path_not_the_working_directory(
173 monkeypatch: pytest.MonkeyPatch, tmp_path: Path
174 ) -> None:
175 """Windows searches the working directory first; a repo could ship an ssh."""
176 on_path = tmp_path / "bin"
177 on_path.mkdir()
178 real = on_path / "ssh"
179 real.write_text("#!/bin/sh\nexit 0\n")
180 real.chmod(0o755)
181 decoy = tmp_path / "repo"
182 decoy.mkdir()
183 (decoy / "ssh").write_text("#!/bin/sh\ntouch pwned\n")
184 (decoy / "ssh").chmod(0o755)
185 monkeypatch.setenv("PATH", str(on_path))
186 monkeypatch.chdir(decoy)
187 assert _client_path("ssh") == str(real)
188
189
190 # `ssh -G`, the one thing this feature parses
191
192
193 def test_forwards_parse_with_a_bind_address_ipv6_and_a_socket_path() -> None:
194 config = parse_config(
195 "host redshift_prod\n"
196 "hostname web-1\n"
197 "user tco\n"
198 "localforward 15439 [data.example.com]:5439\n"
199 "localforward [127.0.0.1]:15440 [other.internal]:5440\n"
200 "localforward [::1]:15441 [::1]:5441\n"
201 "localforward /tmp/harlequin.sock [db.internal]:5432\n"
202 "remoteforward 9000 [localhost]:9000\n"
203 )
204 assert config is not None
205 assert [forward.endpoint for forward in config.forwards] == [
206 # a bare port is polled by name, so both families are tried
207 ("localhost", 15439),
208 ("127.0.0.1", 15440),
209 ("::1", 15441),
210 None,
211 ]
212 assert str(config.forwards[0]) == "localhost:15439 -> data.example.com:5439"
213
214
215 def test_a_wildcard_bind_is_polled_by_name_and_reported_as_written() -> None:
216 """A forward on 0.0.0.0 reaches the whole network; the notice must say so."""
217 config = parse_config("hostname web-1\nlocalforward [0.0.0.0]:15439 [db]:5439\n")
218 assert config is not None
219 assert config.forwards[0].endpoint == ("localhost", 15439)
220 assert str(config.forwards[0]) == "0.0.0.0:15439 -> db:5439"
221
222
223 def test_a_config_with_only_a_dynamic_forward_forwards_nothing() -> None:
224 config = parse_config("hostname web-1\ndynamicforward 1080\n")
225 assert config is not None
226 assert config.forwards == ()
227
228
229 @pytest.mark.parametrize(
230 "text",
231 ["", "usage: ssh [-46AaCfGg...]\n", "Permission denied (publickey).\n", "{}\n"],
232 )
233 def test_output_that_is_not_a_resolved_config_degrades(text: str) -> None:
234 assert parse_config(text) is None
235
236
237 @posix_only
238 def test_a_probe_that_ssh_rejects_is_reported_in_its_own_words(
239 monkeypatch: pytest.MonkeyPatch,
240 ) -> None:
241 """The same argv `start()` would run, so the run ends here either way."""
242 monkeypatch.setenv("FAKE_SSH_PROBE_EXIT", "255")
243 monkeypatch.setenv("FAKE_SSH_STDERR", "Bad local forwarding specification ''")
244 with pytest.raises(HarlequinSshError) as excinfo:
245 resolve_config([str(FAKE_SSH), "web-1"])
246 assert "Bad local forwarding specification" in str(excinfo.value)
247
248
249 @posix_only
250 def test_a_missing_client_degrades() -> None:
251 assert resolve_config(["harlequin-no-such-ssh", "web-1"]) is None
252
253
254 @posix_only
255 def test_the_probe_does_not_spend_the_wait_configured_for_the_tunnel(
256 fake_ssh: None, monkeypatch: pytest.MonkeyPatch
257 ) -> None:
258 """`ssh -G` connects to nothing, so a short --ssh-timeout must not skip it.
259
260 A probe that timed out would leave the tunnel with no forwards to poll, and
261 so nothing to check the local port against.
262 """
263 monkeypatch.setenv("FAKE_SSH_FORWARD", "15439:db.internal:5439")
264 tunnel = build_tunnel("redshift_prod", timeout=0.001)
265 assert tunnel.resolved
266 assert tunnel.endpoints == (("localhost", 15439),)
267
268
269 # building a tunnel, which is the probe plus the argv
270
271
272 @pytest.fixture
273 def fake_ssh(monkeypatch: pytest.MonkeyPatch) -> None:
274 monkeypatch.setattr("harlequin.ssh.SSH", str(FAKE_SSH))
275
276
277 @posix_only
278 def test_a_destination_that_forwards_nothing_names_both_places_to_put_one(
279 fake_ssh: None,
280 ) -> None:
281 with pytest.raises(HarlequinConfigError, match="--ssh-forward") as excinfo:
282 build_tunnel("redshift_prod")
283 assert "LocalForward" in str(excinfo.value)
284
285
286 @posix_only
287 def test_a_forward_from_the_ssh_config_is_the_one_waited_on(
288 fake_ssh: None, monkeypatch: pytest.MonkeyPatch
289 ) -> None:
290 """The motivating case: Harlequin was never told a port number."""
291 monkeypatch.setenv("FAKE_SSH_FORWARD", "15439:data.example.com:5439")
292 tunnel = build_tunnel("redshift_prod")
293 assert tunnel.endpoints == (("localhost", 15439),)
294 assert tunnel.describe() == (
295 "localhost:15439 -> data.example.com:5439 via redshift_prod"
296 )
297
298
299 @posix_only
300 def test_a_probe_that_says_nothing_readable_polls_nothing(
301 fake_ssh: None, monkeypatch: pytest.MonkeyPatch
302 ) -> None:
303 monkeypatch.setenv("FAKE_SSH_PROBE_TEXT", "who knows\n")
304 assert build_tunnel("redshift_prod").endpoints == ()
305
306
307 # the child's lifetime
308
309
310 def test_a_tunnel_holds_its_port_open_and_gives_it_back() -> None:
311 tunnel = started_tunnel()
312 port = tunnel.endpoints[0][1]
313 try:
314 assert accepts(port)
315 assert tunnel.running
316 assert not tunnel.reused
317 finally:
318 tunnel.stop()
319 assert not accepts(port)
320
321
322 def test_a_forward_that_takes_a_moment_is_waited_for(
323 monkeypatch: pytest.MonkeyPatch,
324 ) -> None:
325 monkeypatch.setenv("FAKE_SSH_DELAY", "0.4")
326 tunnel = started_tunnel()
327 try:
328 assert accepts(tunnel.endpoints[0][1])
329 finally:
330 tunnel.stop()
331
332
333 def test_a_child_that_never_opens_the_forward_names_batch_mode(
334 monkeypatch: pytest.MonkeyPatch,
335 ) -> None:
336 monkeypatch.setenv("FAKE_SSH_HANG", "1")
337 tunnel = child_tunnel(free_port(), timeout=0.5)
338 with pytest.raises(HarlequinSshError, match="--ssh-batch-mode"):
339 tunnel.start()
340 assert not tunnel.running
341
342
343 def test_a_child_that_exits_is_reported_in_its_own_words(
344 monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
345 ) -> None:
346 monkeypatch.setenv("FAKE_SSH_STDERR", "Permission denied (publickey).")
347 monkeypatch.setenv("FAKE_SSH_EXIT", "255")
348 with pytest.raises(HarlequinSshError, match="exited with code 255"):
349 child_tunnel(free_port()).start()
350 # on stderr as ssh wrote it, and so not repeated by the error
351 assert "Permission denied (publickey)." in capsys.readouterr().err
352
353
354 def test_a_slow_client_does_not_make_a_bound_port_look_like_a_forward(
355 listener: int, monkeypatch: pytest.MonkeyPatch
356 ) -> None:
357 """ssh binds its forwards only after authenticating.
358
359 A listener already on the port answers for the whole handshake, so nothing
360 but the child exiting or the deadline can say whether the forward is ours.
361 """
362 monkeypatch.setenv("FAKE_SSH_DELAY", "1.5")
363 tunnel = child_tunnel(listener)
364 with pytest.raises(HarlequinSshError):
365 tunnel.start()
366 assert not tunnel.reused
367
368
369 def test_a_slow_client_still_reuses_the_listener_when_asked(
370 listener: int, monkeypatch: pytest.MonkeyPatch
371 ) -> None:
372 monkeypatch.setenv("FAKE_SSH_DELAY", "1.5")
373 tunnel = child_tunnel(listener, allow_reuse=True)
374 tunnel.start()
375 try:
376 assert tunnel.reused
377 finally:
378 tunnel.stop()
379
380
381 def test_a_bound_port_that_ssh_never_answers_for_names_the_flag(
382 listener: int, monkeypatch: pytest.MonkeyPatch
383 ) -> None:
384 """And a timeout under the old settle window no longer reads as success."""
385 monkeypatch.setenv("FAKE_SSH_HANG", "1")
386 tunnel = child_tunnel(listener, timeout=0.5)
387 with pytest.raises(HarlequinSshError, match="--ssh-allow-reuse") as excinfo:
388 tunnel.start()
389 assert "already bound" in str(excinfo.value)
390
391
392 def test_what_ssh_says_while_it_waits_is_shown_while_it_waits(
393 monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
394 ) -> None:
395 """A helper's instructions are worthless after the timeout they caused.
396
397 Tailscale writes "to authenticate, visit ..." here, and it is a URL someone
398 has to open before the tunnel can open -- so it goes to stderr as it
399 arrives rather than being kept for an error.
400 """
401 monkeypatch.setenv(
402 "FAKE_SSH_STDERR",
403 "# Tailscale SSH requires an additional check.\n"
404 "# To authenticate, visit: https://login.tailscale.com/a/l4fc5f072",
405 )
406 monkeypatch.setenv("FAKE_SSH_HANG", "1")
407 tunnel = child_tunnel(free_port(), timeout=0.5)
408 with pytest.raises(HarlequinSshError) as excinfo:
409 tunnel.start()
410 printed = capsys.readouterr().err
411 assert "https://login.tailscale.com/a/l4fc5f072" in printed
412 # and the error does not read it back at someone who has seen it
413 assert "tailscale" not in str(excinfo.value).lower()
414 assert "--ssh-batch-mode" in str(excinfo.value)
415
416
417 def test_what_a_helper_says_on_stdout_is_shown_on_stderr(
418 monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
419 ) -> None:
420 """A `ProxyCommand` helper inherits ssh's streams and picks its own.
421
422 Onto our stderr either way: hsql's stdout carries result sets, and a helper
423 must not be able to corrupt a caller's csv with an authentication notice.
424 """
425 monkeypatch.setenv("FAKE_SSH_STDOUT", "To authenticate, visit: https://example/a")
426 monkeypatch.setenv("FAKE_SSH_HANG", "1")
427 with pytest.raises(HarlequinSshError):
428 child_tunnel(free_port(), timeout=0.5).start()
429 captured = capsys.readouterr()
430 assert "To authenticate, visit: https://example/a" in captured.err
431 assert captured.out == ""
432
433
434 def test_a_line_ssh_left_unfinished_is_still_shown(
435 monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
436 ) -> None:
437 """A prompt has no newline of its own, and is the point of the line."""
438 monkeypatch.setenv("FAKE_SSH_STDERR_PARTIAL", "Enter passphrase for key '/k/id':")
439 monkeypatch.setenv("FAKE_SSH_HANG", "1")
440 with pytest.raises(HarlequinSshError):
441 child_tunnel(free_port(), timeout=0.5).start()
442 assert "Enter passphrase for key" in capsys.readouterr().err
443
444
445 def test_a_caller_that_lost_the_screen_gets_the_words_in_the_error(
446 monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
447 ) -> None:
448 """After a restart there is no stderr a user reads, so the error carries it."""
449 monkeypatch.setenv("FAKE_SSH_STDERR", "Permission denied (publickey).")
450 monkeypatch.setenv("FAKE_SSH_EXIT", "255")
451 tunnel = child_tunnel(free_port())
452 with pytest.raises(HarlequinSshError, match="Permission denied"):
453 tunnel.start(echo_stderr=False)
454 assert "Permission denied" not in capsys.readouterr().err
455
456
457 def test_the_default_wait_is_long_enough_for_a_person() -> None:
458 """An ssh that opens a browser for an identity provider is a slow one."""
459 assert DEFAULT_TIMEOUT >= 30
460
461
462 def test_a_port_that_is_already_bound_fails(
463 listener: int, capsys: pytest.CaptureFixture[str]
464 ) -> None:
465 """Passing the client's own words through, whatever they are.
466
467 Windows says "an attempt was made to access a socket in a way forbidden by
468 its access permissions" where Unix says "address already in use", so what
469 is asserted is that the client's own line reached the user.
470 """
471 with pytest.raises(HarlequinSshError):
472 child_tunnel(listener).start()
473 assert "bind" in capsys.readouterr().err
474
475
476 def test_allow_reuse_connects_through_the_existing_listener(listener: int) -> None:
477 tunnel = child_tunnel(listener, allow_reuse=True)
478 tunnel.start()
479 try:
480 assert tunnel.reused
481 assert not tunnel.running
482 finally:
483 tunnel.stop()
484 # the listener was never ours to close
485 assert accepts(listener)
486
487
488 def test_a_half_open_reuse_fails_like_any_other(listener: int) -> None:
489 """Some ports answering and some not is a state nobody meant."""
490 tunnel = child_tunnel(listener, free_port(), allow_reuse=True)
491 with pytest.raises(HarlequinSshError):
492 tunnel.start()
493 assert not tunnel.reused
494
495
496 def test_a_client_that_is_not_installed_says_so() -> None:
497 tunnel = SshTunnel(["harlequin-no-such-ssh", "web-1"])
498 with pytest.raises(HarlequinSshError, match="could not run"):
499 tunnel.start()
500
501
502 def test_a_tunnel_with_no_port_to_poll_trusts_a_child_that_lives() -> None:
503 """The degraded case: `-G` said nothing, so the adapter is the test."""
504 tunnel = child_tunnel(free_port())
505 tunnel.forwards = ()
506 with tunnel:
507 assert tunnel.running
508
509
510 def test_a_tunnel_with_no_port_to_poll_still_notices_a_child_that_dies(
511 monkeypatch: pytest.MonkeyPatch,
512 ) -> None:
513 monkeypatch.setenv("FAKE_SSH_EXIT", "255")
514 tunnel = child_tunnel(free_port())
515 tunnel.forwards = ()
516 with pytest.raises(HarlequinSshError, match="exited"):
517 tunnel.start()
518
519
520 def test_stopping_twice_is_not_an_error() -> None:
521 tunnel = started_tunnel()
522 tunnel.stop()
523 tunnel.stop()
524 assert not tunnel.running
525
526
527 def test_a_stopped_tunnel_starts_again() -> None:
528 tunnel = started_tunnel()
529 port = tunnel.endpoints[0][1]
530 tunnel.stop()
531 assert not accepts(port)
532 tunnel.start()
533 try:
534 assert accepts(port)
535 finally:
536 tunnel.stop()
537
538
539 # the one test that asks a real client
540
541
542 def real_ssh() -> str | None:
543 path = shutil.which("ssh")
544 if path is None:
545 return None
546 try:
547 subprocess.run([path, "-V"], capture_output=True, timeout=10)
548 except (OSError, subprocess.SubprocessError):
549 return None
550 return path
551
552
553 @pytest.mark.skipif(real_ssh() is None, reason="no ssh client installed")
554 def test_a_real_client_accepts_the_argv_and_says_what_it_would_forward() -> None:
555 argv = build_argv(
556 "harlequin-test-destination", ["15439:data.example.com:5439"], batch_mode=True
557 )
558 config = resolve_config(argv, timeout=30)
559 assert config is not None
560 assert [forward.endpoint for forward in config.forwards] == [("localhost", 15439)]
561
562
563 def test_the_lifecycle_helpers_agree_about_ports(
564 monkeypatch: pytest.MonkeyPatch,
565 ) -> None:
566 """The fake client binds exactly the ports `-G` said it would."""
567 ports: Sequence[int] = (free_port(), free_port())
568 with child_tunnel(*ports):
569 assert all(accepts(port) for port in ports)
570
571
572 # keeping it open, and saying when it is not
573
574
575 @posix_only
576 def test_a_config_with_no_keepalive_gets_one(
577 fake_ssh: None, monkeypatch: pytest.MonkeyPatch
578 ) -> None:
579 """An idle forward behind a NAT is reaped silently, and ssh sends none."""
580 monkeypatch.setenv("FAKE_SSH_FORWARD", "15439:db.internal:5432")
581 monkeypatch.setenv("FAKE_SSH_ALIVE_INTERVAL", "0")
582 assert f"ServerAliveInterval={KEEPALIVE_SECONDS}" in build_tunnel("web-1").argv
583
584
585 @posix_only
586 def test_a_config_that_sets_its_own_keepalive_is_left_alone(
587 fake_ssh: None, monkeypatch: pytest.MonkeyPatch
588 ) -> None:
589 monkeypatch.setenv("FAKE_SSH_FORWARD", "15439:db.internal:5432")
590 monkeypatch.setenv("FAKE_SSH_ALIVE_INTERVAL", "60")
591 assert not any("ServerAlive" in arg for arg in build_tunnel("web-1").argv)
592
593
594 @posix_only
595 def test_a_probe_that_says_nothing_imposes_no_keepalive(
596 fake_ssh: None, monkeypatch: pytest.MonkeyPatch
597 ) -> None:
598 monkeypatch.setenv("FAKE_SSH_PROBE_TEXT", "who knows\n")
599 assert not any("ServerAlive" in arg for arg in build_tunnel("web-1").argv)
600
601
602 @posix_only
603 def test_a_keepalive_carries_its_own_budget(
604 fake_ssh: None, monkeypatch: pytest.MonkeyPatch
605 ) -> None:
606 """`ServerAliveCountMax 0` is inert at interval 0 and lethal at 30."""
607 monkeypatch.setenv("FAKE_SSH_FORWARD", "15439:db.internal:5432")
608 monkeypatch.setenv("FAKE_SSH_ALIVE_INTERVAL", "0")
609 argv = build_tunnel("web-1").argv
610 assert f"ServerAliveCountMax={KEEPALIVE_COUNT}" in argv
611
612
613 def test_the_keepalive_is_parsed_off_the_resolved_config() -> None:
614 config = parse_config("hostname web-1\nserveraliveinterval 60\n")
615 assert config is not None and config.server_alive_interval == 60
616 # real `ssh -G` always prints the keyword; text that does not is not it
617 bare = parse_config("hostname web-1\n")
618 assert bare is not None and bare.server_alive_interval is None
619
620
621 def test_a_child_that_dies_says_so_in_ssh_s_last_words(drop_trigger: Path) -> None:
622 notices: list[str] = []
623 tunnel = started_tunnel(before_start=lambda t: t.watch(notices.append))
624 try:
625 drop_trigger.touch()
626 wait_until(
627 lambda: bool(notices), description="the tunnel to be reported closed"
628 )
629 finally:
630 tunnel.stop()
631 assert notices == ["tunnel closed: Timeout, server web-1 not responding."]
632 assert tunnel.dropped
633
634
635 def test_a_tunnel_watched_after_it_started_is_still_reported(
636 drop_trigger: Path,
637 ) -> None:
638 """The IDE's own order: `cli.py` starts the tunnel, `on_mount` watches it.
639
640 Everything in between -- building the app, mounting the widget tree -- is
641 time the child can die in.
642 """
643 notices: list[str] = []
644 tunnel = started_tunnel()
645 try:
646 drop_trigger.touch()
647 assert tunnel._process is not None
648 tunnel._process.wait()
649 tunnel.watch(notices.append)
650 wait_until(
651 lambda: bool(notices), description="the tunnel to be reported closed"
652 )
653 finally:
654 tunnel.stop()
655 assert notices == ["tunnel closed: Timeout, server web-1 not responding."]
656
657
658 def test_a_reused_listener_is_never_called_closed(
659 listener: int, monkeypatch: pytest.MonkeyPatch
660 ) -> None:
661 """Its child exited by design, and the listener is not Harlequin's to bury."""
662 monkeypatch.setenv("FAKE_SSH_EXIT", "255")
663 notices: list[str] = []
664 tunnel = child_tunnel(listener, allow_reuse=True)
665 tunnel.start()
666 try:
667 assert tunnel.reused
668 tunnel.watch(notices.append)
669 settle()
670 finally:
671 tunnel.stop()
672 assert notices == []
673
674
675 def test_watching_twice_does_not_double_the_notice(drop_trigger: Path) -> None:
676 notices: list[str] = []
677
678 def watch_twice(tunnel: SshTunnel) -> None:
679 tunnel.watch(notices.append)
680 tunnel.watch(notices.append)
681
682 tunnel = started_tunnel(before_start=watch_twice)
683 try:
684 drop_trigger.touch()
685 wait_until(
686 lambda: bool(notices), description="the tunnel to be reported closed"
687 )
688 settle()
689 finally:
690 tunnel.stop()
691 assert len(notices) == 1
692
693
694 def test_a_tunnel_taken_down_on_purpose_is_not_news() -> None:
695 """The control is the test above: the same harness does fire, on a death."""
696 notices: list[str] = []
697 tunnel = started_tunnel(before_start=lambda t: t.watch(notices.append))
698 tunnel.stop()
699 settle(0.5)
700 assert notices == []
701
702
703 # both commands, end to end, against a fake client on PATH
704
705
706 @pytest.fixture
707 def ssh_on_path(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path:
708 """A fake `ssh` the real CLI path will find, and a log of how it was called."""
709 monkeypatch.setenv("PATH", f"{FAKE_SSH.parent}{os.pathsep}{os.environ['PATH']}")
710 record = tmp_path / "argv.jsonl"
711 monkeypatch.setenv("FAKE_SSH_ARGV", str(record))
712 return record
713
714
715 def calls(record: Path) -> list[list[str]]:
716 """Every argv the fake client was run with, probe included."""
717 if not record.exists():
718 return []
719 return [json.loads(line) for line in record.read_text().splitlines()]
720
721
722 def run_hsql(*args: str) -> Result:
723 argv = [str(arg) for arg in args]
724 return CliRunner().invoke(hsql_cli(argv), argv, catch_exceptions=False)
725
726
727 def run_harlequin(*args: str) -> Result:
728 argv = [str(arg) for arg in args]
729 return CliRunner().invoke(harlequin_cli(argv), argv, catch_exceptions=False)
730
731
732 TUNNELED = ["--ssh-host", "redshift_prod", "--ssh-forward"]
733 DUCK = ["-a", "duckdb", "--no-init", ":memory:"]
734
735
736 @posix_only
737 def test_hsql_runs_sql_through_a_tunnel(
738 ssh_on_path: Path, no_discovered_config: None
739 ) -> None:
740 port = free_port()
741 result = run_hsql(
742 *DUCK, *TUNNELED, f"{port}:data.example.com:5439", "-c", "select 1 as one"
743 )
744 assert result.exit_code == 0
745 assert "one" in result.output
746 assert f"ssh: localhost:{port} -> data.example.com:5439 via redshift_prod" in (
747 result.stderr
748 )
749 # the child is gone with the run, rather than left for the user to kill
750 assert not accepts(port)
751
752
753 @posix_only
754 def test_the_forward_reaches_ssh_unchanged_and_repeats_in_order(
755 ssh_on_path: Path, no_discovered_config: None
756 ) -> None:
757 specs = [f"{free_port()}:one.internal:5439", f"{free_port()}:two.internal:5440"]
758 result = run_hsql(
759 *DUCK,
760 "--ssh-host",
761 "tco@web-1",
762 *[arg for spec in specs for arg in ("--ssh-forward", spec)],
763 "--ssh-batch-mode",
764 "-c",
765 "select 1",
766 )
767 assert result.exit_code == 0
768 argv = calls(ssh_on_path)[-1]
769 assert argv[-1] == "tco@web-1"
770 assert [argv[i + 1] for i, arg in enumerate(argv) if arg == "-L"] == specs
771 assert "BatchMode=yes" in argv
772
773
774 @posix_only
775 def test_a_destination_that_forwards_nothing_is_a_usage_error(
776 ssh_on_path: Path, no_discovered_config: None
777 ) -> None:
778 result = run_hsql(*DUCK, "--ssh-host", "redshift_prod", "-c", "select 1")
779 assert result.exit_code == ExitCode.USAGE
780 assert "--ssh-forward" in result.stderr
781 assert "LocalForward" in result.stderr
782
783
784 @posix_only
785 def test_a_tunnel_that_will_not_open_exits_3_quoting_ssh(
786 ssh_on_path: Path, no_discovered_config: None, monkeypatch: pytest.MonkeyPatch
787 ) -> None:
788 monkeypatch.setenv("FAKE_SSH_STDERR", "Permission denied (publickey).")
789 monkeypatch.setenv("FAKE_SSH_EXIT", "255")
790 result = run_hsql(
791 *DUCK, *TUNNELED, f"{free_port()}:db.internal:5432", "-c", "select 1"
792 )
793 assert result.exit_code == ExitCode.CONNECTION
794 assert "Permission denied (publickey)." in result.stderr
795 assert result.stdout == ""
796
797
798 @posix_only
799 def test_the_tunnel_is_not_opened_for_a_mode_that_never_connects(
800 ssh_on_path: Path, no_discovered_config: None
801 ) -> None:
802 result = run_hsql("-a", "duckdb", *TUNNELED, "15439:db.internal:5432", "--info")
803 assert result.exit_code == 0
804 # `ssh -V` to report the client, and nothing else
805 assert calls(ssh_on_path) == [["-V"]]
806 assert json.loads(result.stdout)["ssh"]["version"].startswith("FakeSSH")
807
808
809 @posix_only
810 def test_info_reports_no_client_where_the_machine_has_none(
811 monkeypatch: pytest.MonkeyPatch, tmp_path: Path, no_discovered_config: None
812 ) -> None:
813 monkeypatch.setenv("PATH", str(tmp_path))
814 result = run_hsql("-a", "duckdb", "--info")
815 assert result.exit_code == 0
816 assert json.loads(result.stdout)["ssh"] == {"client": None, "version": None}
817
818
819 @posix_only
820 def test_a_profile_carries_the_tunnel_and_the_details_that_need_it(
821 ssh_on_path: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
822 ) -> None:
823 """§3.1: one key beside the connection details that already work."""
824 port = free_port()
825 config = tmp_path / ".harlequin.toml"
826 config.write_text(
827 "[profiles.redshift]\n"
828 'adapter = "duckdb"\n'
829 "no_init = true\n"
830 'ssh_host = "redshift_prod"\n'
831 f'ssh_forward = ["{port}:data.example.com:5439"]\n'
832 )
833 monkeypatch.setattr(
834 "harlequin.config._search_directories",
835 lambda: [(tmp_path, (".harlequin.toml",))],
836 )
837 result = run_hsql("-P", "redshift", ":memory:", "-c", "select 1 as one")
838 assert result.exit_code == 0, result.stderr
839 assert "redshift_prod" in result.stderr
840 assert calls(ssh_on_path)[-1][-1] == "redshift_prod"
841
842
843 @posix_only
844 def test_the_adapter_is_never_told_a_tunnel_exists(
845 ssh_on_path: Path, no_discovered_config: None, monkeypatch: pytest.MonkeyPatch
846 ) -> None:
847 """The contract: the connection details reach the adapter exactly as typed."""
848 from harlequin.plugins import load_adapter
849
850 handed: dict[str, object] = {}
851
852 def spy(name: str) -> type:
853 adapter_cls = load_adapter(name)
854
855 class Recording(adapter_cls): # type: ignore[valid-type,misc]
856 def __init__(self, **kwargs: object) -> None:
857 handed.update(kwargs)
858 super().__init__(**kwargs)
859
860 return Recording
861
862 monkeypatch.setattr("harlequin.hsql.cli.load_adapter", spy)
863 result = run_hsql(
864 *DUCK, *TUNNELED, f"{free_port()}:data.example.com:5439", "-c", "select 1"
865 )
866 assert result.exit_code == 0, result.stderr
867 assert handed["conn_str"] == (":memory:",)
868 assert not [key for key in handed if key.startswith("ssh")]
869
870
871 @posix_only
872 def test_the_ide_opens_the_tunnel_before_it_starts(
873 ssh_on_path: Path, no_discovered_config: None, monkeypatch: pytest.MonkeyPatch
874 ) -> None:
875 app = MagicMock()
876 # the command exits with it, and a MagicMock is not an exit code
877 app.return_value.return_code = 0
878 monkeypatch.setattr("harlequin.cli.Harlequin", app)
879 port = free_port()
880 result = run_harlequin(
881 "-a",
882 "duckdb",
883 "--no-init",
884 ":memory:",
885 *TUNNELED,
886 f"{port}:data.example.com:5439",
887 )
888 assert result.exit_code == 0
889 tunnel = app.call_args.kwargs["ssh_tunnel"]
890 assert tunnel is not None
891 assert tunnel.host == "redshift_prod"
892 # started before the app was built, and stopped when it returned
893 assert app.return_value.run.called
894 assert not accepts(port)
895
896
897 @posix_only
898 def test_two_bastions_do_not_share_a_catalog_cache(
899 ssh_on_path: Path, no_discovered_config: None, monkeypatch: pytest.MonkeyPatch
900 ) -> None:
901 """Both look like `localhost:15439`, and the details cannot tell them apart."""
902 app = MagicMock()
903 # the command exits with it, and a MagicMock is not an exit code
904 app.return_value.return_code = 0
905 monkeypatch.setattr("harlequin.cli.Harlequin", app)
906 forward = f"{free_port()}:data.example.com:5439"
907 hashes = []
908 for host in ("bastion_one", "bastion_two"):
909 run_harlequin(
910 "-a",
911 "duckdb",
912 "--no-init",
913 ":memory:",
914 "--ssh-host",
915 host,
916 "--ssh-forward",
917 forward,
918 )
919 hashes.append(app.call_args.kwargs["connection_hash"])
920 assert hashes[0] != hashes[1]
921
922
923 def test_both_commands_take_the_same_ssh_options() -> None:
924 """One profile serves both, so a spelling that drifted would only work in one."""
925
926 def spellings(command: click.Command) -> dict[str, tuple[str, ...]]:
927 return {
928 param.name: tuple(param.opts)
929 for param in command.params
930 if param.name is not None and param.name.startswith("ssh_")
931 }
932
933 ide = spellings(harlequin_cli([]))
934 headless = spellings(hsql_cli([]))
935 assert set(ide) == set(SSH_KEYS)
936 assert ide == headless
937
938
939 def test_the_ssh_timeout_is_the_one_default_both_commands_carry() -> None:
940 assert SshOptions.from_config({}).timeout == DEFAULT_SSH_TIMEOUT
941
942
943 @pytest.mark.parametrize(
944 "config",
945 [
946 {"ssh_forward": ["15439:db:5432"]},
947 {"ssh_batch_mode": True},
948 {"ssh_timeout": 30},
949 ],
950 )
951 def test_a_tunnel_with_no_destination_is_refused(config: dict) -> None:
952 with pytest.raises(HarlequinConfigError, match="ssh_host"):
953 take_ssh_keys(dict(config))
954
955
956 def test_a_config_file_may_not_turn_off_the_bound_port_check() -> None:
957 """The fail-closed default of §5.3 stays the caller's to turn off.
958
959 Config files are discovered in the working directory, so a cloned
960 repository supplies one.
961 """
962 profile = {"ssh_host": "web-1", "ssh_allow_reuse": True}
963 with pytest.raises(HarlequinConfigError, match="--ssh-allow-reuse"):
964 take_ssh_keys(dict(profile))
965 assert take_ssh_keys(dict(profile), typed={"ssh_allow_reuse"}) == profile
966
967
968 def test_the_ssh_keys_come_off_whatever_else_a_profile_holds() -> None:
969 profile = {"host": "localhost", "port": 15439, "ssh_host": "web-1"}
970 taken = take_ssh_keys(profile)
971 assert profile == {"host": "localhost", "port": 15439}
972 assert taken == {"ssh_host": "web-1"}
973
974
975 @pytest.mark.parametrize("value", [42, ["a", "b"], {"x": 1}])
976 def test_a_destination_that_is_not_text_is_refused(value: object) -> None:
977 with pytest.raises(HarlequinConfigError, match="ssh_host"):
978 SshOptions.from_config({"ssh_host": value})
979
980
981 def test_a_profile_may_write_one_forward_as_a_string() -> None:
982 options = SshOptions.from_config(
983 {"ssh_host": "web-1", "ssh_forward": "15439:db:5432"}
984 )
985 assert options.forwards == ("15439:db:5432",)
986
987
988 @pytest.mark.parametrize("value", [5432, True, 1.5, {"15439:db:5432": 1}, [42]])
989 def test_a_forward_that_is_not_a_spec_or_a_list_of_them_is_refused(
990 value: object,
991 ) -> None:
992 with pytest.raises(HarlequinConfigError, match="ssh_forward"):
993 SshOptions.from_config({"ssh_host": "web-1", "ssh_forward": value})
994
995
996 def test_a_forward_with_nothing_in_it_is_refused() -> None:
997 """`ssh` answers `-L ""` by refusing the whole run, naming nothing useful."""
998 with pytest.raises(HarlequinConfigError, match="ssh_forward"):
999 SshOptions.from_config(
1000 {"ssh_host": "web-1", "ssh_forward": ["", "15439:db:5432"]}
1001 )
1002
1003
1004 @pytest.mark.parametrize("key", ["ssh_batch_mode", "ssh_allow_reuse"])
1005 @pytest.mark.parametrize("value", ["false", "no", 0, 1])
1006 def test_a_flag_a_profile_did_not_write_as_a_boolean_is_refused(
1007 key: str, value: object
1008 ) -> None:
1009 """`ssh_batch_mode = "false"` read as true is a wrong a user cannot see."""
1010 with pytest.raises(HarlequinConfigError, match=key):
1011 SshOptions.from_config({"ssh_host": "web-1", key: value})
1012
1013
1014 def test_a_timeout_that_is_not_seconds_is_named_as_one() -> None:
1015 """Ahead of the destination check, which would otherwise answer first."""
1016 with pytest.raises(HarlequinConfigError, match="positive number of seconds"):
1017 take_ssh_keys({"ssh_timeout": -5})
1018
1019
1020 def test_two_tunnels_that_forward_different_ports_never_key_alike() -> None:
1021 """`ssh -G` says nothing here, so the specs asked for are what is left."""
1022 one = SshTunnel(["ssh", "web-1"], requested=("15439:a:5439",), host="web-1")
1023 two = SshTunnel(["ssh", "web-1"], requested=("15440:b:5440",), host="web-1")
1024 assert one.cache_material() != two.cache_material()
1025
1026
1027 def test_a_forward_on_every_interface_is_said_out_loud() -> None:
1028 tunnel = SshTunnel(
1029 ["ssh", "web-1"],
1030 forwards=(Forward("[0.0.0.0]:15439", "[db]:5439"),),
1031 host="web-1",
1032 )
1033 assert tunnel.exposed == ("0.0.0.0:15439",)
1034 assert "every interface" in " ".join(tunnel.warnings())
1035
1036
1037 def test_a_loopback_forward_says_nothing_beyond_where_it_goes() -> None:
1038 tunnel = SshTunnel(
1039 ["ssh", "web-1"], forwards=(Forward("15439", "[db]:5439"),), host="web-1"
1040 )
1041 assert tunnel.warnings() == ()
1042
1043
1044 def test_a_tunnel_ssh_would_not_describe_says_it_waited_for_nothing() -> None:
1045 tunnel = SshTunnel(["ssh", "web-1"], resolved=False, host="web-1")
1046 assert "did not wait" in " ".join(tunnel.warnings())
1047
1048
1049 # reopening one that dropped
1050
1051
1052 def test_a_tunnel_that_dropped_asks_to_be_reopened(
1053 drop_trigger: Path, monkeypatch: pytest.MonkeyPatch
1054 ) -> None:
1055 tunnel = started_tunnel(before_start=lambda t: t.watch(lambda notice: None))
1056 port = tunnel.endpoints[0][1]
1057 assert not tunnel.needs_restart
1058 try:
1059 drop_trigger.touch()
1060 wait_until(
1061 lambda: tunnel.needs_restart,
1062 description="the tunnel to be reported dropped",
1063 )
1064 assert not accepts(port)
1065 # the child that comes back stays up
1066 monkeypatch.delenv("FAKE_SSH_DROP_WHEN")
1067 tunnel.restart()
1068 assert accepts(port)
1069 assert not tunnel.needs_restart
1070 finally:
1071 tunnel.stop()
1072
1073
1074 def test_a_restart_never_asks_for_a_credential(
1075 drop_trigger: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
1076 ) -> None:
1077 """Something owns the terminal by now, so a prompt has nowhere to go."""
1078 record = tmp_path / "argv.jsonl"
1079 monkeypatch.setenv("FAKE_SSH_ARGV", str(record))
1080 tunnel = started_tunnel(before_start=lambda t: t.watch(lambda notice: None))
1081 try:
1082 assert "BatchMode=yes" not in calls(record)[-1]
1083 drop_trigger.touch()
1084 wait_until(
1085 lambda: tunnel.needs_restart,
1086 description="the tunnel to be reported dropped",
1087 )
1088 monkeypatch.delenv("FAKE_SSH_DROP_WHEN")
1089 tunnel.restart()
1090 assert "BatchMode=yes" in calls(record)[-1]
1091 # and the tunnel still says what it was configured with
1092 assert "BatchMode=yes" not in tunnel.argv
1093 finally:
1094 tunnel.stop()
1095
1096
1097 def test_two_workers_reopening_at_once_do_not_bury_a_working_tunnel(
1098 drop_trigger: Path, monkeypatch: pytest.MonkeyPatch
1099 ) -> None:
1100 """The loser would otherwise lose the bind race and latch never-retry.
1101
1102 `_execute_query` and `update_schema_data` are exclusive within their own
1103 worker groups and not against each other, so both can arrive at once.
1104 """
1105 tunnel = started_tunnel(before_start=lambda t: t.watch(lambda notice: None))
1106 port = tunnel.endpoints[0][1]
1107 try:
1108 drop_trigger.touch()
1109 wait_until(
1110 lambda: tunnel.needs_restart,
1111 description="the tunnel to be reported dropped",
1112 )
1113 monkeypatch.delenv("FAKE_SSH_DROP_WHEN")
1114
1115 started = threading.Barrier(2)
1116 raised: list[BaseException] = []
1117
1118 def restart() -> None:
1119 started.wait()
1120 try:
1121 tunnel.restart()
1122 except BaseException as e:
1123 raised.append(e)
1124
1125 threads = [threading.Thread(target=restart) for _ in range(2)]
1126 for thread in threads:
1127 thread.start()
1128 for thread in threads:
1129 thread.join(timeout=30)
1130
1131 assert raised == []
1132 assert tunnel.running
1133 assert accepts(port)
1134 assert not tunnel.dropped
1135 finally:
1136 tunnel.stop()
1137
1138
1139 def test_a_restart_that_fails_is_not_tried_again(
1140 drop_trigger: Path, monkeypatch: pytest.MonkeyPatch
1141 ) -> None:
1142 tunnel = started_tunnel(before_start=lambda t: t.watch(lambda notice: None))
1143 drop_trigger.touch()
1144 wait_until(
1145 lambda: tunnel.needs_restart, description="the tunnel to be reported dropped"
1146 )
1147 monkeypatch.setenv("FAKE_SSH_STDERR", "Permission denied (publickey).")
1148 monkeypatch.setenv("FAKE_SSH_EXIT", "255")
1149 with pytest.raises(HarlequinSshError, match="Permission denied"):
1150 tunnel.restart()
1151 assert tunnel.dropped
1152 assert not tunnel.needs_restart