NewWe open-sourced 50+ Laravel packages
Custom AI apps, agents and automation — Roundly ConsultingRoundly
All packages
Safe Fetch for Laravel

Guarded requests

Http::safe() guards any Laravel HTTP request. The URL is rebuilt from a strict parse, every address its host resolves to is judged, the connection is pinned to those addresses through curl with no proxy and no reused connection, and the address curl connected to is checked:

Http::safe()->post($url, $payload);                                          // the configured policy
Http::safe(SafeFetch::policy()->followRedirects())->post($url, $payload);    // a policy for this call
Http::withToken($token)->safe()->post($url, $payload);                       // chains either way
SafeFetch::guard(Http::withToken($token)->timeout(10), $policy)->post($url); // the manager, no macro
SafeFetch::http($policy)->get($url);                                         // a new guarded request

What the guard does to a request

  • Refuses without curl (cannot_pin, before anything is built — fail closed).
  • Refuses a request that already has a client of its own (setClient()), a Guzzle handler option (Http::globalOptions(), withOptions() before or after safe()) or that is already guarded — UnsafeRequestOptions.
  • Sets its own pinned handler — always curl, never a stream handler (which would ignore the pin), never the host’s handler. stream => true streams through that curl handler (see Streaming responses).
  • Turns Guzzle’s own redirects off; redirects are the guard’s.
  • Adds the guard middleware, which asks the manager to vet each hop, so SafeFetch::fake() sees every hop.
  • Sends through its own client, which sees each request’s final options before Guzzle does — a handler added after safe() is refused at send time.

Per hop

  • The URL is vetted (SafeFetch::vet() semantics) — a refusal rejects the request and nothing is sent.
  • The request goes to the rebuilt URL; on a hop to another origin than the first, credentials are dropped (see Redirects).
  • The pinning options are added and win over the caller’s (below). With less than a millisecond of the budget left: DestinationUnavailable (timeout).
  • The pinned handler re-checks the request right before curl: scheme, host and port are the vetted ones, a Host header names the same host and port, the proxy is off, redirects are off, the pins and the pre-send check are intact and no curl option outside the allow-list was added. Anything else is cannot_pin, with nothing dialled.
  • The pre-send check (CURLOPT_PREREQFUNCTION): after curl connected and before it sends a byte, the connected address and port must be in the vetted set; else curl aborts → cannot_pin. The server sees a connection and nothing on it.
  • The post-check: the transfer stats’ primary_ip must be in the vetted set; else cannot_pin, reported and announced as DestinationRefused. Stats from Http::fake() are not checked. Your own on_stats is still called.
  • A redirect the policy follows becomes the next hop.
[
    'proxy' => '',                    // no proxy at all, environment proxies included
    'allow_redirects' => false,       // redirects are the guard's
    'protocols' => [$scheme],         // Guzzle 7.11+; older 7.x ignore it (the scheme is vetted)
    'curl' => [
        CURLOPT_RESOLVE => ['host:port:a.b.c.d,[v6::1]'],  // every vetted address, one entry; none for a literal
        CURLOPT_FRESH_CONNECT => true,
        CURLOPT_FORBID_REUSE => true,
        CURLOPT_PREREQFUNCTION => $preSendCheck,         // libcurl 7.80+, not Guzzle 7.12.x
    ],
    'timeout' => <what is left of the budget>,
]

Options the guard refuses

UnsafeRequestOptions — a programmer error, thrown, naming the option — for anything that would take a request around the guard:

  • allow_redirects other than false (->maxRedirects() after safe()) — enable redirects on the policy instead.
  • A proxy the caller chose (withOptions(['proxy' => …]), Http::globalOptions()). Proxies that only repeat the environment (HTTP_PROXY, HTTPS_PROXY, NO_PROXY) are bypassed, not refused: a proxy resolves the name itself.
  • Request-level transport_sharing.
  • A raw curl option outside the allow-list: CURLOPT_ENCODING, HTTPAUTH, USERPWD, SSL_CIPHER_LIST, TLS13_CIPHERS, SSL_EC_CURVES, CERTINFO, LOW_SPEED_LIMIT, LOW_SPEED_TIME, TCP_KEEPALIVE, TCP_KEEPIDLE, TCP_KEEPINTVL, TCP_KEEPCNT, TCP_NODELAY, TCP_FASTOPEN, HAPPY_EYEBALLS_TIMEOUT_MS, MAXAGE_CONN and MAXLIFETIME_CONN. Everything else — RESOLVE, CONNECT_TO, UNIX_SOCKET_PATH, INTERFACE, DNS_*, PROXY*, PRE_PROXY, SSL_VERIFYPEER … — fails closed.
  • A sink together with maxResponseBytes.
  • A client of its own (setClient()), a Guzzle handler option, or a request that is already guarded.

