proxy

package
v1.0.0-beta.5 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AuditMiddleware

func AuditMiddleware(pub audit.Publisher) func(http.Handler) http.Handler

func EventFromContext

func EventFromContext(ctx context.Context) (*audit.AuditEvent, bool)

func JWTClaimsFromContext

func JWTClaimsFromContext(ctx context.Context) (map[string]any, bool)

func SNIFromContext

func SNIFromContext(ctx context.Context) (string, bool)

func WithEvent

func WithEvent(ctx context.Context, ev *audit.AuditEvent) context.Context

func WithJWTClaims

func WithJWTClaims(ctx context.Context, claims map[string]any) context.Context

func WithMatchedRoute

func WithMatchedRoute(ctx context.Context, rr *RouteRuntime) context.Context

WithMatchedRoute stores the matched RouteRuntime in the request context so that downstream handlers (e.g. the forwarder) can inspect the route that was selected during dispatch.

func WithPrincipal

func WithPrincipal(ctx context.Context, p *Principal) context.Context

Types

type BackendIterator

type BackendIterator interface {
	Next([]*BackendRuntime) (*BackendRuntime, bool)
}

type BackendPool

type BackendPool struct {
	Name          string
	Targets       []*BackendRuntime
	Iterator      BackendIterator
	Impersonation *ImpersonationRuntime
}

func (*BackendPool) Next

func (p *BackendPool) Next(r *http.Request) (*BackendRuntime, bool)

type BackendRuntime

type BackendRuntime struct {
	Name   string
	Labels map[string]string

	URL *url.URL

	CacheTTL time.Duration

	TLSConfig *tls.Config
	Transport http.RoundTripper

	AuthInjector RequestAuthInjector

	Active atomic.Int64
}

type BackendTarget

type BackendTarget struct {
	ID      string
	URL     *url.URL
	Healthy atomic.Bool
	Weight  int
}

type CompiledRoutes

type CompiledRoutes struct {
	Paths        []*RouteRuntime
	PathPrefixes []*RouteRuntime
	Headers      []*RouteRuntime
	SNIExact     map[string][]*RouteRuntime
	JWT          []*RouteRuntime
}

type EvalResult

type EvalResult int

EvalResult is the outcome of evaluating all policies against a request.

const (
	EvalAllow EvalResult = iota
	EvalDeny
)

func EvalPolicies

func EvalPolicies(
	policies []*policyv1.Policy,
	principal *Principal,
	backend *BackendPool,
	req K8sRequest,
) EvalResult

EvalPolicies evaluates the given policies against the principal, backend and k8s request using deny-first semantics:

  1. If any deny rule matches = deny.
  2. If any allow rule matches = allow.
  3. Default = deny.

type Float64Bucket

type Float64Bucket struct {
	Start time.Time
	Count int64
	Sum   float64
}

Float64Bucket stores observation count and sum for a single time interval (float64 histograms such as request duration).

type Float64Histogram

type Float64Histogram struct {
	Histogram metric.Float64Histogram
	Buckets   []Float64Bucket
	// contains filtered or unexported fields
}

func (*Float64Histogram) Record

func (m *Float64Histogram) Record(ctx context.Context, v float64, attrs ...metric.RecordOption)

func (*Float64Histogram) SnapshotBuckets

func (m *Float64Histogram) SnapshotBuckets() []Float64Bucket

type Forwarder

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

func NewForwarder

func NewForwarder(transport http.RoundTripper) *Forwarder

func NewForwarderWithMetrics

func NewForwarderWithMetrics(transport http.RoundTripper, metrics *ProxyMetrics) *Forwarder

func (*Forwarder) Handler

func (f *Forwarder) Handler(pool *BackendPool) http.Handler

type HeaderRuntime

type HeaderRuntime struct {
	Name      string
	Canonical string
	Value     string
}

type ImpersonationRuntime

type ImpersonationRuntime struct {
	Name          string
	Enabled       bool
	UsernameClaim string
	GroupsClaim   string
	ExtraClaims   []string
}

