holt

package module
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 11, 2026 License: MIT Imports: 7 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

🌀 holt

Reverse HTTP tunnels for services that can only dial out.

Go Reference Go Report Card

A holt is an otter's den: a burrow in the riverbank, reachable only through the underwater tunnel its owner dug. Same idea here. A peer that cannot accept inbound connections (behind NAT, in a locked down container, on a field device) dials out to a hub, then serves an ordinary http.Handler back through the connection it opened. The hub gets an http.RoundTripper per peer, and a presence signal for free.

No listener, no inbound port, no published container port on the peer.

⚠️ Alpha, extracted from openotters where it is the sole daemon-to-agent-runtime channel. The wire protocol may still change.

Contents

Get started

brew install openotters/tap/holt

Or with Go:

go install github.com/openotters/holt/cmd/holt@latest

As a library:

go get github.com/openotters/holt

On Kubernetes (multi-arch images on ghcr, chart as an OCI artifact):

helm install holt oci://ghcr.io/openotters/charts/holt

The chart runs the hub with persistent state, a LoadBalancer for the tunnel listener and the admin console kept private; see charts/holt/values.yaml.

Quickstart

Expose a local service through a hub in four commands:

holt hub --ui &                      # run a hub (web console on 127.0.0.1:7001)
holt enroll web                      # mint a join token for a peer named "web"
holt expose localhost:3000 --token <paste>   # on the peer machine

Then reach the peer through the hub:

curl -H 'x-tunnel-peer: web' http://127.0.0.1:7002/

The token bundles the peer's JWT, the hub address, and the hub's self-signed certificate to pin. The tunnel is TLS encrypted and both sides are authenticated, out of the box.

How it works

  peer (dials out)                         hub (public)
      │                                       │
      │-- Tunnel.Attach (bidi gRPC) --------->│   auth middleware → peer id
      │-- Hello ----------------------------->│
      │<----------------------------- Welcome │   registry.Attach(peer)
      │                                       │
      │  http2.Server.ServeConn(tunnel,       │   http2.Transport over tunnel:
      │    yourHandler)                       │   registry.RoundTripper(peer)
      │                                       │
      │◀======= HTTP request =================│   client.Do(req) → peer's handler
      │======== HTTP response ===============>│

Everything rides a single bidirectional gRPC stream. The stream carries raw bytes (TunnelFrame.data, at most 32 KiB per frame); each side runs a standard HTTP/2 endpoint over it, server on the peer, client on the hub. Presence of the tunnel doubles as the peer's liveness signal.

The module has four parts:

  • hub: server side. NewRegistry tracks live tunnels per peer; NewHandler is the Tunnel.Attach implementation you mount behind your auth middleware.
  • dial: client side. dial.Run is a persistent attach loop that serves your http.Handler over the tunnel and redials with jittered backoff. It rides an existing *grpc.ClientConn, so it reuses whatever auth interceptors you already attached.
  • hub/sqldir: a SQL-backed presence directory (SQLite or PostgreSQL) for sharing which peer is attached to which hub across a fleet.
  • root package: the shared Conn (stream to net.Conn adapter), handshake, and GoAway vocabulary.

Use it as a library

The holt CLI is one opinionated packaging (JWT auth, pinned TLS, SQLite state). The library lets you bring your own auth and transport.

Peer side:

cc, _ := grpc.NewClient(hubAddr, grpc.WithTransportCredentials(creds), authInterceptors...)
dial.Run(ctx, dial.Options{Conn: cc, Handler: myHandler, Version: build.Version, Logger: log})

Hub side:

registry := hub.NewRegistry(log)
path, h := holtv1connect.NewTunnelHandler(
    hub.NewHandler(registry, identityFromJWT, log),
    connect.WithInterceptors(authInterceptor),
)
mux.Handle(path, h)

// later, anywhere in the hub process:
client := &http.Client{Transport: registry.RoundTripper(peerID)}

CLI cheat sheet