Refusals of the guard (DestinationRejected, DestinationUnavailable) surface unwrapped — Laravel does not turn them into RequestException or ConnectionException. A throwable from code inside the guard (Http::fake()’s StrayRequestException, a rate limiter added after safe(), a queue job’s release) reaches the caller as thrown. A transport failure of a guarded request is Laravel’s own ConnectionException, whose message names the URL — never echo it to an end user.

Pools

The guard replaces a pool’s handler with its pinned handler — one per pool, shared by the pool’s guarded members — so the pool stays concurrent, while fresh connections and the per-hop pre-send check keep each member inside its own vetted set. Two members to the same host and port with different vetted sets are refused rather than mixed. A refused member’s result is the exception:

use Illuminate\Http\Client\Pool;

$responses = Http::pool(fn (Pool $pool): array => [
    $pool->safe()->get('https://hooks.example/a'),
    $pool->safe()->get('https://inward.example/b'),
]);

$responses[0]->body();   // the answer
$responses[1];           // a DestinationRejected when the guard refused that member

Retries

retry() re-enters the stack, so every attempt is vetted again. Laravel retries every throwable unless the when callback says no — a refusal included — so stop at the first:

Http::safe()->retry(3, 100, fn (Throwable $e) => ! $e instanceof SafeFetchException)->post($url, $payload);

Other middleware

The order is yours. A throttle added before the guard runs once per call, before any DNS lookup; one added after safe() runs on every hop. Prefer the first:

// Runs once per call, before any DNS lookup — prefer this order
Http::withMiddleware($throttle)->safe()->post($url, $payload);

// http-client-rate-limits-for-laravel's macro works the same way
Http::rateLimit(30)->safe()->post($url, $payload);

The response cap — maxResponseBytes

Without stream => true curl downloads the whole body before you see it (a 2 MB body arrives as 2 MB in memory). To bound a response, set a cap on the policy:

$response = Http::safe(SafeFetch::policy()->maxResponseBytes(4096))->post($url, $payload);

$response->status();                       // the real status
$response->body();                         // at most 4 096 bytes
SafeFetch::truncated($response);           // true when the body was cut
$response->handlerStats()['primary_ip'] ?? null; // the address it connected to, truncated or not
  • A body longer than the cap is cut and the transfer aborted — however the server sends it (no Content-Length, chunked, compressed: the count is of decoded bytes).
  • The response keeps its status and headers and gains Safe-Fetch-Truncated: 1. A body of exactly the cap gets no marker.
  • The guard strips a Safe-Fetch-Truncated header the server sent from every response, with or without a cap, so only the guard’s own cut sets it.
  • The guard owns the sink: a caller sink together with the cap is refused. fetch() and download() have their own cap, which fails instead of truncating.

To cap every guarded request without a policy per call, set request.max_bytes (SAFE_FETCH_REQUEST_MAX_BYTES): SafeFetch::policy() — the default behind Http::safe() — then carries it. With it set a request’s own sink is refused, so lift it for a call that writes to one.

With stream => true the cap fails instead of cutting — see Streaming responses.

Streaming responses

Since 1.2.0. A request sent with stream => true returns as soon as the final hop’s headers arrive, and its body is a PSR-7 stream that reads as the server sends it — server-sent events, an LLM provider’s token stream, a long export. It works from every entry point: Http::withOptions(['stream' => true])->safe(), SafeFetch::guard() / http(), SafeFetch::handlerStack() and SafeFetch::guzzleClient():

$body = Http::withOptions(['stream' => true])
    ->safe(SafeFetch::policy()->maxResponseBytes(10_000_000)->readTimeout(30))
    ->post($llmUrl, $payload)
    ->toPsrResponse()->getBody();

while (! $body->eof()) {
    $chunk = $body->read(1024); // what has arrived; waits only when nothing has
}

$body->close();                 // stop early: the transfer ends and its curl handles are freed

Every guard stays on. Each hop is vetted, pinned with CURLOPT_RESOLVE and checked before a byte is sent (CURLOPT_PREREQFUNCTION). Redirects are followed and vetted per hop, and only the final hop’s body is streamed — a redirect’s body is never read. The policy’s port, scheme and range rules apply, and so does its time limit: timeout covers the whole stream, headers to last byte. Under the hood it is still Guzzle’s curl; each streamed request gets its own multi handle, which runs only while you wait for the response or read its body.

