Debian Codegraph @

docs/plans/ssh-tunnels-design.md

raw
1 # SSH tunnels — a design for [#545](https://github.com/tconbeer/harlequin/issues/545)
2
3 Reach a database through an SSH host, from either command, **with any adapter — including
4 out-of-tree ones that are never changed.** Nothing here is implemented yet.
5
6 ## Summary
7
8 - **Harlequin runs `ssh`; it does not touch connection details.** The user's details already
9 name the local end of a forward. Core never learns which adapter option is the host, never
10 parses a DSN, and adds nothing to the adapter API — which is why every adapter works,
11 including ones nobody in this org maintains.
12 - **Four flags, all `--ssh-*`, none of them parsed.** `--ssh-host` and `--ssh-forward` go to
13 `ssh` verbatim. Anything they cannot say goes in a `Host` block, which `--ssh-host` names.
14 - **No new dependencies** — the blocker on the issue since 2025 — and the user's whole
15 `~/.ssh/config` comes for free: `LocalForward`, `ProxyJump`, agent, certificates, `Match`.
16 - **The tunnel starts before Textual**, so a passphrase or 2FA prompt reaches a human — or
17 `--ssh-batch-mode` refuses to prompt at all, for scripts and agents. It is a child process,
18 not `ssh -f`, so it dies with the session instead of outliving it.
19 - **It stays up, and comes back if it drops** (§5.4): keepalives when the user's config sets
20 none, and a lazy restart-and-reconnect in the IDE on the next thing that needs the database.
21
22 ## 1. Ten seconds of SSH
23
24 | | |
25 |---|---|
26 | `-L 15439:redshift.internal:5439` | **local forward.** Listen on `127.0.0.1:15439`; deliver to `redshift.internal:5439` **as resolved by the SSH host**. |
27 | `LocalForward 15439 redshift.internal:5439` | the same directive, in a `~/.ssh/config` `Host` block |
28 | `-N` | run no remote command; I am here for the forwards |
29 | `-f` | fork to the background once the forwards are up |
30 | `-o ExitOnForwardFailure=yes` | exit if a forward cannot be set up, rather than connecting anyway |
31 | `-o BatchMode=yes` | never prompt for a passphrase, password or host key; fail instead |
32 | `ssh -G host` | print the resolved config — `Host`/`Match` blocks plus this command line's flags — and connect to nothing |
33
34 `ssh -fN redshift_prod` and `ssh -L …` are not alternatives. `-f` and `-N` say *how to run*;
35 `-L` and `LocalForward` say *what to forward*, and they are one directive in two places. **A
36 user who already tunnels has the forward in their ssh config**, so `--ssh-forward` is optional
37 and the motivating case (§3.1) never uses it.
38
39 ## 2. The contract
40
41 **The connection details name the local end of the forward.** Harlequin runs the tunnel and
42 touches nothing else. `conn_str` and every adapter option reach the adapter exactly as typed;
43 the adapter is never told a tunnel exists.
44
45 ```
46 ssh_host = "redshift_prod" ─► ssh -N -o ExitOnForwardFailure=yes redshift_prod
47 (the -L comes from ~/.ssh/config)
48
49 host = "localhost" ─► adapter dials 127.0.0.1:15439, the local end of
50 port = 15439 `LocalForward 15439 …:5439`
51 ```
52
53 Consequences worth naming:
54
55 - **Nothing is rewritten**, so `connection_id` and the catalog cache key stay stable across
56 runs, and TLS still verifies the hostname the user asked for.
57 - **DuckDB and SQLite need no special case.** They ignore the tunnel; a duckdb `ATTACH` of
58 `postgres://localhost:15439/prod` goes through it like anything else.
59 - **A profile with `host = "localhost"` is only correct with its tunnel up.** Run it without
60 `ssh_host` and it reaches whatever is on that port locally. Recommend a distinct local port
61 — `15439`, not `5439` — so that mistake is a connection refused rather than the wrong
62 database. The `ssh_*` keys sit in the same profile, so they travel together.
63
64 ## 3. Examples
65
66 ### 3.1 The motivating case: a real `Host` block
67
68 ```
69 Host redshift_prod
70 HostName web-1
71 User tco
72 LocalForward 15439 data-analytics.<aws-acct>.us-east-1.redshift.amazonaws.com:5439
73 ServerAliveInterval 60
74 ServerAliveCountMax 3
75 ```
76
77 Today: `ssh -fN redshift_prod`, then `harlequin --host localhost --port 15439 …`, then
78 remember to kill the ssh.
79
80 ```toml
81 [profiles.redshift]
82 adapter = "postgres"
83 host = "localhost"
84 port = 15439
85 dbname = "prod"
86 ssh_host = "redshift_prod"
87 ```
88
89 `harlequin -P redshift`, `hsql -P redshift -c "select 1"`. **One key.** The connection details
90 are the ones that already work. Local `15439`, remote `5439` — the profile names the local
91 end, which is all the contract says.
92
93 ### 3.2 The same cluster, no `~/.ssh/config`
94
95 ```bash
96 harlequin -a postgres --host localhost --port 15439 --dbname prod --user tco \
97 --ssh-host tco@web-1 \
98 --ssh-forward 15439:data-analytics.<aws-acct>.us-east-1.redshift.amazonaws.com:5439 \
99 --ssh-batch-mode
100 ```
101
102 `HostName` + `User` → `--ssh-host tco@web-1`. `LocalForward` → `--ssh-forward`, the same text
103 with the space turned into a colon. (`--user` is Redshift's user; `tco@` is the SSH host's.)
104 The keepalives have **no flag** — see §8. This is the shape for CI or an agent with no
105 dotfiles; everyone else writes the `Host` block.
106
107 ### 3.3 Others
108
109 | | |
110 |---|---|
111 | database on the SSH host | `--ssh-forward 5432:localhost:5432` — `localhost` is the far side's |
112 | local 5432 already taken | `--ssh-forward 15432:db.internal:5432`, details say `15432` |
113 | two databases, one host | `--ssh-forward` twice; one child, two `-L` |
114 | a jump host in front | `ProxyJump` in the `Host` block. Chains work because `ssh` does them |
115 | Cloud SQL, `kubectl`, SSM | run the proxy yourself and point at its local port — that already works, because of §2. Harlequin just does not own its lifetime (§8) |
116 | not tunneled | no `ssh_host`, no `harlequin.ssh` import, no cost |
117
118 ## 4. The options
119
120 Both commands, since one profile serves both and `hsql` is where it matters most: a cron job
121 cannot ask a human to run `ssh -fN` first.
122
123 | option | profile key | meaning |
124 |---|---|---|
125 | `--ssh-host TEXT` | `ssh_host` | the destination, verbatim to `ssh`: a `Host` alias, `host`, `user@host`, or `ssh://user@host:port` |
126 | `--ssh-forward TEXT` | `ssh_forward` | repeatable; whatever follows `ssh -L`, verbatim. Omit when `ssh_config` has it |
127 | `--ssh-batch-mode` | `ssh_batch_mode` | ssh's `BatchMode`: fail rather than ask for a passphrase, password or host key (§5.2) |
128 | `--ssh-allow-reuse` | `ssh_allow_reuse` | on a bind collision, warn and connect anyway instead of failing (§5.3) |
129 | `--ssh-timeout FLOAT` | `ssh_timeout` | seconds to wait for the forwards (default 10) |
130
131 No short declarations — `-o` is `--output` in both commands. These join the reserved spellings
132 in `first_pass.attach_adapter_options()`; no published adapter appears to claim one.
133
134 **Harlequin parses none of these values.** `ssh` owns its own syntax and error messages, so
135 there is no Harlequin-shaped subset of either to document or to get wrong. The only parsing in
136 this feature is of `ssh -G`'s *output* (§5.1) — something `ssh` prints, not something a user
137 typed.
138
139 `--ssh-host` with no forward anywhere is a usage error naming both places to put one.
140
141 **The start-up notice**, on `hsql`'s stderr (never stdout) and as an IDE notification and
142 debug-screen line:
143
144 ```
145 ssh: 127.0.0.1:15439 -> data-analytics.<aws-acct>.us-east-1.redshift.amazonaws.com:5439 via redshift_prod
146 ```
147
148 It is what tells a user which database they are actually looking at.
149
150 ## 5. Behavior
151
152 `harlequin/ssh.py`, one class:
153
154 ```python
155 class SshTunnel:
156 """An `ssh` child process holding one or more local forwards open."""
157
158 def start(self) -> None:
159 """Start it and block until the forwarded ports accept connections.
160 Raises HarlequinSshError, quoting ssh's stderr."""
161
162 def stop(self) -> None: ...
163 def __enter__(self) -> SshTunnel: ...
164 def __exit__(self, *exc: Any) -> None:
165 self.stop()
166 ```
167
168 ```
169 first_pass -> click parses -> profile merge -> SshTunnel.start() <-- prompts happen HERE
170 |
171 adapter_cls(...) -> tui.run() / hsql runs
172 |
173 ExitStack unwinds -> stop()
174 ```
175
176 - **Before Textual, in the click callback.** Once Textual owns the terminal, `ssh` cannot ask
177 for a passphrase and a 2FA push has nowhere to print "check your phone". It also gives both
178 commands one error path — `pretty_print_error` / `diagnostics.report_error`, exit code 3.
179 - **Foreground, not `-f`.** The child keeps the terminal, so prompts work, and we keep the
180 handle, so it can be killed. Teardown is `terminate()` then `kill()` from a
181 `contextlib.ExitStack` around `tui.run()` and the `hsql` run, plus an `atexit` backstop.
182 - **`ExitOnForwardFailure=yes` is the only `-o` Harlequin imposes on its own**, because a forward that
183 silently did not happen is the one failure a user cannot diagnose. Notably not imposed:
184 `ServerAliveInterval`. A command-line `-o` beats the config file, and §3.1 already sets
185 keepalives — overriding them would be Harlequin retuning someone else's connection.
186 - **The IDE says when the tunnel dies.** A thread waiting on the child posts
187 `tunnel closed: <ssh's last line>`, so a dropped forward is not an unexplained wall of query
188 errors. No reconnect in v1. `hsql` is short-lived; the adapter's error is the whole story.
189
190 ### 5.1 `ssh -G` says what is about to be forwarded
191
192 ```
193 $ ssh -G redshift_prod | grep -i forward
194 localforward 15439 [data-analytics.<aws-acct>.us-east-1.redshift.amazonaws.com]:5439
195 ```
196
197 **Probe with the argv we are about to run.** `ssh -G` echoes command-line `-L` flags back
198 along with the config's, so one call returns one list whether the forward came from
199 `--ssh-forward`, a `Host` block, or both — there are not two sources to keep in agreement.
200
201 Parsing is two whitespace-separated fields after the keyword, each `port`, `[host]:port`, or a
202 socket path (which counts as a forward but is not polled). The same output answers one more
203 question — `serveraliveinterval`, for §5.4. It costs one subprocess, ~10–30ms, no network. If
204 `-G` fails or prints something unparseable, Harlequin degrades: no poll, no forwards-nothing
205 error, no imposed keepalive, a short grace period, and the adapter's connection is the test.
206
207 **Why this step exists at all**: it is the only way to know which local port to wait on before
208 the adapter connects, and in §3.1 — the motivating case — Harlequin never saw a port number.
209 `ssh -f` would signal readiness by exiting, but the surviving process would not be our child
210 and could not be killed at exit, which is the orphaned tunnel this feature removes.
211
212 ### 5.2 Readiness, and prompts
213
214 Connect-poll each local port `-G` reported until `--ssh-timeout` (default 10s), noticing the
215 child exiting early. On failure, the error quotes ssh's stderr verbatim — its diagnostics are
216 better than any we would write.
217
218 **A prompt nobody answers is what the timeout catches**, and catching it late is not good
219 enough for a script: `ssh` asks for a passphrase, a password, or confirmation of an unknown
220 host key, and an unattended caller waits out the whole timeout and then reports something
221 vague. `--ssh-batch-mode` passes `-o BatchMode=yes` — ssh's own name for it, so anyone who
222 knows the `ssh_config` keyword knows the flag — and `ssh` fails immediately, saying which
223 credential it wanted. An agent, a cron job and CI should all set it.
224
225 Without the flag the timeout is still the backstop, so nothing hangs forever — and when it
226 fires with the child still running, the error names the flag, because waiting on input is the
227 likeliest reason a live `ssh` never opened its forwards.
228
229 ### 5.3 A local port that is already bound
230
231 Harlequin always tries to start the tunnel; `ExitOnForwardFailure=yes` means `ssh` exits
232 rather than connecting without the forward. What happens next is the flag:
233
234 | | |
235 |---|---|
236 | default | fail and exit 3, quoting ssh (`bind: Address already in use`) |
237 | `--ssh-allow-reuse` | if **every** forwarded port is now accepting connections, warn and connect anyway |
238
239 ```
240 ssh: 127.0.0.1:15439 is already bound; connecting through the existing listener (--ssh-allow-reuse)
241 ```
242
243 The reuse test is behavioral — the child failed, but the ports answer — rather than a match
244 against ssh's message, so it does not depend on wording. If only some ports answer, that is a
245 half-open state nobody meant: fail either way.
246
247 Failing by default is the safe direction: a port that answers is not proof the right tunnel is
248 behind it. `--ssh-allow-reuse` is for the person who keeps `ssh -fN redshift_prod` running all
249 day and does not want Harlequin fighting it.
250
251 ### 5.4 Keeping it open, and getting it back
252
253 A tunnel that drops after lunch is the difference between a feature people trust and one they
254 work around. Three layers, cheapest first.
255
256 **Keep it alive.** `ssh` sends no keepalives by default, so an idle forward behind a NAT or a
257 corporate firewall is reaped silently. The `-G` probe already reports the resolved
258 `serveraliveinterval`: if it is `0`, Harlequin passes `-o ServerAliveInterval=30`; if the user
259 set one — §3.1 sets 60 — it is left alone. No flag, no override, and the common case stops
260 dropping. Not configurable: a keepalive interval is not a thing anyone should have to tune,
261 and the one person who wants to has a `Host` block.
262
263 **Say so immediately.** A thread waiting on the child posts `tunnel closed: <ssh's last line>`
264 when it exits unexpectedly, so a dead forward is not an unexplained wall of query errors.
265
266 **Recover on next use.** Restarting `ssh` is not enough on its own: the adapter's TCP
267 connection ran *through* the old forward, so it died with it. Recovery is both halves,
268 together, and it happens lazily — before the next thing that needs the database (a query, a
269 catalog refresh), not on a background timer:
270
271 1. the tunnel is marked down when the monitor sees the child exit;
272 2. the next database action restarts `ssh` and re-runs the readiness poll;
273 3. then re-runs `adapter.connect()`, replacing `self.connection`;
274 4. then does what the user asked.
275
276 Three things this has to get right:
277
278 - **Restarts are always `BatchMode=yes`**, whatever the flag said at start-up. Textual owns
279 the terminal now, so a passphrase prompt has nowhere to go. If the restart needs a
280 credential we cannot supply, it fails once with that message and does not retry — the user
281 restarts Harlequin, having been told why.
282 - **Say what was lost.** A reconnect is a new session: open transactions are gone, so are temp
283 tables and anything set with `SET`. The notification says so rather than letting a user
284 believe they are still inside a `BEGIN`.
285 - **One attempt per action, no loop.** The user retries by running their query again. A
286 background retry storm against a bastion that is down is how an account gets locked.
287
288 **`hsql` does none of this.** It is short-lived, its statements are not idempotent, and an
289 unattended caller that loses its connection should fail loudly: the statement errors, and the
290 run exits 3 (or continues, per `--on-error`). Only the keepalive applies to both commands.
291
292 Reconnecting the adapter is useful beyond tunnels — a server restart or an idle timeout kills
293 a connection the same way — but v1 triggers it only from a tunnel that went down, because
294 that is the case it can detect without guessing.
295
296 ## 6. What this touches
297
298 **No public API change.** Nothing in `HarlequinAdapter`, `HarlequinConnection`,
299 `HarlequinCursor`, `AbstractOption`, `catalog.py` or `driver.py`. One new
300 `HarlequinSshError(HarlequinError)`, one new module, and — for §5.4 only — a reconnect path in
301 `app.py` that re-runs `adapter.connect()` on the existing connect worker.
302
303 **No dependency**: `subprocess`, `socket`. `harlequin/ssh.py` imports no Textual and no
304 adapter, joins the "adapter API is reachable without the TUI" contract, and is imported only
305 when `ssh_host` is set — `scripts/cold_start.py` should show no change.
306
307 **One cache-key change.** Two bastions fronting two databases both look like
308 `localhost:15439`, and would share a catalog cache and query history. The ssh destination and
309 the resolved forwards join the hashed material.
310
311 **Config, for free.** A command's click params claim its profile keys, so `ssh_*` become valid
312 profile and JSON-schema keys with no further plumbing; regenerate `schemas/config-v1.json`.
313
314 ## 7. Testing, and phasing
315
316 No SSH server, no `online` marker.
317
318 - **Lifecycle, all three OSes.** `SshTunnel` takes an argv and ports, so tests hand it a
319 Python child: a ~30-line loopback forwarder in `tests/`, covering start, poll, timeout,
320 reuse, half-open, the death notification, and teardown.
321 - **End to end, Unix.** A fake `ssh` on `PATH` that understands `-G` and `-L` exercises the
322 real CLI path including the probe. Skipped on Windows.
323 - **Unit**: `--ssh-forward` reaches argv unchanged and repeats in order; `--ssh-host` is
324 unparsed; `-G` lines with a bind address, IPv6 and a socket path parse; `-G` returning only
325 `dynamicforward` is a usage error; `-G` garbage degrades; no forward anywhere is a usage
326 error; the argv carries `ExitOnForwardFailure` and, with `--ssh-batch-mode`, `BatchMode=yes` and
327 nothing else; `-o` still means `--output`; a timeout with the child alive names
328 `--ssh-batch-mode`; profile round trip; two ssh hosts hash differently.
329 - **Recovery**: `-G` reporting `serveraliveinterval 0` adds `-o ServerAliveInterval=30`, a
330 non-zero one does not; killing the child marks the tunnel down and notifies; the next action
331 restarts it in batch mode, reconnects, and warns about lost session state; a restart that
332 fails does not retry.
333 - One test runs `ssh -V` and skips if absent, proving the argv is accepted by a real client.
334
335 Phasing: **(1)** `harlequin/ssh.py` — argv, `-G` probe and parser, poll, reuse,
336 `HarlequinSshError`; unit and lifecycle tests, no CLI. **(2)** the four options, the
337 `ExitStack`, the notice, the cache key, the end-to-end test. **(3)** the keepalive default, the death
338 notification, `--info` and debug-screen reporting, regenerated schema. **(4)** lazy
339 restart-and-reconnect in the IDE (§5.4), which is the one step that touches `app.py`. **(5)** docs in `harlequin-web` — the
340 contract, and the `Host` block as the recommended setup — plus a `CHANGELOG.md` entry under
341 `[Unreleased]` → Features citing [#545](https://github.com/tconbeer/harlequin/issues/545).
342
343 ## 8. Rejected and deferred
344
345 **Rejected.**
346
347 | | |
348 |---|---|
349 | **Rewriting the adapter's host/port** (the issue's sketch, and this doc's first draft) | Core would have to know which option is the host: a `role=` declaration no adapter has, a name-matching guess, and a DSN rewrite — three mechanisms that can be quietly wrong, to reach where a local forward reaches with none. It also bakes an ephemeral port into `connection_id` and breaks TLS hostname verification unasked. |
350 | **`--ssh-option KEY=VALUE`** | `-o ProxyCommand=…` is arbitrary code execution, and config files are discovered in the working directory — a cloned repo's `pyproject.toml` must not be able to run a command. A deny-list would mostly work, but `KnownHostsCommand` arrived in OpenSSH 8.5, so it is a list to revisit forever and a miss is a hole. Four flags that are a hostname, a forward spec, a boolean and a number have nothing to deny. A `ProxyCommand` in the user's own `~/.ssh/config` is unaffected and always was. |
351 | **`--ssh-config PATH`** (`ssh -F`) | Looks safer — a path, not a keyword — but the file it names can hold a `ProxyCommand`. Same threat, extra step, no deny-list possible. |
352 | **`--ssh-user` / `--ssh-port` / `--ssh-identity`** | `ssh_config` spelled a second time. |
353 | **A configurable local bind address** | `ssh_config` and the forward spec already do it; `0.0.0.0` should take deliberate effort. |
354 | **`require_tunnel = true`** | A distinct local port already turns the mistake into a connection refused. |
355 | **A `{tunnel_port}` placeholder in the conn_str** | General, but a second thing to learn for the same result, and it makes the profile unusable *without* the tunnel. |
356 | **SOCKS (`ssh -D`) with `socket.socket` patched** | Keeps the real hostname, so TLS is untouched — but only works for pure-Python drivers. psycopg2, mysqlclient, ODBC and duckdb open sockets in C. |
357 | **Per-adapter `--ssh-*`** | N implementations, N spellings, and the adapters that need it most are out-of-tree. |
358 | **A library adapters call** | Opt-in, so "any adapter" becomes "adapters that adopted it". Fine *in addition*, for something like the Cloud SQL connector. |
359 | **`sshtunnel`** | Four years without a release, wrapping paramiko for behavior a binary on the machine already has. |
360 | **paramiko in v1** | A `cryptography` dependency on every install, reimplementing the `~/.ssh/config` handling users already have working. |
361 | **"Just run `ssh -fN` yourself"** | Works today, but means a second terminal, an orphaned tunnel to kill, and a profile that only connects if a human ran something first — which `hsql` in a cron job cannot do. |
362
363 **Deferred, and what brings each back.**
364
365 | | |
366 |---|---|
367 | `--ssh-keepalive SECONDS` | someone runs an all-day IDE session with no `~/.ssh/config` and gets dropped (§3.2) |
368 | `--tunnel-command` for non-SSH proxies | a Cloud SQL or `kubectl` user wants Harlequin to own the proxy's lifetime, with an answer to the code-execution problem above |
369 | a paramiko backend, `harlequin[ssh]` | a user on Windows or in a container with no `ssh` binary |
370 | reconnecting a database connection that dropped with the tunnel up | a server restart or idle timeout should recover the same way §5.4 does; v1 only detects the tunnel case |
371 | recovering the Data Catalog's lazy loader | `InteractiveCatalogItem.fetch_children()` runs on the connection the adapter captured when the tree was built, which §5.4's recovery cannot reach. Expanding an unloaded node after a drop fails with a Catalog Error and stays broken until the next full refresh replaces the tree. Bring it back when catalog items can be handed a new connection, rather than by reaching into each adapter's items |
372 | `--ssh-batch-mode` on by default in `hsql` | interactive `hsql` users turn out to be rarer than scripted ones. Default-off is the same behavior in both commands today, which is easier to explain |
373
374 Each is additive: the flags are namespaced, one class has no ABC to satisfy, and no adapter is
375 involved in any of it.