middleware

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2026 License: Apache-2.0 Imports: 36 Imported by: 0

Documentation

Overview

Package middleware provides a collection of middleware functions that handles various aspects of request handling, such as authentication, logging, tracing, and metrics collection.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func APIKeyAuthMiddleware

func APIKeyAuthMiddleware(a APIKeyAuthProvider, apiKeys ...string) func(handler http.Handler) http.Handler

APIKeyAuthMiddleware creates a middleware function that enforces API key authentication based on the provided API keys or a validation function.

func AuthMiddleware

func AuthMiddleware(a AuthProvider) func(handler http.Handler) http.Handler

AuthMiddleware creates a middleware function that enforces authentication based on the method provided.

func BasicAuthMiddleware

func BasicAuthMiddleware(basicAuthProvider BasicAuthProvider) func(handler http.Handler) http.Handler

BasicAuthMiddleware creates a middleware function that enforces basic authentication using the provided BasicAuthProvider.

func CORS

func CORS(middlewareConfigs map[string]string, routes *[]string) func(inner http.Handler) http.Handler

CORS is a middleware that adds CORS (Cross-Origin Resource Sharing) headers to the response.

func Logging

func Logging(probes LogProbes, logger logger) func(inner http.Handler) http.Handler

Logging is a middleware which logs response status and time in milliseconds along with other data.

func Metrics

func Metrics(metrics metrics) func(inner http.Handler) http.Handler

Metrics is a middleware that records request response time metrics using the provided metrics interface.

func OAuth

func OAuth(key PublicKeyProvider, options ...jwt.ParserOption) func(http.Handler) http.Handler

OAuth is a middleware function that validates JWT access tokens using a provided PublicKeyProvider.

func RateLimiter

func RateLimiter(config RateLimiterConfig, m metrics) func(http.Handler) http.Handler

RateLimiter creates a middleware that limits requests based on the configuration.

func Tracer

func Tracer(inner http.Handler) http.Handler

Tracer is a middleware that starts a new OpenTelemetry trace span for each request.

func WSHandlerUpgrade

func WSHandlerUpgrade(c *infra.Container, wsManager *websocket.Manager) func(inner http.Handler) http.Handler

WSHandlerUpgrade middleware upgrades the incoming http request to a websocket connection using websocket upgrader.

Types

type APIKeyAuthProvider

type APIKeyAuthProvider struct {
	ValidateFunc                func(apiKey string) bool
	ValidateFuncWithDatasources func(c *infra.Container, apiKey string) bool
	Container                   *infra.Container
	APIKeys                     []string
}

APIKeyAuthProvider represents a basic authentication provider.

func (*APIKeyAuthProvider) ExtractAuthHeader

func (a *APIKeyAuthProvider) ExtractAuthHeader(r *http.Request) (any, ErrorHTTP)

func (*APIKeyAuthProvider) GetAuthMethod

func (*APIKeyAuthProvider) GetAuthMethod() AuthMethod

type AuthMethod

type AuthMethod int

AuthMethod represents a custom type to define the different authentication methods supported.

const (
	JWTClaim AuthMethod = iota // JWTClaim represents the key used to store JWT claims within the request context.
	Username
	APIKey
)

type AuthProvider

type AuthProvider interface {
	GetAuthMethod() AuthMethod
	ExtractAuthHeader(r *http.Request) (any, ErrorHTTP)
}

func NewAPIKeyAuthProvider

func NewAPIKeyAuthProvider(apiKeys []string) (AuthProvider, error)

NewAPIKeyAuthProvider instantiates an instance of type AuthProvider interface.

func NewAPIKeyAuthProviderWithValidateFunc

func NewAPIKeyAuthProviderWithValidateFunc(c *infra.Container,
	validateFunc func(*infra.Container, string) bool) (AuthProvider, error)

NewAPIKeyAuthProviderWithValidateFunc instantiates an instance of type AuthProvider interface.

func NewBasicAuthProvider

func NewBasicAuthProvider(users map[string]string) (AuthProvider, error)

NewBasicAuthProvider returns an instance of type AuthProvider interface.

func NewBasicAuthProviderWithValidateFunc

func NewBasicAuthProviderWithValidateFunc(c *infra.Container,
	validateFunc func(c *infra.Container, username, password string) bool) (AuthProvider, error)

NewBasicAuthProviderWithValidateFunc returns an instance of type AuthProvider interface.

func NewOAuthProvider

