Sub topic 14
Preventing Abuse: Rate Limits, Validation, and Enumeration
A URL shortener accepts links from strangers and sends other strangers to them. That makes it a useful tool for spammers, phishers, and scrapers. This chapter covers three defenses: validating what users submit, limiting how fast clients can call the API, and making short codes hard to guess in bulk.
It assumes you know basic HTTP status codes, the base62 code scheme from earlier chapters, and simple Python. Each defense below is a layer. No single layer is enough.
What attackers want
| Threat | What the attacker does | Main defense |
|---|---|---|
| Malicious destinations | Shortens phishing or malware links to hide the real address | Validation, blocklists, scanning, takedown |
| Bulk creation | Creates millions of links to fill storage or burn the code space | Rate limits on `POST` |
| Enumeration | Tries many codes to find links other people created | Unpredictable codes, limits on failed lookups |
| Redirect abuse | Creates loops, or links pointing back at the service | Reject own-domain targets |
| Server-side request forgery (SSRF) | Submits internal addresses so the server fetches them | Address checks at connection time |
| Alias squatting | Claims names like `login` or `admin` | Reserved-word list |
Validating submitted URLs
Validate at the trust boundary, which is the create endpoint. Use an allowlist of schemes, not a blocklist. Accepting only http and https rules out javascript:, data:, and file: links. A redirect to one of those could run script in a browser or expose local files.
import ipaddress
from urllib.parse import urlsplit
ALLOWED_SCHEMES = {"http", "https"}
MAX_LENGTH = 2048
OWN_HOSTS = {"sho.rt", "www.sho.rt"}
BLOCKED_HOSTS = {"localhost"}
def validate_long_url(raw: str) -> str:
if len(raw) > MAX_LENGTH:
raise ValueError("URL too long")
if any(c.isspace() or ord(c) < 32 for c in raw):
raise ValueError("whitespace or control characters")
parts = urlsplit(raw)
if parts.scheme.lower() not in ALLOWED_SCHEMES:
raise ValueError("scheme not allowed")
host = (parts.hostname or "").lower()
if not host:
raise ValueError("missing host")
if parts.username or parts.password:
raise ValueError("credentials in URL not allowed")
if host in OWN_HOSTS:
raise ValueError("cannot shorten our own links")
if host in BLOCKED_HOSTS:
raise ValueError("host not allowed")
try:
ip = ipaddress.ip_address(host)
except ValueError:
ip = None # a DNS name, not a literal IP address
if ip and (ip.is_private or ip.is_loopback
or ip.is_link_local or ip.is_reserved):
raise ValueError("non-public address")
return raw
for candidate in ["https://example.com/a?b=1",
"javascript:alert(1)",
"http://127.0.0.1/admin",
"https://sho.rt/abc1234"]:
try:
validate_long_url(candidate)
print("ok ", candidate)
except ValueError as err:
print("rejected", candidate, "-", err)Several choices here are deliberate:
- Length cap. Without one, a client can store megabytes per row.
- Credentials rejected. A link like
https://[email protected]/shows a trusted name before the@, and phishers use that. - Own-domain rejection. A short link that points to another short link allows redirect chains and loops.
- Normalization. Many services also normalize the URL (lowercase host, strip fragments) before storing it. Do that only if you want identical inputs to share a code.
Malicious destinations
Syntax checks cannot tell a phishing page from a news site. Layer these on top:
- Check the host against a blocklist, such as Google Safe Browsing or a commercial feed, when the link is created.
- Rescan stored links periodically. A page can be clean at creation and turn malicious later.
- Keep a
disabledflag on each row, so abuse staff can take a link down without deleting evidence. The redirect path must honor the flag, including cached copies. - For links with a poor reputation score, show an interstitial warning page instead of redirecting.
The cache matters here. A disabled link that stays in the cache for an hour keeps redirecting for an hour. Delete the cache entry when you set the flag, and keep cache lifetimes short enough that you can live with the worst case.
Rate limiting
A rate limit caps how many requests a client can make in a time window. The common algorithm is the token bucket. A bucket holds up to capacity tokens and refills at a steady rate. Each request spends a token. If the bucket is empty, the request is rejected. This allows short bursts while enforcing an average rate.
import time
class TokenBucket:
def __init__(self, capacity: float, refill_per_sec: float, clock=time.monotonic):
self.capacity = capacity
self.refill_per_sec = refill_per_sec
self.clock = clock
self.tokens = capacity
self.last = clock()
def allow(self, cost: float = 1.0):
"""Return (allowed, retry_after_seconds)."""
now = self.clock()
elapsed = now - self.last
self.last = now
self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_per_sec)
if self.tokens >= cost:
self.tokens -= cost
return True, 0.0
return False, (cost - self.tokens) / self.refill_per_sec
buckets = {} # one bucket per client key
def check(client_key: str):
bucket = buckets.setdefault(client_key, TokenBucket(capacity=10, refill_per_sec=1 / 6))
return bucket.allow()
for i in range(12):
allowed, wait = check("203.0.113.9")
print(i, "allowed" if allowed else f"429, retry after {wait:.0f}s")This allows a burst of 10 creations, then one every 6 seconds (10 per minute). The first 10 calls pass and the last two are rejected.
When a request is rejected, return 429 Too Many Requests with a Retry-After header holding the wait in seconds. Well-behaved clients back off.
Choosing limits and keys
Writes and reads need different limits. Creating a link is rare and expensive, so limit it per API key or account and per IP address, for example 10 per minute for anonymous users and more for authenticated ones. Redirects are the hot path. Most are absorbed by the cache or a CDN, so a strict per-IP read limit can hurt legitimate users behind a shared office or mobile carrier address. Limit failed lookups instead (see the next section).
Common failure modes:
- Per-process counters. The in-memory dictionary above counts per server. With ten servers, an attacker gets ten times the limit. Production systems keep the counters in a shared store such as Redis and update them atomically, often with a Lua script.
- Spoofed client IPs.
X-Forwarded-Foris a client-supplied header unless your own proxy overwrote it. Trust only the entries added by proxies you control. - Limiter outage. If the shared store is down, you must pick a policy. Failing open keeps the service up but unprotected. Failing closed protects it but blocks everyone. For a redirect service, fail open on reads and closed on creation.
- Unbounded key growth. One bucket per IP address can use a lot of memory under a spoofed-address flood. Expire idle buckets.
Enumeration
Enumeration means trying many codes to discover links the owner never shared. Short links are often used for unlisted documents, so this is a real privacy risk.
Sequential codes are guessable
With a counter, code 1000001 is followed by 1000002. An attacker only needs to walk the sequence. Counter-based generation is attractive for uniqueness, but the raw counter must not become the code. One fix is to scramble it with a reversible mapping before base62 encoding:
SPACE = 62 ** 7 # all 7-character codes
MULTIPLIER = 1_000_003 # odd and not divisible by 31, so coprime with 62**7
OFFSET = 918_273_645
def scramble(counter: int) -> int:
"""One-to-one mapping from counters to numbers below 62**7."""
return (counter * MULTIPLIER + OFFSET) % SPACE
print([scramble(n) for n in range(1, 5)])Because the multiplier shares no factor with 62**7 (which is built from 2 and 31), each counter value gets a distinct output, so uniqueness is preserved. Feed the result to encode from the base62 chapter. This hides the order from casual scanning. It is not cryptographic, because someone who collects enough samples can work out the pattern. For stronger protection, use random codes or a keyed block cipher.
Random codes still leak under volume
Even random codes can be scanned. Suppose the service holds 100 million links in a space of about 3.5 trillion codes. A random guess hits a real link with probability about 100,000,000 / 3,500,000,000,000, which is roughly 0.0029%. At 1,000 guesses per second, the attacker finds about 0.029 links per second, or about 2,500 links per day. That is slow but not zero, and it scales with the number of requests the attacker can send.
The defenses combine:
- Limit failed lookups. Count
404responses per client and slow or block clients with a high miss rate. Legitimate users rarely miss. - Cache misses briefly. Store a "not found" marker for a short time, so a scan does not turn into a flood of database reads.
- Use longer codes for private links. Each extra character multiplies the space by 62. Ten characters give about 8.4 × 10^17 codes, which pushes the hit rate far down.
- Do not treat the code as a secret. For truly private content, the destination should require authentication. A short link only hides an address.
Custom aliases
Custom aliases let users choose their own codes, which introduces two risks. First, reserve a list of paths your service uses (api, admin, login, static) and reject them. Second, restrict aliases to base62 characters plus - and _, with a minimum length, and compare case-sensitively or not consistently. Visually confusable names (paypa1) are a phishing risk, so consider a review rule for aliases that resemble well-known brands.
Exercise
A service stores 50 million links and uses random 7-character base62 codes (62**7 is about 3.5 trillion). An attacker sends 2,000 random lookups per second. Roughly how many valid links does the attacker find per day, and which single control would reduce this most without affecting normal users?
Show answer
The hit probability per guess is 50,000,000 / 3,500,000,000,000, about 1.43e-5. At 2,000 guesses per second that is about 0.0286 hits per second. Over 86,400 seconds it is about 2,470 links per day. Limiting failed lookups per client is the most effective control, because normal users almost never produce a stream of 404s, while a scanner produces thousands. Lengthening codes also helps but changes the format for every link.
Exercise
Why must the create endpoint reject URLs whose host is your own short domain?
Show answer
A short link pointing to another short link lets users build redirect chains or loops, which waste resources and can hide the final destination from checks. Rejecting your own host keeps every short link one hop from the real target.