Documentation
¶
Overview ¶
Package middleware provides Gin middleware for the tingly-box server.
Middleware Stack ¶
Middleware is applied globally in server.setupMiddleware() in the order below. Every inbound request passes through all layers before reaching a handler.
Request │ ├─ gin.Recovery — panic → 500, prevents process crash ├─ MultiModeMemoryLog — structured HTTP log + in-memory ring buffer ├─ ErrorLog — debug/error log with expr-based path filter ├─ CORS — Access-Control-* headers └─ Auth (per-route) — UserAuth or ModelAuth, applied at route level
Components ¶
MultiModeMemoryLogMiddleware (multi_mode_memory_log.go)
Logs every HTTP request to both a persistent multi-mode logger (text + JSON file via pkg/obs.MultiLogger) and an in-memory circular buffer (500 entries).
For AI-routed requests, the log entry is enriched with routing metadata after the handler returns — these fields are written into the gin context by SetTrackingContext (internal/server/tracking_context.go):
- request_model — model name the client requested
- routed_model — model name actually forwarded to the provider
- routed_provider — provider name selected by the routing pipeline
- scenario — agent scenario (e.g. "claude_code", "openai")
Non-AI routes (system/management APIs) produce no routing fields. Request bodies are stored only for 4xx/5xx responses to limit memory use; they are referenced by a body_ref ID that can be retrieved via GET /api/v1/log/request/:id.
ErrorLogMiddleware (error_log.go)
Writes filtered request/response detail to a rotating debug log file (default: <configDir>/logs/debug.log, 10 MB / 5 files). An Expr expression controls which requests are recorded; the default captures anything under /api/ or /tbe/ with a 4xx/5xx status. The filter can be reloaded at runtime without restarting the server.
AuthMiddleware (auth.go)
Two distinct auth modes are applied at route registration time:
UserAuthMiddleware — web-UI routes; validates a static bearer token from config; sets client_id="user_authenticated".
ModelAuthMiddleware — AI-endpoint routes; supports three methods in priority order: 1. JWT API tokens (multi-tenant, "tb-share-*" prefix, validated from DB) 2. Global config token ("tingly-box-*" prefix) 3. Enterprise context JWT (X-TBE-Context-JWT header, HS256/RS256)
CORS (cors.go)
Applies permissive Access-Control-Allow-* headers required for the single-page web UI. Preflight OPTIONS requests are handled and short- circuited before auth runs.
RateLimit (ratelimit.go)
Token-bucket rate limiter keyed by client IP. Limits are configurable per scenario and fall back to a global default.
Index ¶
- Constants
- func CORS() gin.HandlerFunc
- func CORSWithConfig(config CORSConfig) gin.HandlerFunc
- func RateLimitMiddleware(rl *RateLimiter, authPaths ...string) gin.HandlerFunc
- type APITokenStore
- type AuthMiddleware
- type CORSConfig
- type ErrorDetail
- type ErrorLogMiddleware
- func (dm *ErrorLogMiddleware) Disable()
- func (dm *ErrorLogMiddleware) Enable() error
- func (dm *ErrorLogMiddleware) IsEnabled() bool
- func (dm *ErrorLogMiddleware) Middleware() gin.HandlerFunc
- func (dm *ErrorLogMiddleware) SetFilterExpression(expression string) error
- func (dm *ErrorLogMiddleware) Stop()
- type ErrorResponse
- type FilterContext
- type MultiModeMemoryLogMiddleware
- func (m *MultiModeMemoryLogMiddleware) Clear()
- func (m *MultiModeMemoryLogMiddleware) GetEntries() []*logrus.Entry
- func (m *MultiModeMemoryLogMiddleware) GetEntriesByLevel(level logrus.Level) []*logrus.Entry
- func (m *MultiModeMemoryLogMiddleware) GetEntriesSince(since time.Time) []*logrus.Entry
- func (m *MultiModeMemoryLogMiddleware) GetLatestEntries(n int) []*logrus.Entry
- func (m *MultiModeMemoryLogMiddleware) GetRequestBodyStore() *obs.RequestBodyStore
- func (m *MultiModeMemoryLogMiddleware) Middleware() gin.HandlerFunc
- func (m *MultiModeMemoryLogMiddleware) Size() int
- type RateLimiter
Constants ¶
const ( // MaxRequestBodySize is the maximum size of request body to store (1MB) MaxRequestBodySize = 1024 * 1024 // MaxRequestBodies is the maximum number of request bodies to keep in memory MaxRequestBodies = 50 )
Request body storage configuration
const GinRequestIDKey = "request_id"
GinRequestIDKey is the gin context key under which the per-request correlation id is stored. Handlers and later stages read it via c.GetString(GinRequestIDKey) to tie their logs to the request.
Variables ¶
This section is empty.
Functions ¶
func CORSWithConfig ¶
func CORSWithConfig(config CORSConfig) gin.HandlerFunc
CORSWithConfig returns a CORS middleware handler with custom configuration
func RateLimitMiddleware ¶
func RateLimitMiddleware(rl *RateLimiter, authPaths ...string) gin.HandlerFunc
RateLimitMiddleware returns a Gin middleware for rate limiting This is specifically for auth endpoints (handshake, execute)
Types ¶
type APITokenStore ¶ added in v0.260418.2200
type APITokenStore interface {
ValidateToken(tokenID string) (*db.APITokenRecord, error)
UpdateLastUsed(tokenID string) error
}
APITokenStore interface for token validation (abstracted for testability)
type AuthMiddleware ¶
type AuthMiddleware struct {
// contains filtered or unexported fields
}
AuthMiddleware provides authentication middleware for different types of authentication
func NewAuthMiddleware ¶
func NewAuthMiddleware(cfg *config.Config, jwtManager *auth.JWTManager, apiTokenManager *auth.APITokenManager, apiTokenStore APITokenStore) *AuthMiddleware
NewAuthMiddleware creates a new authentication middleware
func (*AuthMiddleware) ModelAuthMiddleware ¶
func (am *AuthMiddleware) ModelAuthMiddleware() gin.HandlerFunc
ModelAuthMiddleware middleware for OpenAI and Anthropic API authentication The auth will support both `Authorization` and `X-Api-Key` Supports three authentication methods (in order of precedence): 1. JWT API tokens (when multi-tenant is enabled) 2. Global config model token (backward compatibility) 3. Enterprise context JWT (X-TBE-Context-JWT header)
func (*AuthMiddleware) UserAuthMiddleware ¶
func (am *AuthMiddleware) UserAuthMiddleware() gin.HandlerFunc
UserAuthMiddleware middleware for UI and control API authentication
type CORSConfig ¶
type CORSConfig struct {
AllowOrigins string
AllowMethods string
AllowHeaders string
ExposeHeaders string
MaxAge int
HandlePreflight bool
}
CORSConfig defines the configuration for CORS middleware
type ErrorDetail ¶
type ErrorDetail struct {
Message string `json:"message"`
Type string `json:"type"`
Code string `json:"code,omitempty"`
}
ErrorDetail represents error details
type ErrorLogMiddleware ¶
type ErrorLogMiddleware struct {
// contains filtered or unexported fields
}
ErrorLogMiddleware logs requests and responses to a file when debug mode is enabled
func NewErrorLogMiddleware ¶
func NewErrorLogMiddleware(logPath string, maxSizeMB int) *ErrorLogMiddleware
NewErrorLogMiddleware creates a new debug middleware
func (*ErrorLogMiddleware) Disable ¶
func (dm *ErrorLogMiddleware) Disable()
Disable disables debug logging
func (*ErrorLogMiddleware) Enable ¶
func (dm *ErrorLogMiddleware) Enable() error
Enable enables debug logging
func (*ErrorLogMiddleware) IsEnabled ¶
func (dm *ErrorLogMiddleware) IsEnabled() bool
IsEnabled returns whether debug logging is enabled
func (*ErrorLogMiddleware) Middleware ¶
func (dm *ErrorLogMiddleware) Middleware() gin.HandlerFunc
Middleware returns the Gin middleware function
func (*ErrorLogMiddleware) SetFilterExpression ¶
func (dm *ErrorLogMiddleware) SetFilterExpression(expression string) error
SetFilterExpression recompiles and sets a new filter expression
type ErrorResponse ¶
type ErrorResponse struct {
Error ErrorDetail `json:"error"`
}
ErrorResponse represents an error response
type FilterContext ¶
type FilterContext struct {
StatusCode int `expr:"StatusCode"`
Method string `expr:"Method"`
Path string `expr:"Path"`
Query string `expr:"Query"`
}
FilterContext provides the context for filter expression evaluation
type MultiModeMemoryLogMiddleware ¶
type MultiModeMemoryLogMiddleware struct {
// contains filtered or unexported fields
}
MultiModeMemoryLogMiddleware provides Gin middleware with both persistent and memory log storage Logs are written to: 1. Multi-mode logger (text + JSON files for persistence) 2. Memory (circular buffer for quick API access) 3. Request body store (pure memory, referenced by body_ref ID)
func NewMultiModeMemoryLogMiddleware ¶
func NewMultiModeMemoryLogMiddleware(multiLogger *obs.MultiLogger) *MultiModeMemoryLogMiddleware
NewMultiModeMemoryLogMiddleware creates a new middleware with both persistent and memory logging
func (*MultiModeMemoryLogMiddleware) Clear ¶
func (m *MultiModeMemoryLogMiddleware) Clear()
Clear removes all log entries from memory
func (*MultiModeMemoryLogMiddleware) GetEntries ¶
func (m *MultiModeMemoryLogMiddleware) GetEntries() []*logrus.Entry
GetEntries returns all log entries from memory in chronological order
func (*MultiModeMemoryLogMiddleware) GetEntriesByLevel ¶
func (m *MultiModeMemoryLogMiddleware) GetEntriesByLevel(level logrus.Level) []*logrus.Entry
GetEntriesByLevel returns log entries from memory matching the specified level
func (*MultiModeMemoryLogMiddleware) GetEntriesSince ¶
func (m *MultiModeMemoryLogMiddleware) GetEntriesSince(since time.Time) []*logrus.Entry
GetEntriesSince returns log entries from memory after the specified time
func (*MultiModeMemoryLogMiddleware) GetLatestEntries ¶
func (m *MultiModeMemoryLogMiddleware) GetLatestEntries(n int) []*logrus.Entry
GetLatestEntries returns the newest N log entries from memory
func (*MultiModeMemoryLogMiddleware) GetRequestBodyStore ¶ added in v0.260418.2200
func (m *MultiModeMemoryLogMiddleware) GetRequestBodyStore() *obs.RequestBodyStore
GetRequestBodyStore returns the request body store for retrieving stored request bodies
func (*MultiModeMemoryLogMiddleware) Middleware ¶
func (m *MultiModeMemoryLogMiddleware) Middleware() gin.HandlerFunc
Middleware returns a Gin middleware compatible with gin.Logger() It logs all HTTP requests to both the multi-mode logger and memory
func (*MultiModeMemoryLogMiddleware) Size ¶
func (m *MultiModeMemoryLogMiddleware) Size() int
Size returns the current number of stored log entries in memory
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter provides rate limiting functionality
func NewRateLimiter ¶
func NewRateLimiter(maxAttempts int, windowSize, blockDuration time.Duration) *RateLimiter
NewRateLimiter creates a new rate limiter
func (*RateLimiter) Cleanup ¶
func (rl *RateLimiter) Cleanup()
cleanup runs periodically to remove expired entries
func (*RateLimiter) GetStats ¶
func (rl *RateLimiter) GetStats() map[string]interface{}
GetStats returns rate limiting statistics
func (*RateLimiter) ResetIP ¶
func (rl *RateLimiter) ResetIP(ip string)
ResetIP resets the rate limit for a specific IP (admin use only)