Fix SSRF (Server Side Request Forgery) in Fastify
SSRF in Fastify environments typically occurs when an application accepts a user-supplied URL and fetches it using clients like undici, axios, or node-fetch without validation. This allows attackers to scan internal networks, access cloud metadata services (like 169.254.169.254), or bypass firewalls by making the server act as a proxy.
The Vulnerable Pattern
const fastify = require('fastify')({ logger: true }); const { request } = require('undici');
fastify.get(‘/fetch-metadata’, async (request, reply) => { const { targetUrl } = request.query; // CRITICAL VULNERABILITY: Direct use of user input in a network request const { body } = await request(targetUrl); return body; });
The Secure Implementation
To kill SSRF, you must implement a multi-layered defense. First, use the built-in 'URL' constructor to parse input; never use regex for URL parsing. Second, enforce a strict protocol whitelist (HTTPS only) to prevent 'file://' or 'gopher://' attacks. Third, implement a strict domain allowlist. Fourth, disable redirects in your HTTP client (maxRedirections: 0) to prevent 'Open Redirect' to SSRF bypasses. For high-security environments, resolve the hostname to an IP and verify it is not within a private CIDR block (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) before initiating the connection.
const fastify = require('fastify')({ logger: true }); const { request } = require('undici'); const { URL } = require('url');const ALLOWED_DOMAINS = [‘api.trusted-partner.com’, ‘static.internal.io’];
fastify.get(‘/fetch-metadata’, async (req, reply) => { const { targetUrl } = req.query; try { const parsed = new URL(targetUrl);
// 1. Protocol Whitelisting if (parsed.protocol !== 'https:') { return reply.code(400).send({ error: 'Only HTTPS allowed' }); } // 2. Domain Allowlisting if (!ALLOWED_DOMAINS.includes(parsed.hostname)) { return reply.code(403).send({ error: 'Disallowed destination' }); } const { body } = await request(parsed.href, { maxRedirections: 0, // 3. Prevent Redirect SSRF }); return body;
} catch (err) { return reply.code(400).send({ error: ‘Invalid URL’ }); } });
Your Fastify API
might be exposed to SSRF (Server Side Request Forgery)
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.