ImpersonationRuntime holds the compiled impersonation configuration for a backend pool. When non-nil and Enabled is true, the proxy injects Impersonate-User, Impersonate-Group, and Impersonate-Extra-* headers on the outbound request using claims from the authenticated principal's JWT.

type Int64Bucket

type Int64Bucket struct {
	Start time.Time
	Value int64
}

Int64Bucket stores a running sum for a single time interval (counters).

type Int64Counter

type Int64Counter struct {
	Counter metric.Int64Counter
	Current atomic.Int64
	Buckets []Int64Bucket
	// contains filtered or unexported fields
}

func (*Int64Counter) Inc

func (m *Int64Counter) Inc(ctx context.Context, v int64, attrs ...metric.AddOption)

func (*Int64Counter) Load

func (m *Int64Counter) Load() int64

func (*Int64Counter) SnapshotBuckets

func (m *Int64Counter) SnapshotBuckets() []Int64Bucket

type Int64GaugeBucket

type Int64GaugeBucket struct {
	Start time.Time
	Max   int64
}

Int64GaugeBucket stores the maximum gauge value observed during a single time interval (up-down counters such as active requests).

type Int64Histogram

type Int64Histogram struct {
	Histogram metric.Int64Histogram
	Buckets   []Int64HistogramBucket
	// contains filtered or unexported fields
}

func (*Int64Histogram) Record

func (m *Int64Histogram) Record(ctx context.Context, v int64, attrs ...metric.RecordOption)

func (*Int64Histogram) SnapshotBuckets

func (m *Int64Histogram) SnapshotBuckets() []Int64HistogramBucket

type Int64HistogramBucket

type Int64HistogramBucket struct {
	Start time.Time
	Count int64
	Sum   int64
}

Int64HistogramBucket stores observation count and sum for a single time interval (int64 histograms such as request/response size).

type Int64UpDownCounter

type Int64UpDownCounter struct {
	Counter metric.Int64UpDownCounter

	Buckets []Int64GaugeBucket
	// contains filtered or unexported fields
}

func (*Int64UpDownCounter) Add

func (m *Int64UpDownCounter) Add(ctx context.Context, v int64, attrs ...metric.AddOption)

func (*Int64UpDownCounter) SnapshotBuckets

func (m *Int64UpDownCounter) SnapshotBuckets() []Int64GaugeBucket

type JWTRuntime

type JWTRuntime struct {
	Claim string
	Value string
}

type K8sRequest

type K8sRequest struct {
	APIGroup    string
	Resource    string
	SubResource string
	Namespace   string
	Name        string
	Verb        string
}

K8sRequest holds the parsed components of a Kubernetes API request path. It is used during policy evaluation to match ResourceSelector rules.

func ParseK8sRequest

func ParseK8sRequest(ctx context.Context, r *http.Request) K8sRequest

ParseK8sRequest extracts Kubernetes API attributes from an HTTP request. It handles both core API paths (/api/v1/...) and named group paths (/apis/<group>/<version>/...).

Supported path shapes:

/api/v1/namespaces/<ns>/<resource>/<name>/<subresource>
/apis/<group>/<version>/namespaces/<ns>/<resource>/<name>/<subresource>
/api/v1/<resource>/<name>
/apis/<group>/<version>/<resource>/<name>

type LeastConnectionsLB

type LeastConnectionsLB struct{}

func (*LeastConnectionsLB) Next

func (r *LeastConnectionsLB) Next(targets []*BackendRuntime) (*BackendRuntime, bool)

type Principal

type Principal struct {
	Subject         string
	User            string
	Groups          []string
	Issuer          string
	Audience        []string
	ServiceAccounts []string
	Claims          map[string]any
	ExpiresAt       time.Time
}

Principal represents the authenticated identity extracted from a JWT.

func ExtractJWT

func ExtractJWT(r *http.Request, pubKey *ecdsa.PublicKey) (*Principal, map[string]any, error)

