feat: add CORS and rate limiting middleware

CORS:
- Configurable allowed origins (wildcard "*" or specific domains)
- Handles OPTIONS preflight with configurable methods, headers, max-age
- Exposed headers support for browser API access
- Env override: CORS_ALLOWED_ORIGINS

Rate Limiting:
- In-memory per-IP sliding window counter
- Configurable request limit and time window
- Background goroutine cleans up stale IP entries
- HTTP 429 with Retry-After header when exceeded
- Extracts real IP from X-Forwarded-For and X-Real-IP (proxy-aware)
- Env overrides: RATE_LIMIT_REQUESTS, RATE_LIMIT_WINDOW, RATE_LIMIT_CLEANUP_INTERVAL
- Set requests=0 in config to disable

Both wired into main.go as middleware chain: rate_limit → cors → handler.
Config example updated with [cors] and [rate_limit] sections.
Full test coverage for both middleware packages.
This commit is contained in:
Franz Kafka 2026-03-21 15:54:52 +00:00
parent 4c54ed5b56
commit ebeaeeef21
8 changed files with 616 additions and 6 deletions

View file

@ -11,10 +11,12 @@ import (
// Config is the top-level configuration for the gosearch service.
type Config struct {
Server ServerConfig `toml:"server"`
Upstream UpstreamConfig `toml:"upstream"`
Engines EnginesConfig `toml:"engines"`
Cache CacheConfig `toml:"cache"`
Server ServerConfig `toml:"server"`
Upstream UpstreamConfig `toml:"upstream"`
Engines EnginesConfig `toml:"engines"`
Cache CacheConfig `toml:"cache"`
CORS CORSConfig `toml:"cors"`
RateLimit RateLimitConfig `toml:"rate_limit"`
}
type ServerConfig struct {
@ -40,6 +42,22 @@ type CacheConfig struct {
DefaultTTL string `toml:"default_ttl"` // Cache TTL (e.g. "5m", default "5m")
}
// CORSConfig holds CORS middleware settings.
type CORSConfig struct {
AllowedOrigins []string `toml:"allowed_origins"`
AllowedMethods []string `toml:"allowed_methods"`
AllowedHeaders []string `toml:"allowed_headers"`
ExposedHeaders []string `toml:"exposed_headers"`
MaxAge int `toml:"max_age"`
}
// RateLimitConfig holds per-IP rate limiting settings.
type RateLimitConfig struct {
Requests int `toml:"requests"` // Max requests per window (default: 30)
Window string `toml:"window"` // Time window (e.g. "1m", default: "1m")
CleanupInterval string `toml:"cleanup_interval"` // Stale entry cleanup interval (default: "5m")
}
type BraveConfig struct {
APIKey string `toml:"api_key"`
AccessToken string `toml:"access_token"`
@ -84,6 +102,10 @@ func defaultConfig() *Config {
DB: 0,
DefaultTTL: "5m",
},
RateLimit: RateLimitConfig{
Window: "1m",
CleanupInterval: "5m",
},
}
}
@ -124,6 +146,18 @@ func applyEnvOverrides(cfg *Config) {
if v := os.Getenv("VALKEY_CACHE_TTL"); v != "" {
cfg.Cache.DefaultTTL = v
}
if v := os.Getenv("CORS_ALLOWED_ORIGINS"); v != "" {
cfg.CORS.AllowedOrigins = splitCSV(v)
}
if v := os.Getenv("RATE_LIMIT_REQUESTS"); v != "" {
fmt.Sscanf(v, "%d", &cfg.RateLimit.Requests)
}
if v := os.Getenv("RATE_LIMIT_WINDOW"); v != "" {
cfg.RateLimit.Window = v
}
if v := os.Getenv("RATE_LIMIT_CLEANUP_INTERVAL"); v != "" {
cfg.RateLimit.CleanupInterval = v
}
}
// HTTPTimeout parses the configured timeout string into a time.Duration.
@ -147,6 +181,22 @@ func (c *Config) CacheTTL() time.Duration {
return 5 * time.Minute
}
// RateLimitWindow parses the rate limit window into a time.Duration.
func (c *Config) RateLimitWindow() time.Duration {
if d, err := time.ParseDuration(c.RateLimit.Window); err == nil && d > 0 {
return d
}
return time.Minute
}
// RateLimitCleanupInterval parses the cleanup interval into a time.Duration.
func (c *Config) RateLimitCleanupInterval() time.Duration {
if d, err := time.ParseDuration(c.RateLimit.CleanupInterval); err == nil && d > 0 {
return d
}
return 5 * time.Minute
}
func splitCSV(s string) []string {
if s == "" {
return nil