Every Request, Every Record
An agent added sharing to your document app. The owner of a document can share it with a teammate as a viewer, who can read it, or as an editor, who can change it. You share a document with a colleague as a viewer and open the app as her. The Edit button is gone, so the feature looks finished. The endpoint behind the page looks like this.
app.patch("/api/documents/:id", requireSession, async (req, res) => {
const role = await roleOn(req.session.userId, req.params.id); // "owner" | "editor" | "viewer" | null
if (role === null) return res.status(404).end();
const { rows } = await db.query(
`UPDATE documents SET title = $1, body = $2, updated_at = now()
WHERE id = $3
RETURNING id, title, body`,
[req.body.title, req.body.body, req.params.id],
);
res.json(rows[0]);
});A stranger gets a 404, because the handler looks up the caller's role on this document and stops when there is none. Everyone with any role then gets the write. Your colleague opens the browser's developer tools, copies the request the page makes, changes the method to PATCH and adds a body. The document is overwritten. The hidden button kept an honest user from clicking it, and the endpoint never asked whether a viewer may edit.
The requireSession middleware did its job, and so did the role lookup. The handler confirmed who is asking and that the caller has some standing on this document. It skipped the question of what that standing allows. The plainest form of this bug is an endpoint that returns any record whose ID you put in the URL after checking only that you are logged in. This handler gets one step past that and still fails.
Two questions on every request
Authentication answers "who is making this request?" A password, a passkey or a session cookie is evidence of identity. Authorization answers "may this caller perform this action on this particular thing?" That second question has a different answer for every combination of user, action and record, so it has to be asked every time.
Authorization happens at two levels. Function-level authorization decides whether this kind of user may call this kind of endpoint at all: members may edit documents, and only admins may delete a whole workspace. Object-level authorization decides whether this caller may touch this specific record in this way: the colleague may read the quarterly plan because it was shared with her, and may not edit it. A missing object-level check is what the OWASP API Security Top 10 lists first, under the name broken object-level authorization, or BOLA. A right to a record is not one right. Reading, editing, deleting and sharing each need their own answer.
Before an endpoint reads or changes an object, it has to confirm four things:
- The request carries a valid credential: the session exists on the server, or the token's signature, expiry and issuer check out.
- The caller's role allows this action on this type of object.
- This specific object belongs to the caller's account, or was shared with them at a level that allows this action.
- Every field in the response is one this caller is allowed to see. An internal moderation note on the document row should stay on the server.
The agent's code does the first, and half of the third. Here is the handler with the action check added.
type Role = "owner" | "editor" | "viewer";
type Action = "read" | "edit" | "share";
const ALLOWED: Record<Action, Role[]> = {
read: ["owner", "editor", "viewer"],
edit: ["owner", "editor"],
share: ["owner"],
};
async function roleOn(userId: string, documentId: string): Promise<Role | null> {
const { rows } = await db.query(
"SELECT role FROM document_members WHERE document_id = $1 AND user_id = $2",
[documentId, userId],
);
return rows[0]?.role ?? null;
}
app.patch("/api/documents/:id", requireSession, async (req, res) => {
const role = await roleOn(req.session.userId, req.params.id);
if (role === null) return res.status(404).end();
if (!ALLOWED.edit.includes(role)) return res.status(403).end();
const { rows } = await db.query(
`UPDATE documents SET title = $1, body = $2, updated_at = now()
WHERE id = $3
RETURNING id, title, body`,
[req.body.title, req.body.body, req.params.id],
);
res.json(rows[0]);
});The role is resolved on the server, from the session's user ID and the document ID in the path, and nothing in the request body can claim a role. A new action has to be added to the table on purpose, and an action missing from it is allowed to nobody. The response lists columns by name, which covers the fourth check.

