Web Security 17 ๐ก๏ธ API Security, Rate Limiting & Bot Defense โ Protecting REST/GraphQL endpoints against abuse, scraping, and credential stuffing
An API is a different threat surface from a web page, and the difference is structural rather than a matter of degree. A page is consumed by a browser that enforces the same-origin policy, that hides the response from a cross-origin script, and that renders through an HTML parser which sanitises nothing but executes nothing unexpected. An API is consumed by whatever the caller says it is, and it returns the data the caller asked for with no enforcement layer between the response and the caller’s disk. There is no same-origin policy on an API endpoint. The authorization check you wrote is the only authorization check there is.
The failure modes follow from that. OWASP’s API Security Top 10, revised in 2023, opens with Broken Object Level Authorization โ the endpoint that accepts an object ID and returns the object without confirming the caller may see it โ and closes with Unsafe Consumption of APIs, the endpoint that trusts a third-party response without validating it. Between those two sit the failure modes this chapter covers: unrestricted resource consumption, the absence of which is unbounded pagination and unbounded query complexity; broken authentication, which in the API context means an endpoint that accepts a credential and does not distinguish a brute-force attempt from a legitimate retry; and unrestricted access to sensitive business flows, which is the scraping problem stated in OWASP’s own vocabulary.
Rate limiting is the control that appears in every one of those categories, and it is the one most commonly implemented at a single layer with a single key. A per-IP limit at the CDN does nothing against a credential-stuffing run distributed across ten thousand residential proxies, each sending three requests. A per-user limit does nothing against an anonymous endpoint. The working design is layered: a coarse edge limit that absorbs volumetric floods, a per-identity limit that follows the account across networks, and a scoped business-flow limit that counts the thing that actually costs money โ signups, password resets, checkout attempts, SMS sends.
Bot defense and its credential-stuffing subset are the third pillar, and they exist because the rate limit is a cost control rather than an authentication control. A bot that stays under the limit still authenticates successfully if the password is right, and a credential-stuffing run against a breached password list will find the right password for some fraction of accounts no matter how slowly it goes. Defeating it requires knowing which passwords are already leaked, which device the account normally uses, and whether the request bears the marks of a real browser session at all.
This chapter works through those layers in the order a request encounters them. First the authorization failures that no amount of rate limiting fixes, then the rate-limiting algorithms and their distributed implementations, then bot defense and the credential-stuffing specifics, then the GraphQL surface where a single request can be arbitrarily expensive, and finally the anti-scraping design that makes bulk extraction economically pointless even when it is technically possible.
Key point: A rate limit is a cost control, not an authentication control โ it slows an attacker but does not stop one, so it belongs in a layered design with per-identity keying, breach-aware password policy, and a bot signal that survives a proxy rotation.
Why it exists
The object-authorization problem. The classic API vulnerability is not exotic. It is GET /api/invoices/1042 returning invoice 1042 because the handler looked up the row and never checked whether the row’s customer_id matched the token’s subject. This is OWASP API1:2023, Broken Object Level Authorization, and it is first in the list because it is both the most common and the most damaging. It is not a rate-limiting problem and no rate limit mitigates it โ a single request is enough โ which is why any treatment of API abuse that starts with rate limiting has started in the wrong place.
The resource-consumption problem. OWASP API4:2023 is Unrestricted Resource Consumption, and it covers everything from a ?limit=1000000 pagination parameter to an unbounded GraphQL query that fans out across a nested relationship ten levels deep. The API’s cost to serve is a function of the request, and the requester controls the request. Where a web page has a fixed rendering cost, an API has a cost the caller selects, and the absence of an upper bound on that selection is the vulnerability.
The credential-stuffing problem. Stuffing is not brute force. Brute force guesses; stuffing replays. The attacker holds a list of email-and-password pairs from a breach of some unrelated service and tries them against your login endpoint, because a meaningful share of people reuse passwords across sites. It is slow, distributed, low-and-slow by design, and almost invisible to a per-IP rate limit. OWASP catalogues it as an automated threat and the defence is upstream of the endpoint: reject passwords that appear in known breaches, require a second factor for a new device, and make the login response identical in content and timing whether the account exists or not.
The scraping economics problem. Scraping is not a security failure in the cryptographic sense โ the data is public, the visitor is authorised to see it. What the scraper does is extract at a rate and volume no human would, which is a business problem: the price list is competitive intelligence, the user directory is a marketing list, the inventory is a trading signal. Defending it is an exercise in raising the cost of extraction relative to its value, and the mechanisms are detection, asymmetry, and legal rather than cryptographic: pagination limits, honeypot fields, rate shaping, and terms of service that a scraping operation has to actively disregard.
The distributed-state problem. A rate limiter that counts in process memory works on one server and fails on ten. Each instance counts independently, so a limit of one hundred per minute becomes one thousand per minute across ten instances. Getting it right requires shared state โ Redis, usually โ and shared state introduces a new failure mode: the limiter becomes a dependency on the request path, and a Redis outage that fails closed takes the whole API down while one that fails open removes the protection entirely. The choice between those two is a deliberate design decision and it is usually not made explicitly.
The distributed-attacker problem. A single IP sending ten thousand requests is easy. Ten thousand IPs sending one request each is not, and residential proxy networks rent exactly that capability by the million. Any control keyed solely on the network address is defeated by construction. The controls that survive are keyed on something the attacker has to acquire per target โ an account, a session, a payment instrument โ and those keys are the ones worth building.
The trade-off. Every control on the request path adds latency, a failure mode, and a false-positive risk. A rate limiter adds a Redis round trip. A CAPTCHA adds a conversion-rate drop. A strict account lockout adds a denial-of-service vector, because an attacker who can lock any account by guessing at it has turned your defence into their attack. The design is not “add more controls” โ it is to place cheap controls early, expensive controls late, and make the expensive controls trigger on risk rather than on every request.
a. Authorization before rate limiting โ BOLA, BFLA, and property-level exposure
The first control is not a limiter. It is the check that the authenticated caller is authorised for the specific object and the specific function, and it is first because it is the only control whose absence is catastrophic at a single request.
Broken Object Level Authorization is the object check. A handler receives an identifier and must confirm that the caller’s subject owns, or is otherwise entitled to, the object it names โ on every request, resolved server-side, never inferred from a client-supplied claim.
// The correct shape: scope the query by the caller's subject
app.get("/api/invoices/:id", authenticate, async (req, res) => {
const invoice = await db.invoice.findFirst({
where: {
id: req.params.id,
// Ownership is a WHERE clause, not an if statement after the fetch
customerId: req.user.sub,
},
select: { id: true, total: true, status: true },
});
// A non-owned object is indistinguishable from a missing one
if (!invoice) return res.status(404).json({ error: "not_found" });
return res.json(invoice);
});
The where clause is doing the work, not the conditional. A fetch followed by an if is a fetch that has already read the row, and the row is now in memory and in the logs and possibly in an error message. Scoping the query makes the non-owned object genuinely absent, and returning 404 rather than 403 avoids confirming that the object exists โ a 403 on a non-owned invoice is an enumeration oracle.
Broken Function Level Authorization is the same failure one level up: the caller is authorised for the object but not for the operation. The reliable pattern is a default-deny router where every route declares the role or scope it requires, rather than a default-open router where individual routes remember to check.
const routes = [
{ method: "get", path: "/api/invoices/:id", scope: "invoice:read" },
{ method: "post", path: "/api/invoices/:id/refund", scope: "invoice:refund" },
{ method: "delete", path: "/api/users/:id", scope: "user:admin" },
];
// Every route carries its required scope; nothing is implicitly public
for (const route of routes) {
app[route.method](route.path, authenticate, requireScope(route.scope), handlers[route.path]);
}
function requireScope(scope) {
return (req, res, next) => {
// Missing scope is a 403; the route never registered an implicit allow
if (!req.user?.scopes?.includes(scope)) {
return res.status(403).json({ error: "forbidden" });
}
next();
};
}
Broken Object Property Level Authorization is the newer and subtler one โ the object is authorised but the response includes fields the caller should not see, or the request body allows fields the caller should not set. It is mass assignment seen from both ends. The mitigation is an explicit allowlist of writable fields per role, and an explicit selection of readable fields, which means the ORM’s select: true defaults and the framework’s automatic body-to-model binding are both liabilities.
b. Rate limiting โ algorithms, keys, and distributed counters
Every rate limiter answers the same question: has this key exceeded its allowance in this window. The algorithms differ in how they answer it and in the shape of the traffic they admit.
Fixed window counts requests per calendar bucket โ one hundred per minute, reset at the minute boundary. It is trivial to implement with a single INCR and EXPIRE, and it has a well-known flaw: a caller can send one hundred requests at 11:59:59 and another one hundred at 12:00:00, doubling the intended rate across a two-second span.
Sliding window fixes the boundary problem by weighting the previous bucket by how far into the current one the request lands. It is cheap โ two counters per key โ and accurate enough for almost every real use.
Token bucket models a allowance that refills at a constant rate and permits bursts up to the bucket’s capacity. It is the right algorithm when the traffic is legitimately bursty: an integration that sends fifty requests after a user action and then goes quiet should be able to do that, and a fixed window would punish it as if it were a flood.
Leaky bucket and the closely related Generic Cell Rate Algorithm smooth the output rate rather than bounding the burst. They are the right choice when the downstream is the constraint โ a legacy database that genuinely cannot handle more than ten writes a second โ rather than when the client’s behaviour is the concern.
-- Token bucket in a single atomic Redis script
-- KEYS[1] = bucket key
-- ARGV = capacity, refill tokens/ms, now (ms), cost
local capacity = tonumber(ARGV[1])
local refill = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local cost = tonumber(ARGV[4])
local state = redis.call("HMGET", KEYS[1], "tokens", "ts")
local tokens = tonumber(state[1]) or capacity
local ts = tonumber(state[2]) or now
-- Refill proportionally to the time elapsed since the last update
local delta = math.max(0, now - ts) * refill
tokens = math.min(capacity, tokens + delta)
local allowed = tokens >= cost
if allowed then tokens = tokens - cost end
-- A single round trip: read, refill, decide, write
redis.call("HMSET", KEYS[1], "tokens", tokens, "ts", now)
redis.call("PEXPIRE", KEYS[1], math.ceil(capacity / refill))
-- Returns 1/0 for the decision and the remaining tokens for the headers
return { allowed and 1 or 0, math.floor(tokens) }
The script is the important part. A limiter implemented as a GET followed by a SET is a race condition: two concurrent requests both read the same token count, both conclude they are within the limit, and both proceed. Redis executes a Lua script atomically, so the read-decide-write sequence is one operation, which is the only way the counter is correct under concurrency.
The key is the more consequential decision than the algorithm. Keying on the client IP is the default and the weakest option: it collapses everyone behind a corporate NAT into one bucket, and it is defeated entirely by a residential proxy network. A layered key set is the working design.
// Compose the limiter from a cheap local tier and an accurate shared tier
import { RateLimiterRedis, RateLimiterMemory } from "rate-limiter-flexible";
// Per-instance pre-filter: absorbs a flood before it reaches Redis
const localTier = new RateLimiterMemory({ points: 200, duration: 1 });
// Shared truth: consistent across every instance behind the load balancer
const sharedTier = new RateLimiterRedis({
storeClient: redis,
keyPrefix: "rl",
points: 100,
duration: 60,
});
export async function limit(req, res, next) {
// Three keys: the identity, the network, and the route being hit
const keys = [
`user:${req.user?.sub ?? "anon"}`,
`ip:${req.ip}`,
`route:${req.method}:${req.route.path}`,
];
for (const key of keys) {
try {
// The identity key is the one that survives a proxy rotation
const result = await sharedTier.consume(key);
res.setHeader("RateLimit-Remaining", result.remainingPoints);
res.setHeader("RateLimit-Reset", Math.ceil(result.msBeforeNext / 1000));
} catch (rej) {
// Exceeding the limit throws with the retry window attached
res.setHeader("Retry-After", Math.ceil(rej.msBeforeNext / 1000));
return res.status(429).json({ error: "rate_limited" });
}
}
next();
}
The header names are worth getting right because clients increasingly read them to back off voluntarily. The IETF draft defines RateLimit-Limit, RateLimit-Remaining, and RateLimit-Reset, and an older de facto convention used X-RateLimit-*. GitHub sends x-ratelimit-limit, x-ratelimit-remaining, and x-ratelimit-reset in epoch seconds; Stripe sends RateLimit-Limit, RateLimit-Remaining, and RateLimit-Reset. Adoption is uneven enough that sending both families is the pragmatic choice, and Retry-After on the 429 is what actually drives most client behaviour.
The fail-open versus fail-closed decision deserves to be explicit. A limiter backed by Redis is a new hard dependency on every request, and a Redis outage becomes an API outage if the limiter fails closed. For a public read endpoint the right answer is usually fail-open with an alert; for a login endpoint it is fail-closed, because the alternative is an unbounded credential-stuffing run. Encoding that decision per route rather than globally is the part teams skip.
// The failure policy is a property of the route, not of the limiter
const policies = {
"/api/login": { failMode: "closed", points: 5, duration: 60 },
"/api/products": { failMode: "open", points: 100, duration: 60 },
};
async function consume(key, policy) {
try {
return await limiter.consume(key, policy.points);
} catch (err) {
if (err instanceof RateLimiterRes) throw err; // genuinely over the limit
// The store itself failed: apply the route's declared policy
if (policy.failMode === "closed") throw new TooManyRequests();
return null; // fail open, log loudly
}
}
c. Bot defense and credential stuffing โ signals, breach awareness, and step-up
Bot defense begins with the admission that client-side signals are advisory. A user agent is a string the client chooses. A Referer is a header the client sets. TLS fingerprints are harder to fake because they emerge from the actual handshake, but a botnet of real browsers produces real fingerprints. Every signal is a vote, and the vote is combined into a risk score rather than a verdict.
The signals that carry weight divide into three groups. Transport-level: the JA3 and JA4 TLS fingerprints, the header order and casing the client emits, whether HTTP/2 settings frames match the claimed browser, and whether the connection reuses a session the way a browser would. Session-level: whether the session has a plausible history โ a page view before the API call, a mouse path, a scroll, a focus event โ and whether the timing between those events resembles a human. Identity-level: whether this account has been seen from this device before, whether the ASN is a datacenter or a residential network, and whether the request volume for this account is anomalous relative to its own history.
// A risk score combining transport, session, and identity signals
export function scoreLogin(req, account) {
let risk = 0;
// Datacenter ASNs are where proxies live; residential traffic is the long tail
if (isDatacenterAsn(req.asn)) risk += 30;
// A fresh session with no page view is characteristic of a scripted client
if (!req.session?.pageViews) risk += 20;
// A device the account has never used is the strongest single signal
if (!account.knownDevices.includes(req.deviceFingerprint)) risk += 25;
// A country the account has never authenticated from
if (!account.knownCountries.includes(req.geo.country)) risk += 15;
// Impossible travel: two logins from far apart within minutes
if (account.lastLoginAt && impossibleTravel(account, req)) risk += 40;
return Math.min(risk, 100);
}
// The action is graduated, not binary
function actionFor(risk) {
if (risk < 30) return "allow"; // proceed normally
if (risk < 60) return "challenge"; // prove humanness, then proceed
return "step_up"; // require a second factor
}
Step-up is the control that actually stops credential stuffing, because stuffing succeeds when the password is correct. If the password is correct and the device is new, the second factor is what stands between the attacker and the account. A TOTP code, a passkey, or an emailed one-time link all serve; the modern preference is WebAuthn, since a passkey is bound to the origin and cannot be phished or replayed at all.
The other half of the defence is upstream, at registration and at password change. A password that appears in a known breach is already in the attacker’s wordlist, so accepting it is accepting a future stuffing success. The Pwned Passwords range API answers the question without sending the password anywhere: SHA-1 the password, send the first five hex characters, receive every suffix matching that prefix with a count, and compare locally.
import { createHash } from "node:crypto";
export async function isBreached(password) {
// SHA-1 is required by the API, not chosen for security here
const hash = createHash("sha1").update(password).digest("hex").toUpperCase();
const prefix = hash.slice(0, 5);
const suffix = hash.slice(5);
// k-anonymity: the server never learns which password was checked
const res = await fetch(`https://api.pwnedpasswords.com/range/${prefix}`);
const body = await res.text();
// The response is Suffix:Count pairs, one per line
for (const line of body.split("\n")) {
const [candidate, count] = line.trim().split(":");
if (candidate === suffix) return Number(count) > 0;
}
return false;
}
Storage is the other upstream control. OWASP’s Password Storage guidance is Argon2id as the first choice, with a minimum configuration of 19 MiB of memory, two iterations, and one degree of parallelism โ parameters chosen so that the cost is borne by the attacker’s cracking rig rather than by the server’s login path. The verification comparison must be constant-time, which every reputable library handles internally and hand-rolled code almost never does.
import argon2 from "argon2";
// Registration: hash with the OWASP-recommended Argon2id floor
const hash = await argon2.hash(password, {
type: argon2.argon2id,
memoryCost: 19456, // 19 MiB
timeCost: 2, // two iterations
parallelism: 1,
});
// Login: verify, and be careful that the failure path is indistinguishable
const valid = await argon2.verify(hash, password);
The indistinguishable failure path is where most login endpoints leak. If an unknown email returns immediately and a known email returns after 200 ms of Argon2 verification, the timing difference is an account-enumeration oracle that needs no brute force at all. The mitigation is to verify against a dummy hash when the account is not found, so both paths pay the same cost, and to return the same body in both cases.
// A placeholder hash computed once at boot, never matching any real password
const DUMMY_HASH = await argon2.hash("dummy-password-for-timing");
export async function login(email, password) {
const account = await db.user.findUnique({ where: { email } });
// Verify against a real hash or a dummy one: same work either way
const valid = await argon2.verify(account?.passwordHash ?? DUMMY_HASH, password);
// Both branches return the same shape; the caller cannot tell which ran
if (!account || !valid) return { ok: false, error: "invalid_credentials" };
return { ok: true, account };
}
d. GraphQL โ depth, complexity, aliases, and batching
GraphQL concentrates the resource-consumption problem into a single endpoint. A REST API has one cost per route; a GraphQL API has a cost determined by the query, and the query is written by the caller. A naive schema exposes user { posts { comments { author { posts { comments { ... } } } } } }, and a fifty-byte request can generate a hundred thousand database reads.
Depth limiting is the crudest control and the easiest to reason about. It rejects any query whose nesting exceeds a fixed number of levels. It is necessary and insufficient: a query three levels deep with fifty aliases at each level is shallow and enormous.
import depthLimit from "graphql-depth-limit";
import { ApolloServer } from "@apollo/server";
const server = new ApolloServer({
typeDefs,
resolvers,
// Rejects anything nested deeper than eight levels before execution
validationRules: [depthLimit(8)],
});
Complexity analysis is the control that actually bounds cost. Each field is assigned a weight โ one for a scalar, higher for a list that resolves per parent โ and the total is compared to a budget before execution. The weight must scale with the arguments, because posts(first: 10) and posts(first: 1000) are the same field with a thousand-fold different cost.
import {
getComplexity,
simpleEstimator,
fieldExtensionsEstimator,
} from "graphql-query-complexity";
const complexityRule = createComplexityLimitRule(1000, {
onCost: (cost) => logger.debug({ cost }, "graphql query cost"),
createError: (max, actual) =>
new GraphQLError(`Query cost ${actual} exceeds maximum of ${max}`),
});
// In the plugin, estimate cost before execution and reject over budget
const complexity = getComplexity({
schema,
query: document,
variables,
estimators: [
// Per-field weights declared in the schema via extensions
fieldExtensionsEstimator(),
// Fallback: a scalar is 1, a list multiplies by the first argument
simpleEstimator({ defaultComplexity: 1 }),
],
});
if (complexity > 1000) throw new GraphQLError("Query too expensive");
Aliases and fragments are the bypass that depth and complexity both miss if they are counted naively. A single query can include the same field fifty times under fifty aliases, and a fragment can be spread repeatedly. The controls are the ones GraphQL’s own parser exposes: maxTokens in recent graphql-js releases, a validation rule that counts operation and field occurrences rather than levels, and a rule that rejects queries whose alias count exceeds a small threshold.
Batching is the same abuse one layer up. Many GraphQL servers accept an array of operations in a single HTTP request, which skips an HTTP-level rate limiter entirely โ the caller sends one request containing a thousand login mutations. The fix is to count operations against the rate limit rather than requests, and to disable batched mutations outright while permitting batched queries.
// Count operations, not HTTP requests, against the limiter
const operations = Array.isArray(body) ? body.length : 1;
await limiter.consume(`user:${userId}`, operations);
// Batched queries are fine; batched mutations are a credential-stuffing vector
if (Array.isArray(body) && body.some((op) => /^\s*mutation/.test(op.query))) {
return res.status(400).json({ error: "batched_mutations_disabled" });
}
Introspection is worth disabling in production but not for the reason commonly given. It is not a security control โ the schema is discoverable through field-suggestion errors, through the shape of the error messages, and through trial. It raises the effort slightly and makes casual enumeration less rewarding, and the real protection is field-level authorization in the resolvers, applied per-field regardless of whether the schema was discovered.
e. Anti-scraping โ asymmetry, enumeration detection, and tarpits
Scraping defense starts with an economic argument rather than a technical one: the scraper’s cost must exceed the data’s value. A public product catalogue priced at $0.002 per request is free to extract; the same catalogue behind cursor pagination that requires an opaque token, at $0.50 per thousand requests with a human challenge every hundred, is not.
Enumeration detection is the first mechanism. Sequential integer IDs make the entire dataset addressable; a scraper walks 1 through N and has everything. The fix is opaque, non-sequential identifiers โ UUIDv7, ULID, or a hash of the row โ so that discovering the next valid ID requires the previous response rather than arithmetic.
// Opaque cursor pagination: the next page requires the current response
export async function listProducts({ cursor, limit = 20 }) {
// Hard ceiling on page size; the caller cannot request 100000
const take = Math.min(Math.max(limit, 1), 50);
// The cursor encodes the sort key, not the offset, so pages stay stable
const after = cursor ? decodeCursor(cursor) : null;
const rows = await db.product.findMany({
take: take + 1, // one extra row tells us if more exist
...(after && { cursor: { id: after }, skip: 1 }),
orderBy: { createdAt: "desc" },
});
const hasMore = rows.length > take;
return {
items: rows.slice(0, take),
nextCursor: hasMore ? encodeCursor(rows[take - 1].id) : null,
};
}
Honeypots catch the classes of scraper that do not render a page the way a browser does. A hidden form field that a human cannot see and a naive crawler fills; a link in the page that is display: none and points at a trap route; a field in the JSON whose name suggests value and whose reading marks the caller. Any submission of the hidden field, any request to the trap route, is a positive identification that needs no heuristic.
<!-- Visible only to a parser; a browser never renders or submits it -->
<form method="post" action="/api/search">
<input type="text" name="q" placeholder="Search" />
<div aria-hidden="true" style="position:absolute;left:-9999px">
<input type="text" name="company_url" tabindex="-1" autocomplete="off" />
</div>
<button type="submit">Search</button>
</form>
Tarpits are the last resort and the most adversarial. Rather than blocking a suspected scraper, the server serves deliberately slow responses โ a small setTimeout before each byte, an artificially long Content-Length delivered in fragments, a response that streams one result per second. The scraper can still extract the data; the extraction takes long enough that the operator either gives up or pays for enough infrastructure that the economics flip. A tarpit is invisible to a legitimate user because it only fires for traffic already classified as automated.
// Progressive delay applied only to traffic already flagged as automated
export async function shape(req, res, next) {
const classification = await classify(req);
if (classification === "automated") {
// Each subsequent request from this fingerprint waits longer
const strikes = await strikesFor(req);
const delay = Math.min(2 ** strikes * 100, 30_000);
await new Promise((r) => setTimeout(r, delay));
await recordStrike(req);
}
next();
}
The legal layer sits outside the code but is worth stating because it is the one that produces a remedy. Terms of service that prohibit automated extraction, robots.txt directives that a commercial crawler is expected to honour, and a documented contact route for licensing the dataset all convert a technical arms race into a legal one. The technical controls establish which requests were automated and which were told not to be; the terms are what make that distinction actionable.
Complete Example Session
// ============================================
// PART 1: THE OWNERSHIP CHECK
// ============================================
app.get("/api/invoices/:id", authenticate, async (req, res) => {
const invoice = await db.invoice.findFirst({
// Ownership is expressed in the query, not in a post-fetch conditional
where: { id: req.params.id, customerId: req.user.sub },
select: { id: true, total: true, status: true },
});
if (!invoice) return res.status(404).json({ error: "not_found" });
res.json(invoice);
});
// ============================================
// PART 2: THE SCOPE MATRIX
// ============================================
const SCOPES = {
"GET /api/invoices/:id": "invoice:read",
"POST /api/invoices/:id/refund": "invoice:refund",
"DELETE /api/users/:id": "user:admin",
};
function requireScope(req, res, next) {
// Default deny: an unlisted route has no scope and is refused
const needed = SCOPES[`${req.method} ${req.route.path}`];
if (!needed || !req.user?.scopes?.includes(needed)) {
return res.status(403).json({ error: "forbidden" });
}
next();
}
// ============================================
// PART 3: THE TOKEN BUCKET
// ============================================
const script = `
local cap = tonumber(ARGV[1])
local refill = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local cost = tonumber(ARGV[4])
local s = redis.call("HMGET", KEYS[1], "tokens", "ts")
local tokens = tonumber(s[1]) or cap
local ts = tonumber(s[2]) or now
tokens = math.min(cap, tokens + math.max(0, now - ts) * refill)
local ok = tokens >= cost
if ok then tokens = tokens - cost end
redis.call("HMSET", KEYS[1], "tokens", tokens, "ts", now)
redis.call("PEXPIRE", KEYS[1], math.ceil(cap / refill))
return { ok and 1 or 0, math.floor(tokens) }
`;
// ============================================
// PART 4: THE LAYERED LIMITER
// ============================================
async function limit(req, res, next) {
const buckets = [
{ key: `user:${req.user?.sub ?? req.ip}`, capacity: 100, refillPerMs: 100 / 60000 },
{ key: `route:${req.method}:${req.route.path}`, capacity: 20, refillPerMs: 20 / 60000 },
];
for (const b of buckets) {
const [ok, remaining] = await redis.eval(
script, 1, b.key, b.capacity, b.refillPerMs, Date.now(), 1,
);
res.setHeader("RateLimit-Remaining", remaining);
if (!ok) {
// Retry-After is what clients actually honour
res.setHeader("Retry-After", Math.ceil(b.capacity / (b.refillPerMs * 1000)));
return res.status(429).json({ error: "rate_limited" });
}
}
next();
}
// ============================================
// PART 5: THE BREACHED-PASSWORD CHECK
// ============================================
async function isBreached(password) {
const h = createHash("sha1").update(password).digest("hex").toUpperCase();
const res = await fetch(`https://api.pwnedpasswords.com/range/${h.slice(0, 5)}`);
const body = await res.text();
return body.split("\n").some((l) => l.startsWith(h.slice(5)));
}
// ============================================
// PART 6: THE TIMING-SAFE LOGIN
// ============================================
const DUMMY = await argon2.hash("timing-placeholder");
async function login(email, password) {
const account = await db.user.findUnique({ where: { email } });
// Same Argon2 cost whether or not the account exists
const valid = await argon2.verify(account?.passwordHash ?? DUMMY, password);
if (!account || !valid) return { ok: false, error: "invalid_credentials" };
return { ok: true, account };
}
// ============================================
// PART 7: THE RISK SCORE
// ============================================
function risk(req, account) {
let score = 0;
if (isDatacenterAsn(req.asn)) score += 30;
if (!account.knownDevices.includes(req.fingerprint)) score += 25;
if (!account.knownCountries.includes(req.geo.country)) score += 15;
if (!req.session?.pageViews) score += 20;
return Math.min(score, 100);
}
// ============================================
// PART 8: THE GRAPHQL BUDGET
// ============================================
const server = new ApolloServer({
typeDefs,
resolvers,
validationRules: [depthLimit(8), complexityRule],
});
// Count operations, not HTTP requests, against the limiter
const ops = Array.isArray(body) ? body.length : 1;
await limiter.consume(`user:${userId}`, ops);
// ============================================
// PART 9: THE OPAQUE CURSOR
// ============================================
const take = Math.min(Math.max(limit, 1), 50);
const rows = await db.product.findMany({
take: take + 1,
...(after && { cursor: { id: after }, skip: 1 }),
orderBy: { createdAt: "desc" },
});
// ============================================
// PART 10: THE TARPIT
// ============================================
if (classification === "automated") {
const strikes = await strikesFor(req);
await new Promise((r) => setTimeout(r, Math.min(2 ** strikes * 100, 30000)));
}
The ten parts covered the ownership check, the default-deny scope matrix, the atomic token bucket, the layered limiter with per-route keys, the breach check, the timing-safe login, the risk score, the GraphQL budget, the opaque cursor, and the tarpit.
Quick Reference
Rate Limiting Algorithms
| Algorithm | Burst Allowed | Boundary Flaw |
|---|---|---|
| Fixed window | At the boundary | Double rate across reset |
| Sliding window | Bounded | None material |
| Sliding log | None | Memory grows with requests |
| Token bucket | Up to capacity | None |
| Leaky bucket | Smoothed | Delays legitimate bursts |
Limiter Keys
| Key | Survives Proxy Rotation | Notes |
|---|---|---|
ip | No | Collapses NAT users |
user | Yes | Requires authentication |
api_key | Yes | Hash the key at rest |
session | Partially | Rotate on login |
route | n/a | Coarse global limit |
Rate Limit Headers
| Header | Meaning |
|---|---|
RateLimit-Limit | Allowance in the window |
RateLimit-Remaining | Requests left |
RateLimit-Reset | Seconds until reset |
Retry-After | Seconds to wait after a 429 |
X-RateLimit-* | Legacy de facto variant |
Bot Signals
| Signal | Layer | Spoofable |
|---|---|---|
| JA3 / JA4 fingerprint | TLS | Hard |
| Header order | HTTP | Moderate |
| Datacenter ASN | Network | No |
| Known device | Identity | No |
| Session history | Session | Easy |
| User agent | HTTP | Trivial |
Credential Stuffing Defenses
| Control | Effect |
|---|---|
| Breached-password rejection | Removes known-good passwords |
| Argon2id hashing | Raises offline cracking cost |
| Uniform timing and response | Removes the enumeration oracle |
| Step-up on new device | Blocks the successful guess |
| WebAuthn / passkeys | Removes the reusable secret |
Best Practices
โ Do This:
// Scope the query by the caller, not the response by the caller
where: { id: req.params.id, customerId: req.user.sub } // โ
// Return 404 for non-owned objects
if (!invoice) return res.status(404).json({ error: "not_found" }); // โ
// Count in one atomic script
redis.eval(script, 1, key, cap, rate, now, cost); // โ
// Verify against a dummy hash when the account is missing
await argon2.verify(account?.hash ?? DUMMY, password); // โ
// Count GraphQL operations, not HTTP requests
await limiter.consume(`user:${id}`, operations); // โ
// Cap page size server-side
const take = Math.min(limit, 50); // โ
โ Don’t Do This:
// Fetch then check: the row is already in memory
const inv = await db.invoice.findUnique({ where: { id } });
if (inv.customerId !== req.user.sub) return res.sendStatus(403); // โ
// Read-then-write counters race under concurrency
const n = await redis.get(key);
await redis.set(key, n + 1); // โ
// Leak account existence through the response body
if (!account) return res.status(404).json({ error: "no_user" }); // โ
// Rate limit the HTTP request, not the GraphQL operation
await limiter.consume(userId); // โ
// Key everything on the IP alone
await limiter.consume(req.ip); // โ
// Unlimited page size
const take = req.query.limit; // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Cross-tenant data leak | Ownership not in the query | Scope by subject |
| 403 confirms existence | Distinguishing forbidden from absent | Return 404 for both |
| Limit ineffective in scale-out | In-process counter | Shared Redis counter |
| Limit bypassed by proxies | Keyed on IP only | Add identity key |
| Account enumeration | Different timing or bodies | Dummy hash, same body |
| Login DoS via lockout | Lockout is attacker-triggerable | Backoff plus challenge |
| GraphQL cost unbounded | Depth-only limiting | Complexity with arguments |
| Batching skips the limit | Counting requests | Count operations |
| Scraper walks sequential IDs | Auto-increment keys | Opaque identifiers |
| Honeypot never fires | Field rendered visibly | Hide with CSS and aria-hidden |
Real-World Examples
1. Scoped fetch
db.invoice.findFirst({ where: { id, customerId: req.user.sub } });
2. Default-deny scope
if (!SCOPES[`${req.method} ${req.route.path}`]) return res.sendStatus(403);
3. Atomic increment
await redis.eval(bucketScript, 1, key, cap, rate, Date.now(), 1);
4. Retry-After on 429
res.setHeader("Retry-After", Math.ceil(msBeforeNext / 1000));
5. Timing parity
const valid = await argon2.verify(account?.hash ?? DUMMY, password);
6. Breach check
const prefix = createHash("sha1").update(pw).digest("hex").slice(0, 5);
7. Depth limit
validationRules: [depthLimit(8)]
8. Operation counting
const ops = Array.isArray(body) ? body.length : 1;
9. Opaque pagination
const take = Math.min(Math.max(limit, 1), 50);
10. Tarpit delay
await new Promise((r) => setTimeout(r, Math.min(2 ** strikes * 100, 30000)));
Visual
The Request Pipeline
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ INCOMING REQUEST โ
โ โ โ
โ โผ โ
โ [1] Edge limiter coarse, per-IP, volumetric โ
โ โ โ
โ โผ โ
โ [2] Authenticate token, key, or session โ
โ โ โ
โ โผ โ
โ [3] Scope check default deny โ
โ โ โ
โ โผ โ
โ [4] Identity limit per account, survives proxies โ
โ โ โ
โ โผ โ
โ [5] Object authz ownership in the query โ
โ โ โ
โ โผ โ
โ [6] Handler the only code that has the data โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Token Bucket Over Time
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CAPACITY = 10, REFILL = 1 token / 100ms โ
โ โ
โ tokens โ
โ 10 โคโโโโ โ
โ 8 โคโโโโโโ โ
โ 6 โคโโโโโโโโ โ
โ 4 โคโโโโโโโโโโ โ
โ 2 โคโโโโโโโโโโโโ โ
โ 0 โผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโบ time โ
โ burst of 6 steady 10/s burst again โ
โ โ
โ Bursts pass up to capacity; sustained rate is capped โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Credential Stuffing Layers
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ATTACKER HOLDS email + password pairs from breach โ
โ โ
โ password in breach? โโ yes โโโบ rejected at signup โ
โ โ no โ
โ โผ โ
โ login attempt โโโบ rate limit per account + per IP โ
โ โ โ
โ โผ โ
โ password correct? โโ no โโโบ uniform 401, same time โ
โ โ yes โ
โ โผ โ
โ known device? โโ no โโโบ step-up: TOTP or passkey โ
โ โ yes โ
โ โผ โ
โ session issued โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
GraphQL Cost Surface
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ QUERY COST โ
โ โ
โ { product(id: 1) { name } } depth 2, cost 1 โ
โ โ
โ { product(id: 1) { depth 4, cost 100 โ
โ reviews(first: 50) { โ
โ author { name } } } } โ
โ โ
โ { a:product(id:1){...} depth 2, cost 5000 โ
โ b:product(id:2){...} aliases bypass depth โ
โ ... 50 aliases } โ
โ โ
โ ONE HTTP REQUEST โโโบ unbounded database reads โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| OWASP API1:2023 | Broken Object Level Authorization |
| OWASP API4:2023 | Unrestricted Resource Consumption |
| OWASP API5:2023 | Broken Function Level Authorization |
| Rate limit status | 429 Too Many Requests (RFC 6585) |
| Retry header | Retry-After |
| Draft headers | RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset |
| Atomic counter | Redis Lua script or EVAL |
| Recommended KDF | Argon2id, 19 MiB, 2 iterations, 1 lane |
| Breach lookup | Pwned Passwords range API, 5-char SHA-1 prefix |
| GraphQL depth limit | Typical ceiling 7โ10 |
| GraphQL cost budget | Per-schema, argument-scaled |
Key takeaways:
- Authorization comes before rate limiting. A rate limit slows an attacker down; a missing object check hands over the data on the first request. The ownership condition belongs in the query’s
WHEREclause so that a non-owned row is genuinely absent rather than fetched and then discarded. - A limiter without atomicity is not a limiter. Read-then-write counters race under concurrency and let bursts through at exactly the moment the limit matters. The read, the refill, the decision, and the write must be one server-side operation.
- The key matters more than the algorithm. Per-IP limiting collapses NAT users into one bucket and is defeated entirely by residential proxies. Per-identity keying is the one that holds, and it requires authentication to exist.
- Credential stuffing is defeated upstream of the endpoint. Reject breached passwords at registration, hash with Argon2id, return identical responses in identical time, and require a second factor when the device is new. A rate limit only makes the stuffing slower.
- GraphQL needs a cost model, not a depth limit. Depth alone misses aliases and argument inflation, and operation batching skips an HTTP-layer limiter completely. Count what the query will actually resolve.
- Scraping is an economics problem. Sequential IDs make the dataset addressable, bounded pagination makes extraction slow, honeypots make automation identifiable, and tarpits make it pay. The technical controls identify the behaviour; the terms of service make it actionable.
Remember: Every one of these mechanisms is a cost control, and none of them is an authentication control. A rate limiter, a bot score, a complexity budget, and a tarpit all change how much the attacker has to spend to get what they want โ they do not change whether they are allowed to have it. That question is answered by authorization, by the ownership check in the query and the scope check on the route, and it has to be answered first, on the first request, before any of the other layers are reached. Build the layers in the order the request travels: reject what must never be served, then slow what should not be fast, then measure the traffic that remains and decide whether it is a customer or a crawler.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!