How to Implement Permission Checks Without Data Leaks
Enforce authorization without leaking: check at the object level, avoid 403-versus-404 leaks, filter lists by permission, and test every path.
On this page
Introduction
Authorization is where applications most often leak data, not because the login is broken but because a check is missing on a specific object. A route may require authentication and even a role, yet still let a caller act on another user’s record by changing the id in the URL. This is the insecure direct object reference class, and it survives because the missing check is invisible in code that otherwise looks protected.
This tutorial covers object-level authorization, the choice between 403 and 404 to avoid leaking existence, scoping list queries to the caller’s permission, and testing every verb and route. The examples use a typical REST API, and the reasoning applies to any access-controlled resource.
Authorize the object, not just the route
A route-level check answers ‘may this caller use this endpoint’, which is necessary but not sufficient. The object-level check answers ‘may this caller act on this specific resource’. Fetch the resource by id and verify the caller is permitted on it, whether by ownership, a shared grant, or a role scoped to that object, before performing the action. Without it, the id is an authorization parameter the caller controls.
Do the object check on every verb that touches the resource: read, update, delete, and any action endpoint. It is common to see the read path checked and the update path forgotten, or the opposite, so a user can read but not edit, or worse, edit what they cannot read. Centralize the check in a function that takes the caller and the resource, and call it in every path.
async function getDocument(ctx, id) {
const doc = await documents.findById(id);
if (!doc) return { status: 404 };
if (doc.ownerId !== ctx.userId && !ctx.scopes.includes('docs:read:any')) {
// do not confirm existence if the object belongs to someone else
return { status: 404 };
}
return { status: 200, body: doc };
}
async function updateDocument(ctx, id, patch) {
const doc = await documents.findById(id);
if (!doc || (doc.ownerId !== ctx.userId && !ctx.scopes.includes('docs:write:any'))) {
return { status: 404 }; // same object-level gate on the write path
}
await documents.applyPatch(id, patch);
return { status: 204 };
}
Choose 403 or 404 to avoid leaking existence
The status code is itself information. A 403 ‘forbidden’ confirms the object exists and the caller is simply not allowed, which an attacker can use to enumerate ids: a 403 means the id is real, a 404 means it is not. If existence is sensitive, return 404 for both the missing object and the forbidden one, so the two are indistinguishable.
When existence is not sensitive, 403 is clearer and helps legitimate users understand the failure. Decide per resource: a private document’s existence is sensitive, so return 404; a public resource with a restricted action might use 403 without leaking anything more than the public listing already reveals. Apply the choice consistently, and never return a different status for the two cases by accident.
function notFoundOrForbidden(caller, resource) {
if (!resource) return 404;
if (!canAccess(caller, resource)) {
return resource.existenceSensitive ? 404 : 403;
}
return null;
}
Scope list queries by permission
A single-object check does not protect a list endpoint. A query that returns all documents and then filters them in application code leaks the count and, if a filter is forgotten, the contents. Push the permission into the query: select only rows the caller may see, using an owner column, a membership table, or a row-level security policy, so the database returns only permitted rows.
The same applies to aggregates and counts. A total that includes other users’ rows leaks their volume even if the rows themselves are hidden. Include the permission predicate in every aggregate so a count reflects only the caller’s permitted set. This is also where row-level security earns its place, since it applies the predicate to every query without relying on each one to remember it.
-- list and count within the caller's permission, not filtered afterwards
SELECT id, title FROM documents
WHERE owner_id = $1
OR id IN (SELECT document_id FROM document_grants WHERE user_id = $1)
ORDER BY created_at DESC
LIMIT 50;
Guard privileges that grant future access
Some fields control who can access what later: an owner, a sharing list, a role. A user who can edit those can grant themselves access to another’s data, so writes to them need their own checks. Do not let an update endpoint accept an owner or a grant list unless the caller already has the right to change them, or a permission escalation follows from an otherwise ordinary edit.
Treat permission fields as immutable unless a specific, checked operation changes them. A patch that includes ownerId should be rejected unless the caller is an administrator, and a share operation should verify the caller may share the object and does not exceed their own access. Keep these decisions in named functions, not in the general update path, so they are reviewed and tested as security logic.
function applyPatchChecked(caller, doc, patch) {
const protectedFields = ['ownerId', 'grants', 'role'];
for (const f of protectedFields) {
if (f in patch && !caller.canChangeSharing(doc)) {
throw new Error('cannot modify protected field: ' + f);
}
}
return applyPatch(doc, patch);
}
Test every access path
Write tests that, as user A, attempt to read, update, and delete user B’s object by id, on every route and verb, and assert each is denied with the chosen status. Include the list endpoints and assert the other user’s object does not appear and does not affect a count. Include a test that a patch to a permission field is rejected. These tests catch the missing check that a route-level test would not.
# as user A, try to touch user B's document
curl -s -o /dev/null -w '%{http_code}\n' -H "Authorization: Bearer $A" http://localhost:3000/documents/$B_DOC # 404
curl -s -o /dev/null -w '%{http_code}\n' -H "Authorization: Bearer $A" -X PATCH -d '{"title":"x"}' http://localhost:3000/documents/$B_DOC # 404
curl -s -H "Authorization: Bearer $A" http://localhost:3000/documents | grep -c "$B_DOC" # 0
Common pitfalls
Checking only the route and not the object, a 403-versus-404 difference that lets ids be enumerated, filtering a list in application code instead of in the query, forgetting the update and delete paths, and letting a patch change an owner or a grant list are the recurring mistakes. Object-level checks on every verb, a deliberate status choice, permission-scoped queries, and protected-field guards address them.
Conclusion
Authorization leaks happen at the object, not the route. Check permission on the specific resource for every verb, choose 403 or 404 deliberately to avoid confirming existence, push the permission into list and count queries, and guard the fields that grant future access. Self-check by acting as one user against another’s object on every path and asserting denial. Then a guessed id is not a key to someone else’s data.
Sources: OWASP: Authorization cheat sheet, OWASP: Insecure direct object references (IDOR), MITRE: CWE-639 authorization bypass through user-controlled key.
FAQ
- Why is checking the route not enough?
- A route check confirms the caller may call that endpoint, not that they may act on that object. Without an object-level check, changing the id in the URL lets one user reach another's record. Authorize the resource, not just the route.
- 403 or 404 for an object the user cannot access?
- If confirming the object exists is itself sensitive, return 404 so the caller cannot enumerate ids. If existence is not sensitive, 403 is clearer. Decide per resource and apply it consistently.
Report a problem with this articleOpens a pre-filled issue on GitHub.