middleware

package
v0.1.93 Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2026 License: MIT Imports: 34 Imported by: 0

Documentation

Overview

Package middleware provides HTTP middleware for the application.

Package middleware provides HTTP middleware for the application.

Package middleware provides HTTP middleware for the application.

Index

Constants

View Source
const (
	// HeaderAPIVersion is the custom header for API version negotiation.
	HeaderAPIVersion = "X-API-Version"

	// ContextKeyAPIVersion is the Gin context key for the resolved API version.
	ContextKeyAPIVersion = "api_version"

	// CurrentAPIVersion is the latest supported API version.
	CurrentAPIVersion = 1

	// MinAPIVersion is the minimum supported API version.
	MinAPIVersion = 1
)

Variables

This section is empty.

Functions

func APIVersion added in v0.1.90

func APIVersion() gin.HandlerFunc

APIVersion returns a middleware that extracts the API version from request headers and sets it in the Gin context. It checks two sources in order:

  1. X-API-Version header (e.g., "1")
  2. Accept header (e.g., "application/vnd.orris.v1+json")

If neither is present, the current version is used as default. The resolved version is echoed back via the X-API-Version response header.

func CORS

func CORS(allowedOrigins []string) gin.HandlerFunc

CORS returns a Gin middleware for handling Cross-Origin Resource Sharing

func CSRF added in v0.1.91

func CSRF() gin.HandlerFunc

CSRF returns a middleware that validates CSRF tokens using the Double Submit Cookie pattern. For mutating requests (POST, PUT, DELETE, PATCH), it compares the csrf_token cookie value against the X-CSRF-Token header value. Safe methods (GET, HEAD, OPTIONS) are always skipped.

func CustomLogger

func CustomLogger(log logger.Interface) gin.HandlerFunc

func GetAPIVersion added in v0.1.90

func GetAPIVersion(c *gin.Context) int

GetAPIVersion returns the API version from the Gin context. Returns CurrentAPIVersion if not set.

func Logger

func Logger(log logger.Interface) gin.HandlerFunc

func Recovery

func Recovery(log logger.Interface) gin.HandlerFunc

func SecurityHeaders

func SecurityHeaders() gin.HandlerFunc

SecurityHeaders returns a middleware that sets security headers

Types

type AuthMiddleware

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

func NewAuthMiddleware

func NewAuthMiddleware(jwtService *auth.JWTService, userRepo user.Repository, cookieConfig config.CookieConfig, logger logger.Interface) *AuthMiddleware

func (*AuthMiddleware) OptionalAuth

func (m *AuthMiddleware) OptionalAuth() gin.HandlerFunc

func (*AuthMiddleware) RequireAuth

func (m *AuthMiddleware) RequireAuth() gin.HandlerFunc

type ForwardAgentTokenMiddleware

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

ForwardAgentTokenMiddleware provides authentication middleware for forward agents.

func NewForwardAgentTokenMiddleware

func NewForwardAgentTokenMiddleware(
	validateTokenUC ValidateForwardAgentTokenExecutor,
	logger logger.Interface,
) *ForwardAgentTokenMiddleware

NewForwardAgentTokenMiddleware creates a new instance of ForwardAgentTokenMiddleware.

func (*ForwardAgentTokenMiddleware) RequireForwardAgentToken

func (m *ForwardAgentTokenMiddleware) RequireForwardAgentToken() gin.HandlerFunc

RequireForwardAgentToken is a middleware that validates forward agent tokens. It supports both Authorization header (Bearer token) and query parameter (?token=xxx). On successful validation, it sets forward_agent_id and forward_agent_name in the context.

type ForwardQuotaMiddleware added in v0.1.6

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

ForwardQuotaMiddleware enforces forward rule quotas based on user's subscription plan

func NewForwardQuotaMiddleware added in v0.1.6

func NewForwardQuotaMiddleware(
	forwardRuleRepo forward.Repository,
	subscriptionRepo subscription.SubscriptionRepository,
	planRepo subscription.PlanRepository,
	quotaService usecases.QuotaService,
	logger logger.Interface,
) *ForwardQuotaMiddleware

