This commit is contained in:
Javier Casares 2026-08-10 16:21:45 +00:00
commit cc1bca74fa
10 changed files with 770 additions and 204 deletions

View file

@ -163,7 +163,7 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
$options = $this->prepareDefaults($options);
return $this->transfer(
$request->withUri($this->buildUri($request->getUri(), $options), $request->hasHeader('Host')),
$request->withUri($this->buildUri($request->getUri(), $options), self::shouldPreserveHost($request)),
$options
);
}
@ -309,6 +309,30 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
return $uri;
}
/**
* Whether to preserve an existing Host header when the URI changes.
*
* A header matching the current URI carries no explicit override and is
* regenerated after base URI resolution or IDN conversion. Other values
* are preserved as deliberate overrides, as PSR-7 requires.
*/
private static function shouldPreserveHost(RequestInterface $request): bool
{
if (!$request->hasHeader('Host')) {
return false;
}
$uri = $request->getUri();
$host = $uri->getHost();
$port = $uri->getPort();
if ($port !== null) {
$host .= ':'.$port;
}
return $host !== $request->getHeaderLine('Host');
}
/**
* Configures the default options for a client.
*/

View file

@ -11,6 +11,11 @@ use Psr\Http\Message\ResponseInterface;
*/
class CookieJar implements CookieJarInterface
{
private const MAX_SET_COOKIE_FIELD_LENGTH = 8190;
private const MAX_SET_COOKIE_FIELDS = 50;
private const MAX_REQUEST_COOKIES = 150;
private const MAX_COOKIE_HEADER_LENGTH = 8190;
/**
* @var SetCookie[] Loaded cookie data
*/
@ -172,7 +177,7 @@ class CookieJar implements CookieJarInterface
$maxAge = $cookie->getMaxAge();
if ($maxAge !== null && $maxAge <= 0) {
if ($cookie->getDomain() !== null) {
$this->clear($cookie->getDomain(), $cookie->getPath(), $cookie->getName());
$this->removeCookie($cookie);
}
return false;
@ -184,6 +189,7 @@ class CookieJar implements CookieJarInterface
// identical.
if ($c->getPath() !== $cookie->getPath()
|| $c->getDomain() !== $cookie->getDomain()
|| $c->getHostOnly() !== $cookie->getHostOnly()
|| $c->getName() !== $cookie->getName()
) {
continue;
@ -234,14 +240,23 @@ class CookieJar implements CookieJarInterface
public function extractCookies(RequestInterface $request, ResponseInterface $response): void
{
if ($cookieHeader = $response->getHeader('Set-Cookie')) {
$accepted = 0;
foreach ($cookieHeader as $cookie) {
if (\strlen($cookie) > self::MAX_SET_COOKIE_FIELD_LENGTH) {
continue;
}
$sc = SetCookie::fromString($cookie);
$domain = $sc->getDomain();
if ($domain === null || $domain === '') {
$sc->setDomain($request->getUri()->getHost());
$sc->setHostOnly(true);
} elseif (\substr($domain, -1) === '.' && '' !== \trim($domain, '.')) {
// Keep pure-dot domains rejected by the dot-only fix.
$sc->setDomain($request->getUri()->getHost());
$sc->setHostOnly(true);
} else {
$sc->setHostOnly(false);
}
if (0 !== \strpos($sc->getPath(), '/')) {
$sc->setPath($this->getCookiePathFromRequest($request));
@ -251,7 +266,9 @@ class CookieJar implements CookieJarInterface
}
// Note: At this point `$sc->getDomain()` being a public suffix should
// be rejected, but we don't want to pull in the full PSL dependency.
$this->setCookie($sc);
if ($this->setCookie($sc) && ++$accepted === self::MAX_SET_COOKIE_FIELDS) {
break;
}
}
}
}
@ -284,6 +301,7 @@ class CookieJar implements CookieJarInterface
public function withCookieHeader(RequestInterface $request): RequestInterface
{
$values = [];
$headerLength = 8;
$uri = $request->getUri();
$scheme = $uri->getScheme();
$host = $uri->getHost();
@ -296,8 +314,19 @@ class CookieJar implements CookieJarInterface
&& !$cookie->isExpired()
&& (!$cookie->getSecure() || $scheme === 'https')
) {
$values[] = $cookie->getName().'='
.$cookie->getValue();
$name = (string) $cookie->getName();
$value = (string) $cookie->getValue();
$separatorLength = $values === [] ? 0 : 2;
$valueLength = \strlen($name) + 1 + \strlen($value);
if ($headerLength + $separatorLength + $valueLength > self::MAX_COOKIE_HEADER_LENGTH) {
break;
}
$values[] = $name.'='.$value;
$headerLength += $separatorLength + $valueLength;
if (\count($values) === self::MAX_REQUEST_COOKIES) {
break;
}
}
}
@ -314,11 +343,36 @@ class CookieJar implements CookieJarInterface
{
$cookieValue = $cookie->getValue();
if (($cookieValue === null || $cookieValue === '') && $cookie->getDomain() !== null) {
$this->clear(
$cookie->getDomain(),
$cookie->getPath(),
$cookie->getName()
);
$this->removeCookie($cookie);
}
}
private function removeCookie(SetCookie $cookie): void
{
$this->cookies = \array_filter(
$this->cookies,
static function (SetCookie $stored) use ($cookie): bool {
return !($stored->getName() === $cookie->getName()
&& $stored->getPath() === $cookie->getPath()
&& self::cookieDomainsEqual($stored->getDomain(), $cookie->getDomain())
&& $stored->getHostOnly() === $cookie->getHostOnly());
}
);
}
private static function cookieDomainsEqual(?string $first, ?string $second): bool
{
if ($first === null || $second === null) {
return $first === $second;
}
if (isset($first[0]) && $first[0] === '.') {
$first = \substr($first, 1);
}
if (isset($second[0]) && $second[0] === '.') {
$second = \substr($second, 1);
}
return Psr7\Utils::caselessEquals($first, $second);
}
}

View file

@ -60,7 +60,9 @@ class FileCookieJar extends CookieJar
/** @var SetCookie $cookie */
foreach ($this as $cookie) {
if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
$json[] = $cookie->toArray();
$data = $cookie->toArray();
$data['HostOnly'] = $cookie->getHostOnly();
$json[] = $data;
}
}
@ -100,8 +102,17 @@ class FileCookieJar extends CookieJar
}
if (\is_array($data)) {
$cookies = [];
foreach ($data as $cookie) {
$this->setCookie(new SetCookie($cookie));
if (!\is_array($cookie) || !\array_key_exists('HostOnly', $cookie) || !\is_bool($cookie['HostOnly'])) {
throw new \RuntimeException("Invalid cookie file: {$filename}");
}
$cookies[] = new SetCookie($cookie);
}
foreach ($cookies as $cookie) {
$this->setCookie($cookie);
}
} elseif (\is_scalar($data) && !empty($data)) {
throw new \RuntimeException("Invalid cookie file: {$filename}");

View file

@ -50,7 +50,9 @@ class SessionCookieJar extends CookieJar
/** @var SetCookie $cookie */
foreach ($this as $cookie) {
if (CookieJar::shouldPersist($cookie, $this->storeSessionCookies)) {
$json[] = $cookie->toArray();
$data = $cookie->toArray();
$data['HostOnly'] = $cookie->getHostOnly();
$json[] = $data;
}
}
@ -78,12 +80,17 @@ class SessionCookieJar extends CookieJar
$data = \json_decode($json, true);
if (\is_array($data)) {
$cookies = [];
foreach ($data as $cookie) {
if (!\is_array($cookie)) {
if (!\is_array($cookie) || !\array_key_exists('HostOnly', $cookie) || !\is_bool($cookie['HostOnly'])) {
throw new \RuntimeException('Invalid cookie data');
}
$this->setCookie(new SetCookie($cookie));
$cookies[] = new SetCookie($cookie);
}
foreach ($cookies as $cookie) {
$this->setCookie($cookie);
}
} elseif (\is_scalar($data) && \strlen((string) $data)) {
throw new \RuntimeException('Invalid cookie data');

View file

@ -2,6 +2,7 @@
namespace GuzzleHttp\Cookie;
use GuzzleHttp\Handler\HostValidator;
use GuzzleHttp\Psr7;
/**
@ -29,6 +30,11 @@ class SetCookie
*/
private $data;
/**
* @var bool Whether this cookie was set without a Domain attribute
*/
private $hostOnly = false;
/**
* Create a new SetCookie object from a string.
*
@ -76,6 +82,9 @@ class SetCookie
continue 2;
}
}
if (Psr7\Utils::caselessEquals('HostOnly', $key)) {
continue;
}
$data[$key] = $value;
}
}
@ -90,6 +99,14 @@ class SetCookie
{
$this->data = self::$defaults;
if (\array_key_exists('HostOnly', $data)) {
if (!\is_bool($data['HostOnly'])) {
throw new \InvalidArgumentException('Cookie field "HostOnly" must be a boolean');
}
$this->setHostOnly($data['HostOnly']);
unset($data['HostOnly']);
}
if (isset($data['Name'])) {
$this->setName($data['Name']);
}
@ -157,6 +174,9 @@ class SetCookie
{
$str = $this->data['Name'].'='.($this->data['Value'] ?? '').'; ';
foreach ($this->data as $k => $v) {
if ($k === 'Domain' && $this->getHostOnly()) {
continue;
}
if ($k !== 'Name' && $k !== 'Value' && $v !== null && $v !== false) {
if ($k === 'Expires') {
$str .= 'Expires='.\gmdate('D, d M Y H:i:s \G\M\T', $v).'; ';
@ -171,7 +191,12 @@ class SetCookie
public function toArray(): array
{
return $this->data;
$data = $this->data;
if ($this->getHostOnly()) {
$data['HostOnly'] = true;
}
return $data;
}
/**
@ -246,6 +271,26 @@ class SetCookie
$this->data['Domain'] = null === $domain ? null : (string) $domain;
}
/**
* Get whether this cookie is scoped to the origin host only.
*
* @return bool
*/
public function getHostOnly()
{
return $this->hostOnly;
}
/**
* Set whether this cookie is scoped to the origin host only.
*
* @param bool $hostOnly Set to true for host-only cookies
*/
public function setHostOnly(bool $hostOnly): void
{
$this->hostOnly = $hostOnly;
}
/**
* Get the path.
*
@ -445,7 +490,11 @@ class SetCookie
{
$cookieDomain = $this->getDomain();
if (null === $cookieDomain) {
return true;
return !$this->getHostOnly();
}
if ($this->getHostOnly()) {
return Psr7\Utils::asciiToLower($domain) === Psr7\Utils::asciiToLower($cookieDomain);
}
// Remove the leading '.' as per spec in RFC 6265.
@ -464,6 +513,12 @@ class SetCookie
return true;
}
// A percent-escaped cookie domain can decode to another host spelling.
// Keep it exact-match-only to avoid extending that host's cookie scope.
if (\strpos($cookieDomain, '%') !== false) {
return false;
}
// IP literals and numeric hosts are exact-match-only per RFC 6265.
// Only the exact match above may succeed for those cookie domains.
if (self::isIpAddressOrNumericHost($cookieDomain)) {
@ -500,7 +555,14 @@ class SetCookie
$labels = \explode('.', $host);
$last = (string) \end($labels);
return $last !== '' && \ctype_digit($last);
if ($last !== '' && \ctype_digit($last)) {
return true;
}
// Apply the transport's decimal, octal and hexadecimal inet_aton-style
// grammar. Omitting range checks conservatively holds some names to an
// exact match.
return HostValidator::isNumericIpv4Host(\rtrim($host, '.'));
}
/**

View file

@ -70,6 +70,8 @@ class CurlHandler
public function __invoke(RequestInterface $request, array $options): PromiseInterface
{
HostValidator::assertRequestHost($request);
if (isset($options['delay'])) {
\usleep($options['delay'] * 1000);
}

View file

@ -345,6 +345,8 @@ class CurlMultiHandler
public function __invoke(RequestInterface $request, array $options): PromiseInterface
{
HostValidator::assertRequestHost($request);
if ($this->connectionCapsApplied
&& \defined('CURLOPT_SHARE')
&& isset($options['curl'])

View file

@ -0,0 +1,198 @@
<?php
namespace GuzzleHttp\Handler;
use GuzzleHttp\Exception\RequestException;
use Psr\Http\Message\RequestInterface;
/**
* Rejects request hosts that a handler could resolve differently from the host
* the request names.
*
* @internal
*/
final class HostValidator
{
private function __construct()
{
}
/**
* Asserts that a request names one unambiguous network host.
*
* The URI host and every Host header value must use printable ASCII without
* percent escapes. The URI host must also exclude authority delimiters and
* numeric-looking parts followed by trailing dots. Handlers reparse the URI
* but send the Host header as given, so ambiguous spellings can name
* different connection and request hosts.
*
* @throws RequestException
*/
public static function assertRequestHost(RequestInterface $request): void
{
$host = $request->getUri()->getHost();
self::assertUriHostValue($host, $request);
self::assertNoAuthorityDelimiter($host, $request);
self::assertNotADottedAddress($host, $request);
foreach ($request->getHeader('Host') as $value) {
self::assertHostHeaderValue((string) $value, $request);
}
}
/**
* @throws RequestException
*/
private static function assertUriHostValue(string $value, RequestInterface $request): void
{
if (!self::isPrintableAscii($value)) {
throw new RequestException(\sprintf('The request URI host "%s" must contain only printable ASCII characters, because a handler can otherwise connect to a host that differs from the one the request names. An internationalized host name has an A-label form that this rule accepts.', self::escape($value)), $request);
}
if (\strpos($value, '%') !== false) {
throw new RequestException(\sprintf('The request URI host "%s" must not contain a percent escape, because a handler can decode it and then connect to a host that differs from the one the request names.', self::escape($value)), $request);
}
}
/**
* The Host header is sent rather than reparsed for the connection, so its
* diagnostics describe a request authority the caller did not write.
*
* @throws RequestException
*/
private static function assertHostHeaderValue(string $value, RequestInterface $request): void
{
if (!self::isPrintableAscii($value)) {
throw new RequestException(\sprintf('The request Host header "%s" must contain only printable ASCII characters, because an intermediary or an origin server can otherwise read it as an authority that differs from the one the request names. An internationalized host name has an A-label form that this rule accepts.', self::escape($value)), $request);
}
if (\strpos($value, '%') !== false) {
throw new RequestException(\sprintf('The request Host header "%s" must not contain a percent escape, because an intermediary or an origin server can decode it and then read it as an authority that differs from the one the request names.', self::escape($value)), $request);
}
}
/**
* Matches the accepted shape positively so a PCRE failure rejects.
*/
private static function isPrintableAscii(string $value): bool
{
return \preg_match('/\A[\x21-\x7E]*\z/D', $value) === 1;
}
/**
* Rejects a delimiter the transport could treat as the end of the URI host.
*
* This mirrors GuzzleHttp\Psr7\Uri::assertValidHost() and only affects
* third-party UriInterface values. Host headers may carry a port and are
* sent verbatim.
*
* @throws RequestException
*/
private static function assertNoAuthorityDelimiter(string $host, RequestInterface $request): void
{
$message = 'The request URI host "%s" must not contain a URI authority delimiter, because a handler reparses the URI and can then connect to a host that differs from the one the request names.';
// Match the accepted shape positively so a PCRE engine failure rejects.
if (\preg_match('/\A[^\/?#@\\\\]*\z/D', $host) !== 1) {
throw new RequestException(\sprintf($message, self::escape($host)), $request);
}
if (\strpos($host, '[') !== false || \strpos($host, ']') !== false) {
if (\strpos($host, '[') !== 0 || \substr($host, -1) !== ']') {
throw new RequestException(\sprintf($message, self::escape($host)), $request);
}
return;
}
if (\strpos($host, ':') !== false) {
throw new RequestException(\sprintf($message, self::escape($host)), $request);
}
}
/**
* Rejects one to four numeric-looking parts followed by trailing dots.
*
* libcurl 8.21.0 drops a trailing dot from inet_aton-style numeric hosts
* before connecting, while other validators treat the input as a name.
* Testing the shape also rejects some out-of-range values that transports
* keep as names; isNumericIpv4Host() explains that fail-closed tradeoff.
* Plain numeric shorthand stays accepted.
*
* @throws RequestException
*/
private static function assertNotADottedAddress(string $host, RequestInterface $request): void
{
if (\substr($host, -1) !== '.') {
return;
}
if (!self::isNumericIpv4Host(\rtrim($host, '.'))) {
return;
}
throw new RequestException(\sprintf('The request URI host "%s" must not be written as one to four decimal, octal or hexadecimal parts followed by one or more trailing dots, because a handler can read that spelling as an IPv4 address and connect to that address while the rest of the process reads a name.', self::escape($host)), $request);
}
/**
* Reports whether a value has the transport's inet_aton-style shape: one
* to four decimal, 0-prefixed octal, or 0x-prefixed hexadecimal parts.
*
* Range and 32-bit overflow checks are deliberately omitted. This may
* reject a trailing-dot spelling the transport reads as a name, but avoids
* missing one it resolves as an address. No PCRE is used.
*/
public static function isNumericIpv4Host(string $host): bool
{
if ($host === '') {
return false;
}
$parts = \explode('.', $host);
if (\count($parts) > 4) {
return false;
}
foreach ($parts as $part) {
if (!self::isNumericIpv4Part($part)) {
return false;
}
}
return true;
}
private static function isNumericIpv4Part(string $part): bool
{
if ($part === '') {
return false;
}
if ($part[0] === '0' && isset($part[1]) && ($part[1] === 'x' || $part[1] === 'X')) {
return \strlen($part) > 2 && \strspn($part, '0123456789abcdefABCDEF', 2) === \strlen($part) - 2;
}
$digits = $part[0] === '0' ? '01234567' : '0123456789';
return \strspn($part, $digits) === \strlen($part);
}
/**
* Escapes non-printable bytes as uppercase \xNN for safe diagnostics.
* Printable delimiters and dots stay visible. The result is not a
* reversible encoding.
*/
private static function escape(string $value): string
{
$escaped = '';
for ($offset = 0, $length = \strlen($value); $offset < $length; ++$offset) {
$byte = \ord($value[$offset]);
$escaped .= $byte >= 0x21 && $byte <= 0x7E ? $value[$offset] : \sprintf('\\x%02X', $byte);
}
return $escaped;
}
}

View file

@ -4,6 +4,7 @@ namespace GuzzleHttp\Handler;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\TransferException;
use GuzzleHttp\Multiplexing;
use GuzzleHttp\Promise as P;
use GuzzleHttp\Promise\FulfilledPromise;
@ -187,11 +188,10 @@ class StreamHandler
} catch (\InvalidArgumentException $e) {
throw $e;
} catch (\Exception $e) {
// Determine if the error was a networking error.
if (self::isConnectionError($e->getMessage())) {
$e = new ConnectException($e->getMessage(), $request, $e);
} else {
$e = $e instanceof RequestException ? $e : new RequestException($e->getMessage(), $request, null, $e);
if (!$e instanceof TransferException) {
$e = self::isConnectionError($e->getMessage())
? new ConnectException($e->getMessage(), $request, $e)
: new RequestException($e->getMessage(), $request, null, $e);
}
$this->invokeStats($options, $request, $startTime, null, $e);
@ -428,6 +428,8 @@ class StreamHandler
throw new RequestException('URI must include a scheme and host. Use an absolute URI, a network-path reference starting with //, or configure a base_uri.', $request);
}
HostValidator::assertRequestHost($request);
// HTTP/1.1 streams using the PHP stream wrapper require a
// Connection: close header
if ($request->getProtocolVersion() === '1.1'

View file

@ -210,7 +210,7 @@ class RedirectMiddleware
if ($options['allow_redirects']['referer']
&& $modify['uri']->getScheme() === $request->getUri()->getScheme()
) {
$uri = $request->getUri()->withUserInfo('');
$uri = $request->getUri()->withUserInfo('')->withFragment('');
$modify['set_headers']['Referer'] = (string) $uri;
} else {
$modify['remove_headers'][] = 'Referer';