Sub topic 14
Preventing abuse: rate limits, validation, and enumeration
This chapter assumes you know basic HTTP status codes and headers, and that you have read the chapters on the API design and short code generation. A URL shortener is open to the public and redirects browsers to arbitrary destinations. That makes it attractive to spammers, phishers, and scrapers. Three controls cover most of the risk: rate limiting, input validation, and protection against code enumeration.
Why shorteners attract abuse
A short link hides its destination. Attackers use that to send people to phishing pages or malware. They also create millions of links to exhaust storage, or guess codes to read other people's links. Your service's domain reputation suffers when spam links circulate, and mail providers may start blocking it.
Rate limiting
A rate limit caps how many requests a client can make in a time window. Limit the write path (POST /links) much more tightly than the read path, because reads are cheap and cached while writes consume storage and code space.
A common approach is a token bucket. Each client has a bucket that holds up to N tokens. Each request removes one token, and tokens refill at a steady rate. A client can burst up to N requests, then is held to the refill rate.
import time
class TokenBucket:
def __init__(self, capacity: int, refill_per_sec: float):
self.capacity = capacity
self.refill_per_sec = refill_per_sec
self.tokens = float(capacity)
self.updated = time.monotonic()
def allow(self) -> bool:
now = time.monotonic()
elapsed = now - self.updated
self.updated = now
self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_per_sec)
if self.tokens >= 1:
self.tokens -= 1
return True
return False
bucket = TokenBucket(capacity=10, refill_per_sec=0.5)
print([bucket.allow() for _ in range(12)])The first ten calls return True, and the last two return False. When a request is denied, respond with 429 Too Many Requests and a Retry-After header.
In production, the bucket lives in a shared store such as Redis, keyed by API key or IP address. An in-process bucket only limits one server.
Validating input
Treat every submitted URL as untrusted.
- Accept only
httpandhttpsschemes. Rejectjavascript:,data:, andfile:URLs. - Set a maximum length, for example 2,048 characters.
- Parse the URL with a real parser instead of a regular expression.
- Reject hosts that resolve to private or loopback addresses if your service ever fetches the URL, for example to generate a preview. Otherwise an attacker can use it to probe your internal network (server-side request forgery).
- Reject links that point back to your own domain, which prevents redirect loops.
- Check the destination against a blocklist such as Google Safe Browsing, at creation time and again periodically, since a harmless page can turn malicious later.
from urllib.parse import urlparse
def validate_url(url: str) -> bool:
if len(url) > 2048:
return False
parsed = urlparse(url)
return parsed.scheme in ("http", "https") and bool(parsed.hostname)
print(validate_url("https://example.com/a"))
print(validate_url("javascript:alert(1)"))Enumeration
Enumeration means walking through short codes to discover links. With a counter-based generator, codes are sequential once encoded, so an attacker can request 1000, 1001, 1002, and so on. This reveals private URLs and lets them estimate your total volume.
Mitigations:
- Use random or hash-based codes, so neighbors are unrelated.
- Keep the code space sparse. Seven base62 characters give about 3.5 trillion codes, so a billion stored links leave a guess with roughly a 0.03% chance of hitting anything.
- Rate limit failed lookups per client, since enumeration produces many 404 responses.
- If you must use a counter, scramble the number with a keyed permutation before base62 encoding.
Never rely on an obscure code as access control. Links that must be private need authentication.
Exercise
Your service uses sequential IDs encoded in base62. Name the abuse this allows and one change that reduces it.
Show answer
Sequential codes allow enumeration: an attacker increments the code to discover other users' links and estimate volume. Switch to random or hash-based codes, or scramble the counter with a keyed permutation before encoding. Rate limiting failed lookups also helps.