NewForwardQuotaMiddleware creates a new forward quota middleware

func (*ForwardQuotaMiddleware) CheckRuleLimit added in v0.1.6

func (m *ForwardQuotaMiddleware) CheckRuleLimit() gin.HandlerFunc

CheckRuleLimit verifies that the user hasn't exceeded their forward rule count limit

func (*ForwardQuotaMiddleware) CheckRuleTypeAllowed added in v0.1.6

func (m *ForwardQuotaMiddleware) CheckRuleTypeAllowed() gin.HandlerFunc

CheckRuleTypeAllowed verifies that the requested rule type is allowed by the user's subscription plan

func (*ForwardQuotaMiddleware) CheckSubscriptionRuleLimit added in v0.1.53

func (m *ForwardQuotaMiddleware) CheckSubscriptionRuleLimit() gin.HandlerFunc

CheckSubscriptionRuleLimit verifies that the subscription hasn't exceeded its forward rule count limit. Requires subscription_id to be set in context by SubscriptionOwnerMiddleware.

NOTE: This is a soft limit check (first line of defense). Due to the time gap between checking the count here and actually creating the rule in the handler, there's a small race window under high concurrency. The use case layer should perform a secondary check within a database transaction for strict enforcement.

func (*ForwardQuotaMiddleware) CheckSubscriptionRuleTypeAllowed added in v0.1.53

func (m *ForwardQuotaMiddleware) CheckSubscriptionRuleTypeAllowed() gin.HandlerFunc

CheckSubscriptionRuleTypeAllowed verifies that the requested rule type is allowed by the subscription's plan. Requires subscription to be set in context by SubscriptionOwnerMiddleware.

func (*ForwardQuotaMiddleware) CheckSubscriptionTrafficLimit added in v0.1.53

func (m *ForwardQuotaMiddleware) CheckSubscriptionTrafficLimit() gin.HandlerFunc

CheckSubscriptionTrafficLimit verifies that the subscription hasn't exceeded its forward traffic limit. Uses QuotaService for unified quota calculation. Requires subscription_id to be set in context by SubscriptionOwnerMiddleware.

func (*ForwardQuotaMiddleware) CheckTrafficLimit added in v0.1.6

func (m *ForwardQuotaMiddleware) CheckTrafficLimit() gin.HandlerFunc

CheckTrafficLimit verifies that the user hasn't exceeded their forward traffic limit. Uses QuotaService for unified quota calculation.

type ForwardRuleOwnerMiddleware added in v0.1.6

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

ForwardRuleOwnerMiddleware ensures users can only access their own forward rules

func NewForwardRuleOwnerMiddleware added in v0.1.6

func NewForwardRuleOwnerMiddleware(
	forwardRuleRepo forward.Repository,
	logger logger.Interface,
) *ForwardRuleOwnerMiddleware

NewForwardRuleOwnerMiddleware creates a new forward rule owner middleware

func (*ForwardRuleOwnerMiddleware) RequireOwnership added in v0.1.6

func (m *ForwardRuleOwnerMiddleware) RequireOwnership() gin.HandlerFunc

RequireOwnership ensures the authenticated user owns the forward rule

func (*ForwardRuleOwnerMiddleware) RequireOwnershipByRuleID added in v0.1.53

func (m *ForwardRuleOwnerMiddleware) RequireOwnershipByRuleID() gin.HandlerFunc

RequireOwnershipByRuleID ensures the authenticated user owns the forward rule and the rule belongs to the subscription specified in the URL. This method gets rule ID from :rule_id URL parameter instead of :id. Designed for routes like /subscriptions/:sid/forward-rules/:rule_id

RESTful semantics: If the rule exists but doesn't belong to the subscription, returns 404 (resource not found in this context) rather than 403.

type NodeOwnerMiddleware added in v0.1.6

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

NodeOwnerMiddleware validates that the user owns the node being accessed

func NewNodeOwnerMiddleware added in v0.1.6

func NewNodeOwnerMiddleware(nodeRepo node.NodeRepository, log logger.Interface) *NodeOwnerMiddleware

NewNodeOwnerMiddleware creates a new node owner middleware

func (*NodeOwnerMiddleware) RequireOwnership added in v0.1.6

func (m *NodeOwnerMiddleware) RequireOwnership() gin.HandlerFunc

RequireOwnership ensures the user owns the node specified in the URL parameter

type NodeQuotaMiddleware added in v0.1.6

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

NodeQuotaMiddleware validates user node quotas

func NewNodeQuotaMiddleware added in v0.1.6

func NewNodeQuotaMiddleware(
	nodeRepo node.NodeRepository,
	subscriptionRepo subscription.SubscriptionRepository,
	planRepo subscription.PlanRepository,
	log logger.Interface,
) *NodeQuotaMiddleware

NewNodeQuotaMiddleware creates a new node quota middleware

func (*NodeQuotaMiddleware) CheckNodeLimit added in v0.1.6

func (m *NodeQuotaMiddleware) CheckNodeLimit() gin.HandlerFunc

CheckNodeLimit validates that the user hasn't exceeded their node limit

type NodeTokenMiddleware

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

func NewNodeTokenMiddleware

func NewNodeTokenMiddleware(
	validateTokenUC ValidateNodeTokenExecutor,
	logger logger.Interface,
) *NodeTokenMiddleware

func (*NodeTokenMiddleware) RequireNodeToken

func (m *NodeTokenMiddleware) RequireNodeToken() gin.HandlerFunc

func (*NodeTokenMiddleware) RequireNodeTokenHeader

func (m *NodeTokenMiddleware) RequireNodeTokenHeader() gin.HandlerFunc

RequireNodeTokenHeader is a middleware for RESTful API that validates X-Node-Token header

func (*NodeTokenMiddleware) RequireNodeTokenQuery

func (m *NodeTokenMiddleware) RequireNodeTokenQuery() gin.HandlerFunc

RequireNodeTokenQuery is a middleware that validates node token from query parameter

func (*NodeTokenMiddleware) RequireNodeTokenWS added in v0.1.33

func (m *NodeTokenMiddleware) RequireNodeTokenWS() gin.HandlerFunc

RequireNodeTokenWS is a middleware for WebSocket connections that validates token from query parameter. WebSocket connections cannot use custom headers during handshake, so token must be in query param.

type RateLimiter

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

RateLimiter provides Redis-backed IP rate limiting using a fixed-window counter. Each IP gets a counter key with TTL equal to the window duration. This works correctly in multi-instance deployments since all instances share Redis.

func NewRateLimiter

func NewRateLimiter(redisClient *redis.Client, limit int, window time.Duration) *RateLimiter

NewRateLimiter creates a new Redis-backed rate limiter. limit is the maximum number of requests allowed per window. window is the duration of the fixed time window.

func (*RateLimiter) Limit

func (rl *RateLimiter) Limit() gin.HandlerFunc

Limit returns a Gin middleware that enforces the rate limit per client IP.

type SubscriptionOwnerMiddleware

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

SubscriptionOwnerMiddleware ensures users can only access their own subscriptions

func NewSubscriptionOwnerMiddleware

func NewSubscriptionOwnerMiddleware(
	subscriptionRepo subscription.SubscriptionRepository,
	logger logger.Interface,
) *SubscriptionOwnerMiddleware

NewSubscriptionOwnerMiddleware creates a new subscription owner middleware

func (*SubscriptionOwnerMiddleware) RequireOwnership

func (m *SubscriptionOwnerMiddleware) RequireOwnership() gin.HandlerFunc

RequireOwnership ensures the authenticated user owns the subscription. Gets subscription SID from :sid URL parameter.

type SubscriptionRateLimitMiddleware

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

func NewSubscriptionRateLimitMiddleware

func NewSubscriptionRateLimitMiddleware(
	limiter ratelimit.RateLimiter,
	logger logger.Interface,
) *SubscriptionRateLimitMiddleware

func (*SubscriptionRateLimitMiddleware) CustomLimit

func (m *SubscriptionRateLimitMiddleware) CustomLimit(requestsPerMinute int) gin.HandlerFunc

func (*SubscriptionRateLimitMiddleware) LimitBySubscription

func (m *SubscriptionRateLimitMiddleware) LimitBySubscription() gin.HandlerFunc

type SubscriptionSecurityMiddleware

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

SubscriptionSecurityMiddleware is a Gin middleware that verifies subscription URL signatures

func NewSubscriptionSecurityMiddleware

func NewSubscriptionSecurityMiddleware(
	signer *SubscriptionURLSigner,
	logger logger.Interface,
) *SubscriptionSecurityMiddleware

NewSubscriptionSecurityMiddleware creates a new subscription security middleware

func (*SubscriptionSecurityMiddleware) PreventReplay

func (m *SubscriptionSecurityMiddleware) PreventReplay(maxAge int64) gin.HandlerFunc

PreventReplay is a Gin middleware that prevents replay attacks using timestamp validation maxAge defines the maximum age of a request in seconds (e.g., 300 for 5 minutes)

func (*SubscriptionSecurityMiddleware) VerifySignature

func (m *SubscriptionSecurityMiddleware) VerifySignature() gin.HandlerFunc

VerifySignature is a Gin middleware that verifies subscription URL signatures

type SubscriptionTokenMiddleware

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

func NewSubscriptionTokenMiddleware

func NewSubscriptionTokenMiddleware(
	validateTokenUseCase *usecases.ValidateSubscriptionTokenUseCase,
	logger logger.Interface,
) *SubscriptionTokenMiddleware

func (*SubscriptionTokenMiddleware) RequireSubscriptionToken

func (m *SubscriptionTokenMiddleware) RequireSubscriptionToken() gin.HandlerFunc

func (*SubscriptionTokenMiddleware) RequireSubscriptionTokenWithScope

func (m *SubscriptionTokenMiddleware) RequireSubscriptionTokenWithScope(scope string) gin.HandlerFunc

type SubscriptionURLSigner

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

SubscriptionURLSigner handles subscription URL signing and verification

func NewSubscriptionURLSigner

func NewSubscriptionURLSigner(secretKey string, logger logger.Interface) *SubscriptionURLSigner

NewSubscriptionURLSigner creates a new subscription URL signer

func (*SubscriptionURLSigner) GenerateURL

func (s *SubscriptionURLSigner) GenerateURL(subscriptionID uint, expiresAt time.Time, baseURL string) string

GenerateURL generates a signed subscription URL Parameters:

  • subscriptionID: the subscription ID
  • expiresAt: expiration time of the URL
  • baseURL: base URL for the subscription endpoint

Returns the complete signed URL

func (*SubscriptionURLSigner) Verify

func (s *SubscriptionURLSigner) Verify(subscriptionID uint, expiresAt int64, signature string) bool

Verify verifies the signature of a subscription URL Parameters:

  • subscriptionID: the subscription ID from URL
  • expiresAt: expiration timestamp from URL
  • signature: signature from URL

Returns true if signature is valid and not expired

type ValidateForwardAgentTokenExecutor

type ValidateForwardAgentTokenExecutor interface {
	Execute(ctx context.Context, cmd usecases.ValidateForwardAgentTokenCommand) (*usecases.ValidateForwardAgentTokenResult, error)
}

ValidateForwardAgentTokenExecutor defines the interface for validating forward agent tokens.

type ValidateNodeTokenExecutor

type ValidateNodeTokenExecutor interface {
	Execute(ctx context.Context, cmd usecases.ValidateNodeTokenCommand) (*usecases.ValidateNodeTokenResult, error)
}

Jump to

Keyboard shortcuts

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