Introducing a new way to review your PRs.

Read the announcement

hcavarsan / kftray

kubectl port-forward manager and reverse tunnel (ngrok-like) for exposing local services publicly, with TLS termination, HTTP traffic inspection, UDP forwarding, multi-hop proxy routing through k8s clusters, stateful config via filesystem or git - GUI and TUI available

View on GitHub

19 documents · Updated Nov 23, 2026

docs / connection-forwarding

Connection forwarding

Connection forwarding turns a saved connection configuration into a managed local network connection. It selects a path for Kubernetes, SSH, or endpoint exposure, owns the local and remote resources, and reports one running state that the desktop and terminal interfaces can start, inspect, and stop.

Forwarding model

Each configuration describes a local address and port, a protocol, and a remote destination. The forwarding subsystem uses that description to choose direct Kubernetes forwarding, a relay-backed path, an SSH route, or endpoint exposure.

Connection typeLocal resultRemote relationship
Kubernetes service or podTCP or UDP listenerConnects to the selected service or pod in the configured cluster
Kubernetes relay-backed connectionTCP or UDP listenerUses a managed relay when the protocol or workload needs one
SSH forwardingTCP listenerOpens channels through a shared SSH session to the remote address
Endpoint exposureConfigured local service endpointCreates cluster exposure resources and a reverse tunnel to the local service

The Config model is the shared contract for these choices. Its workload type, protocol, local endpoint, remote destination, SSH provider, and exposure settings describe the desired connection. Runtime listeners and tunnel objects remain owned by the forwarding lifecycle. References: crates/…/config_model.rs• L78-160, crates/…/config_model.rs• L202-225

Forwarding paths

The dispatcher gives every connection the same start, state, and stop experience. It then hands the connection to the path that understands its destination.

This diagram shows how one saved configuration becomes a managed local connection.

flowchart TD
    A[Saved connection configuration] --> B{Workload type}
    B -->|service or pod| C[Kubernetes listener]
    B -->|UDP or proxy| D[Kubernetes relay listener]
    B -->|ssh-port-forward| E[SSH route and TCP listener]
    B -->|expose| F[Cluster exposure and reverse tunnel]
    C --> G[Managed running state]
    D --> G
    E --> G
    F --> G
    G --> H[Local client traffic]

The Kubernetes path selects a service, pod, or relay target. Its cluster API connection can use an HTTP or SOCKS5 proxy when the cluster is reached through another network. The SSH path validates a provider and checks the remote destination before it opens the local listener. The exposure path first removes resources left by an earlier attempt, then creates an owned relay, service, and optional public ingress before it starts a reverse tunnel. See Kubernetes port forwarding, SSH forwarding, and Endpoint exposure and TLS for path-specific behavior. References: crates/…/start.rs• L1127-1240, crates/…/proxy.rs• L18-61, crates/…/mod.rs• L164-236, crates/…/mod.rs• L24-35, crates/…/mod.rs• L93-333, crates/…/kubernetes.rs• L70-282

Local endpoint

The local endpoint is the stable surface that applications use after a forward starts. It can use a fixed port or let the operating system choose one, and it can bind to the default loopback address or a configured local address.

Before remote work begins, the subsystem claims the local address and checks the requested port. Custom loopback addresses and host aliases have tracked ownership, so one connection cannot remove resources still used by another. References: crates/…/local_port.rs• L31-130, crates/…/start.rs• L398-484, crates/…/start.rs• L903-1053

Managed process

The managed process is the ownership record for one active connection. It groups the listener task, connection workers, cancellation signal, optional tunnel client, and the configuration snapshot needed for cleanup.

The process registry lets status and stop operations find live work by configuration ID. A listener or tunnel that ends unexpectedly causes the owning forward to stop instead of leaving a false running state. SSH listener failure is handled even when its pooled session remains alive. Endpoint exposure also watches the reverse tunnel and starts cleanup when that tunnel ends. References: crates/…/port_forward.rs• L35-48, crates/…/port_forward.rs• L223-245, crates/…/mod.rs• L348-380, crates/…/mod.rs• L241-265

Start lifecycle

Starting a connection is a guarded sequence that claims local resources, establishes the remote path, starts the listener, and only then publishes the running state. This order prevents a partial start from appearing as a usable connection.

When the subsystem processes a start request, it follows this sequence:

  1. It registers the configuration as starting and takes the lifecycle locks for that configuration.
  2. It checks that the configuration still exists and that another process does not own an active forward.
  3. It claims the local address and any host alias.
  4. It establishes the selected remote path. SSH startup also checks that the configured destination responds before it accepts the forward.
  5. It binds the local listener and prepares any TLS or tunnel work. Endpoint exposure waits for its relay and reverse tunnel to become ready.
  6. It records the start-time snapshot and running state, then transfers local-resource ownership to the managed process.
  7. It returns the actual local port and connection result to the caller.