ExtractJWT validates the Bearer JWT in the Authorization header, extracts claims into the request context, and populates a Principal. It returns (principal, flatClaims, error). On error the caller should respond 403 and not forward the request.

func PrincipalFromContext

func PrincipalFromContext(ctx context.Context) (*Principal, bool)

type Proxy

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

func NewProxy

func NewProxy(runtime *RuntimeStore, opts ...ProxyOption) *Proxy

NewProxy creates a Proxy that serves requests from the given runtime store. If pubKey is non-nil, JWT extraction and policy enforcement are enabled.

func (*Proxy) ServeHTTP

func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request)

type ProxyMetrics

type ProxyMetrics struct {
	// Request metrics
	RequestsTotal     Int64Counter
	RequestDuration   Float64Histogram
	ActiveRequests    Int64UpDownCounter
	RequestSizeBytes  Int64Histogram
	ResponseSizeBytes Int64Histogram

	// Backend metrics
	BackendRequestsTotal   Int64Counter
	BackendRequestDuration Float64Histogram
	BackendActiveRequests  Int64UpDownCounter

	// Auth metrics
	AuthRequestsTotal      Int64Counter
	PolicyEvaluationsTotal Int64Counter

	// Route matching metrics
	RouteMatchesTotal Int64Counter
	RouteNoMatchTotal Int64Counter
}

ProxyMetrics holds all OpenTelemetry instruments for the proxy.

func InitMetrics

func InitMetrics(meter metric.Meter) (*ProxyMetrics, error)

InitMetrics creates a fully-initialised ProxyMetrics from the given OTel meter. Each metric is backed by both an OTel instrument (for Prometheus scraping) and a rolling in-memory time series (for the web UI).

type ProxyOption

type ProxyOption func(*Proxy)

func WithMeter

func WithMeter(m metric.Meter) ProxyOption

func WithMetrics

func WithMetrics(m *ProxyMetrics) ProxyOption

func WithPublicKey

func WithPublicKey(key *ecdsa.PublicKey) ProxyOption

WithPublicKey enables JWT extraction and policy enforcement using the given ECDSA public key.

func WithPublisher

func WithPublisher(pub audit.Publisher) ProxyOption

type RequestAuthInjector

type RequestAuthInjector interface {
	Apply(req *http.Request) error
}

type RoundRobinLB

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

func (*RoundRobinLB) Next

func (r *RoundRobinLB) Next(targets []*BackendRuntime) (*BackendRuntime, bool)

type RouteMatchKind

type RouteMatchKind uint8
const (
	RouteMatchKindPathPrefix RouteMatchKind = iota + 1
	RouteMatchKindPath
	RouteMatchKindHeader
	RouteMatchKindSNI
	RouteMatchKindJWT
)

type RouteRuntime

type RouteRuntime struct {
	Name    string
	Kind    RouteMatchKind
	Timeout time.Duration

	Path       string
	PathPrefix string
	Header     *HeaderRuntime
	SNI        string
	JWT        *JWTRuntime

	Handler     http.Handler
	BackendPool *BackendPool
}

func MatchedRouteFromContext

func MatchedRouteFromContext(ctx context.Context) (*RouteRuntime, bool)

MatchedRouteFromContext retrieves the RouteRuntime stored by WithMatchedRoute.

type RuntimeConfig

type RuntimeConfig struct {
	Version uint64

	Routes   CompiledRoutes
	Backends map[string]*BackendPool
	Policies []*policyv1.Policy
}

func (*RuntimeConfig) Match

func (rc *RuntimeConfig) Match(r *http.Request) (*RouteRuntime, bool)

type RuntimeStore

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

func NewRuntimeStore

func NewRuntimeStore() *RuntimeStore

func (*RuntimeStore) Load

func (s *RuntimeStore) Load() *RuntimeConfig

func (*RuntimeStore) Store

func (s *RuntimeStore) Store(rt *RuntimeConfig)

Jump to

Keyboard shortcuts

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