client

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2026 License: AGPL-3.0 Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DisconnectNormal        = protocol.DisconnectNormal
	DisconnectBufferFull    = protocol.DisconnectBufferFull
	DisconnectDialFailed    = protocol.DisconnectDialFailed
	DisconnectTimeout       = protocol.DisconnectTimeout
	DisconnectLocalError    = protocol.DisconnectLocalError
	DisconnectShutdown      = protocol.DisconnectShutdown
	DisconnectSessionEnded  = protocol.DisconnectSessionEnded
	DisconnectPauseViolated = protocol.DisconnectPauseViolated
	DisconnectUnknown       = protocol.DisconnectUnknown
)
View Source
const (
	TransportTCP = protocol.TransportTCP
	TransportUDP = protocol.TransportUDP
)
View Source
const (
	DefaultHighWaterMark = 48
	DefaultLowWaterMark  = 16
	DefaultMaxBuffer     = 64
)

Flow control default thresholds.

Variables

View Source
var ErrNoRoute = errors.New("client: no route configured")

ErrNoRoute is returned by connect handlers to indicate that the request should fall back to the default configuration-based routing.

Functions

This section is empty.

Types

type AttestationConfig

type AttestationConfig struct {
	Command                    string            `yaml:"command"`
	Args                       []string          `yaml:"args"`
	Env                        map[string]string `yaml:"env"`
	TimeoutSeconds             int               `yaml:"timeoutSeconds"`
	CacheHandshakeSeconds      int               `yaml:"cacheHandshakeSeconds"`
	HMACSecret                 string            `yaml:"hmacSecret"`
	HMACSecretFile             string            `yaml:"hmacSecretFile"`
	TokenTTLSeconds            int               `yaml:"tokenTTLSeconds"`
	HandshakeMaxAgeSeconds     int               `yaml:"handshakeMaxAgeSeconds"`
	ReauthIntervalSeconds      int               `yaml:"reauthIntervalSeconds"`
	ReauthGraceSeconds         int               `yaml:"reauthGraceSeconds"`
	MaintenanceGraceCapSeconds int               `yaml:"maintenanceGraceCapSeconds"`
	AuthorizerStatusURI        string            `yaml:"authorizerStatusUri"`
	PolicyVersion              string            `yaml:"policyVersion"`
	OutboundAllowed            bool              `yaml:"outboundAllowed"`
	AllowedOutboundPorts       []int             `yaml:"allowedOutboundPorts"`
}

type AttestationOptions

type AttestationOptions struct {
	Command                    string
	Args                       []string
	Env                        map[string]string
	Timeout                    time.Duration
	CacheHandshake             time.Duration
	HMACSecret                 string
	HMACSecretFile             string
	TokenTTL                   time.Duration
	HandshakeMaxAgeSeconds     int
	ReauthIntervalSeconds      int
	ReauthGraceSeconds         int
	MaintenanceGraceCapSeconds int
	AuthorizerStatusURI        string
	PolicyVersion              string
	OutboundAllowed            bool
	AllowedOutboundPorts       []int
}

AttestationOptions contains configuration for generating attestation tokens.

type BackendConfig

type BackendConfig struct {
	Name             string              `yaml:"name"`
	Hostname         string              `yaml:"hostname"`
	Hostnames        []string            `yaml:"hostnames"`
	TCPPorts         []int               `yaml:"tcpPorts,omitempty"`
	UDPRoutes        []UDPRouteConfig    `yaml:"udpRoutes,omitempty"`
	NexusAddresses   []string            `yaml:"nexusAddresses"`
	Weight           int                 `yaml:"weight"`
	Attestation      AttestationConfig   `yaml:"attestation"`
	PortMappings     map[int]PortMapping `yaml:"portMappings"`
	HealthChecks     HealthCheckConfig   `yaml:"healthChecks"`
	FlowControl      FlowControlConfig   `yaml:"flowControl"`
	Socks5ListenAddr string              `yaml:"socks5ListenAddr,omitempty"`
}

func (BackendConfig) ToClientConfig

func (b BackendConfig) ToClientConfig(nexusAddr string) ClientBackendConfig

ToClientConfig converts a BackendConfig (YAML-parsed) into a ClientBackendConfig suitable for passing to client.New. The nexusAddr parameter selects which of the backend's NexusAddresses to use.

type CategorizedError

type CategorizedError struct {
	Err      error
	Category ErrorCategory
	Reason   string // Machine-readable reason code
}

type Client

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

Client manages the full lifecycle for one configured backend service.

func New

func New(cfg ClientBackendConfig, opts ...Option) (*Client, error)

New creates a new Client instance for a specific backend configuration.

func (*Client) Start

func (c *Client) Start(ctx context.Context)

Start initiates the client's connection loop.

func (*Client) Stats