func NewOAuthProvider(config OauthConfigs, options ...jwt.ParserOption) (AuthProvider, error)

NewOAuthProvider generates a OAuthProvider for the given OauthConfigs and jwt.ParserOption.

type BasicAuthProvider

type BasicAuthProvider struct {
	Users                       map[string]string
	ValidateFunc                func(username, password string) bool
	ValidateFuncWithDatasources func(c *infra.Container, username, password string) bool
	Container                   *infra.Container
}

BasicAuthProvider represents a basic authentication provider.

func (*BasicAuthProvider) ExtractAuthHeader

func (a *BasicAuthProvider) ExtractAuthHeader(r *http.Request) (any, ErrorHTTP)

ExtractAuthHeader retrieves & returns validated value from auth header.

func (*BasicAuthProvider) GetAuthMethod

func (*BasicAuthProvider) GetAuthMethod() AuthMethod

GetAuthMethod returns authMethod Username.

type Config

type Config struct {
	CorsHeaders map[string]string
	LogProbes   LogProbes
}

func GetConfigs

func GetConfigs(c config.Config) Config

type ErrorBadRequest

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

func NewBadRequest

func NewBadRequest(fields []Field) ErrorBadRequest

func (ErrorBadRequest) Error

func (e ErrorBadRequest) Error() string

func (ErrorBadRequest) StatusCode

func (ErrorBadRequest) StatusCode() int

type ErrorForbidden

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

func NewUnauthorized

func NewUnauthorized(message string) ErrorForbidden

func (ErrorForbidden) Error

func (e ErrorForbidden) Error() string

func (ErrorForbidden) StatusCode

func (ErrorForbidden) StatusCode() int

type ErrorHTTP

type ErrorHTTP interface {
	StatusCode() int
	error
}

ErrorHTTP represents an error specific to HTTP operations.

type ErrorInvalidAuthorizationHeader

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

ErrorInvalidAuthorizationHeader represents the scenario where the auth header errMessage is invalid.

func NewInvalidAuthorizationHeaderError

func NewInvalidAuthorizationHeaderError(key string) ErrorInvalidAuthorizationHeader

func (ErrorInvalidAuthorizationHeader) Error

func (ErrorInvalidAuthorizationHeader) StatusCode

func (ErrorInvalidAuthorizationHeader) StatusCode() int

type ErrorInvalidAuthorizationHeaderFormat

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

ErrorInvalidAuthorizationHeaderFormat represents the scenario where the auth header errMessage is invalid.

func NewInvalidAuthorizationHeaderFormatError

func NewInvalidAuthorizationHeaderFormatError(key, format string) ErrorInvalidAuthorizationHeaderFormat

func (ErrorInvalidAuthorizationHeaderFormat) Error

func (ErrorInvalidAuthorizationHeaderFormat) StatusCode

type ErrorInvalidConfiguration

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

func NewInvalidConfigurationError

func NewInvalidConfigurationError(message string) ErrorInvalidConfiguration

func (ErrorInvalidConfiguration) Error

func (ErrorInvalidConfiguration) StatusCode

func (ErrorInvalidConfiguration) StatusCode() int

type ErrorMissingAuthHeader

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

ErrorMissingAuthHeader represents the scenario where the auth header is missing from the request.

func NewMissingAuthHeaderError

func NewMissingAuthHeaderError(key string) ErrorMissingAuthHeader

func (ErrorMissingAuthHeader) Error

func (e ErrorMissingAuthHeader) Error() string

func (ErrorMissingAuthHeader) StatusCode

func (ErrorMissingAuthHeader) StatusCode() int

type Field

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

type JSONWebKey

type JSONWebKey struct {
	ID   string `json:"kid"`
	Type string `json:"kty"`

	Modulus         string `json:"n"`
	PublicExponent  string `json:"e"`
	PrivateExponent string `json:"d"`
}

JSONWebKey represents a JSON Web Key.

type JWKNotFound

type JWKNotFound struct {
}

JWKNotFound is an error type indicating a missing JSON Web Key Set (JWKS).

func (JWKNotFound) Error

func (JWKNotFound) Error() string

type JWKS

type JWKS struct {
	Keys []JSONWebKey `json:"keys"`
}

JWKS represents a JSON Web Key Set.

type JWKSProvider

type JWKSProvider interface {
	GetWithHeaders(ctx context.Context, path string, queryParams map[string]any,
		headers map[string]string) (*http.Response, error)
}

type LogProbes

