api

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2025 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package api provides API protection mechanisms for the LLMrecon tool.

Package api provides API protection mechanisms for the LLMrecon tool.

Package api provides API protection mechanisms for the LLMrecon tool.

Package api provides API protection mechanisms for the LLMrecon tool.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Anomaly

type Anomaly struct {
	// Type is the type of anomaly
	Type AnomalyType `json:"type"`
	// Level is the severity level of the anomaly
	Level AnomalyLevel `json:"level"`
	// Description is a description of the anomaly
	Description string `json:"description"`
	// Timestamp is the time the anomaly was detected
	Timestamp time.Time `json:"timestamp"`
	// ClientIP is the client IP associated with the anomaly
	ClientIP string `json:"client_ip,omitempty"`
	// Path is the request path associated with the anomaly
	Path string `json:"path,omitempty"`
	// Method is the HTTP method associated with the anomaly
	Method string `json:"method,omitempty"`
	// UserAgent is the user agent associated with the anomaly
	UserAgent string `json:"user_agent,omitempty"`
	// RequestID is the request ID associated with the anomaly
	RequestID string `json:"request_id,omitempty"`
	// Count is the count associated with the anomaly
	Count int `json:"count,omitempty"`
	// Threshold is the threshold that was exceeded
	Threshold int `json:"threshold,omitempty"`
	// Duration is the duration associated with the anomaly
	Duration time.Duration `json:"duration,omitempty"`
}

Anomaly represents a detected anomaly

type AnomalyDetector

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

AnomalyDetector implements anomaly detection for API requests

func NewAnomalyDetector

func NewAnomalyDetector(config *AnomalyDetectorConfig) *AnomalyDetector

NewAnomalyDetector creates a new anomaly detector

func (*AnomalyDetector) ClearAnomalies

func (ad *AnomalyDetector) ClearAnomalies()

ClearAnomalies clears the list of detected anomalies

func (*AnomalyDetector) Close

func (ad *AnomalyDetector) Close()

Close stops the anomaly detector

func (*AnomalyDetector) GetAnomalies

func (ad *AnomalyDetector) GetAnomalies() []*Anomaly

GetAnomalies returns the list of detected anomalies

func (*AnomalyDetector) Middleware

func (ad *AnomalyDetector) Middleware(next http.Handler) http.Handler

Middleware returns a middleware function for anomaly detection

func (*AnomalyDetector) RecordRequest

func (ad *AnomalyDetector) RecordRequest(r *http.Request)

RecordRequest records a request for anomaly detection

type AnomalyDetectorConfig

type AnomalyDetectorConfig struct {
	// Enabled indicates whether anomaly detection is enabled
	Enabled bool
	// WindowSize is the size of the sliding window for rate calculations
	WindowSize time.Duration
	// RateSpikeThreshold is the threshold for rate spikes
	RateSpikeThreshold int
	// UnusualPathThreshold is the threshold for unusual paths
	UnusualPathThreshold int
	// UnusualMethodThreshold is the threshold for unusual methods
	UnusualMethodThreshold int
	// UnusualUserAgentThreshold is the threshold for unusual user agents
	UnusualUserAgentThreshold int
	// UnusualIPThreshold is the threshold for unusual IPs
	UnusualIPThreshold int
	// UnusualPatternThreshold is the threshold for unusual patterns
	UnusualPatternThreshold int
	// LearningMode indicates whether the detector is in learning mode
	LearningMode bool
	// LearningPeriod is the learning period
	LearningPeriod time.Duration
	// AlertCallback is a callback function for anomaly alerts
	AlertCallback func(anomaly *Anomaly)
}

AnomalyDetectorConfig represents the configuration for an anomaly detector

func DefaultAnomalyDetectorConfig

func DefaultAnomalyDetectorConfig() *AnomalyDetectorConfig

DefaultAnomalyDetectorConfig returns the default anomaly detector configuration

type AnomalyLevel

type AnomalyLevel int

AnomalyLevel represents the severity level of an anomaly

const (
	// AnomalyLevelInfo is for informational anomalies
	AnomalyLevelInfo AnomalyLevel = iota
	// AnomalyLevelWarning is for warning anomalies
	AnomalyLevelWarning
	// AnomalyLevelAlert is for alert anomalies
	AnomalyLevelAlert
	// AnomalyLevelCritical is for critical anomalies
	AnomalyLevelCritical
)

type AnomalyType

type AnomalyType string

AnomalyType represents the type of anomaly

