Principle:2giosangmitom Sqmeow nvim SSH Tunneling
| Knowledge Sources | |
|---|---|
| Domains | Networking, Connection_Management |
| Last Updated | 2026-10-16 14:00 GMT |
Overview
A network tunneling principle that forwards a local port through SSH to reach databases behind a bastion host, with the tunnel lifecycle tied to the connection's lifetime.
Description
SSH Tunneling is the principle of establishing a secure SSH port-forwarding session to reach a database that is not directly accessible from the user's machine. A free local port is bound, the SSH binary is spawned with -N -L forwarding options, and the database URL is rewritten to point at 127.0.0.1:<local_port>. The tunnel process is killed when the connection closes.
This principle addresses the common pattern of databases sitting behind a bastion host for security. The tunnel is transparent to the adapter: it receives a rewritten URL that looks like a local connection. Default ports are inferred from the dialect when the URL omits one.
Constraints: File-based databases (SQLite, DuckDB), MongoDB SRV addresses (which resolve hosts through DNS), and multi-host cluster URLs (which name several hosts) cannot go through a single tunnel. SSH is run with BatchMode=yes and ExitOnForwardFailure=yes for non-interactive, fail-fast behavior.
Usage
Use this principle when a database connection specifies an SSH jump target and the database host is reachable only through that bastion. The tunnel is established before adapter selection and is held for the connection's lifetime.
Theoretical Basis
The principle uses SSH local port forwarding:
- Port allocation: Bind
127.0.0.1:0to get a free local port. - Forwarding:
ssh -N -L 127.0.0.1:LOCAL:HOST:PORT user@bastionforwards the local port to the database through the bastion. - Readiness: Poll the local port until it accepts connections (up to
CONNECT_TIMEOUT), or report the SSH error if the process exits. - Lifetime: The tunnel process is killed on drop, tying the tunnel's lifecycle to the connection's.
# Abstract pattern (NOT real implementation):
async def open_ssh_tunnel(ssh: str, url: str, via: str) -> tuple[str, Tunnel]:
host, port = parse_db_host(url) # default port from dialect
local = bind_free_port()
child = spawn(ssh, "-N", "-L", f"127.0.0.1:{local}:{host}:{port}", via)
wait_for_port(local, timeout=10) # or report ssh exit
rewritten = url.replace(host, f"127.0.0.1:{local}")
return rewritten, Tunnel(child) # killed on drop