type LogProbes struct {
	Disabled bool
	Paths    []string
}

type OAuthProvider

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

func (*OAuthProvider) ExtractAuthHeader

func (p *OAuthProvider) ExtractAuthHeader(r *http.Request) (any, ErrorHTTP)

func (*OAuthProvider) GetAuthMethod

func (*OAuthProvider) GetAuthMethod() AuthMethod

GetAuthMethod returns JWTClaim authMethod.

type OauthConfigs

type OauthConfigs struct {
	Provider        JWKSProvider
	RefreshInterval time.Duration
	Path            string
}

OauthConfigs holds configuration for OAuth middleware.

type PublicKeyProvider

type PublicKeyProvider interface {
	Get(kid string) *rsa.PublicKey
}

PublicKeyProvider defines an interface for retrieving a public key by its key ID.

func NewOAuth

func NewOAuth(config OauthConfigs) PublicKeyProvider

NewOAuth creates a PublicKeyProvider that periodically fetches and updates public keys from a JWKS endpoint.

type PublicKeys

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

PublicKeys stores a map of public keys identified by their key ID (kid).

func (*PublicKeys) Get

func (p *PublicKeys) Get(kid string) *rsa.PublicKey

Get retrieves a public key from the PublicKeys map by its key ID.

type RateLimiterConfig

type RateLimiterConfig struct {
	RequestsPerSecond float64
	Burst             int
	PerIP             bool
	Store             RateLimiterStore // Optional: defaults to in-memory store
	TrustedProxies    bool             // If true, trust X-Forwarded-For and X-Real-IP headers
	MaxKeys           int64            // Maximum unique rate limit keys (0 = default 100000)
}

RateLimiterConfig holds configuration for rate limiting.

Note: The default implementation uses in-memory token buckets and is suitable for single-pod deployments. In multi-pod deployments, each pod will enforce limits independently. For distributed rate limiting across multiple pods, a Redis-backed store can be implemented in a future update.

Security: When using PerIP=true, only enable TrustedProxies if your application is behind a trusted reverse proxy (nginx, ALB, etc.) that sets X-Forwarded-For. Without trusted proxies, clients can spoof IP addresses to bypass rate limits.

Cleanup: The rate limiter starts a background goroutine that runs for the application lifetime. This is acceptable for long-running servers but consider calling Store.StopCleanup() in shutdown handlers if needed.

func (RateLimiterConfig) Validate

func (c RateLimiterConfig) Validate() error

Validate checks if the configuration values are valid.

type RateLimiterStore

type RateLimiterStore interface {
	Allow(ctx context.Context, key string, config RateLimiterConfig) (allowed bool, retryAfter time.Duration, err error)
	StartCleanup(ctx context.Context)
	StopCleanup()
}

RateLimiterStore abstracts the storage and cleanup for rate limiter buckets. This interface matches the one defined in pkg/kite/service for consistency.

Note: The config parameter in Allow() is provided for interface compatibility. Implementations may use a stored configuration and ignore this parameter.

func NewMemoryRateLimiterStore

func NewMemoryRateLimiterStore(config RateLimiterConfig) RateLimiterStore

NewMemoryRateLimiterStore creates a new in-memory rate limiter store. The config is stored to ensure consistent rate limiting for all keys.

type RequestLog

type RequestLog struct {
	TraceID      string `json:"trace_id,omitempty"`
	SpanID       string `json:"span_id,omitempty"`
	StartTime    string `json:"start_time,omitempty"`
	ResponseTime int64  `json:"response_time,omitempty"`
	Method       string `json:"method,omitempty"`
	UserAgent    string `json:"user_agent,omitempty"`
	IP           string `json:"ip,omitempty"`
	URI          string `json:"uri,omitempty"`
	Response     int    `json:"response,omitempty"`
}

RequestLog represents a log entry for HTTP requests.

func (*RequestLog) PrettyPrint

func (rl *RequestLog) PrettyPrint(writer io.Writer)

type StatusResponseWriter

type StatusResponseWriter struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

StatusResponseWriter Defines own Response Writer to be used for logging of status - as http.ResponseWriter does not let us read status.

func (*StatusResponseWriter) Hijack

Hijack implements the http.Hijacker interface. So that we are able to upgrade to a websocket connection that requires the responseWriter implementation to implement this method.

func (*StatusResponseWriter) WriteHeader

func (w *StatusResponseWriter) WriteHeader(status int)

Jump to

Keyboard shortcuts

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