const (
	// AnomalyTypeRateSpike represents a sudden spike in request rate
	AnomalyTypeRateSpike AnomalyType = "rate_spike"
	// AnomalyTypeUnusualPath represents access to unusual paths
	AnomalyTypeUnusualPath AnomalyType = "unusual_path"
	// AnomalyTypeUnusualMethod represents use of unusual HTTP methods
	AnomalyTypeUnusualMethod AnomalyType = "unusual_method"
	// AnomalyTypeUnusualUserAgent represents use of unusual user agents
	AnomalyTypeUnusualUserAgent AnomalyType = "unusual_user_agent"
	// AnomalyTypeUnusualIP represents access from unusual IPs
	AnomalyTypeUnusualIP AnomalyType = "unusual_ip"
	// AnomalyTypeUnusualPattern represents unusual access patterns
	AnomalyTypeUnusualPattern AnomalyType = "unusual_pattern"
)

type IPAllowlist

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

IPAllowlist implements IP allowlisting for API requests

func NewIPAllowlist

func NewIPAllowlist(config *IPAllowlistConfig) (*IPAllowlist, error)

NewIPAllowlist creates a new IP allowlist

func (*IPAllowlist) AddIP

func (al *IPAllowlist) AddIP(ip string) error

AddIP adds an IP to the allowlist

func (*IPAllowlist) GetClientIP

func (al *IPAllowlist) GetClientIP(r *http.Request) string

GetClientIP gets the client IP from a request

func (*IPAllowlist) IsAllowed

func (al *IPAllowlist) IsAllowed(ip string) bool

IsAllowed checks if an IP is allowed

func (*IPAllowlist) IsEnabled

func (al *IPAllowlist) IsEnabled() bool

IsEnabled returns whether the allowlist is enabled

func (*IPAllowlist) IsExempt

func (al *IPAllowlist) IsExempt(path string) bool

IsExempt checks if a path is exempt from IP allowlisting

func (*IPAllowlist) Middleware

func (al *IPAllowlist) Middleware(next http.Handler) http.Handler

Middleware returns a middleware function for IP allowlisting

func (*IPAllowlist) RemoveIP

func (al *IPAllowlist) RemoveIP(ip string)

RemoveIP removes an IP from the allowlist

func (*IPAllowlist) SaveToFile

func (al *IPAllowlist) SaveToFile() error

SaveToFile saves the allowlist to a file

func (*IPAllowlist) SetEnabled

func (al *IPAllowlist) SetEnabled(enabled bool)

SetEnabled sets whether the allowlist is enabled

type IPAllowlistConfig

type IPAllowlistConfig struct {
	// Enabled indicates whether the allowlist is enabled
	Enabled bool
	// AllowedIPs is a list of allowed IPs
	AllowedIPs []string
	// AllowedCIDRs is a list of allowed CIDR blocks
	AllowedCIDRs []string
	// IPHeaderName is the name of the header containing the client IP
	IPHeaderName string
	// TrustedProxies is a list of trusted proxy IPs
	TrustedProxies []string
	// ConfigFile is the path to the allowlist configuration file
	ConfigFile string
	// ExemptPaths is a list of paths exempt from IP allowlisting
	ExemptPaths []string
}

IPAllowlistConfig represents the configuration for an IP allowlist

func DefaultIPAllowlistConfig

func DefaultIPAllowlistConfig() *IPAllowlistConfig

DefaultIPAllowlistConfig returns the default IP allowlist configuration

type LogEntry

type LogEntry struct {
	// Timestamp is the time of the log entry
	Timestamp time.Time `json:"timestamp"`
	// Level is the log level
	Level LogLevel `json:"level"`
	// RequestID is the ID of the request
	RequestID string `json:"request_id,omitempty"`
	// Method is the HTTP method
	Method string `json:"method,omitempty"`
	// Path is the request path
	Path string `json:"path,omitempty"`
	// ClientIP is the client IP
	ClientIP string `json:"client_ip,omitempty"`
	// StatusCode is the response status code
	StatusCode int `json:"status_code,omitempty"`
	// Duration is the request duration in milliseconds
	Duration int64 `json:"duration,omitempty"`
	// Headers are the request or response headers
	Headers map[string]string `json:"headers,omitempty"`
	// Body is the request or response body
	Body string `json:"body,omitempty"`
	// Error is an error message
	Error string `json:"error,omitempty"`
	// Message is a log message
	Message string `json:"message,omitempty"`
}

LogEntry represents a log entry

type LogLevel

type LogLevel int

LogLevel represents the level of logging

const (
	// LogLevelDebug is for debug logs
	LogLevelDebug LogLevel = iota
	// LogLevelInfo is for informational logs
	LogLevelInfo
	// LogLevelWarning is for warning logs
	LogLevelWarning
	// LogLevelError is for error logs
	LogLevelError
)

type RateLimiter

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

RateLimiter implements rate limiting for API requests

func NewRateLimiter

func NewRateLimiter(config *RateLimiterConfig) *RateLimiter

NewRateLimiter creates a new rate limiter

func (*RateLimiter) CleanupLimiters

func (rl *RateLimiter) CleanupLimiters(maxAge time.Duration)

CleanupLimiters removes expired limiters

func (*RateLimiter) GetClientIP

func (rl *RateLimiter) GetClientIP(r *http.Request) string

GetClientIP gets the client IP from a request

func (*RateLimiter) GetLimiter

func (rl *RateLimiter) GetLimiter(clientIP string) *rate.Limiter

GetLimiter gets a rate limiter for a client

func (*RateLimiter) GetStatistics

func (rl *RateLimiter) GetStatistics() *RateLimiterStats

GetStatistics returns statistics about the rate limiter

func (*RateLimiter) IsExempt

func (rl *RateLimiter) IsExempt(clientIP string, path string) bool

IsExempt checks if a client is exempt from rate limiting

func (*RateLimiter) Middleware

func (rl *RateLimiter) Middleware(next http.Handler) http.Handler

Middleware returns a middleware function for rate limiting

type RateLimiterConfig

type RateLimiterConfig struct {
	// RequestsPerMinute is the maximum number of requests per minute
	RequestsPerMinute int
	// BurstSize is the maximum burst size
	BurstSize int
	// IPHeaderName is the name of the header containing the client IP
	IPHeaderName string
	// TrustedProxies is a list of trusted proxy IPs
	TrustedProxies []string
	// ExemptIPs is a list of IPs exempt from rate limiting
	ExemptIPs []string
	// ExemptPaths is a list of paths exempt from rate limiting
	ExemptPaths []string
}

RateLimiterConfig represents the configuration for a rate limiter

func DefaultRateLimiterConfig

func DefaultRateLimiterConfig() *RateLimiterConfig

DefaultRateLimiterConfig returns the default rate limiter configuration

type RateLimiterStats

type RateLimiterStats struct {
	// ActiveLimiters is the number of active rate limiters
	ActiveLimiters int `json:"active_limiters"`
	// RequestsPerMinute is the configured requests per minute
	RequestsPerMinute int `json:"requests_per_minute"`
	// BurstSize is the configured burst size
	BurstSize int `json:"burst_size"`
	// ExemptPathsCount is the number of exempt paths
	ExemptPathsCount int `json:"exempt_paths_count"`
	// ExemptIPsCount is the number of exempt IPs
	ExemptIPsCount int `json:"exempt_ips_count"`
}

RateLimiterStats represents statistics about the rate limiter

type SecureLogger

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

SecureLogger implements secure logging for API requests and responses

func NewSecureLogger

func NewSecureLogger(config *SecureLoggerConfig) (*SecureLogger, error)

NewSecureLogger creates a new secure logger

func (*SecureLogger) Log

func (sl *SecureLogger) Log(level LogLevel, requestID string, message string, err error)

Log logs a message

func (*SecureLogger) Middleware

func (sl *SecureLogger) Middleware(next http.Handler) http.Handler

Middleware returns a middleware function for secure logging

type SecureLoggerConfig

type SecureLoggerConfig struct {
	// Level is the minimum log level to record
	Level LogLevel
	// LogRequests indicates whether to log requests
	LogRequests bool
	// LogResponses indicates whether to log responses
	LogResponses bool
	// LogHeaders indicates whether to log headers
	LogHeaders bool
	// LogBodies indicates whether to log request and response bodies
	LogBodies bool
	// MaxBodySize is the maximum size of a body to log
	MaxBodySize int
	// SensitiveHeaders is a list of headers that contain sensitive information
	SensitiveHeaders []string
	// SensitiveFields is a list of JSON fields that contain sensitive information
	SensitiveFields []string
	// SensitivePatterns is a list of regex patterns for sensitive information
	SensitivePatterns []string
	// RedactionString is the string to use for redaction
	RedactionString string
	// OutputWriter is the writer to use for log output
	OutputWriter io.Writer
}

SecureLoggerConfig represents the configuration for a secure logger

func DefaultSecureLoggerConfig

func DefaultSecureLoggerConfig() *SecureLoggerConfig

DefaultSecureLoggerConfig returns the default secure logger configuration

Jump to

Keyboard shortcuts

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