holt hub                     # run the hub (tunnel, admin, proxy listeners)
holt hub --ui                # same, plus the web console on the admin port
holt enroll <peer>           # mint a join token for a peer
holt expose <addr> --token <t>  # expose a local HTTP service through the hub
holt ls                      # list live tunnels
holt kill <peer>             # disconnect a tunnel (the peer may reconnect)
holt block <peer>            # disconnect AND ban the peer id
holt unblock <peer>          # lift a block

Run holt <cmd> --help for details. Hub state (certificate, JWT secret, blocklist) lives in ~/.holt.

Output is friendly by default: a welcome banner with the addresses, readable logs, tables and checkmarks. For production, switch to the classic structured logs with --log-format json (or the HOLT_LOG_FORMAT=json environment variable).

Operating the hub

The Registry is the operational surface over live tunnels:

registry.ListTunnels()             // every live tunnel on this hub
registry.Tunnel(peer)              // one, with attach time and peer version
registry.CountTunnels()            // how many are up
registry.StopTunnel(peer, reason)  // force one closed (GoAway to the peer)
registry.StopAllTunnels(reason)    // drain, e.g. on shutdown
registry.Attached(peer)            // is peer attached to THIS hub?
registry.Watch(ctx)                // stream attach/detach events

The same surface is exposed over the wire by the Admin gRPC service (holt ls, holt kill, ...) and by the web console.

Presence directory

RoundTripper needs the live HTTP/2 connection, which only the owning hub holds, so live connections are always local. What is pluggable is presence: which peer is attached, to which hub, since when. That is the Directory interface, in-memory by default (a single hub needs nothing else).

For a fleet, back it with SQL so any hub can answer "is peer X attached, and where?". hub/sqldir supports SQLite and PostgreSQL and imports only database/sql (you bring the driver):

db, _ := sql.Open("sqlite", "file:presence.db")           // or pgx/stdlib
dir := sqldir.New(db, sqldir.SQLite); _ = dir.Migrate(ctx)

reg := hub.NewRegistry(log,
    hub.WithHubID("hub-eu-1"),   // stable per-instance id, recorded in rows
    hub.WithDirectory(dir))
_ = reg.ClearStale(ctx)          // drop rows this hub left after a crash

reg.LookupPeer(ctx, peer)        // fleet-wide: which hub owns it
reg.Peers(ctx)                   // fleet-wide roster

Cross-hub request forwarding (dialing a peer attached to another hub) is left to the application; LookupPeer tells it which hub to forward to.

Identity

Peer identity is the application's job, never the handshake's. The hub Handler takes an Identity func(ctx) (peer string, err error) that reads whatever your middleware established: a JWT claim, an mTLS SAN, a header. A second in-band source of truth could only ever agree, or be an attack.

Liveness and lifecycle

  • Inner HTTP/2 PINGs (ReadIdleTimeout) detect a wedged peer end to end, through the tunnel, not just a dead TCP socket.
  • A second Attach for the same peer replaces the first (GoAway("superseded")), so a crashed-and-redialed peer never waits out a keepalive timeout.
  • Terminal GoAway reasons (superseded, token-revoked, peer-stopping) stop the peer redialing; everything else is retried with backoff.

Observability

The hub emits OTel metrics (holt.tunnels.active / .attaches / .detaches) and a span per tunnel (holt.tunnel, tagged with peer, version, detach reason). It uses the global OTel providers by default, which are a no-op until you install an SDK: instrumentation is always present, never mandatory, and costs nothing when unconfigured.

hub.NewRegistry(log, hub.WithMeterProvider(mp))
hub.NewHandler(reg, id, log, hub.WithTracerProvider(tp))

Examples

Every example under examples/ is runnable with go run:

Example What it shows
echo Smallest end-to-end demo, hub and peer in one process
client-server Standalone hub and peer as two programs
authenticated Bearer-token auth interceptors on both sides
transport-tls Mutual TLS on the outer gRPC hop
encrypted Plaintext outer hop, mutual TLS inside the tunnel
join-token Token-based enrollment, like the CLI does it
grpc-tunnel A peer serving gRPC (not just HTTP) through the tunnel

There is also cmd/starter-client, a minimal peer meant to be copied as the starting point of your own.

Development

Everything goes through Task:

