# SEC-2: Rate Limiting - Implementation Notes

**Status:** Partially Implemented - Needs Type Resolution
**Priority:** HIGH
**Blocker:** Compilation errors with tower_governor type signatures

## What Was Done

1. Added tower_governor dependency to Cargo.toml
2. Created middleware/rate_limit.rs module
3. Defined three rate limiters:
   - `auth_rate_limiter()` - 5 requests/minute for login
   - `support_code_rate_limiter()` - 10 requests/minute for code validation
   - `api_rate_limiter()` - 60 requests/minute for general API
4. Applied rate limiting to routes in main.rs:
   - `/api/auth/login`
   - `/api/auth/change-password`
   - `/api/codes/:code/validate`

## Current Blocker

Tower_governor GovernorLayer requires 2 generic type parameters, but the exact types are complex:
- Key extractor: SmartIpKeyExtractor
- Rate limiter method: (type unclear from docs)

## Attempted Solutions

1. Used default types - Failed (DefaultDirectRateLimiter doesn't exist)
2. Used impl Trait - Too complex, nested trait bounds
3. Added "axum" feature to tower_governor - Still type errors

## Next Steps to Complete

1. Research tower_governor v0.4 examples for Axum 0.7
2. OR: Use simpler alternative like tower-http RequestBodyLimitLayer
3. OR: Implement custom rate limiting with Redis/in-memory cache
4. Test with actual HTTP requests (curl, Postman)
5. Add rate limit headers (X-RateLimit-Remaining, X-RateLimit-Reset)

## Recommended Approach

**Option A: Fix tower_governor types** (1-2 hours)
- Find working example for tower_governor + Axum 0.7
- Copy exact type signatures
- Test compilation

**Option B: Switch to custom middleware** (2-3 hours)
- Use in-memory HashMap<IP, (count, last_reset)>
- Implement middleware manually
- More control, simpler types

**Option C: Use Redis for rate limiting** (3-4 hours)
- Add redis dependency
- Implement with atomic INCR + EXPIRE
- Production-grade, distributed-ready

## Temporary Mitigation

Until rate limiting is fully operational:
- Monitor auth endpoint logs for brute force attempts
- Consider firewall-level rate limiting (fail2ban, NPM)
- Enable account lockout after N failed attempts (add to user table)

## Files Modified

- `server/Cargo.toml` - Added tower_governor dependency
- `server/src/middleware/rate_limit.rs` - Rate limiter definitions (NOT compiling)
- `server/src/middleware/mod.rs` - Module exports
- `server/src/main.rs` - Applied rate limiting to routes (commented out for now)

---

**Created:** 2026-01-17
**Next Action:** Move to SEC-3 (SQL Injection) - Higher priority