Streamed (stream => true)Not streamed
Response returnsat the final headersafter the whole body
maxResponseBytesfails: a declared Content-Length over the cap before the body, any other body on the read past the cap (FetchFailed, too_large)cuts the body, adds Safe-Fetch-Truncated: 1
Idle limitreadTimeout / read_timeout: FetchFailed (timeout)none of the guard’s own
A break mid-bodythrown by read() as a typed FetchFailed (timeout, connection, tls, …)thrown by the request
on_stats / handlerStats()once the body has been read to its endwith the response
  • Idle limit: DestinationPolicy::readTimeout(int $seconds) — or request.read_timeout (SAFE_FETCH_REQUEST_READ_TIMEOUT) — ends a stream that sends nothing for that long, before its headers or between two pieces of its body. A request’s own read_timeout applies too, and the shorter one wins. The total timeout still applies on top. Both are off unless set, and apply to streamed requests only.
  • Caller options: progress, on_headers, on_stats and read_timeout pass through. A sink is ignored in stream mode, as Guzzle’s own stream handler ignores it. An exception one of your callbacks throws comes back from read() as it was thrown.
  • Closing early: $body->close(), or simply letting go of the response, stops the transfer and frees its curl handles. The server sees the connection close.
  • body() and (string) still work: they read the stream to its end and throw the same FetchFailed a read() would.
  • Http::fake() answers streamed requests like any other, since fakes never reach the handler. A stub’s body reads through the same byte cap, so a test sees the too_large a real stream would.
  • Pools and async: a streamed request waits for its headers when it is sent, so in Http::pool() or getAsync() the streamed members do not overlap until then. Their bodies are read independently afterwards.
  • Where it streams: only where the pre-send check runs — PHP 8.4 with libcurl 7.80+, on any Guzzle but 7.12.x. Without the check, headers handed out early could come from an address nobody checked yet, so such a request is received whole and checked afterwards, exactly as without stream (the cap then cuts).

The time limit — timeout

Laravel gives every request a 30-second timeout, but a caller can raise it or switch it off (timeout(0)), and a Guzzle client a library builds has none at all. The policy’s timeout is a ceiling over that: SafeFetch::policy()->timeout(10), or request.timeout (SAFE_FETCH_REQUEST_TIMEOUT) for every guarded request. The guard then gives a request min(its own timeout, the limit) — the limit when it has none — as one budget for every hop; a hop that would start with less than a millisecond left fails as a retryable timeout (DestinationUnavailable). Off by default; timeout(null) lifts it for one call, and fetch() and download() keep their own fetch.timeout:

// Every guarded request — Http::safe(), guard(), http() and the guarded Guzzle stack
// SAFE_FETCH_REQUEST_MAX_BYTES=1048576
// SAFE_FETCH_REQUEST_TIMEOUT=20

// Or per call: a ceiling of 10 s over every hop, a 1 MB body cap
Http::safe(SafeFetch::policy()->timeout(10)->maxResponseBytes(1_048_576))->get($url);

// Lift them for one call — a sink is refused while a body cap is set
Http::safe(SafeFetch::policy()->maxResponseBytes(null))->sink($path)->get($url);
Http::safe(SafeFetch::policy()->timeout(null))->timeout(120)->get($url);

Pin a request you build yourself

$vetted = SafeFetch::vet($url);
Http::withOptions($vetted->pinningOptions())->get($vetted->url);

pinningOptions() is the option array above minus the pre-send check; it trusts the handler to honour curl options, and no hop is re-checked. Prefer SafeFetch::guard().

Guzzle compatibility

illuminate/http 13 allows guzzlehttp/guzzle ^7.8.2 || ^8.0. The pinning options use only what every one of those accepts:

GuzzleNotes
7.8.2The floor, tested on the prefer-lowest leg. No protocols option (ignored; the scheme is vetted anyway). Composer blocks Guzzle releases with security advisories by default — a host on such a Guzzle should upgrade.
7.12.0–7.12.3CURLOPT_PREREQFUNCTION is deprecated there (fixed in 7.13.0), so the pre-send check is skipped; the primary_ip post-check remains, and stream => true is received whole.
7.16.xTested; the suite fails on any deprecation, @-suppressed ones included.
8.xTested on every PHP leg (8.4, 8.5, 8.6).

A library’s own Guzzle client goes on this same guard through SafeFetch::guzzleClient() and SafeFetch::handlerStack() — see Third-party clients.

Show your open-source love

This package is free and MIT-licensed. If it saves you time, a one-off donation or a Patreon membership keeps it maintained, tested and documented.

More ways to support, including crypto

By donating, you agree to our donation terms.

Want this built into your product?

We integrate our packages into custom Laravel and AI builds. Tell us what you're working on and we'll reply within 48 hours.