Defensive Programming can be very easy with Symfony HttpClient
Source: Dev.to
Problem
If your app lets users submit URLs that you then fetch—for link previews, webhooks, or RSS feeds—you have a serious security problem waiting to happen. An attacker can submit something like http://127.0.0.1/admin or http://169.254.169.254 (AWS metadata endpoint) and your server will happily fetch it. This is a Server‑Side Request Forgery (SSRF) attack.
Solution
Symfony provides a built‑in solution: NoPrivateNetworkHttpClient. It decorates your existing HTTP client and blocks requests to private IP ranges (or any ranges you configure).
Before
getPayload()
->getString('url');
$response = $this->client
->request('GET', $url);
return new JsonResponse(
$response->getContent()
);
}
}
After
safeClient = new NoPrivateNetworkHttpClient($client);
}
#[Route('/api/preview', methods: ['POST'])]
public function preview(
Request $request,
): JsonResponse {
$url = $request->getPayload()
->getString('url');
$response = $this->safeClient
->request('GET', $url);
return new JsonResponse(
$response->getContent()
);
}
}
NoPrivateNetworkHttpClient is a decorator, so you simply wrap your existing client—no other code changes are required. Consult the Symfony documentation to configure the specific IPs or IP ranges you want to disallow.
If you fetch user‑submitted URLs and aren’t using this decorator, you should start doing so.
Watch the explanation on YouTube.