Fix BOLA (Broken Object Level Authorization) in Fastify
BOLA (Broken Object Level Authorization) is the #1 threat in the OWASP API Security Top 10. In Fastify, this occurs when an endpoint exposes a resource by an identifier (like a UUID or auto-incrementing ID) without verifying if the authenticated user has the rights to access that specific object. Attackers simply iterate through IDs to exfiltrate data. To kill BOLA, you must enforce authorization at the data-access layer using the user's identity context.
The Vulnerable Pattern
fastify.get('/api/invoice/:id', async (request, reply) => {
const { id } = request.params;
// VULNERABILITY: Blindly trusting the ID from the URL
const invoice = await db.invoices.findOne({ id });
if (!invoice) return reply.code(404).send({ error: 'Not found' });
return invoice;
});
The Secure Implementation
The fix relies on 'Scoped Queries'. Instead of fetching a resource by its ID alone, the database query is constrained by the 'ownerId' or 'tenantId' derived from the authenticated user's session. If an attacker tries to access an ID that doesn't belong to them, the query returns null, effectively neutralizing the unauthorized access. Always use Fastify hooks (preHandler) to ensure 'request.user' is populated via a trusted source like a verified JWT before the handler executes.
fastify.get('/api/invoice/:id', { preHandler: [fastify.authenticate] }, async (request, reply) => { const { id } = request.params; const userId = request.user.id; // Extracted from verified JWT/Session// FIX: Scope the query to the authenticated user’s ID const invoice = await db.invoices.findOne({ id, ownerId: userId });
if (!invoice) { // Return 404 to prevent resource enumeration/ID guessing return reply.code(404).send({ error: ‘Invoice not found’ }); } return invoice; });
Your Fastify API
might be exposed to BOLA (Broken Object Level Authorization)
74% of Fastify apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.