middleware

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 29, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetToken added in v0.2.0

func GetToken(ctx context.Context) *token.Token

GetToken retrieves the validated token from the context.

func SetRawToken added in v0.2.0

func SetRawToken(ctx context.Context, raw string) context.Context

SetRawToken stores the raw bearer token string in the context. This should be called by the transport layer after extracting it from HTTP headers.

func SetToken added in v0.2.0

func SetToken(ctx context.Context, t *token.Token) context.Context

SetToken stores a validated token in the request context.

Types

type AuthMiddleware

type AuthMiddleware struct {
	PassthroughMiddleware
	// contains filtered or unexported fields
}

AuthMiddleware verifies Ed25519 signatures on incoming JSON-RPC requests.

func NewAuthMiddleware

func NewAuthMiddleware(store auth.KeyStore, mode string, logger *slog.Logger, onAuth func(string), didBlocklist []string) *AuthMiddleware

NewAuthMiddleware creates a new AuthMiddleware. mode should be "open", "verified", or "closed". onAuth is called with "verified", "failed", or "unsigned" for each request.

func (*AuthMiddleware) Name

func (a *AuthMiddleware) Name() string

Name returns the name of this middleware.

func (*AuthMiddleware) ProcessRequest

func (a *AuthMiddleware) ProcessRequest(ctx context.Context, req *jsonrpc.Request) (*jsonrpc.Request, error)

ProcessRequest verifies the request signature and enforces the auth policy.

type Chain

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

Chain runs a list of middlewares in order.

func BuildChain

func BuildChain(entries []config.MiddlewareEntry, deps Dependencies) (*Chain, func(), error)

BuildChain creates a middleware Chain from config entries and dependencies.

func NewChain

func NewChain(items ...Middleware) *Chain

NewChain creates a new Chain from the provided middlewares.

func (*Chain) ProcessRequest

func (c *Chain) ProcessRequest(ctx context.Context, req *jsonrpc.Request) (*jsonrpc.Request, []byte, error)

ProcessRequest runs each middleware's ProcessRequest in order. On the first error, it returns nil, an error payload (JSON-encoded error response + newline) suitable for writing to the upstream caller, and the original error.

func (*Chain) ProcessResponse

func (c *Chain) ProcessResponse(ctx context.Context, resp *jsonrpc.Response) (*jsonrpc.Response, error)

ProcessResponse runs each middleware's ProcessResponse in order. On the first error it returns nil and the error.

type Dependencies

type Dependencies struct {
	DB           *storage.DB
	Logger       *slog.Logger
	Metrics      *monitor.Metrics
	KeyStore     auth.KeyStore
	TelCol       *telemetry.Collector
	SecMode      string // "open", "verified", or "closed"
	TokenStore   *token.Store
	DIDBlocklist []string
}

Dependencies holds shared resources needed by middleware factories.

type GuardConfig

type GuardConfig struct {
	RateLimitPerMin    int           // requests per minute per method (0 = unlimited)
	MaxBodySize        int64         // max request body size in bytes (0 = unlimited)
	IPBlocklist        []string      // CIDR strings to block
	IPAllowlist        []string      // CIDR strings to allow (empty = allow all)
	BruteForceMaxFails int           // consecutive failures before auto-block (0 = disabled)
	BruteForceWindow   time.Duration // window for tracking failures (default 5m)
	BruteForceBlockDur time.Duration // how long to block (default 10m)
	ValidateJSONRPC    bool          // reject malformed JSON-RPC payloads
}

GuardConfig holds configuration for the guard middleware.

type GuardMiddleware

type GuardMiddleware struct {
	PassthroughMiddleware
	// contains filtered or unexported fields
}

GuardMiddleware enforces rate limits, request size limits, IP-based access control, brute force protection, and malformed payload detection.

func NewGuardMiddleware

func NewGuardMiddleware(cfg GuardConfig, logger *slog.Logger, onReject func()) *GuardMiddleware

NewGuardMiddleware creates a GuardMiddleware from the given config.

func (*GuardMiddleware) CheckIPAccess

func (g *GuardMiddleware) CheckIPAccess(ipStr string) error

CheckIPAccess checks if an IP is allowed/blocked by the guard's IP lists. Returns an error if the IP is blocked.

func (*GuardMiddleware) Name

func (g *GuardMiddleware) Name() string

Name returns the name of this middleware.

func (*GuardMiddleware) ProcessRequest

func (g *GuardMiddleware) ProcessRequest(ctx context.Context, req *jsonrpc.Request) (*jsonrpc.Request, error)

ProcessRequest enforces size limits, rate limits, brute force checks, and malformed JSON-RPC validation on incoming requests.