func (c *Client) Stats() Stats

Stats returns a snapshot of current client statistics. This is a lightweight operation that reads atomic counters.

func (*Client) StatsDetailed

func (c *Client) StatsDetailed() Stats

StatsDetailed returns stats including per-connection details. This is a more expensive operation that iterates over all connections. Results are cached for 1 second to prevent excessive CPU usage.

func (*Client) Stop

func (c *Client) Stop()

Stop gracefully shuts down the client and its connections.

type ClientBackendConfig

type ClientBackendConfig struct {
	Name             string
	Hostnames        []string
	TCPPorts         []int
	UDPRoutes        []UDPRouteConfig
	NexusAddress     string
	Weight           int
	Attestation      AttestationOptions
	PortMappings     map[int]PortMapping
	HealthChecks     HealthCheckConfig
	FlowControl      FlowControlConfig
	Socks5ListenAddr string
}

type CommandTokenProvider

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

CommandTokenProvider implements TokenProvider by invoking an external command.

func NewCommandTokenProvider

func NewCommandTokenProvider(cfg AttestationOptions) (*CommandTokenProvider, error)

NewCommandTokenProvider returns a TokenProvider backed by an external command.

func (*CommandTokenProvider) IssueToken

func (c *CommandTokenProvider) IssueToken(ctx context.Context, req TokenRequest) (Token, error)

IssueToken invokes the configured command to retrieve an attestation token.

type Config

type Config struct {
	Backends []BackendConfig `yaml:"backends"`
}

func LoadConfig

func LoadConfig(path string) (*Config, error)

type ConnState

type ConnState uint32
const (
	ConnStatePending  ConnState = iota // Dial in progress
	ConnStateActive                    // Connected, relaying data
	ConnStateDraining                  // Graceful shutdown, no new data
	ConnStateClosed                    // Terminal state
)

type ConnectHandler

type ConnectHandler func(ctx context.Context, req ConnectRequest) (net.Conn, error)

ConnectHandler is invoked whenever the proxy asks us to establish a new local connection. Returning ErrNoRoute will defer to the default port-mapping behaviour. Any other error is treated as fatal for that request.

type ConnectRequest

type ConnectRequest struct {
	BackendName      string
	ClientID         uuid.UUID
	Hostname         string
	OriginalHostname string
	Port             int
	ClientIP         string
	IsTLS            bool
	Transport        Transport // "tcp" or "udp" (defaults to "tcp" if empty)
}

ConnectRequest provides context about a client connection request coming from the Nexus proxy.

type ConnectionStats

type ConnectionStats struct {
	ClientID     string
	Hostname     string
	State        ConnState
	BytesIn      int64
	BytesOut     int64
	BufferLevel  int
	Paused       bool
	ConnectedAt  time.Time
	LastActivity time.Time
	IsUDP        bool
}

ConnectionStats provides per-connection statistics.

type DisconnectReason

type DisconnectReason = protocol.DisconnectReason

DisconnectReason is an alias for protocol.DisconnectReason so library consumers can reference disconnect reasons without importing protocol.

type ErrorCategory

type ErrorCategory int
const (
	ErrorTransient ErrorCategory = iota // Retry with backoff
	ErrorPermanent                      // Don't retry, surface to user
	ErrorRateLimit                      // Retry with longer backoff
)

type Event

type Event struct {
	Type      EventType
	Timestamp time.Time

	// Connection context (if applicable)
	ClientID string
	Hostname string

	// Error context (if applicable)
	Error  error
	Reason string
}

Event represents a client lifecycle event.

type EventHandler

type EventHandler func(Event)

EventHandler is a callback function for client events.

type EventType

type EventType int

EventType represents the type of client event.

const (
	EventConnected EventType = iota
	EventDisconnected
	EventConnectionOpened
	EventConnectionClosed
	EventPaused
	EventResumed
	EventError
	EventReauthStarted
	EventReauthCompleted
)

func (EventType) String

func (e EventType) String() string

type FlowControlConfig

type FlowControlConfig struct {
	// HighWaterMark is the buffer level at which we send pause_stream (default: 48)
	HighWaterMark int `yaml:"highWaterMark"`
	// LowWaterMark is the buffer level at which we send resume_stream (default: 16)
	LowWaterMark int `yaml:"lowWaterMark"`
	// MaxBuffer is the hard limit on buffered messages before closing connection (default: 64)
	MaxBuffer int `yaml:"maxBuffer"`
}

FlowControlConfig configures per-connection flow control parameters. These control when pause/resume messages are sent to Nexus.

type HMACTokenProvider

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

HMACTokenProvider produces tokens signed with a shared secret.

func NewHMACTokenProvider

func NewHMACTokenProvider(opts AttestationOptions, backendName string, hostnames []string, tcpPorts []int, udpRoutes []UDPRouteConfig, weight int) (*HMACTokenProvider, error)