The two refusals differ on purpose. A viewer already knows the document exists, so a 403 tells her nothing new. A stranger gets a 404, the same answer as for an ID that does not exist, so the endpoint cannot be used to learn which IDs are real.
Switching to random IDs, such as UUIDs, makes guessing harder but leaves the hole open. IDs leak through shared links, support tickets, logs and other API responses. Once someone has an ID, only the permission check stands between them and the record.
Proving the fix with a viewer and an editor
You find this bug by acting as several people. Create one account for each role, share a document at each level, then try every action as every account. The test sends its requests straight to the API with each account's cookie, the way the colleague's copied request did, so it does not depend on which buttons the interface shows.
import { test, expect } from "bun:test";
test("only owners and editors can change a document", async () => {
const owner = await signUpAndLogIn("owner@example.com");
const viewer = await signUpAndLogIn("viewer@example.com");
const editor = await signUpAndLogIn("editor@example.com");
const stranger = await signUpAndLogIn("stranger@example.com");
const doc = await createDocument(owner, { title: "Q3 plan", body: "original" });
await shareDocument(owner, doc.id, viewer.email, "viewer");
await shareDocument(owner, doc.id, editor.email, "editor");
const patch = (who: { cookie: string }, body: string) =>
fetch(`${BASE_URL}/api/documents/${doc.id}`, {
method: "PATCH",
headers: { cookie: who.cookie, "content-type": "application/json" },
body: JSON.stringify({ title: "Q3 plan", body }),
});
expect((await patch(viewer, "vandalized")).status).toBe(403);
expect((await patch(stranger, "vandalized")).status).toBe(404);
expect((await readDocument(owner, doc.id)).body).toBe("original");
expect((await patch(editor, "revised")).status).toBe(200);
expect((await readDocument(owner, doc.id)).body).toBe("revised");
});The test reads the document back after the refused attempts, because a handler can write first and return an error afterward. The editor's request is the control. Without it, an endpoint that refuses everyone would pass, and you would have proved nothing. Run the same swap against every endpoint that takes an ID in the path, the query string or the body, including the ones that update, delete and share. A missing check on DELETE is worse than one on GET.
Storing passwords
Authentication usually starts with a password, and the way you store it decides what happens after a breach. An agent asked to "hash passwords" will sometimes write this.
import { createHash } from "node:crypto";
const stored = createHash("sha256").update(password).digest("hex");SHA-256 was designed to be fast, which suits checking file integrity and works against you here. If an attacker copies your users table, they can guess passwords offline, on their own hardware, with no rate limit and no lockout. A single current gaming GPU computes billions of SHA-256 hashes per second.
Work out what that means. A password of eight lowercase letters and digits has 36⁸ possibilities, about 2.8 trillion. At ten billion guesses per second, trying every one takes under five minutes. In practice attackers start with lists of real leaked passwords, so common choices fall in the first second.

Two fixes are needed. The first is a salt: a random value, different for each user, stored next to the hash and mixed into it. Without salts, two users with the same password have the same hash, and one computed guess tests every account at once. With salts, the attacker has to redo the work for each user.
The second fix is a hash designed to be slow, such as Argon2id, scrypt or bcrypt. All three mix in a per-user salt and are tunable, so the cost settings let you choose how much work each guess takes. Argon2id and scrypt raise the memory cost of a guess, which limits how many a GPU can run side by side. bcrypt raises the compute cost only. Suppose they bring the attacker down to 10,000 guesses per second. The same 2.8 trillion possibilities now take about nine years instead of five minutes. Weak passwords from a leaked list still fall, but everything else becomes expensive, and you get time to notice the breach and force resets.

