Broken Access Control
IDOR, privilege escalation, and implementing role-based access control that actually prevents unauthorized actions
Skills taught: websecurity.access-control, websecurity.idor, websecurity.privilege-escalation, websecurity.rbac, websecurity.abac
IDOR — Insecure Direct Object Reference
IDOR is the #1 access control vulnerability: an API endpoint that uses a user-supplied ID to look up a resource without checking whether the requesting user is allowed to access that resource. It's simple, it's everywhere, and it's often missed in code review because it looks like normal CRUD code.
// VULNERABLE — no ownership check
app.get('/api/invoices/:id', authenticate, async (req, res) => {
const invoice = await db.invoices.findById(req.params.id);
if (!invoice) return res.status(404).json({ error: 'Not found' });
res.json(invoice); // Returns ANY invoice to ANY authenticated user
});
// Attack: attacker has invoice id=100 (their own)
// They try GET /api/invoices/101, 102, 103... and read all invoices
// Sequential or guessable IDs make this trivial
// SECURE — ownership check on every request
app.get('/api/invoices/:id', authenticate, async (req, res) => {
const invoice = await db.invoices.findById(req.params.id);
if (!invoice) return res.status(404).json({ error: 'Not found' });
// Check ownership — does this invoice belong to the requesting user?
if (invoice.userId !== req.user.id) {
// Return 404, not 403 — don't reveal the resource exists
// A 403 tells the attacker 'this id is valid but you can't access it'
return res.status(404).json({ error: 'Not found' });
}
res.json(invoice);
});
// ALTERNATIVE — query by user AND id simultaneously
// Even cleaner: impossible to retrieve a resource you don't own
app.get('/api/invoices/:id', authenticate, async (req, res) => {
const invoice = await db.invoices.findOne({
id: req.params.id,
userId: req.user.id, // Combined query — no ownership check needed separately
});
if (!invoice) return res.status(404).json({ error: 'Not found' });
res.json(invoice);
});
Role-based access control (RBAC)
// Define roles and their permissions
const PERMISSIONS = {
'user': ['read:own-profile', 'read:own-invoices', 'write:own-profile'],
'admin': ['read:own-profile', 'read:own-invoices', 'write:own-profile',
'read:all-users', 'write:all-users', 'delete:users', 'read:all-invoices'],
} as const;
type Role = keyof typeof PERMISSIONS;
type Permission = (typeof PERMISSIONS)[Role][number];
// Permission check middleware factory
function requirePermission(permission: Permission) {
return (req: Request, res: Response, next: NextFunction) => {
const userRole = req.user?.role as Role;
const userPermissions = PERMISSIONS[userRole] ?? [];
if (!userPermissions.includes(permission)) {
return res.status(403).json({ error: 'Forbidden' });
}
next();
};
}
// Apply at route level
app.get('/api/admin/users', authenticate, requirePermission('read:all-users'), listUsers);
app.delete('/api/admin/users/:id', authenticate, requirePermission('delete:users'), deleteUser);
// PRIVILEGE ESCALATION — a common mistake
app.put('/api/users/:id', authenticate, async (req, res) => {
// VULNERABLE: user can send { role: 'admin' } and escalate themselves
await db.users.update(req.params.id, req.body);
// SECURE: only allow updating fields the user is permitted to change
const { name, email, avatar } = req.body; // Allowlist fields explicitly
await db.users.update(req.params.id, { name, email, avatar });
// 'role' is not in the allowlist — cannot be changed via this endpoint
});
// Admin-only endpoint to change roles
app.put('/api/admin/users/:id/role',
authenticate,
requirePermission('write:all-users'),
async (req, res) => {
const { role } = req.body;
if (!['user', 'moderator', 'admin'].includes(role)) {
return res.status(400).json({ error: 'Invalid role' });
}
await db.users.update(req.params.id, { role });
res.json({ success: true });
}
);
Tip: Use UUIDs instead of sequential IDs for user-facing resources. Sequential IDs (1, 2, 3...) make IDOR trivial — an attacker just increments the number. UUIDs (550e8400-e29b-41d4-a716-446655440000) are unguessable. They don't replace ownership checks (you still need to verify the user owns the resource), but they dramatically increase the difficulty of a brute-force IDOR attack. Use crypto.randomUUID() (built into Node.js 15+) or the uuid package.
Frequently Asked Questions
What's the difference between authentication and authorization?
Authentication is 'who are you?' — verifying identity (login with password, JWT, session cookie). Authorization is 'what are you allowed to do?' — checking permissions after identity is confirmed. The access control bugs in this lesson are authorization failures: the user is authenticated (we know who they are) but the app doesn't check if they're authorized to access that specific resource. Both checks are required; most auth bugs are actually authorization bugs.