269 lines
7.6 KiB
Markdown
269 lines
7.6 KiB
Markdown
# Subtask: Rate Limiting for Abuse Prevention
|
|
|
|
**Parent Task**: Decomp/001
|
|
**Subtask ID**: Decomp/001-10
|
|
**Dependencies**: Decomp/001-04 (Redirect Endpoint), Decomp/001-06 (Caching Layer)
|
|
|
|
## Description
|
|
|
|
Implement rate limiting to prevent abuse of the URL shortening service. Protect against URL creation spam, excessive redirect requests, and potential DoS attacks. Use token bucket or sliding window algorithm with Redis backend.
|
|
|
|
## Requirements
|
|
|
|
- Rate limit URL creation endpoint (e.g., 10 requests/minute)
|
|
- Rate limit redirect endpoint (e.g., 100 requests/second per IP)
|
|
- Rate limit analytics API (e.g., 60 requests/minute)
|
|
- Configurable limits per endpoint
|
|
- IP-based and API-key-based limiting
|
|
- Return standard rate limit headers (RateLimit-* headers)
|
|
- Sliding window algorithm for accurate limiting
|
|
- Whitelist for trusted IPs/API keys
|
|
|
|
## Technical Specifications
|
|
|
|
**Rate limiting algorithm**: Sliding Window Log (accurate, memory-efficient)
|
|
|
|
**Redis data structure**:
|
|
```
|
|
# Key format: ratelimit:{endpoint}:{identifier}
|
|
# Value: sorted set of timestamps
|
|
# Score: timestamp of request
|
|
# Member: unique request ID (UUID)
|
|
|
|
ZADD ratelimit:create:192.168.1.1 <timestamp> <request_id>
|
|
ZREMRANGEBYSCORE ratelimit:create:192.168.1.1 0 <now - window>
|
|
ZCARD ratelimit:create:192.168.1.1
|
|
```
|
|
|
|
**Rate limiter implementation**:
|
|
```python
|
|
import time
|
|
import uuid
|
|
from typing import Optional, Tuple
|
|
|
|
class RateLimiter:
|
|
"""
|
|
Sliding window rate limiter using Redis.
|
|
|
|
Window: time interval in seconds
|
|
Limit: max requests allowed within window
|
|
"""
|
|
|
|
def __init__(self, redis_client):
|
|
self.redis = redis_client
|
|
|
|
def is_allowed(
|
|
self,
|
|
key: str,
|
|
limit: int,
|
|
window: int
|
|
) -> Tuple[bool, dict]:
|
|
"""
|
|
Check if request is allowed under rate limit.
|
|
|
|
Args:
|
|
key: Unique identifier (e.g., "create:192.168.1.1")
|
|
limit: Max requests per window
|
|
window: Time window in seconds
|
|
|
|
Returns:
|
|
(allowed, meta) where meta contains:
|
|
- remaining: requests left in window
|
|
- reset_at: unix timestamp when limit resets
|
|
- retry_after: seconds to wait if not allowed
|
|
"""
|
|
now = time.time()
|
|
window_start = now - window
|
|
request_id = str(uuid.uuid4())
|
|
|
|
pipe = self.redis.pipeline()
|
|
|
|
# Remove old entries outside the window
|
|
pipe.zremrangebyscore(key, 0, window_start)
|
|
|
|
# Count current requests in window
|
|
pipe.zcard(key)
|
|
|
|
# Add this request
|
|
pipe.zadd(key, {request_id: now})
|
|
|
|
# Set expiry on the key (cleanup)
|
|
pipe.expire(key, window + 1)
|
|
|
|
results = pipe.execute()
|
|
current_count = results[1]
|
|
|
|
allowed = current_count < limit
|
|
remaining = max(0, limit - current_count - 1)
|
|
reset_at = int(now + window)
|
|
retry_after = int(window - (now % window)) if not allowed else 0
|
|
|
|
return allowed, {
|
|
'limit': limit,
|
|
'remaining': remaining,
|
|
'reset': reset_at,
|
|
'retry_after': retry_after
|
|
}
|
|
|
|
def get_key(self, endpoint: str, identifier: str) -> str:
|
|
"""Generate Redis key for rate limiting."""
|
|
return f"ratelimit:{endpoint}:{identifier}"
|
|
```
|
|
|
|
**Rate limit configuration**:
|
|
```python
|
|
RATE_LIMITS = {
|
|
# URL creation: strict to prevent spam
|
|
'create_url': {
|
|
'limit': 10,
|
|
'window': 60, # per minute
|
|
'burst': 5 # allow burst
|
|
},
|
|
|
|
# Redirects: generous per IP
|
|
'redirect': {
|
|
'limit': 100,
|
|
'window': 1, # per second
|
|
'burst': 20
|
|
},
|
|
|
|
# Analytics API
|
|
'analytics': {
|
|
'limit': 60,
|
|
'window': 60, # per minute
|
|
'burst': 10
|
|
},
|
|
|
|
# QR code generation
|
|
'qr_code': {
|
|
'limit': 30,
|
|
'window': 60, # per minute
|
|
'burst': 5
|
|
}
|
|
}
|
|
|
|
# Higher limits for authenticated users
|
|
AUTHENTICATED_MULTIPLIER = 10
|
|
```
|
|
|
|
**Middleware decorator**:
|
|
```python
|
|
from functools import wraps
|
|
from flask import request, jsonify
|
|
|
|
def rate_limit(endpoint: str):
|
|
"""
|
|
Decorator to apply rate limiting to an endpoint.
|
|
|
|
Returns 429 Too Many Requests if limit exceeded.
|
|
"""
|
|
def decorator(f):
|
|
@wraps(f)
|
|
def wrapped(*args, **kwargs):
|
|
# Get identifier (IP or API key)
|
|
identifier = get_rate_limit_identifier(request)
|
|
config = RATE_LIMITS[endpoint]
|
|
|
|
# Check if whitelisted
|
|
if is_whitelisted(identifier):
|
|
return f(*args, **kwargs)
|
|
|
|
# Check rate limit
|
|
limiter = RateLimiter(get_redis())
|
|
key = limiter.get_key(endpoint, identifier)
|
|
allowed, meta = limiter.is_allowed(
|
|
key,
|
|
config['limit'],
|
|
config['window']
|
|
)
|
|
|
|
# Set rate limit headers
|
|
set_rate_limit_headers(meta)
|
|
|
|
if not allowed:
|
|
response = jsonify({
|
|
'error': 'Rate limit exceeded',
|
|
'retry_after': meta['retry_after']
|
|
})
|
|
response.status_code = 429
|
|
response.headers['Retry-After'] = str(meta['retry_after'])
|
|
return response
|
|
|
|
return f(*args, **kwargs)
|
|
|
|
return wrapped
|
|
return decorator
|
|
|
|
def get_rate_limit_identifier(request) -> str:
|
|
"""Extract identifier for rate limiting."""
|
|
# Prefer API key over IP
|
|
api_key = request.headers.get('X-API-Key')
|
|
if api_key:
|
|
return f"apikey:{api_key}"
|
|
|
|
# Fallback to IP address
|
|
ip = request.headers.get('X-Forwarded-For', request.remote_addr)
|
|
return f"ip:{ip}"
|
|
|
|
def set_rate_limit_headers(meta: dict):
|
|
"""Set standard rate limit HTTP headers."""
|
|
flask.response.headers['X-RateLimit-Limit'] = str(meta['limit'])
|
|
flask.response.headers['X-RateLimit-Remaining'] = str(meta['remaining'])
|
|
flask.response.headers['X-RateLimit-Reset'] = str(meta['reset'])
|
|
```
|
|
|
|
**Apply to endpoints**:
|
|
```python
|
|
@app.route('/api/shorten', methods=['POST'])
|
|
@rate_limit('create_url')
|
|
def create_short_url():
|
|
...
|
|
|
|
@app.route('/<short_code>')
|
|
@rate_limit('redirect')
|
|
def redirect(short_code: str):
|
|
...
|
|
|
|
@app.route('/api/stats/<short_code>')
|
|
@rate_limit('analytics')
|
|
def get_stats(short_code: str):
|
|
...
|
|
```
|
|
|
|
## Acceptance Criteria
|
|
|
|
- [ ] Rate limit enforced on URL creation (10/min)
|
|
- [ ] Rate limit enforced on redirects (100/sec per IP)
|
|
- [ ] 429 response with Retry-After header when exceeded
|
|
- [ ] Rate limit headers present on all responses
|
|
- [ ] Sliding window accurately counts requests
|
|
- [ ] Whitelist bypasses rate limiting
|
|
- [ ] API keys get higher limits than anonymous IPs
|
|
|
|
## Notes
|
|
|
|
**Trade-offs**:
|
|
- Token bucket vs sliding window: Sliding window chosen for accuracy
|
|
- Redis vs in-memory: Redis required for distributed systems
|
|
- Per-IP vs per-user: Per-IP simpler, per-user requires authentication
|
|
|
|
**Edge cases**:
|
|
- Multiple users behind NAT: counted as one (acceptable)
|
|
- IPv6 addresses: normalize to /64 or /48 prefix
|
|
- Distributed systems: Redis must be shared across instances
|
|
|
|
**Performance**:
|
|
- Redis operations: O(log N) for ZADD, O(M) for ZREMRANGEBYSCORE
|
|
- Expected latency: <5ms per rate limit check
|
|
- Connection pooling required for high throughput
|
|
|
|
**Security considerations**:
|
|
- Rate limit bypass attempts: check X-Forwarded-For chain
|
|
- DDoS protection: rate limiting is first line, not only defense
|
|
- API key exposure: don't log keys, use hash for identification
|
|
|
|
**Alternatives considered**:
|
|
- Fixed window: rejected, allows double requests at window boundary
|
|
- Token bucket: rejected, requires more state, sliding window sufficient
|
|
- Local-only limiting: rejected, doesn't work in distributed setup
|