NewHMACTokenProvider returns a TokenProvider that signs JWTs locally using HS256.

func (*HMACTokenProvider) IssueToken

func (h *HMACTokenProvider) IssueToken(ctx context.Context, req TokenRequest) (Token, error)

IssueToken signs a JWT that encodes the attestation claims expected by Nexus.

type HealthCheckConfig

type HealthCheckConfig struct {
	Enabled           bool `yaml:"enabled"`
	InactivityTimeout int  `yaml:"inactivityTimeout"`
	PongTimeout       int  `yaml:"pongTimeout"`
}

type Option

type Option func(*Client)

Option mutates a Client during construction.

func WithConnectHandler

func WithConnectHandler(handler ConnectHandler) Option

WithConnectHandler registers a custom connect handler. The handler is invoked before the default port-mapping logic. Returning ErrNoRoute (or a nil connection) will fall back to the default handler.

func WithEventHandler

func WithEventHandler(handler EventHandler) Option

WithEventHandler registers a callback for client lifecycle events. Events are delivered asynchronously in order via a dedicated goroutine. The handler should not block for extended periods as this can cause events to be dropped. Passing nil disables event delivery.

func WithTokenProvider

func WithTokenProvider(provider TokenProvider) Option

WithTokenProvider installs a TokenProvider that is consulted for handshake, attestation, and re-auth tokens. Passing nil restores the default provider.

type PortMapping

type PortMapping struct {
	Default string            `yaml:"default"`
	Hosts   map[string]string `yaml:"hosts"`
	// contains filtered or unexported fields
}

func (PortMapping) Resolve

func (pm PortMapping) Resolve(hostname string) (string, bool)

type Stats

type Stats struct {
	// Connection metrics
	ActiveConnections  int64
	TotalConnections   int64
	PendingConnections int64

	// Data transfer
	BytesSentTotal        int64
	BytesReceivedTotal    int64
	MessagesSentTotal     int64
	MessagesReceivedTotal int64

	// Queue metrics
	ControlQueueDepth int
	DataQueueDepth    int // Number of connections with pending data

	// Error metrics
	DroppedConnections int64
	TransientErrors    int64
	PermanentErrors    int64
	RateLimitHits      int64
	EnqueueTimeouts    int64

	// Flow control
	PausedConnections int64
	PauseViolations   int64

	// Event metrics
	DroppedEvents int64

	// UDP metrics
	UDPDroppedPackets int64

	// Session metrics
	SessionUptime   time.Duration
	LastUpdated     time.Time
	ReconnectCount  int64
	LastConnectedAt time.Time

	// Per-connection stats (optional, can be expensive)
	ConnectionStats map[string]ConnectionStats
}

Stats provides a snapshot of client statistics.

type Token

type Token struct {
	Value  string
	Expiry time.Time
}

Token encapsulates the token value and an optional expiry.

type TokenProvider

type TokenProvider interface {
	IssueToken(ctx context.Context, req TokenRequest) (Token, error)
}

TokenProvider issues attestation tokens for a given request.

type TokenRequest

type TokenRequest struct {
	Stage                TokenStage
	SessionNonce         string
	BackendName          string
	Hostnames            []string
	TCPPorts             []int
	UDPRoutes            []UDPRouteConfig
	Weight               int
	OutboundAllowed      bool
	AllowedOutboundPorts []int
}

TokenRequest conveys the contextual information for issuing a token. Note: TCPPorts and UDPRoutes are used by CommandTokenProvider (passed as env vars) but HMACTokenProvider uses its own stored config values for these fields.

type TokenStage

type TokenStage string

TokenStage identifies which step of the attestation workflow is requesting a token.

const (
	StageHandshake TokenStage = "handshake"
	StageAttest    TokenStage = "attest"
	StageReauth    TokenStage = "reauth"
)

type Transport

type Transport = protocol.Transport

Transport is an alias for protocol.Transport so library consumers can use client.TransportTCP without importing the protocol package separately.

type UDPRouteConfig

type UDPRouteConfig struct {
	Port                   int  `yaml:"port"`
	FlowIdleTimeoutSeconds *int `yaml:"flowIdleTimeoutSeconds,omitempty"`
}

UDPRouteConfig defines a UDP port claim with optional flow idle timeout. FlowIdleTimeoutSeconds specifies how long the server waits before cleaning up an idle UDP flow. If nil, the server uses its default timeout. If set to 0, behavior depends on server implementation (typically uses default or no timeout).

func CopyUDPRoutes

func CopyUDPRoutes(in []UDPRouteConfig) []UDPRouteConfig

CopyUDPRoutes creates a deep copy of UDPRouteConfig slice.

Jump to

Keyboard shortcuts

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