Documentation
¶
Overview ¶
Package bifrost provides the embeddable runtime for Bifrost self-hosted TCP tunnels.
A Bifrost deployment has two roles. A server runs on a reachable relay and accepts connector sessions. A client runs near a private TCP service and dials the server with an outbound TLS connection. Once a connector is admitted, the server can open streams to the private target through the tunnel.
The package is intentionally focused on the tunnel data path. It does not perform HTTP routing, DNS management, browser-facing TLS termination, account management, or application authentication. Those concerns belong to the embedding product, reverse proxy, or target service.
Most standalone deployments use the bifrost-server and bifrost-client binaries. Use this package when embedding the tunnel runtime into another Go program, Caddy module, control plane, or test harness.
Index ¶
- Constants
- func Copy(ctx context.Context, a net.Conn, b net.Conn, opts CopyOptions)
- func RunClient(ctx context.Context, cfg ClientConfig, opts ClientOptions) error
- func RunServer(ctx context.Context, cfg ServerConfig, opts ServerOptions) error
- type AcceptDecision
- type AcceptProvider
- type AcceptRequest
- type ClientConfig
- type ClientOptions
- type ConnectionPolicy
- type CopyOptions
- type Direction
- type Guardrails
- type Listener
- type NoopObserver
- type NoopStreamObserver
- type Observer
- type PassiveLatencyObservation
- type PassiveLatencyObserver
- type PassiveLatencySnapshotter
- type PassiveLatencyState
- type PassiveLatencyStore
- type PlanLimits
- type ProxyStreamOptions
- type Runtime
- type Server
- func (s *Server) OpenStream(ctx context.Context, endpointKey string) (net.Conn, error)
- func (s *Server) PassiveLatencyObservation(endpointKey string, now time.Time) PassiveLatencyObservation
- func (s *Server) PassiveLatencySnapshot(now time.Time) []PassiveLatencyObservation
- func (s *Server) ProxyStream(ctx context.Context, endpointKey string, ingressConn net.Conn) error
- func (s *Server) ProxyStreamWithOptions(ctx context.Context, endpointKey string, ingressConn net.Conn, ...) error
- func (s *Server) Run(ctx context.Context) error
- type ServerConfig
- type ServerOptions
- type StaticClient
- type StreamObserver
Constants ¶
const ( // TokenHeader is the normalized hello header name that carries the connector // token used by static admission providers. TokenHeader = acceptor.TokenHeader // ALPN is the TLS application protocol negotiated by Bifrost tunnel // connections. ALPN = protocol.ALPN // PolicyRejectIfExists rejects a new connector session when the endpoint key // already has an active session. PolicyRejectIfExists = acceptor.PolicyRejectIfExists // PolicyReplaceExisting closes an existing session and lets the new // connector session take ownership of the endpoint key. PolicyReplaceExisting = acceptor.PolicyReplaceExisting // PolicyAllowParallel allows multiple active connector sessions for the same // endpoint key up to ConnectionPolicy.MaxParallel. PolicyAllowParallel = acceptor.PolicyAllowParallel )
const ( // DirectionIngressToEndpoint counts bytes flowing from the server-side // ingress connection toward the private endpoint. DirectionIngressToEndpoint = metrics.DirectionIngressToEndpoint // DirectionEndpointToIngress counts bytes flowing from the private endpoint // back to the server-side ingress connection. DirectionEndpointToIngress = metrics.DirectionEndpointToIngress )
Variables ¶
This section is empty.
Functions ¶
func Copy ¶
Copy proxies bytes between a and b until one side closes, ctx is canceled, or the idle timeout is reached. Copy closes both connections before returning.
func RunClient ¶
func RunClient(ctx context.Context, cfg ClientConfig, opts ClientOptions) error
RunClient runs a connector until ctx is canceled. The connector maintains an outbound session to ServerURL and forwards each accepted stream to TargetAddress, unless StreamHandler is set in opts.
func RunServer ¶
func RunServer(ctx context.Context, cfg ServerConfig, opts ServerOptions) error
RunServer constructs and runs a Server until ctx is canceled or the server returns an error.
Types ¶
type AcceptDecision ¶
AcceptDecision is the provider result for a connector session.
type AcceptProvider ¶
AcceptProvider decides whether an inbound connector session should be accepted and, if accepted, which endpoint, limits, and ownership policy it receives.
func NewStaticAcceptProvider ¶
func NewStaticAcceptProvider(clients []StaticClient) (AcceptProvider, error)
NewStaticAcceptProvider builds an AcceptProvider from static token-backed clients. The provider rejects missing, unknown, and duplicate tokens.
type AcceptRequest ¶
AcceptRequest describes a connector session after TLS and protocol hello validation. Header names are normalized before the request reaches a provider.
type ClientConfig ¶
type ClientConfig struct {
// ServerURL is the relay address in host:port form.
ServerURL string
// Headers contains additional hello headers sent to the relay. TokenHeader is
// managed by the CLI configuration path and should not be duplicated here.
Headers map[string]string
// TargetAddress is the private TCP target reached for every accepted stream.
TargetAddress string
// TLSCAFile optionally points at a CA bundle used to verify the relay
// certificate. When empty, the system trust store is used.
TLSCAFile string
// TLSServerName overrides the TLS server name used to verify the relay
// certificate.
TLSServerName string
// TLSInsecureSkipVerify disables relay certificate verification. It is
// development-only.
TLSInsecureSkipVerify bool
// AdminListen enables the optional admin HTTP listener for readiness and
// metrics when non-empty.
AdminListen string
}
ClientConfig configures a Bifrost connector runtime.
type ClientOptions ¶
type ClientOptions struct {
// Logger receives structured runtime logs. A nil logger uses the internal
// default.
Logger *slog.Logger
// Observer receives lifecycle and byte-count events. It may be nil.
Observer Observer
// StreamHandler overrides the default TCP target dialer. Embedders can use it
// to handle accepted streams in-process instead of dialing TargetAddress.
StreamHandler func(context.Context, net.Conn)
// AdminReady is called with the admin listener address when AdminListen is
// enabled and ready.
AdminReady func(net.Addr)
}
ClientOptions supplies dependencies and callbacks for an embedded connector.
type ConnectionPolicy ¶
type ConnectionPolicy = acceptor.ConnectionPolicy
ConnectionPolicy controls how multiple sessions for the same endpoint key are handled.
type CopyOptions ¶
type CopyOptions struct {
// BufferSize sets the copy buffer size. A zero or invalid value uses the
// runtime default.
BufferSize int
// IdleTimeout closes the proxy after both directions have been idle for the
// configured duration. Zero disables idle timeout handling.
IdleTimeout time.Duration
// OnBytes is called with the copy direction and byte count for each successful
// copy chunk.
OnBytes func(direction string, n int64)
}
CopyOptions tunes Copy.
type Direction ¶ added in v0.3.0
Direction describes the side of a proxied stream that produced bytes.
type Guardrails ¶
type Guardrails struct {
// MaxSessions limits active connector sessions on the server.
MaxSessions int
// MaxStreamsPerSession is the upper bound for a session's concurrent stream
// limit.
MaxStreamsPerSession int
// MaxBandwidthBPSPerSession is the upper bound for a session's byte-per-second
// bandwidth limit.
MaxBandwidthBPSPerSession int64
// MinStreamIdleTimeout is the shortest idle timeout a provider decision may
// request.
MinStreamIdleTimeout time.Duration
// MaxStreamIdleTimeout is the longest idle timeout a provider decision may
// request.
MaxStreamIdleTimeout time.Duration
// MaxHeaders limits the number of hello headers accepted from a connector.
MaxHeaders int
// MaxHeaderBytes limits the combined size of hello header names and values.
MaxHeaderBytes int
}
Guardrails sets server-wide ceilings for sessions and per-session decisions.
Zero fields use the runtime defaults. Guardrails are enforced after provider defaults are applied, so a custom AcceptProvider cannot grant limits above these ceilings.
type Listener ¶ added in v0.3.1
Listener describes a server-side listener specification. Use ListenerSpec to build values without depending on the internal listener package path.
func ListenerSpec ¶
ListenerSpec returns a listener specification for the supplied network and address. Supported networks are "unix" and "tcp"; unknown networks are passed through as a listener type with address set.
type NoopObserver ¶ added in v0.3.0
NoopObserver is an Observer implementation that ignores every event.
type NoopStreamObserver ¶ added in v0.3.0
type NoopStreamObserver = metrics.NoopStream
NoopStreamObserver is a StreamObserver implementation that ignores every event.
type Observer ¶ added in v0.3.0
Observer receives tunnel lifecycle and byte-count events.
func NewMultiObserver ¶ added in v0.3.0
NewMultiObserver returns one Observer that fans out events to every non-nil observer in order. It returns a no-op observer when no observers are supplied.
type PassiveLatencyObservation ¶ added in v0.4.0
type PassiveLatencyObservation = latency.Observation
PassiveLatencyObservation is the latest passive latency state for one endpoint. It carries only endpoint key, latency milliseconds, observation time, and controlled state.
type PassiveLatencyObserver ¶ added in v0.4.0
PassiveLatencyObserver receives endpoint-keyed passive session latency observations derived from Bifrost session/mux control traffic.
type PassiveLatencySnapshotter ¶ added in v0.4.0
type PassiveLatencySnapshotter = latency.Snapshotter
PassiveLatencySnapshotter exposes endpoint-keyed passive latency state.
type PassiveLatencyState ¶ added in v0.4.0
PassiveLatencyState is the controlled state for a passive latency observation.
const ( // PassiveLatencyOK means a fresh passive latency observation is available. PassiveLatencyOK PassiveLatencyState = latency.StateOK // PassiveLatencyUnknown means no passive observation is available for the // endpoint. PassiveLatencyUnknown PassiveLatencyState = latency.StateUnknown // PassiveLatencyStale means the latest passive observation is older than the // store's freshness window. PassiveLatencyStale PassiveLatencyState = latency.StateStale )
type PassiveLatencyStore ¶ added in v0.4.0
PassiveLatencyStore records latest passive latency observations by endpoint.
func NewPassiveLatencyStore ¶ added in v0.4.0
func NewPassiveLatencyStore(staleAfter time.Duration) *PassiveLatencyStore
NewPassiveLatencyStore returns an endpoint-keyed passive latency store. A non-positive staleAfter keeps observations in ok state until replaced.
type PlanLimits ¶
type PlanLimits = limits.PlanLimits
PlanLimits contains per-session stream, bandwidth, and idle-time limits.
type ProxyStreamOptions ¶ added in v0.4.1
type ProxyStreamOptions struct {
// Observer receives byte-count and end events for this proxied stream in
// addition to the server's configured endpoint observer.
Observer StreamObserver
}
ProxyStreamOptions configures one server-side proxied stream.
type Runtime ¶
type Runtime struct {
// HandshakeTimeout bounds TLS and Bifrost hello negotiation work.
HandshakeTimeout time.Duration
// StreamCopyBufferBytes sets the copy buffer size used for proxied streams.
StreamCopyBufferBytes int
// TunnelKeepAliveInterval is the yamux keepalive ping interval.
TunnelKeepAliveInterval time.Duration
// TunnelKeepAliveTimeout is the maximum wait for a keepalive response before
// closing the tunnel session.
TunnelKeepAliveTimeout time.Duration
}
Runtime contains low-level tunnel runtime tuning.
Zero fields use the runtime defaults.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is an embedded Bifrost relay runtime.
func NewServer ¶
func NewServer(cfg ServerConfig, opts ServerOptions) (*Server, error)
NewServer validates the server configuration and returns a relay runtime ready to be started with Server.Run.
func (*Server) OpenStream ¶
OpenStream opens a new stream to an active endpoint and returns it as a net.Conn. The endpoint must have an admitted connector session.
func (*Server) PassiveLatencyObservation ¶ added in v0.4.0
func (s *Server) PassiveLatencyObservation(endpointKey string, now time.Time) PassiveLatencyObservation
PassiveLatencyObservation returns the latest passive latency state for endpointKey. Unknown is returned when no observation exists.
func (*Server) PassiveLatencySnapshot ¶ added in v0.4.0
func (s *Server) PassiveLatencySnapshot(now time.Time) []PassiveLatencyObservation
PassiveLatencySnapshot returns latest passive latency state for every observed endpoint.
func (*Server) ProxyStream ¶
ProxyStream attaches ingressConn to a new stream for endpointKey and copies bytes in both directions until either side closes or ctx is canceled.
func (*Server) ProxyStreamWithOptions ¶ added in v0.4.1
func (s *Server) ProxyStreamWithOptions(ctx context.Context, endpointKey string, ingressConn net.Conn, opts ProxyStreamOptions) error
ProxyStreamWithOptions attaches ingressConn to a new stream for endpointKey and copies bytes in both directions until either side closes or ctx is canceled.
type ServerConfig ¶
type ServerConfig struct {
// Listen is the address used by the server when it creates its own connector
// listener. It defaults to the internal server default when empty.
Listen string
// TLSCertFile is the certificate file presented to connector clients when
// TLSConfig is nil.
TLSCertFile string
// TLSKeyFile is the private key file for TLSCertFile when TLSConfig is nil.
TLSKeyFile string
// TLSConfig is an optional externally managed TLS configuration. Embedders
// should include ALPN in NextProtos or use a TLS policy that negotiates ALPN.
TLSConfig *tls.Config
// Clients defines token-backed static connector sessions. It is ignored when
// ServerOptions.AcceptProvider is set.
Clients []StaticClient
// Guardrails sets server-wide ceilings enforced after every admission
// decision.
Guardrails Guardrails
// Runtime tunes handshake, copy buffer, and tunnel keepalive behavior.
Runtime Runtime
// AdminListen enables the optional admin HTTP listener for readiness and
// Prometheus-style metrics when non-empty.
AdminListen string
}
ServerConfig configures a Bifrost relay runtime.
TLSConfig can be supplied by embedders that already manage certificates. When TLSConfig is nil, TLSCertFile and TLSKeyFile are used. Clients configures the built-in static admission provider unless ServerOptions.AcceptProvider is set.
type ServerOptions ¶
type ServerOptions struct {
// Logger receives structured runtime logs. A nil logger uses the internal
// default.
Logger *slog.Logger
// AcceptProvider overrides ServerConfig.Clients with custom admission logic.
AcceptProvider AcceptProvider
// Observer receives lifecycle and byte-count events. It may be nil.
Observer Observer
// PassiveLatencyObserver receives endpoint-keyed passive latency
// observations. It may be nil; the Server still keeps its own latest
// observation snapshot.
PassiveLatencyObserver PassiveLatencyObserver
// Listener supplies an already-created connector listener. When set, Listen in
// ServerConfig is informational and the server does not create a listener.
Listener net.Listener
// Ready is called with the connector listener address after the server is
// accepting connector sessions.
Ready func(net.Addr)
// AdminReady is called with the admin listener address when AdminListen is
// enabled and ready.
AdminReady func(net.Addr)
}
ServerOptions supplies dependencies and callbacks for an embedded server.
type StaticClient ¶
type StaticClient = acceptor.StaticClient
StaticClient describes one token-backed connector accepted by NewStaticAcceptProvider.
type StreamObserver ¶ added in v0.3.0
type StreamObserver = metrics.StreamObserver
StreamObserver receives byte-count and end events for one proxied stream.
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
bifrost-client
command
|
|
|
bifrost-server
command
|
|
|
bifrostctl
command
|
|
|
internal
|
|
|
acceptor
Package acceptor contains Bifrost connector admission interfaces and the static token-backed provider used by standalone deployments.
|
Package acceptor contains Bifrost connector admission interfaces and the static token-backed provider used by standalone deployments. |
|
latency
Package latency stores endpoint-keyed passive session latency observations.
|
Package latency stores endpoint-keyed passive session latency observations. |
|
limits
Package limits defines the per-session limits, server guardrails, and small runtime helpers used by the Bifrost tunnel data path.
|
Package limits defines the per-session limits, server guardrails, and small runtime helpers used by the Bifrost tunnel data path. |
|
metrics
Package metrics defines Bifrost observer interfaces and the in-memory metrics implementation used by the standalone admin endpoint.
|
Package metrics defines Bifrost observer interfaces and the in-memory metrics implementation used by the standalone admin endpoint. |