task                # list all tasks
task build          # build ./bin/holt
task dev            # run a hub with the web console from source
task test:race      # tests with the race detector
task lint           # golangci-lint (same config as CI)
task gen            # regenerate protobuf stubs (Go + TypeScript)
task ui:build       # rebuild the embedded web console
task check          # full local gate, same as CI

The web console is a small React app under ui/, embedded into the binary with go:embed.

License

MIT

Documentation

Overview

Package holt implements a reverse HTTP tunnel over a single bidirectional protobuf stream: a peer that can only dial OUT attaches to a hub, then serves an ordinary http.Handler back through the attached stream. The hub gets an http.RoundTripper per peer and a presence signal for free.

The module ships both halves:

  • hub: the server side — accept Attach streams, keep a registry of live tunnels, dial "through" any peer with a RoundTripper.
  • dial: the client side — a persistent attach loop that serves a handler over the tunnel and redials with backoff.

This package holds what both halves share: the frame-level net.Conn adapter, the handshake, and the GoAway vocabulary.

Index

Constants

View Source
const (
	ReasonSuperseded   = "superseded"
	ReasonTokenRevoked = "token-revoked"
	ReasonShuttingDown = "shutting-down"
	ReasonPeerStopping = "peer-stopping"
	// ReasonClosed is an operator-initiated close (e.g. an admin
	// "kill"): terminal, so the peer stops redialing until it is
	// restarted or re-enrolled.
	ReasonClosed = "closed"
)

Well-known GoAway reasons. Superseded, credential revocation, and deliberate stop are terminal for the peer (no redial); everything else means "redial with backoff".

View Source
const MaxDataFrame = 32 * 1024

MaxDataFrame caps one TunnelFrame data payload — keeps inner HTTP/2 stream interleaving granular and stays far under gRPC's 4 MiB message ceiling.

View Source
const ProtocolVersion = 1

ProtocolVersion is the tunnel framing version spoken by this module, offered in Hello and confirmed in Welcome.

Variables

This section is empty.

Functions

func ClientHandshake

func ClientHandshake(stream FrameStream, peerVersion string) error

ClientHandshake sends Hello and requires Welcome as the first reply. Called by the dial side on a fresh stream.

func GoAwayReason

func GoAwayReason(err error) string

GoAwayReason returns the GoAway reason carried by err, or "" when err is not a GoAway.

func ServerHandshake

func ServerHandshake(stream FrameStream) (*holtv1.Hello, error)

ServerHandshake requires Hello as the first frame and answers Welcome. Called by the hub on a fresh stream. Returns the peer's Hello for observability.

func TerminalReason

func TerminalReason(reason string) bool

TerminalReason reports whether a GoAway reason tells the peer to stop redialing.

Types

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

Conn adapts an Attach stream to a net.Conn carrying raw bytes as TunnelFrame data frames. Read is single-reader — the HTTP/2 session on top owns it — and writes are serialised internally because streams do not allow concurrent sends.

Close seals the adapter: it waits out any in-flight write, then makes every later I/O attempt fail locally with net.ErrClosed instead of reaching the stream. Hub handlers rely on this — the HTTP/2 transport's background goroutines (ping, resets) outlive the stream handler, and a late write to a finished handler's stream panics inside connect.

func NewConn

func NewConn(stream FrameStream, opts ...ConnOption) *Conn

NewConn wraps an attached (post-handshake) stream.

func (*Conn) Close

func (c *Conn) Close() error

Close seals the adapter (see the type comment) and runs the configured close func once.

func (*Conn) LastError

func (c *Conn) LastError() error

LastError returns the first terminal read error; a GoAway from the far end surfaces here with its reason intact.

func (*Conn) LocalAddr

func (c *Conn) LocalAddr() net.Addr

func (*Conn) Read

func (c *Conn) Read(p []byte) (int, error)

Read returns buffered tunnel bytes, receiving the next data frame when the buffer is empty. A GoAway ends the stream with io.EOF after recording the reason (see LastError).

func (*Conn) RemoteAddr

func (c *Conn) RemoteAddr() net.Addr

func (*Conn) SendGoAway

func (c *Conn) SendGoAway(reason string) error

SendGoAway emits a GoAway frame under the write mutex so it can never interleave with a data frame.

