Documentation
¶
Overview ¶
Package guardgo provides a Redis-backed API protection middleware with a single atomic Redis roundtrip (Lua) on the critical path and optional asynchronous pattern analysis (rules) off the critical path.
Index ¶
- Variables
- func ApplyRateLimitHeaders(h http.Header, d Decision)
- func Echo(engine *Engine) echo.MiddlewareFunc
- func Fiber(engine *Engine) fiber.Handler
- func Gin(engine *Engine) gin.HandlerFunc
- func Guard(cfg MiddlewareConfig) (func(http.Handler) http.Handler, error)
- func MustGuard(cfg MiddlewareConfig) func(http.Handler) http.Handler
- type AdaptiveBanConfig
- type BehavioralConfig
- type BloomConfig
- type CompiledRuleset
- type Decision
- type Engine
- func GuardHTTP(cfg MiddlewareConfig) (func(http.Handler) http.Handler, *Engine, error)
- func MustNew(cfg MiddlewareConfig) *Engine
- func New(cfg MiddlewareConfig) *Engine
- func NewDefault() *Engine
- func NewEngine(cfg MiddlewareConfig) (*Engine, error)
- func NewWithError(cfg MiddlewareConfig) (*Engine, error)
- func NewWithRedisAddr(redisAddr string) *Engine
- func (e *Engine) Check(ctx context.Context, r *http.Request) (allowed bool, reason Reason, counter int64)
- func (e *Engine) Close()
- func (e *Engine) Config() MiddlewareConfig
- func (e *Engine) Middleware(next http.Handler) http.Handler
- func (e *Engine) Process(ctx context.Context, r *http.Request) Decision
- type Evaluator
- type MatchTarget
- type Metrics
- type MiddlewareConfig
- type NopMetrics
- type NopStatsCollector
- type Reason
- type ReputationConfig
- type Rule
- type RulesetManager
- type RulesetStats
- type SelfHealingConfig
- type SignatureRule
- type StatsCollector
- type TracingConfig
Constants ¶
This section is empty.
Variables ¶
var ErrRulesetPathEmpty = errors.New("github.com/Zhaba1337228/GuardGo: ruleset path is empty")
Functions ¶
func ApplyRateLimitHeaders ¶
ApplyRateLimitHeaders writes standard rate-limit headers for client visibility.
func Echo ¶
func Echo(engine *Engine) echo.MiddlewareFunc
Echo returns an Echo middleware based on the provided Engine.
func Gin ¶
func Gin(engine *Engine) gin.HandlerFunc
Gin returns a Gin middleware based on the provided Engine.
Types ¶
type AdaptiveBanConfig ¶
type AdaptiveBanConfig struct {
Enabled bool
// ThreatKeyWindow is a rolling window for counting "threatful" requests per IP.
// Default: 10m.
ThreatKeyWindow time.Duration
// ThreatCountThreshold triggers a ban when the per-IP threat count within
// ThreatKeyWindow reaches this value. Default: 100.
ThreatCountThreshold int64
// BanTTL is the ban duration once ThreatCountThreshold is reached.
// Default: DefaultBanTTL.
BanTTL time.Duration
// QueueSize is the buffered channel size for background analysis. Default: 8192.
QueueSize int
// Workers is the number of background workers. Default: 2 * GOMAXPROCS.
Workers int
// CaptureHeaders lists headers to snapshot for rules. Default: []{"User-Agent"}.
CaptureHeaders []string
}
type BehavioralConfig ¶
type BehavioralConfig struct {
Enabled bool
// RiskWindow is TTL for per-IP risk score.
RiskWindow time.Duration
// ScoreThreshold pushes IP into penalty box.
ScoreThreshold int64
// PenaltyTTL is duration of penalty box mode.
PenaltyTTL time.Duration
// PenaltyBanTTL is ban duration after failed penalty checks.
PenaltyBanTTL time.Duration
// RequireUserAgent enforces User-Agent header in penalty mode.
RequireUserAgent bool
// RequireReferer enforces Referer header in penalty mode.
RequireReferer bool
// QueryDiversityThreshold adds risk when query diversity spikes.
QueryDiversityThreshold int
// HeaderDiversityThreshold adds risk when header diversity spikes.
HeaderDiversityThreshold int
// DiversityWeight contributes to risk when thresholds exceeded.
DiversityWeight int64
}
type BloomConfig ¶
type CompiledRuleset ¶
type CompiledRuleset struct {
Any *dfa.Matcher
Query *dfa.Matcher
Headers *dfa.Matcher
Path *dfa.Matcher
}
func CompileRuleset ¶
func CompileRuleset(rules []SignatureRule) *CompiledRuleset
func LoadRulesetFile ¶
func LoadRulesetFile(path string) (*CompiledRuleset, error)
func (*CompiledRuleset) Stats ¶
func (r *CompiledRuleset) Stats() RulesetStats
type Decision ¶
type Decision struct {
Allowed bool
Reason Reason
Counter int64
Limit int
Remaining int
ResetAt time.Time
StatusCode int
}
Decision is a normalized engine output used by all middleware adapters.
func (Decision) StatusCodeOr ¶
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine is the request-decision core. It is safe for concurrent use after NewEngine returns and until Close is called.
func GuardHTTP ¶
GuardHTTP is a convenience helper to construct an Engine and return a net/http middleware.
func MustNew ¶
func MustNew(cfg MiddlewareConfig) *Engine
MustNew returns a new Engine instance or panics.
func New ¶
func New(cfg MiddlewareConfig) *Engine
New returns a new Engine instance and panics if construction fails. This enables 1-line DX: guard := guardgo.New(guardgo.DefaultConfig()).
func NewEngine ¶
func NewEngine(cfg MiddlewareConfig) (*Engine, error)
NewEngine constructs an Engine, applying defaults and starting background workers if any reactive subsystem (rules, reputation, behavior, ruleset reload) is configured.
func NewWithError ¶
func NewWithError(cfg MiddlewareConfig) (*Engine, error)
NewWithError returns a new Engine instance with explicit error handling.
func NewWithRedisAddr ¶
NewWithRedisAddr creates Engine using only Redis address and defaults.
func (*Engine) Check ¶
func (e *Engine) Check(ctx context.Context, r *http.Request) (allowed bool, reason Reason, counter int64)
Check performs critical-path checks:
- local blacklist cache
- Redis Lua (blacklist + rate-limit counter)
It returns allowed, reason code and current counter value.
func (*Engine) Close ¶
func (e *Engine) Close()
Close stops background workers and releases attached resources. Safe to call multiple times.
func (*Engine) Config ¶
func (e *Engine) Config() MiddlewareConfig
Config returns effective engine configuration with defaults applied.
func (*Engine) Middleware ¶
Middleware returns a net/http middleware.
type Evaluator ¶
Evaluator calculates request risk score. Returned value is added to reputation score for current actor.
type MatchTarget ¶
type MatchTarget string
const ( MatchQuery MatchTarget = "query" MatchHeaders MatchTarget = "headers" MatchPath MatchTarget = "path" MatchAny MatchTarget = "any" )
type MiddlewareConfig ¶
type MiddlewareConfig struct {
// Redis is required unless you only use the local blacklist cache.
Redis *redis.Client
// MaxRequests is the maximum number of requests allowed per Window for a key.
MaxRequests int
Window time.Duration
// Rules are evaluated asynchronously (best-effort) to support adaptive bans.
// Rules MUST NOT read or depend on r.Body.
Rules []Rule
// Evaluators calculate additive reputation score.
Evaluators []Evaluator
// FailOpen allows traffic when Redis is unavailable or returns an error.
FailOpen bool
// Prefix is used to build Redis keys. Default: "github.com/Zhaba1337228/GuardGo".
Prefix string
// CacheSize is the local blacklist LRU size. Default: 4096.
CacheSize int
// DefaultBanTTL is used by adaptive banning when no rule-specific TTL exists.
// Default: 1h.
DefaultBanTTL time.Duration
// AdaptiveBan enables background adaptive banning.
AdaptiveBan AdaptiveBanConfig
// KeyFunc defines rate-limit key. Default: IP.
KeyFunc func(r *http.Request) string
// IPFunc extracts the client IP for ban keys and default KeyFunc.
// Default: RemoteAddr host part.
IPFunc func(r *http.Request) string
// Metrics is optional. If nil, metrics are no-ops.
Metrics Metrics
// Stats is optional generic telemetry collector.
// If nil, telemetry calls are dropped.
Stats StatsCollector
// OnError is optional error callback (Redis/Lua/background).
OnError func(err error)
// DenyStatusCode is used by middleware adapters when request is blocked.
// Default: 429.
DenyStatusCode int
// Bloom enables optional in-memory bloom filter short-circuit.
// If enabled and IP is definitely not blacklisted (negative bloom test),
// request is allowed without Redis roundtrip.
Bloom BloomConfig
// Tracing enables OpenTelemetry spans for request processing.
Tracing TracingConfig
// SelfHealing dynamically adjusts effective request limits based on behavior.
SelfHealing SelfHealingConfig
// RulesetFile points to JSON/YAML signatures loaded at startup.
RulesetFile string
// DynamicRules allows hot-swapping signatures without recreating Engine.
DynamicRules *RulesetManager
// CompiledRules allows direct in-memory ruleset wiring (no file required).
CompiledRules *CompiledRuleset
// AutoReloadOnSIGHUP enables ruleset hot reload on POSIX SIGHUP signal.
// Applicable when RulesetFile or DynamicRules is configured.
AutoReloadOnSIGHUP bool
// Behavioral enables risk scoring and penalty-box flow.
Behavioral BehavioralConfig
// Reputation controls score pipeline and dynamic backoff bans.
Reputation ReputationConfig
}
func DefaultConfig ¶
func DefaultConfig() MiddlewareConfig
DefaultConfig returns a ready-to-use configuration with sane defaults.
func NewConfigFromRedisAddr ¶
func NewConfigFromRedisAddr(redisAddr string, maxRequests int, window time.Duration) MiddlewareConfig
NewConfigFromRedisAddr creates minimal config from Redis address.
type NopMetrics ¶
type NopMetrics struct{}
func (NopMetrics) IncAllowed ¶
func (NopMetrics) IncAllowed()
func (NopMetrics) IncBlacklisted ¶
func (NopMetrics) IncBlacklisted()
func (NopMetrics) IncRateLimited ¶
func (NopMetrics) IncRateLimited()
func (NopMetrics) IncRedisErrors ¶
func (NopMetrics) IncRedisErrors()
func (NopMetrics) ObserveLuaLatency ¶
func (NopMetrics) ObserveLuaLatency(d time.Duration)
type NopStatsCollector ¶
type NopStatsCollector struct{}
type ReputationConfig ¶
type ReputationConfig struct {
Enabled bool
// WarningLevel moves actor into penalty box.
WarningLevel float64
// Threshold triggers blacklist via reputation Lua script.
Threshold float64
// ScoreWindow controls reputation hash TTL.
ScoreWindow time.Duration
// PenaltyTTL is strict-mode duration.
PenaltyTTL time.Duration
// BackoffWindow controls how long attack attempt counter lives.
BackoffWindow time.Duration
// BanLevel1 is ban duration for first serious attack.
BanLevel1 time.Duration
// BanLevel2 is ban duration for second serious attack.
BanLevel2 time.Duration
// BanLevel3 is ban duration for third and next attack.
BanLevel3 time.Duration
}
type Rule ¶
Rule evaluates a request and returns an integer threat weight. Higher values represent higher confidence/more dangerous patterns.
Rules MUST NOT read or depend on r.Body. They may read URL, Method, Host and headers.
type RulesetManager ¶
type RulesetManager struct {
// contains filtered or unexported fields
}
func NewRulesetManager ¶
func NewRulesetManager(path string) (*RulesetManager, error)
func (*RulesetManager) Current ¶
func (m *RulesetManager) Current() *CompiledRuleset
func (*RulesetManager) Reload ¶
func (m *RulesetManager) Reload() error
func (*RulesetManager) ReloadOnSignal ¶
type RulesetStats ¶
type SelfHealingConfig ¶
type SelfHealingConfig struct {
Enabled bool
// Window is a rolling analysis period.
Window time.Duration
// MinSamples controls the minimum traffic volume before adaptation.
MinSamples int
// CleanTrafficThreshold is the minimum clean ratio to activate spike detection.
CleanTrafficThreshold float64
// SpikeFactor triggers stricter limits when a single IP exceeds max*SpikeFactor.
SpikeFactor float64
// MaxSensitivity is upper bound of adaptive multiplier.
MaxSensitivity float64
// DecayStep controls how quickly sensitivity returns to normal per window.
DecayStep float64
}
type SignatureRule ¶
type SignatureRule struct {
Name string `json:"name" yaml:"name"`
Match MatchTarget `json:"match" yaml:"match"`
Pattern string `json:"pattern" yaml:"pattern"`
Weight int64 `json:"weight" yaml:"weight"`
CountThreshold int `json:"count_threshold" yaml:"count_threshold"`
}
type StatsCollector ¶
StatsCollector is a vendor-neutral contract for custom telemetry export. Implement this interface to forward metrics to Prometheus, Datadog, OTEL, etc.
type TracingConfig ¶
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
adapters
|
|
|
cmd
|
|
|
guardgo-agent
command
|
|
|
guardgo-cli
command
|
|
|
examples
|
|
|
gin-basic
command
|
|
|
nethttp-basic
command
|
|
|
presets-basic
command
|
|
|
internal
|
|
|
pkg
|
|