Build Safer Server-Side Fetch Features: An SSRF Review Checklist

A service that accepts a hostname or URL and fetches it from the server is a network client controlled in part by a caller. That pattern appears in URL previews, webhook testers, certificate checkers, image importers, uptime checks, and DNS tools. If the application can reach destinations that ordinary users cannot, a weak target check can turn the feature into a proxy to internal systems or cloud metadata services. OWASP classifies this as server-side request forgery (SSRF).

The defense depends on what the feature must do. If it only needs to call a known provider, an allowlist is usually simpler and safer than accepting arbitrary destinations. If arbitrary public hosts are a real product requirement, use layered validation and outbound network controls. The examples below are for defensive engineering and authorized testing of your own application.

Decide whether callers need to supply a URL

Prefer structured input such as a hostname, then let the server choose the scheme, port, path, and request method. A full URL lets a caller influence several parsing decisions at once: credentials in the authority, unusual IP representations, alternate schemes, fragments, ports, paths, and query parameters. If a URL is essential, parse it with one well-maintained URL implementation, require https: unless the function explicitly supports another scheme, reject username/password components, restrict ports, and rebuild the outbound URL from validated pieces.

Do not use a substring or prefix rule such as url.startsWith("https://trusted.example"); an attacker-controlled authority can contain that text in a different location. Compare the parsed hostname exactly against an allowlist. Be careful when internationalized domain names or trailing dots are accepted: normalize them consistently before policy checks and logs.

Validate the resolved address, not only the spelling

A syntactically valid public-looking name may resolve to a private or special-use address. Resolve both IPv4 and IPv6 records and reject the target if any answer is not allowed. Include loopback, private, link-local, multicast, unspecified, reserved, and IPv4-mapped IPv6 ranges. Test alternate numeric address forms against the exact URL parser and network library used by the application; parsers can normalize forms differently.

Checking DNS once and letting the HTTP client resolve the hostname again creates a time-of-check/time-of-use gap. A domain can return a public address during validation and a private one during connection. Pin the connection to an address that passed validation, while preserving the hostname for TLS certificate validation and the HTTP Host header. If the HTTP client cannot safely pin a validated address, use an egress proxy or another network-layer control rather than assuming a prior lookup is sufficient.

An explicit allowlist is preferable when possible. For an open public fetcher, blocklists are a risk-reduction control, not a proof that every destination is safe. Cloud egress rules should independently prevent access to metadata and internal address ranges.

Treat every redirect as a new destination

Automatic redirects bypass a check that only examines the initial host. Disable automatic redirect following. If redirects are part of the product behavior, accept only a small bounded number, resolve each Location relative to the current URL, parse it again, apply the complete policy, resolve and validate its addresses, and pin the next connection. Do not forward authorization, cookies, or other sensitive headers across origins. For many security tools, returning the initial response's redirect status and location is safer than following it.

Bound the network work

SSRF prevention is also about resource use and information exposure. Set a short connection and total timeout, cap response bytes while streaming, limit redirect count, restrict methods to what the feature needs, and avoid returning raw upstream error messages. Do not send credentials or user-supplied headers to the target. A generic “target could not be checked” response can be paired with a request ID in server logs. Do not log full URLs if query strings may contain tokens or private data.

Rate-limit requests per client and target. Apply global concurrency limits so one caller cannot exhaust serverless function slots. Cache deterministic results carefully, but do not allow one caller to use cache behavior to infer another user's data. If a feature only needs DNS, use a DNS resolver rather than making a general HTTP request.

Write tests that prove no connection was attempted

For rejected targets, assert both the API error and the absence of a socket or fetch. Cover loopback literals, private IPv4 and IPv6, link-local cloud metadata addresses, IPv4-mapped IPv6, unusual numeric spellings, credentials in URLs, unsupported ports and schemes, and hostnames that resolve to blocked ranges. Mock DNS so a normal-looking test name returns a private answer. Also mock a mixed public/private answer and require rejection of the whole name rather than choosing the public result opportunistically.

Add redirect cases: a public first response redirects to loopback, to a private IPv6 address, and to another hostname that resolves differently on the second lookup. Assert that each case is blocked before a connection is opened. Include an allowed public destination test so the guard does not silently disable valid product behavior. Keep tests deterministic and local; do not probe a third-party service or cloud metadata endpoint.

An illustrative test shape is:

const fetchSpy = vi.spyOn(globalThis, 'fetch');
const response = await app.request('/check?host=internal.test');

expect(response.status).toBe(400);
expect(await response.json()).toMatchObject({ code: 'FORBIDDEN_TARGET' });
expect(fetchSpy).not.toHaveBeenCalled();

The production implementation may use an HTTP dispatcher or socket adapter instead of global fetch; spy on the lowest connection boundary the service actually uses. A high-level mock that returns an error without checking whether a connection was attempted will miss the security property.

Review deployment and operations too

Use an outbound firewall or isolated egress proxy to deny internal ranges even if application validation regresses. Keep metadata-service protections enabled in the cloud platform. Make the outbound service identity distinct from application storage and control-plane identities. Monitor blocked-target counts, unusual request volume, timeouts, and unexpected destinations, while keeping sensitive URL data out of routine logs. Revisit the address policy when runtimes, DNS libraries, or networking infrastructure change.

SSRF protections should be centralized so each new feature does not invent a slightly different hostname check. A shared helper should own parsing, address classification, resolution, redirects, connection pinning, limits, and safe errors. Service-specific code should provide only the allowed operation and target policy. This makes regression testing and future review substantially easier.

Review checklist

  1. Can the product use a fixed destination allowlist instead of arbitrary URLs?
  2. Does the server construct the URL from validated components?
  3. Are every DNS answer and all IPv4/IPv6 special ranges checked?
  4. Is the socket pinned to a validated address to prevent DNS rebinding?
  5. Are redirects disabled or revalidated hop by hop?
  6. Are ports, schemes, methods, timeouts, response bytes, concurrency, and request rates bounded?
  7. Do negative tests assert that no socket or fetch occurs?
  8. Does network egress policy independently block internal and metadata destinations?

OWASP's SSRF Prevention Cheat Sheet discusses allowlists, DNS resolution, redirect handling, and network-layer controls. RFC 3986 defines URI authority and host syntax; its special forms are one reason ad hoc URL parsing is risky. Use the parser and connection behavior from your real runtime when writing regression tests.

References


Editorial status: Owner authorized publication without an individual reviewer. Guidance is defensive and intended for controlled testing.