func (*Conn) SetDeadline

func (c *Conn) SetDeadline(time.Time) error

Deadlines are accepted but not enforced: liveness comes from the HTTP/2 session's PING on top and the stream's own context.

func (*Conn) SetReadDeadline

func (c *Conn) SetReadDeadline(time.Time) error

func (*Conn) SetWriteDeadline

func (c *Conn) SetWriteDeadline(time.Time) error

func (*Conn) Write

func (c *Conn) Write(p []byte) (int, error)

Write chunks p into data frames of at most MaxDataFrame bytes.

type ConnOption

type ConnOption func(*Conn)

ConnOption configures a Conn.

func WithCloseFunc

func WithCloseFunc(fn func() error) ConnOption

WithCloseFunc runs fn once when the Conn is closed — the dial side passes the stream's CloseSend so the hub sees a clean EOF.

func WithSides

func WithSides(local, remote string) ConnOption

WithSides labels LocalAddr/RemoteAddr for logs ("hub"/"peer").

type FrameStream

type FrameStream interface {
	Send(*holtv1.TunnelFrame) error
	Recv() (*holtv1.TunnelFrame, error)
}

FrameStream is the frame-level view of an Attach stream. The gRPC client stream (holtv1.Tunnel_AttachClient) satisfies it directly; the hub wraps connect's BidiStream (whose receive method is named Receive) with a one-line adapter.

type GoAwayError

type GoAwayError struct{ Reason string }

GoAwayError carries the far end's GoAway reason.

func (GoAwayError) Error

func (e GoAwayError) Error() string

Directories

