Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Principle:2giosangmitom Sqmeow nvim SSH Tunneling

From Leeroopedia
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:

  1. Port allocation: Bind 127.0.0.1:0 to get a free local port.
  2. Forwarding: ssh -N -L 127.0.0.1:LOCAL:HOST:PORT user@bastion forwards the local port to the database through the bastion.
  3. Readiness: Poll the local port until it accepts connections (up to CONNECT_TIMEOUT), or report the SSH error if the process exits.
  4. 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

Related Pages

Implemented By

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment