middleware

package
v4.0.0-alpha.7 Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// SignatureHeader 签名头
	SignatureHeader = "X-Signature"
	// TimestampHeader 时间戳头
	TimestampHeader = "X-Timestamp"
	// NonceHeader 随机数头 (防重放)
	NonceHeader = "X-Nonce"
	// MaxTimeDiff 最大时间差 (秒)
	MaxTimeDiff = 300 // 5分钟
)

Variables

This section is empty.

Functions

func AdminAuth

func AdminAuth() gin.HandlerFunc

AdminAuth 绠$悊鍛樿璇佷腑闂翠欢

func AppTokenAuth

func AppTokenAuth() gin.HandlerFunc

CORS 璺ㄥ煙涓棿浠?

func AuditLog

func AuditLog() gin.HandlerFunc

AuditLog returns a gin middleware that records all admin API operations to both structured slog output and the v2_audit_log database table. It only applies to requests whose path starts with /api/v2/admin/.

func CORS

func CORS() gin.HandlerFunc

CORS 跨域中间件 — 支持配置允许的源,默认仅允许配置列表中的源

func JWTAuth

func JWTAuth() gin.HandlerFunc

JWTAuth JWT 璁よ瘉涓棿浠?

func Logger

func Logger() gin.HandlerFunc

Logger 鏃ュ織涓棿浠?

func NodeAPIKeyAuth

func NodeAPIKeyAuth() gin.HandlerFunc

NodeAPIKeyAuth 鑺傜偣 API Key 璁よ瘉涓棿浠?(鏂扮増)

func NodeAPIKeyHeaderAuth

func NodeAPIKeyHeaderAuth() gin.HandlerFunc

NodeAPIKeyHeaderAuth is the package-download authentication boundary. API keys in URLs leak through logs, browser history and proxy caches, so this variant accepts only X-API-Key while preserving legacy query fallback on the older node APIs.

func NodeAuth

func NodeAuth() gin.HandlerFunc

NodeAuth enforces node-scoped auth via required `node_id + X-API-Key`.

func NodeSecureLogger

func NodeSecureLogger() gin.HandlerFunc

NodeSecureLogger 节点专用安全日志 记录节点通信详情,用于审计和问题排查

func Recovery

func Recovery() gin.HandlerFunc

Recovery 鎭㈠涓棿浠?

func RequestID

func RequestID() gin.HandlerFunc

RequestID propagates or creates a request identifier for tracing.

func SecureLogger

func SecureLogger() gin.HandlerFunc

SecureLogger 安全日志中间件 自动脱敏敏感信息,记录请求详情

func SecurityHeaders

func SecurityHeaders() gin.HandlerFunc

SecurityHeaders applies a conservative set of production-safe response headers.

func SignatureAuth

func SignatureAuth() gin.HandlerFunc

SignatureAuth 请求签名验证中间件 签名算法: HMAC-SHA256(timestamp + method + path + body, secret) 需要配合 NodeAPIKeyAuth 使用,依赖 context 中的 node 信息

func StrictSignatureAuth

func StrictSignatureAuth() gin.HandlerFunc

StrictSignatureAuth 严格签名验证(必须有签名)

func VerifyNodeSignature

func VerifyNodeSignature(apiKey, timestamp, method, path, body, signature string) bool

VerifyNodeSignature 验证节点签名(独立函数,用于特殊场景)

func WriteAuditLog

func WriteAuditLog(entry *AuditLogEntry)

WriteAuditLog 写入审计日志(可扩展为写入数据库或外部系统)

Types

type AuditLogEntry

type AuditLogEntry struct {
	Timestamp   time.Time      `json:"timestamp"`
	Action      string         `json:"action"`
	UserID      uint           `json:"user_id,omitempty"`
	NodeID      uint           `json:"node_id,omitempty"`
	IP          string         `json:"ip"`
	UserAgent   string         `json:"user_agent"`
	Path        string         `json:"path"`
	Method      string         `json:"method"`
	StatusCode  int            `json:"status_code"`
	Latency     time.Duration  `json:"latency"`
	RequestBody string         `json:"request_body,omitempty"`
	Extra       map[string]any `json:"extra,omitempty"`
}

AuditLogEntry 审计日志结构

type RateLimiter

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

RateLimiter is a thread-safe per-IP rate limiter using token buckets.

func NewRateLimiter

func NewRateLimiter(rate, burst float64, opts ...RateLimiterOption) *RateLimiter

NewRateLimiter creates a new RateLimiter with the given rate and burst.

  • rate: sustained requests per second
  • burst: maximum burst size (initial tokens)

func (*RateLimiter) Middleware

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

Middleware returns a gin.HandlerFunc that enforces rate limiting per client IP.

func (*RateLimiter) MiddlewareForContextKey

func (rl *RateLimiter) MiddlewareForContextKey(contextKey string) gin.HandlerFunc

MiddlewareForContextKey enforces independent buckets for an authenticated identity stored in Gin context, such as a node_id.

func (*RateLimiter) StartCleanup

func (rl *RateLimiter) StartCleanup(interval time.Duration)

StartCleanup starts a periodic cleanup goroutine. It should be called once at application startup.

type RateLimiterOption

type RateLimiterOption func(*RateLimiter)

RateLimiterOption configures optional behaviour on a RateLimiter.

func WithExemptPaths

func WithExemptPaths(paths []string) RateLimiterOption

WithExemptPaths sets URL path prefixes that bypass rate limiting.

func WithTTL

func WithTTL(ttl time.Duration) RateLimiterOption

WithTTL sets the expiry duration for unused buckets.

func WithTestModeBypass

func WithTestModeBypass(enabled bool) RateLimiterOption

WithTestModeBypass controls whether gin.TestMode bypasses this limiter. Existing API limiters keep the historical bypass; security-sensitive node downloads can exercise the exact limiter in integration tests.

Jump to

Keyboard shortcuts

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