Cancellation and setup errors roll back resources that the start has claimed. Exposure creation keeps each cluster create operation intact when its result is unknown, tracks resources by ownership and object identity, and rolls back only after it can classify the outcome. References: crates/…/start.rs• L903-1120, crates/…/start.rs• L1123-1240, crates/…/mod.rs• L164-321, crates/…/mod.rs• L93-318, crates/…/kubernetes.rs• L70-282, crates/…/kubernetes.rs• L354-404

Running state

Running state links a local process to its configuration. It tells the user interface whether the connection is active and carries retry or error information when the remote path is reconnecting or has failed.

The state also stores the configuration snapshot used at start time. This protects cleanup when a user edits or deletes the configuration while the connection still owns a port, alias, or cluster resource. SSH session changes are reflected as retrying or failed state without making the listener the source of truth for session health. References: crates/…/config_state_model.rs• L6-36, crates/…/config_state.rs• L234-378, crates/…/mod.rs• L383-416

Stop lifecycle

Stopping cancels startup or runtime tasks first, removes the managed process from the local registry, and then releases the resources recorded in its startup snapshot. The same stop path handles Kubernetes forwarding, SSH forwarding, and endpoint exposure.

Cleanup has two responsibilities:

  • Local cleanup releases listeners, custom loopback addresses, and host-file entries.
  • Remote cleanup removes relays or exposure resources created by the configuration.

The subsystem keeps an obligation when a release is incomplete. It persists cluster obligations across restarts and retries them during stop-all or reconciliation. A remote resource is not treated as gone only because a delete request was accepted. Exposure cleanup checks the deployment, service, and ingress until they disappear, and it keeps public-ingress history when the configuration later changes to private. References: crates/…/stop.rs• L545-605, crates/…/stop.rs• L1201-1287, crates/…/stop.rs• L1760-1843, crates/…/mod.rs• L38-77, crates/…/kubernetes.rs• L1286-1403, crates/…/kubernetes.rs• L1513-1561

Process ownership

Process ownership prevents one kftray process from stopping a forward owned by another process. The registry and the persisted state use the start-time owner and snapshot to distinguish a live forward from stale state.

Lifecycle locks cover the gap between checking a configuration and registering its listener. Cleanup uses the recorded destination and local resources rather than the current configuration row, so a later edit cannot redirect cleanup to another cluster or alias. Exposure resources use an installation identity and configuration label, then use UID checks during deletion so a replacement with the same name is not removed. References: crates/…/start.rs• L1333-1415, crates/…/stop.rs• L487-542, crates/…/stop.rs• L2215-2385, crates/…/kubernetes.rs• L285-315, crates/…/kubernetes.rs• L433-525

Privilege boundary

Privilege-sensitive work is limited to local network setup. The subsystem can ask the helper service to add loopback aliases, bind denied loopback ports, and update host-file entries. Ordinary local listeners and endpoint exposure through Kubernetes do not require elevation.

The desktop can run a read-only preflight before a batch start. At runtime, the helper is used when a local bind or address setup needs privilege. Cleanup reports an unavailable privilege path instead of retrying it forever, while other cleanup failures remain tracked for a later stop. References: crates/…/privileges.rs• L29-83, crates/…/privileged_bind.rs• L25-87, crates/…/start.rs• L692-854, crates/…/stop.rs• L1326-1499

Traffic handling

After a listener accepts a client, the forwarding path carries bytes in both directions until the client, upstream, or cancellation signal ends the connection. TCP forwarding can inspect HTTP traffic for logs on supported workload types, but it must stop HTTP handling when the connection changes to an opaque protocol such as WebSocket.

HTTP logging waits for complete response bodies, including split or chunked responses. It limits buffered request and response data so an opaque stream cannot grow the log buffer without bound. After a valid upgrade response, the forward preserves the handshake and passes later frame bytes without treating them as HTTP log data. References: crates/…/tcp_forwarder.rs• L26-29, crates/…/tcp_forwarder.rs• L324-481, crates/…/tcp_forwarder.rs• L600-855, crates/…/tests.rs• L527-557

Failure handling

Forwarding errors are handled according to whether the affected path can recover. Remote reachability failures can produce retry state, while invalid configuration, failed setup, or a dead listener stops the affected connection and starts cleanup.

