GuardAPI Logo
GuardAPI

Fix Logic Flow Bypass in Fastify

Logic flow bypasses in Fastify often manifest when developers assume that calling 'reply.send()' acts like a 'return' statement. In an async handler, execution continues unless explicitly halted. Attackers exploit this to trigger side effects (like database writes) even after a 401 Unauthorized response has been issued. Proper flow control requires strict lifecycle management and explicit returns.

The Vulnerable Pattern

fastify.post('/api/reset-password', async (request, reply) => {
  const { token, newPassword } = request.body;

if (!isValidToken(token)) { reply.code(403).send({ error: ‘Invalid token’ }); // VULNERABILITY: Missing ‘return’. The code below executes anyway. }

// This side effect occurs even if the token is invalid await db.users.updatePassword(request.user.id, newPassword); return { message: ‘Password updated’ }; });

The Secure Implementation

The fix involves two layers of defense. First, use 'return reply' or 'return' after sending an error response in async handlers to prevent execution fall-through. Second, shift authorization and validation logic into 'preHandler' hooks. Fastify's lifecycle is designed so that if a hook sends a response and returns the reply object, the subsequent handler is never executed, providing a clean separation of concerns and preventing logic bypasses.

fastify.post('/api/reset-password', {
  preHandler: async (request, reply) => {
    if (!isValidToken(request.body.token)) {
      reply.code(403).send({ error: 'Invalid token' });
      return reply; // Explicitly halt the lifecycle
    }
  }
}, async (request, reply) => {
  // This handler only executes if the preHandler succeeds
  await db.users.updatePassword(request.user.id, request.body.newPassword);
  return { message: 'Password updated' };
});
System Alert • ID: 9890
Target: Fastify API
Potential Vulnerability

Your Fastify API might be exposed to Logic Flow Bypass

74% of Fastify apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

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.