func (*GuardMiddleware) RecordFailure

func (g *GuardMiddleware) RecordFailure(key string)

RecordFailure records a failed request for brute force tracking.

type LogMiddleware

type LogMiddleware struct {
	PassthroughMiddleware
	// contains filtered or unexported fields
}

LogMiddleware records request/response pairs to the database.

func NewLogMiddleware

func NewLogMiddleware(db *storage.DB, logger *slog.Logger, recorder Recorder, onMessage func(direction, method string, latencyMs float64)) *LogMiddleware

NewLogMiddleware creates a LogMiddleware and starts its background writer. recorder may be nil to disable telemetry forwarding. onMessage may be nil to skip Prometheus counter/histogram updates.

func (*LogMiddleware) Close

func (lm *LogMiddleware) Close()

Close shuts down the background writer.

func (*LogMiddleware) Name

func (lm *LogMiddleware) Name() string

Name returns the name of this middleware.

func (*LogMiddleware) ProcessRequest

func (lm *LogMiddleware) ProcessRequest(ctx context.Context, req *jsonrpc.Request) (*jsonrpc.Request, error)

ProcessRequest records the request and stores pending state.

func (*LogMiddleware) ProcessResponse

func (lm *LogMiddleware) ProcessResponse(ctx context.Context, resp *jsonrpc.Response) (*jsonrpc.Response, error)

ProcessResponse looks up the pending request, computes latency, and enqueues a log entry.

func (*LogMiddleware) SetAuthStatus

func (lm *LogMiddleware) SetAuthStatus(reqID, status, agentHash string)

SetAuthStatus updates the pending request's auth status and agent hash.

type Middleware

type Middleware interface {
	Name() string
	ProcessRequest(ctx context.Context, req *jsonrpc.Request) (*jsonrpc.Request, error)
	ProcessResponse(ctx context.Context, resp *jsonrpc.Response) (*jsonrpc.Response, error)
}

Middleware processes JSON-RPC requests and responses in a pipeline.

type PassthroughMiddleware

type PassthroughMiddleware struct{}

PassthroughMiddleware is a no-op Middleware useful for embedding.

func (PassthroughMiddleware) Name

Name returns the name of this middleware.

func (PassthroughMiddleware) ProcessRequest

ProcessRequest passes the request through unchanged.

func (PassthroughMiddleware) ProcessResponse

ProcessResponse passes the response through unchanged.

type Recorder

type Recorder interface {
	Record(event telemetry.Event)
}

Recorder forwards telemetry events to an external collector. Satisfied by *telemetry.Collector.

type SwappableChain

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

SwappableChain wraps a Chain and allows atomic replacement for hot-reload.

func NewSwappableChain

func NewSwappableChain(chain *Chain) *SwappableChain

NewSwappableChain creates a SwappableChain wrapping the provided Chain.

func (*SwappableChain) ProcessRequest

func (sc *SwappableChain) ProcessRequest(ctx context.Context, req *jsonrpc.Request) (*jsonrpc.Request, []byte, error)

ProcessRequest delegates to the current Chain's ProcessRequest under a read lock.

func (*SwappableChain) ProcessResponse

func (sc *SwappableChain) ProcessResponse(ctx context.Context, resp *jsonrpc.Response) (*jsonrpc.Response, error)

ProcessResponse delegates to the current Chain's ProcessResponse under a read lock.

func (*SwappableChain) Swap

func (sc *SwappableChain) Swap(chain *Chain)

Swap atomically replaces the underlying Chain.

type TokenMiddleware added in v0.2.0

type TokenMiddleware struct {
	PassthroughMiddleware
	// contains filtered or unexported fields
}

TokenMiddleware validates bearer tokens and enforces quotas.

func NewTokenMiddleware added in v0.2.0

func NewTokenMiddleware(store *token.Store, logger *slog.Logger) *TokenMiddleware

NewTokenMiddleware creates a TokenMiddleware.

func (*TokenMiddleware) Name added in v0.2.0

func (tm *TokenMiddleware) Name() string

Name returns the middleware name.

func (*TokenMiddleware) ProcessRequest added in v0.2.0

func (tm *TokenMiddleware) ProcessRequest(ctx context.Context, req *jsonrpc.Request) (*jsonrpc.Request, error)

ProcessRequest validates the token and checks quotas/permissions.

Directories

Path Synopsis
Package httpauth provides shared HTTP-based agent authentication logic used by both A2A and HTTP API middleware.
Package httpauth provides shared HTTP-based agent authentication logic used by both A2A and HTTP API middleware.

Jump to

Keyboard shortcuts

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