Path Synopsis
api
v1
cmd
holt command
Command holt is the operator CLI for a reverse-tunnel hub: run the hub, enroll peers, and manage live tunnels.
Command holt is the operator CLI for a reverse-tunnel hub: run the hub, enroll peers, and manage live tunnels.
holt/internal/clog
Package clog builds the CLI logger.
Package clog builds the CLI logger.
holt/internal/jwtauth
Package jwtauth issues and verifies the HMAC-SHA256 JWTs peers present when attaching to the hub.
Package jwtauth issues and verifies the HMAC-SHA256 JWTs peers present when attaching to the hub.
holt/internal/selfsigned
Package selfsigned generates and persists the hub's self-signed TLS certificate — used to encrypt the tunnel transport — and its JWT secret, as files in the config folder.
Package selfsigned generates and persists the hub's self-signed TLS certificate — used to encrypt the tunnel transport — and its JWT secret, as files in the config folder.
holt/internal/store
Package store is the hub's durable non-secret state: a single SQLite database under the config directory (~/.holt/holt.db).
Package store is the hub's durable non-secret state: a single SQLite database under the config directory (~/.holt/holt.db).
holt/internal/style
Package style is the CLI's small output vocabulary: a success mark, a dim note, and a bordered table.
Package style is the CLI's small output vocabulary: a success mark, a dim note, and a bordered table.
holt/internal/token
Package token is the copy-paste enrollment token that carries everything a peer needs to join: the hub's tunnel address, the JWT that authenticates it, and the hub's self-signed cert to pin (so the TLS-encrypted tunnel is verified, not blindly trusted).
Package token is the copy-paste enrollment token that carries everything a peer needs to join: the hub's tunnel address, the JWT that authenticates it, and the hub's self-signed cert to pin (so the TLS-encrypted tunnel is verified, not blindly trusted).
holt/internal/webui
Package webui owns the hub's embedded web console.
Package webui owns the hub's embedded web console.
starter-client command
Command starter-client is a minimal, self-contained holt peer — a template to copy when writing your own client.
Command starter-client is a minimal, self-contained holt peer — a template to copy when writing your own client.
Package dial is the client half of the holt: a persistent attach loop that dials the hub, serves an http.Handler over the reverse tunnel, and redials with jittered backoff until the context ends or the hub sends a terminal GoAway.
Package dial is the client half of the holt: a persistent attach loop that dials the hub, serves an http.Handler over the reverse tunnel, and redials with jittered backoff until the context ends or the hub sends a terminal GoAway.
examples
authenticated command
Command authenticated shows the identity seam: the hub derives each peer's ID from a bearer token (a stand-in for a JWT claim or mTLS SAN), so the RoundTripper is keyed by an authenticated identity the peer cannot spoof — the Attach handshake carries no identity at all.
Command authenticated shows the identity seam: the hub derives each peer's ID from a bearer token (a stand-in for a JWT claim or mTLS SAN), so the RoundTripper is keyed by an authenticated identity the peer cannot spoof — the Attach handshake carries no identity at all.
certs
Package certs is a tiny demo PKI for the separated client/server holt examples.
Package certs is a tiny demo PKI for the separated client/server holt examples.
client-server/client command
Command client is a standalone holt peer.
Command client is a standalone holt peer.
client-server/server command
Command server is a standalone holt hub.
Command server is a standalone holt hub.
echo command
Command echo is the smallest end-to-end holt demo: it stands up a hub and a peer in one process, the peer serves an HTTP handler that only it could serve, and the hub reaches that handler by dialing back THROUGH the tunnel the peer opened.
Command echo is the smallest end-to-end holt demo: it stands up a hub and a peer in one process, the peer serves an HTTP handler that only it could serve, and the hub reaches that handler by dialing back THROUGH the tunnel the peer opened.
encrypted/client command
Command client is a holt peer that dials the hub over a PLAINTEXT transport but serves its handler over MUTUAL TLS INSIDE the tunnel.
Command client is a holt peer that dials the hub over a PLAINTEXT transport but serves its handler over MUTUAL TLS INSIDE the tunnel.
encrypted/server command
Command server is a holt hub whose OUTER gRPC hop is plaintext, but which runs MUTUAL TLS INSIDE each tunnel.
Command server is a holt hub whose OUTER gRPC hop is plaintext, but which runs MUTUAL TLS INSIDE each tunnel.
grpc-tunnel/client command
Command client is a holt peer that serves a real gRPC service over the tunnel — with server reflection, so grpcurl can call it through the hub without any .proto files.
Command client is a holt peer that serves a real gRPC service over the tunnel — with server reflection, so grpcurl can call it through the hub without any .proto files.
grpc-tunnel/server command
Command server is a holt hub that lets you call a peer's gRPC service through the tunnel with grpcurl.
Command server is a holt hub that lets you call a peer's gRPC service through the tunnel with grpcurl.
join-token/client command
Command client joins the hub using a COPY-PASTE TOKEN — no cert files, no shared filesystem.
Command client joins the hub using a COPY-PASTE TOKEN — no cert files, no shared filesystem.
join-token/server command
Command server is a mutual-TLS holt hub that hands out its client credential as a COPY-PASTE TOKEN instead of writing files.
Command server is a mutual-TLS holt hub that hands out its client credential as a COPY-PASTE TOKEN instead of writing files.
transport-tls/client command
Command client is a holt peer that dials the hub over MUTUAL TLS.
Command client is a holt peer that dials the hub over MUTUAL TLS.
transport-tls/server command
Command server is a holt hub that secures the OUTER gRPC connection with MUTUAL TLS.
Command server is a holt hub that secures the OUTER gRPC connection with MUTUAL TLS.
hub
Package hub is the server half of the holt: it accepts Attach streams from peers, keeps a registry of live tunnels keyed by peer ID, and lets the application dial "through" any attached peer with an ordinary http.RoundTripper.
Package hub is the server half of the holt: it accepts Attach streams from peers, keeps a registry of live tunnels keyed by peer ID, and lets the application dial "through" any attached peer with an ordinary http.RoundTripper.
admin
Package admin implements the holt hub's Admin gRPC service over a *hub.Registry: list live tunnels, force one closed, and — when a Blocker is supplied — ban/unban a peer id.
Package admin implements the holt hub's Admin gRPC service over a *hub.Registry: list live tunnels, force one closed, and — when a Blocker is supplied — ban/unban a peer id.
sqldir
Package sqldir is a SQL-backed hub.Directory: a shared peer-presence store so a fleet of hubs can each see who is attached where.
Package sqldir is a SQL-backed hub.Directory: a shared peer-presence store so a fleet of hubs can each see who is attached where.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL