fix(rate-limit): add NORA_RATE_LIMIT_ENABLED flag and SmartIpKeyExtractor

- Add enabled field to RateLimitConfig (default: true, env: NORA_RATE_LIMIT_ENABLED)
- Skip rate limiter layers entirely when disabled
- Replace PeerIpKeyExtractor with SmartIpKeyExtractor for upload/general routes
  to correctly identify clients behind reverse proxies and Docker bridge networks
- Keep PeerIpKeyExtractor for auth routes (stricter brute-force protection)

Root cause: PeerIpKeyExtractor saw all Docker bridge traffic as single IP (172.17.0.1),
exhausting GCRA bucket for all clients simultaneously. With burst=1M, recovery time
reached 84000+ seconds.
This commit is contained in:
2026-03-03 08:51:33 +00:00
parent fb0f80ac5a
commit 7f8e3cfe68
4 changed files with 57 additions and 36 deletions

View File

@@ -10,6 +10,7 @@
use crate::config::RateLimitConfig;
use tower_governor::governor::GovernorConfigBuilder;
use tower_governor::key_extractor::SmartIpKeyExtractor;
/// Create rate limiter layer for auth endpoints (strict protection against brute-force)
pub fn auth_rate_limiter(
@@ -35,11 +36,12 @@ pub fn auth_rate_limiter(
pub fn upload_rate_limiter(
config: &RateLimitConfig,
) -> tower_governor::GovernorLayer<
tower_governor::key_extractor::PeerIpKeyExtractor,
SmartIpKeyExtractor,
governor::middleware::StateInformationMiddleware,
axum::body::Body,
> {
let gov_config = GovernorConfigBuilder::default()
.key_extractor(SmartIpKeyExtractor)
.per_second(config.upload_rps)
.burst_size(config.upload_burst)
.use_headers()
@@ -53,11 +55,12 @@ pub fn upload_rate_limiter(
pub fn general_rate_limiter(
config: &RateLimitConfig,
) -> tower_governor::GovernorLayer<
tower_governor::key_extractor::PeerIpKeyExtractor,
SmartIpKeyExtractor,
governor::middleware::StateInformationMiddleware,
axum::body::Body,
> {
let gov_config = GovernorConfigBuilder::default()
.key_extractor(SmartIpKeyExtractor)
.per_second(config.general_rps)
.burst_size(config.general_burst)
.use_headers()
@@ -102,6 +105,7 @@ mod tests {
#[test]
fn test_custom_config() {
let config = RateLimitConfig {
enabled: true,
auth_rps: 10,
auth_burst: 20,
upload_rps: 500,