The start API returns one result per configuration. A mixed batch keeps successful local ports while reporting failed configurations separately. A stop or shutdown reports incomplete cleanup instead of claiming that a listener or remote resource is gone when it may still exist. Exposure create timeouts and transport failures remain uncertain until ownership can be checked or a later reconciliation pass resolves them. References: crates/…/port_forward_error.rs• L4-35, crates/…/port_forward_error.rs• L173-190, crates/…/start.rs• L1418-1493, crates/…/stop.rs• L2137-2158, crates/…/kubernetes.rs• L346-404

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep workload classification aligned with the dispatcher so each new type selects matching start and stop behavior.
  • Keep the start snapshot and pending-cleanup identity aligned with every local or remote resource a path can create.
  • Keep privilege preflight rules aligned with local address, host-file, and bind operations.
  • Keep SSH listener ownership checks aligned with session state so a dead listener cannot leave a running forward.
  • Keep HTTP log mode detection aligned with protocol upgrades so raw WebSocket or TCP data is not recorded as HTTP.
  • Keep deferred host-file writes aligned with startup claims so an abandoned start cannot remove resources from a newer start.
  • Keep Kubernetes proxy scheme handling aligned across TLS and non-TLS client paths so a proxy does not work for only one cluster connection mode.
  • Keep proxy credentials scoped to the proxy protocol so credentials are not sent in a plain request to an HTTPS proxy.
  • Keep HTTP log size limits and stream-mode transitions aligned so large or opaque responses do not consume unbounded memory.
  • Keep exposure ownership labels, cleanup selectors, and UID checks aligned so one installation cannot delete another installation's resources.
  • Keep exposure history keyed by the resolved cluster and namespace so a public ingress remains discoverable after a configuration changes or a cluster context moves.
  • Keep exposure cancellation boundaries aligned with uncertain create requests so an abandoned Kubernetes request keeps its cleanup obligation.

Important failure modes

TriggerConsequenceGuard
The requested local port is already in useThe forward does not contact the remote targetLocal bind checks run before listener setup
Startup is cancelled after local resources are claimedA loopback alias or host entry can remainStartup records cleanup obligations and rollback or reconciliation retries them
A running configuration is edited before stopCleanup can target the wrong address or clusterThe process registry and state keep the start-time snapshot
SSH destination validation cannot reach the targetThe local listener is not publishedStartup checks the destination before registration
The SSH listener fails while the session remains connectedThe connection can appear healthy if only session state is watchedListener failure schedules cleanup for the owning task
The exposure tunnel never becomes readyThe configuration cannot report a usable forwardStartup waits for readiness and rolls back created resources
An exposure create request times out or loses its responseA cluster resource may exist without a returned nameThe attempt stays uncertain and uses owned, UID-scoped cleanup or later reconciliation
A public exposure changes to private before cleanupA public ingress can continue to route traffic to the new tunnelDestination-scoped ingress history keeps ingress cleanup enabled
Exposure resources share a name with a replacementCleanup can remove the replacementUID preconditions limit deletion to the recorded object
The open-stream budget is fullA new local connection is closed even when the upstream is healthyStream admission treats back-pressure separately from upstream failure
A cluster delete request is accepted but resources remainRemote resources may remain active or replaceableDeletion waits for disappearance and keeps the cleanup obligation on timeout
Privileged loopback cleanup has no helper or elevationThe alias can remain on the hostCleanup reports privilege unavailability separately from retryable failures
A Kubernetes proxy uses an unsupported schemeThe cluster client cannot start through the proxyClient creation rejects schemes other than HTTP, HTTPS, SOCKS5, and SOCKS5H
Proxy credentials contain escaped charactersThe proxy receives the wrong login or passwordProxy user information is decoded before HTTP or SOCKS5 authentication
HTTP logging sees an incomplete, oversized, or opaque responseLogs can be incomplete, or raw stream data can be misread as HTTPFraming checks, size bounds, and WebSocket mode stop unsafe buffering

Key files

FileWhy to read it
crates/…/config_model.rsDefines the configuration contract and forwarding choices.
crates/…/start.rsShows common startup, local resource claims, dispatch, cancellation, and registration.
crates/…/stop.rsShows ownership checks, cleanup, stop-all behavior, and reconciliation.
crates/…/listener.rsShows local TCP and UDP listener ownership and shutdown.
crates/…/tcp_forwarder.rsShows byte forwarding and the boundary between HTTP logging and upgraded streams.
crates/…/proxy.rsShows how Kubernetes clients reach clusters through supported proxy types.
crates/…/port_forward.rsDefines the managed runtime process.
crates/…/mod.rsShows SSH validation, pooled session use, listener lifecycle, and session state.
crates/…/mod.rsShows endpoint resource creation, tunnel readiness, cancellation, and cleanup.
crates/…/kubernetes.rsShows exposure resource ownership, relay readiness, bounded creation, and deletion verification.
crates/…/websocket_client.rsShows exposure reconnects and HTTP or raw tunnel traffic.
crates/…/privileges.rsExplains read-only privilege checks before start.
crates/…/privileged_bind.rsShows the helper boundary for denied local binds.
crates/…/portforward.rsShows the desktop command boundary and exit-time cleanup.