The playground takes the attacker's side against a table stored the agent's way. Browsers do not ship Argon2id, so the slow hash it times is PBKDF2, an older design that the OWASP cheat sheet still accepts at 600,000 iterations of HMAC-SHA-256.
const bytes = (s: string) => new TextEncoder().encode(s);
const hex = (buf: ArrayBuffer) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join("");
const sha256 = async (s: string) => hex(await crypto.subtle.digest("SHA-256", bytes(s)));
// The stolen users table. Passwords were stored as SHA-256 with no salt.
const users = [
{ name: "alice", hash: await sha256("sunshine1") },
{ name: "bob", hash: await sha256("vR7#qe!2Lm") },
{ name: "carol", hash: await sha256("sunshine1") },
];
// The attacker's guess list. Real lists hold billions of leaked passwords.
const guesses = ["123456", "password", "qwerty", "iloveyou", "sunshine1", "letmein"];
let computed = 0;
for (const guess of guesses) {
const h = await sha256(guess);
computed++;
for (const u of users) if (u.hash === h) console.log(`cracked ${u.name}: ${guess}`);
}
console.log(`${computed} hashes checked against all ${users.length} accounts at once`);
// How fast can this one browser tab guess with SHA-256?
let n = 0;
const start = performance.now();
while (performance.now() - start < 500) await sha256(`guess-${n++}`);
console.log(`SHA-256: about ${(Math.round((n * 2) / 1000) * 1000).toLocaleString("en-US")} guesses per second`);
// One guess through a slow hash.
const material = await crypto.subtle.importKey("raw", bytes("sunshine1"), "PBKDF2", false, ["deriveBits"]);
const t = performance.now();
await crypto.subtle.deriveBits({ name: "PBKDF2", hash: "SHA-256", salt: bytes("alice-random-salt"), iterations: 600_000 }, material, 256);
console.log(`PBKDF2 at 600,000 rounds: ${Math.round(performance.now() - t)} ms per guess`);Output
Alice and Carol fall to the same single guess, because the same password gave them the same hash. Compare the two speeds it prints: each PBKDF2 guess costs thousands of times the work of a SHA-256 guess, and an attacker pays that price on every guess for every user.
On the server, Argon2id takes a few lines.
// Bun's built-in Argon2id, with its default cost settings. In Node, the argon2 package does the same job.
async function hashPassword(password: string): Promise<string> {
return Bun.password.hash(password, { algorithm: "argon2id" }); // a random salt is generated and stored in the result
}
async function checkPassword(stored: string, attempt: string): Promise<boolean> {
return Bun.password.verify(attempt, stored); // false on a wrong password
}The stored string starts with $argon2id$ and carries the cost settings and the salt alongside the hash, so you can raise the cost later and rehash each user's password at their next login. To catch the mistake in review, search for md5, sha1, sha256 or sha512 anywhere near the word "password," and for any hashing call that does not generate a per-user salt.
Passkeys remove the stored secret entirely. The user's device holds a private key, the server stores only the matching public key, and each login signs a fresh challenge from the server. The browser ties each passkey to the site's domain, so a look-alike phishing domain cannot get a valid signature, and a stolen copy of your database contains nothing an attacker can log in with.
Tokens that prove nothing
After login, the server gives the client something to present on later requests. A session cookie is a random ID that points to a record on the server. A signed token, usually a JSON Web Token (JWT), carries the user's identity and an expiry time inside it, with a signature that proves the server issued it.
The signature only helps if you check it. This line reads the token's contents and verifies nothing.
const claims = jwt.decode(token); // jsonwebtoken: parses the payload, checks nothingAnyone can write a token that says "sub": "admin" and it will be accepted. The correct call verifies the signature, pins the algorithm, and checks issuer and audience, and the code after it requires an expiry.
const claims = jwt.verify(token, publicKey, {
algorithms: ["RS256"],
issuer: "https://auth.example.com",
audience: "api.example.com",
}) as jwt.JwtPayload;
if (typeof claims.exp !== "number") throw new Error("token has no expiry");Pinning the algorithm matters because the token's own header names the algorithm used to sign it, and the attacker writes that header. Older versions of several JWT libraries accepted "alg": "none", meaning no signature at all, or could be tricked into checking an HMAC signature using the server's public key as the secret. Telling the library which algorithm you expect closes both. jwt.verify in the jsonwebtoken package rejects an expired token only when the token carries an exp claim. A token with no exp never expires, which is why the line after the call rejects any payload without a numeric one. In other libraries, confirm how expiry is checked.
The playground builds toy versions of both calls on the browser's HMAC, so it signs with HS256 where the call above uses RS256. The toy verify rejects any token that is not exactly three parts, pins the algorithm, checks the signature, issuer and audience, and requires an unexpired exp. It hands both a real token and seven bad ones.
const bytes = (s: string) => new TextEncoder().encode(s);
const b64url = (b: Uint8Array) => btoa(String.fromCharCode(...b)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
const unb64url = (s: string) => Uint8Array.from(atob(s.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));
const part = (o: object) => b64url(bytes(JSON.stringify(o)));
const json = (s: string) => JSON.parse(new TextDecoder().decode(unb64url(s)));
const key = await crypto.subtle.importKey("raw", bytes("a server secret of at least 32 bytes"), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
const NOW = 1_800_000_000; // a fixed clock, in seconds
async function sign(claims: object): Promise<string> {
const data = `${part({ alg: "HS256", typ: "JWT" })}.${part(claims)}`;
const sig = new Uint8Array(await crypto.subtle.sign("HMAC", key, bytes(data)));
return `${data}.${b64url(sig)}`;
}
// Like jwt.decode: reads the payload, checks nothing.
function decode(token: string) {
return json(token.split(".")[1]);
}
const ISSUER = "https://auth.example.com";
const AUDIENCE = "api.example.com";
// Like jwt.verify with the algorithm, issuer and audience pinned, followed by the required-expiry check.
async function verify(token: string) {
const segments = token.split(".");
if (segments.length !== 3) throw new Error("malformed token");
const [header, payload, sig] = segments;
const alg = json(header).alg;
if (alg !== "HS256") throw new Error(`algorithm ${alg} not allowed`);
if (!(await crypto.subtle.verify("HMAC", key, unb64url(sig), bytes(`${header}.${payload}`)))) throw new Error("bad signature");
const claims = json(payload);
if (claims.iss !== ISSUER) throw new Error("wrong issuer");
if (claims.aud !== AUDIENCE) throw new Error("wrong audience");
if (typeof claims.exp !== "number") throw new Error("token has no expiry");
if (claims.exp <= NOW) throw new Error("token expired");
return claims;
}
const ours = { iss: ISSUER, aud: AUDIENCE };
const issued = await sign({ ...ours, sub: "user-42", exp: NOW + 900 });
const [issuedHeader, , issuedSig] = issued.split(".");
const tokens: Record<string, string> = {
"issued by the server": issued,
"alg none, sub admin": `${part({ alg: "none", typ: "JWT" })}.${part({ ...ours, sub: "admin", exp: NOW + 900 })}.`,
"payload edited to admin": `${issuedHeader}.${part({ ...ours, sub: "admin", exp: NOW + 900 })}.${issuedSig}`,
"signed, no exp": await sign({ ...ours, sub: "user-42" }),
"signed, expired": await sign({ ...ours, sub: "user-42", exp: NOW - 60 }),
"signed, other issuer": await sign({ iss: "https://other.example", aud: AUDIENCE, sub: "admin", exp: NOW + 900 }),
"signed for another API": await sign({ iss: ISSUER, aud: "billing.example.com", sub: "user-42", exp: NOW + 900 }),
"issued, extra segment": `${issued}.extra`,
};
for (const [label, token] of Object.entries(tokens)) {
const result = await verify(token).then((c) => `accepted as ${c.sub}`, (e: Error) => `rejected, ${e.message}`);
console.log(`${label.padEnd(24)} decode: ${decode(token).sub.padEnd(8)} verify: ${result}`);
}Output
Signed tokens have a cost that Evert Pot's essay on JWTs spells out: with purely stateless verification the server stores nothing, so logging a user out or revoking a stolen token does nothing until the token expires. Immediate revocation needs a server-side check, such as a denylist of token IDs or a per-user session version that each token must match. If you use stateless tokens, keep their lifetime short, minutes rather than days, and pair them with a refresh token that the server can revoke.
Reset and invite tokens
A password-reset link is a credential. Whoever holds it can take over the account. So it needs the same care as a password, and two properties the agent's version often lacks: it must expire, and it must work once.
import { randomBytes, createHash } from "node:crypto";
const token = randomBytes(32).toString("base64url"); // goes in the email
const tokenHash = createHash("sha256").update(token).digest("hex"); // goes in the database
await db.query(
`INSERT INTO reset_tokens (user_id, token_hash, expires_at)
VALUES ($1, $2, now() + interval '30 minutes')`,
[userId, tokenHash],
);Storing only the hash means a leaked database gives the attacker no working links. A fast hash is correct here, unlike with passwords, because the token is 256 random bits and there is nothing to guess from a list. Redeeming the token consumes it in a single statement that checks and marks it, so two simultaneous requests cannot both succeed. That statement and the password update run in one transaction, so a failure between them cannot use up the token without changing the password.
BEGIN;
UPDATE reset_tokens
SET used_at = now()
WHERE token_hash = $1 AND used_at IS NULL AND expires_at > now()
RETURNING user_id;
-- a row came back: UPDATE users SET password_hash = $2 WHERE id = <that user_id>;
-- no row came back: ROLLBACK
COMMIT;No row returned means the token is unknown, used or expired. Redeem it when the user submits the new-password form, not when the link is opened, because email security scanners open links automatically. After the transaction commits, invalidate the user's existing sessions and any other outstanding reset tokens.
The block above is PostgreSQL. The playground runs the same consuming statement on SQLite, which spells the clock datetime('now'), and next to it the agent's version, a lookup that only asks whether the token exists. changes() reports how many rows the last update claimed.
CREATE TABLE reset_tokens (
token_hash TEXT PRIMARY KEY,
user_id INTEGER NOT NULL,
expires_at TEXT NOT NULL,
used_at TEXT
);
INSERT INTO reset_tokens VALUES
('hash-of-link-A', 7, datetime('now', '+30 minutes'), NULL),
('hash-of-link-B', 8, datetime('now', '-5 minutes'), NULL);
CREATE TABLE attempts (attempt TEXT, accepted INTEGER);
-- The consuming statement, three times.
UPDATE reset_tokens SET used_at = datetime('now')
WHERE token_hash = 'hash-of-link-A' AND used_at IS NULL AND expires_at > datetime('now');
INSERT INTO attempts VALUES ('consume: link A, first use', changes());
UPDATE reset_tokens SET used_at = datetime('now')
WHERE token_hash = 'hash-of-link-A' AND used_at IS NULL AND expires_at > datetime('now');
INSERT INTO attempts VALUES ('consume: link A, second use', changes());
UPDATE reset_tokens SET used_at = datetime('now')
WHERE token_hash = 'hash-of-link-B' AND used_at IS NULL AND expires_at > datetime('now');
INSERT INTO attempts VALUES ('consume: link B, expired', changes());
-- The agent's version: does a token with this hash exist?
INSERT INTO attempts SELECT 'lookup: link A, already used', count(*)
FROM reset_tokens WHERE token_hash = 'hash-of-link-A';
INSERT INTO attempts SELECT 'lookup: link B, expired', count(*)
FROM reset_tokens WHERE token_hash = 'hash-of-link-B';
SELECT attempt, accepted FROM attempts;Output
Delegated access

Sometimes a user wants another system to act for them: a calendar app reading their email, or a deploy tool pushing to their repository. OAuth handles this by giving the other system an access token with a limited scope, which the user can revoke, instead of the user's password. Current guidance, collected in RFC 9700, is to use the authorization-code flow with PKCE for every kind of client.
Delegation creates a specific risk that Norm Hardy described in "The Confused Deputy": a program that holds its own broad authority gets tricked into using it for someone who lacks that authority. An agent's integration that runs with an admin token and acts on any user's request is that program. The fix is the one from the document endpoint: authorize each action for the user it acts for first, then let the integration use its own credentials, scoped to what it needs. The confused deputy skips that first step and spends its own authority on whoever asks.
An endpoint may act on a record only after a check that names the caller, the record and the action. If you cannot point to the line that ties this caller to this record for this action, the endpoint serves anyone with a login.