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