This commit is contained in:
Javier Casares 2026-08-17 15:50:51 +00:00
commit a80a4aa4f9
77 changed files with 3186001 additions and 9155 deletions

17
vendor/guzzlehttp/guzzle/.editorconfig vendored Normal file
View file

@ -0,0 +1,17 @@
# EditorConfig is awesome: https://editorconfig.org/
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending for every file
# Indent with 4 spaces
[*]
charset = utf-8
end_of_line = lf
indent_style = space
indent_size = 4
insert_final_newline = true
trim_trailing_whitespace = true
[Makefile]
indent_style = tab

View file

@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
$config = (new PhpCsFixer\Config())
->setRiskyAllowed(true)
->setRules([
'@PHP71Migration:risky' => true,
'@PHPUnit75Migration:risky' => true,
'@PSR12:risky' => true,
'@Symfony' => true,
'global_namespace_import' => false,
'no_superfluous_phpdoc_tags' => [
'allow_mixed' => true,
],
'phpdoc_annotation_without_dot' => false,
'phpdoc_summary' => false,
'phpdoc_to_comment' => false,
'single_line_throw' => false,
'void_return' => false,
'yoda_style' => false,
])
->setFinder(
PhpCsFixer\Finder::create()
->in(__DIR__.'/src')
->in(__DIR__.'/tests')
->name('*.php')
->append([__FILE__])
)
;
return $config;

14
vendor/guzzlehttp/guzzle/Dockerfile vendored Normal file
View file

@ -0,0 +1,14 @@
FROM composer:latest as setup
WORKDIR /guzzle
RUN set -xe \
&& composer init --name=guzzlehttp/test --description="Simple project for testing Guzzle scripts" --author="Márk Sági-Kazár <mark.sagikazar@gmail.com>" --no-interaction \
&& composer require guzzlehttp/guzzle
FROM php:7.4
WORKDIR /guzzle
COPY --from=setup /guzzle /guzzle

77
vendor/guzzlehttp/guzzle/Makefile vendored Normal file
View file

@ -0,0 +1,77 @@
help:
@echo "Please use \`make <target>' where <target> is one of"
@printf " %-32s %s\n" "start-server" "to start the test server"
@printf " %-32s %s\n" "stop-server" "to stop the test server"
@printf " %-32s %s\n" "test" "to perform unit tests. Provide TEST to perform a specific test."
@printf " %-32s %s\n" "coverage" "to perform unit tests with code coverage. Provide TEST to perform a specific test."
@printf " %-32s %s\n" "coverage-show" "to show the code coverage report"
@printf " %-32s %s\n" "clean" "to remove build artifacts"
@printf " %-32s %s\n" "static" "to run static checks on the codebase"
@printf " %-32s %s\n" "static-phpstan" "to run phpstan on the codebase"
@printf " %-32s %s\n" "static-phpstan-update-baseline" "to regenerate the phpstan baseline file"
@printf " %-32s %s\n" "static-codestyle-fix" "to run php-cs-fixer on the codebase, writing the changes"
@printf " %-32s %s\n" "static-codestyle-check" "to run php-cs-fixer on the codebase"
@printf " %-32s %s\n" "static-composer-normalize-fix" "to run composer-normalize on composer.json, writing changes"
@printf " %-32s %s\n" "static-composer-normalize-check" "to run composer-normalize on composer.json"
start-server: stop-server
node vendor/guzzlehttp/test-server/src/server.js &> /dev/null &
./vendor/bin/http_test_server &> /dev/null &
stop-server:
@PID=$(shell ps axo pid,command \
| grep 'vendor/guzzlehttp/test-server/src/server.js' \
| grep -v grep \
| cut -f 1 -d " "\
) && [ -n "$$PID" ] && kill $$PID || true
@PID=$(shell ps axo pid,command \
| grep 'vendor/bin/http_test_server' \
| grep -v grep \
| cut -f 1 -d " "\
) && [ -n "$$PID" ] && kill $$PID || true
test: start-server
vendor/bin/phpunit
$(MAKE) stop-server
coverage: start-server
vendor/bin/phpunit --coverage-html=build/artifacts/coverage
$(MAKE) stop-server
coverage-show: view-coverage
view-coverage:
open build/artifacts/coverage/index.html
clean:
rm -rf artifacts/*
static: static-phpstan static-codestyle-check static-composer-normalize-check
static-phpstan:
composer install
composer bin phpstan update
vendor/bin/phpstan analyze $(PHPSTAN_PARAMS)
static-phpstan-update-baseline:
composer install
composer bin phpstan update
$(MAKE) static-phpstan PHPSTAN_PARAMS="--generate-baseline"
static-codestyle-fix:
composer install
composer bin php-cs-fixer update
vendor/bin/php-cs-fixer fix --diff $(CS_PARAMS)
static-codestyle-check:
$(MAKE) static-codestyle-fix CS_PARAMS="--dry-run"
static-composer-normalize-fix:
composer install
composer bin composer-normalize update
composer bin composer-normalize normalize --diff $(COMPOSER_NORMALIZE_PARAMS) ../../composer.json
static-composer-normalize-check:
$(MAKE) static-composer-normalize-fix COMPOSER_NORMALIZE_PARAMS="--dry-run"
.PHONY: coverage-show view-coverage

View file

@ -0,0 +1,259 @@
parameters:
ignoreErrors:
-
message: '#^Negated boolean expression is always false\.$#'
identifier: booleanNot.alwaysFalse
count: 1
path: src/Client.php
-
message: '#^Result of && is always false\.$#'
identifier: booleanAnd.alwaysFalse
count: 1
path: src/Cookie/SetCookie.php
-
message: '#^Strict comparison using \!\=\= between null and null will always evaluate to false\.$#'
identifier: notIdentical.alwaysFalse
count: 1
path: src/Cookie/SetCookie.php
-
message: '#^Cannot cast mixed to string\.$#'
identifier: cast.string
count: 1
path: src/Env.php
-
message: '#^Strict comparison using \!\=\= between string and null will always evaluate to true\.$#'
identifier: notIdentical.alwaysTrue
count: 1
path: src/Env.php
-
message: '#^Parameter \#1 \$ch of function curl_error expects resource, CurlHandle\|resource given\.$#'
identifier: argument.type
count: 1
path: src/Handler/CurlFactory.php
-
message: '#^Parameter \#1 \$ch of function curl_getinfo expects resource, CurlHandle\|resource given\.$#'
identifier: argument.type
count: 2
path: src/Handler/CurlFactory.php
-
message: '#^Parameter \#1 \$ch of function curl_reset expects resource, CurlHandle\|resource given\.$#'
identifier: argument.type
count: 1
path: src/Handler/CurlFactory.php
-
message: '#^Parameter \#1 \$ch of function curl_setopt expects resource, CurlHandle\|resource given\.$#'
identifier: argument.type
count: 7
path: src/Handler/CurlFactory.php
-
message: '#^Parameter \$handle of method GuzzleHttp\\Handler\\CurlFactory\:\:applyCurlOptions\(\) has invalid type CurlHandle\.$#'
identifier: class.notFound
count: 1
path: src/Handler/CurlFactory.php
-
message: '#^Parameter \$handle of method GuzzleHttp\\Handler\\CurlFactory\:\:clearEasyHandleCallbacks\(\) has invalid type CurlHandle\.$#'
identifier: class.notFound
count: 1
path: src/Handler/CurlFactory.php
-
message: '#^Parameter \$handle of method GuzzleHttp\\Handler\\CurlFactory\:\:discardHandle\(\) has invalid type CurlHandle\.$#'
identifier: class.notFound
count: 1
path: src/Handler/CurlFactory.php
-
message: '#^Property GuzzleHttp\\Handler\\CurlFactory\:\:\$handles has unknown class CurlHandle as its type\.$#'
identifier: class.notFound
count: 1
path: src/Handler/CurlFactory.php
-
message: '#^Offset ''handle_factory''\|''transport_sharing'' on array\{handle_factory\: true, transport_sharing\: true\} in isset\(\) always exists and is not nullable\.$#'
identifier: isset.offset
count: 1
path: src/Handler/CurlHandler.php
-
message: '#^Parameter \#1 \$ch of function curl_errno expects resource, CurlHandle\|resource given\.$#'
identifier: argument.type
count: 1
path: src/Handler/CurlHandler.php
-
message: '#^Parameter \#1 \$ch of function curl_exec expects resource, CurlHandle\|resource given\.$#'
identifier: argument.type
count: 1
path: src/Handler/CurlHandler.php
-
message: '#^Method GuzzleHttp\\Handler\\CurlMultiHandler\:\:getMultiHandle\(\) has invalid return type CurlMultiHandle\.$#'
identifier: class.notFound
count: 1
path: src/Handler/CurlMultiHandler.php
-
message: '#^Parameter \#1 \$ch of function curl_setopt expects resource, CurlHandle\|resource given\.$#'
identifier: argument.type
count: 8
path: src/Handler/CurlMultiHandler.php
-
message: '#^Parameter \#1 \$mh of function curl_multi_add_handle expects resource, CurlMultiHandle\|resource given\.$#'
identifier: argument.type
count: 1
path: src/Handler/CurlMultiHandler.php
-
message: '#^Parameter \#1 \$mh of function curl_multi_close expects resource, CurlMultiHandle\|resource given\.$#'
identifier: argument.type
count: 2
path: src/Handler/CurlMultiHandler.php
-
message: '#^Parameter \#1 \$mh of function curl_multi_exec expects resource, CurlMultiHandle\|resource given\.$#'
identifier: argument.type
count: 1
path: src/Handler/CurlMultiHandler.php
-
message: '#^Parameter \#1 \$mh of function curl_multi_info_read expects resource, CurlMultiHandle\|resource given\.$#'
identifier: argument.type
count: 1
path: src/Handler/CurlMultiHandler.php
-
message: '#^Parameter \#1 \$mh of function curl_multi_remove_handle expects resource, CurlMultiHandle\|resource given\.$#'
identifier: argument.type
count: 2
path: src/Handler/CurlMultiHandler.php
-
message: '#^Parameter \#1 \$mh of function curl_multi_select expects resource, CurlMultiHandle\|resource given\.$#'
identifier: argument.type
count: 3
path: src/Handler/CurlMultiHandler.php
-
message: '#^Parameter \#2 \$ch of function curl_multi_add_handle expects resource, CurlHandle\|resource given\.$#'
identifier: argument.type
count: 1
path: src/Handler/CurlMultiHandler.php
-
message: '#^Parameter \#2 \$ch of function curl_multi_remove_handle expects resource, CurlHandle\|resource given\.$#'
identifier: argument.type
count: 2
path: src/Handler/CurlMultiHandler.php
-
message: '#^Parameter \$handle of method GuzzleHttp\\Handler\\CurlMultiHandler\:\:clearEasyHandleCallbacks\(\) has invalid type CurlHandle\.$#'
identifier: class.notFound
count: 1
path: src/Handler/CurlMultiHandler.php
-
message: '#^Parameter \$handle of method GuzzleHttp\\Handler\\CurlMultiHandler\:\:removeHandleFromMulti\(\) has invalid type CurlHandle\.$#'
identifier: class.notFound
count: 1
path: src/Handler/CurlMultiHandler.php
-
message: '#^Property GuzzleHttp\\Handler\\CurlMultiHandler\:\:\$multiHandle \(CurlMultiHandle\|resource\|null\) is never assigned CurlMultiHandle so it can be removed from the property type\.$#'
identifier: property.unusedType
count: 1
path: src/Handler/CurlMultiHandler.php
-
message: '#^Property GuzzleHttp\\Handler\\CurlMultiHandler\:\:\$multiHandle has unknown class CurlMultiHandle as its type\.$#'
identifier: class.notFound
count: 1
path: src/Handler/CurlMultiHandler.php
-
message: '#^Strict comparison using \=\=\= between false and resource will always evaluate to false\.$#'
identifier: identical.alwaysFalse
count: 1
path: src/Handler/CurlMultiHandler.php
-
message: '#^Property GuzzleHttp\\Handler\\EasyHandle\:\:\$handle has unknown class CurlHandle as its type\.$#'
identifier: class.notFound
count: 1
path: src/Handler/EasyHandle.php
-
message: '#^Offset ''max_host_connections''\|''max_total…''\|''transport_sharing'' on array\{max_host_connections\: true, max_total_connections\: true, transport_sharing\: true\} in isset\(\) always exists and is not nullable\.$#'
identifier: isset.offset
count: 1
path: src/Handler/StreamHandler.php
-
message: '#^Call to function array_key_exists\(\) with 0 and array\{callable\(callable&THandler\)\: \(callable&THandler\), string\|null\} will always evaluate to true\.$#'
identifier: function.alreadyNarrowedType
count: 1
path: src/HandlerStack.php
-
message: '#^Call to function is_array\(\) with array\{callable\(callable&THandler\)\: \(callable&THandler\), string\|null\} will always evaluate to true\.$#'
identifier: function.alreadyNarrowedType
count: 1
path: src/HandlerStack.php
-
message: '#^Call to function is_callable\(\) with callable\(\)\: mixed&THandler will always evaluate to true\.$#'
identifier: function.alreadyNarrowedType
count: 2
path: src/HandlerStack.php
-
message: '#^Call to function is_callable\(\) with callable\(callable&THandler\)\: \(callable&THandler\) will always evaluate to true\.$#'
identifier: function.alreadyNarrowedType
count: 2
path: src/HandlerStack.php
-
message: '#^Result of && is always false\.$#'
identifier: booleanAnd.alwaysFalse
count: 1
path: src/HandlerStack.php
-
message: '#^Result of \|\| is always false\.$#'
identifier: booleanOr.alwaysFalse
count: 2
path: src/HandlerStack.php
-
message: '#^Instanceof between ArrayAccess\<int, array\<string, mixed\>\> and ArrayAccess will always evaluate to true\.$#'
identifier: instanceof.alwaysTrue
count: 1
path: src/Middleware.php
-
message: '#^Result of && is always false\.$#'
identifier: booleanAnd.alwaysFalse
count: 1
path: src/Middleware.php
-
message: '#^Method GuzzleHttp\\Pool\:\:keyedRequestOptions\(\) should return array\{base_uri\?\: Psr\\Http\\Message\\UriInterface\|string, allow_redirects\?\: array\{max\?\: int, strict\?\: bool, referer\?\: bool, protocols\?\: non\-empty\-array\<string\>, on_redirect\?\: callable\(Psr\\Http\\Message\\RequestInterface, Psr\\Http\\Message\\ResponseInterface, Psr\\Http\\Message\\UriInterface\)\: mixed, track_redirects\?\: bool\}\|bool, auth\?\: array\{0\: string, 1\: string, 2\?\: string\|null\}\|string\|false\|null, body\?\: callable\-object\|Iterator\|Psr\\Http\\Message\\StreamInterface\|resource\|string\|Stringable\|null, cert\?\: array\{0\: string, 1\?\: string\|null\}\|string, cert_type\?\: string, connect_timeout\?\: float\|int, cookies\?\: GuzzleHttp\\Cookie\\CookieJarInterface\|false, \.\.\.\} but returns array\{base_uri\?\: Psr\\Http\\Message\\UriInterface\|string, allow_redirects\?\: array\{max\?\: int, strict\?\: bool, referer\?\: bool, protocols\?\: non\-empty\-array\<string\>, on_redirect\?\: \(callable\(Psr\\Http\\Message\\RequestInterface, Psr\\Http\\Message\\ResponseInterface, Psr\\Http\\Message\\UriInterface, int\|string\)\: mixed\)\|\(Closure\(Psr\\Http\\Message\\RequestInterface, Psr\\Http\\Message\\ResponseInterface, Psr\\Http\\Message\\UriInterface\)\: void\), track_redirects\?\: bool\}\|bool, auth\?\: array\{0\: string, 1\: string, 2\?\: string\|null\}\|string\|false\|null, body\?\: callable\-object\|Iterator\|Psr\\Http\\Message\\StreamInterface\|resource\|string\|Stringable\|null, cert\?\: array\{0\: string, 1\?\: string\|null\}\|string, cert_type\?\: string, connect_timeout\?\: float\|int, cookies\?\: GuzzleHttp\\Cookie\\CookieJarInterface\|false, \.\.\.\}\.$#'
identifier: return.type
count: 1
path: src/Pool.php
-
message: '#^Parameter \#1 \$options of class GuzzleHttp\\Handler\\CurlHandler constructor expects array\{handle_factory\?\: GuzzleHttp\\Handler\\CurlFactoryInterface\|null, transport_sharing\?\: mixed\}, array\<string, mixed\> given\.$#'
identifier: argument.type
count: 2
path: src/Utils.php

View file

@ -0,0 +1,13 @@
includes:
- phpstan-baseline.neon
- vendor-bin/phpstan/vendor/phpstan/phpstan-deprecation-rules/rules.neon
parameters:
ignoreErrors:
-
identifier: missingType.iterableValue
level: 9
paths:
- src
bootstrapFiles:
- tests/bootstrap-phpstan.php

View file

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="./tests/bootstrap.php"
backupGlobals="true"
colors="true"
executionOrder="random"
failOnRisky="true"
failOnWarning="true"
convertDeprecationsToExceptions="true"
>
<testsuites>
<testsuite name="Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
<coverage>
<include>
<directory suffix=".php">src</directory>
</include>
</coverage>
<php>
<server name="TEST_SERVER" value="http://127.0.0.1:10000/server.php" />
</php>
</phpunit>

View file

@ -0,0 +1,515 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Auth;
use GuzzleHttp\Psr7;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* @internal
*/
final class DigestAuth
{
/**
* @var array<string, array{hash: string, sess: bool, rank: int, header: string}>
*/
private const ALGORITHMS = [
'MD5' => ['hash' => 'md5', 'sess' => false, 'rank' => 10, 'header' => 'MD5'],
'MD5-SESS' => ['hash' => 'md5', 'sess' => true, 'rank' => 11, 'header' => 'MD5-sess'],
'SHA-256' => ['hash' => 'sha256', 'sess' => false, 'rank' => 20, 'header' => 'SHA-256'],
'SHA-256-SESS' => ['hash' => 'sha256', 'sess' => true, 'rank' => 21, 'header' => 'SHA-256-sess'],
'SHA-512-256' => ['hash' => 'sha512/256', 'sess' => false, 'rank' => 30, 'header' => 'SHA-512-256'],
'SHA-512-256-SESS' => ['hash' => 'sha512/256', 'sess' => true, 'rank' => 31, 'header' => 'SHA-512-256-sess'],
];
/**
* @var array<string, true>
*/
private const DIGEST_CHALLENGE_PARAMETER_NAMES = [
'realm' => true,
'domain' => true,
'nonce' => true,
'opaque' => true,
'stale' => true,
'algorithm' => true,
'qop' => true,
'charset' => true,
'userhash' => true,
];
private function __construct()
{
}
public static function selectChallenge(
#[\SensitiveParameter]
ResponseInterface $response
): ?DigestChallenge {
$selected = null;
foreach ($response->getHeader('WWW-Authenticate') as $header) {
foreach (self::parseAuthenticateHeader($header) as $challenge) {
if ($challenge['scheme'] !== 'digest' || $challenge['invalid']) {
continue;
}
$digest = self::createChallenge($challenge['params']);
if ($digest === null) {
continue;
}
if ($selected === null || $digest->algorithm['rank'] > $selected->algorithm['rank']) {
$selected = $digest;
}
}
}
return $selected;
}
public static function authorizationHeader(
#[\SensitiveParameter]
RequestInterface $request,
DigestChallenge $challenge,
string $username,
#[\SensitiveParameter]
string $password,
string $cnonce,
string $nc = '00000001'
): ?string {
if ($challenge->algorithm['sess'] && $challenge->qop === null) {
return null;
}
$uri = $request->getRequestTarget();
if ($uri === '') {
$uri = '/';
}
foreach ([$username, $challenge->realm, $challenge->nonce, $uri, $cnonce] as $value) {
if (!self::isHeaderSafe($value)) {
return null;
}
}
if ($challenge->opaque !== null && !self::isHeaderSafe($challenge->opaque)) {
return null;
}
if ($challenge->qop !== null && !self::isNonceCount($nc)) {
return null;
}
$hash = $challenge->algorithm['hash'];
$ha1 = \hash($hash, $username.':'.$challenge->realm.':'.$password);
if ($challenge->algorithm['sess']) {
$ha1 = \hash($hash, $ha1.':'.$challenge->nonce.':'.$cnonce);
}
$ha2 = \hash($hash, $request->getMethod().':'.$uri);
$response = $challenge->qop === null
? \hash($hash, $ha1.':'.$challenge->nonce.':'.$ha2)
: \hash($hash, $ha1.':'.$challenge->nonce.':'.$nc.':'.$cnonce.':'.$challenge->qop.':'.$ha2);
if ($challenge->userhash) {
$headerUsername = \hash($hash, $username.':'.$challenge->realm);
if ($headerUsername === false) {
return null;
}
} else {
$headerUsername = $username;
}
$parts = [
'username='.self::quote($headerUsername),
'realm='.self::quote($challenge->realm),
'nonce='.self::quote($challenge->nonce),
'uri='.self::quote($uri),
'response='.self::quote($response),
'algorithm='.$challenge->algorithm['header'],
];
if ($challenge->opaque !== null) {
$parts[] = 'opaque='.self::quote($challenge->opaque);
}
if ($challenge->qop !== null) {
$parts[] = 'qop='.$challenge->qop;
$parts[] = 'nc='.$nc;
$parts[] = 'cnonce='.self::quote($cnonce);
}
if ($challenge->userhash) {
$parts[] = 'userhash=true';
}
return 'Digest '.\implode(', ', $parts);
}
/**
* @return list<array{scheme: string, params: array<string, string>, invalid: bool}>
*/
public static function parseAuthenticateHeader(string $header): array
{
$length = \strlen($header);
$offset = 0;
$challenges = [];
while (true) {
self::skipSeparators($header, $offset, $length);
if ($offset >= $length) {
break;
}
$scheme = self::readToken($header, $offset, $length);
if ($scheme === null) {
break;
}
self::skipWhitespace($header, $offset, $length);
if (self::skipToken68Challenge($header, $offset, $length)) {
$challenges[] = [
'scheme' => Psr7\Utils::asciiToLower($scheme),
'params' => [],
'invalid' => false,
];
continue;
}
$params = [];
$invalid = false;
while ($offset < $length) {
self::skipWhitespace($header, $offset, $length);
if ($offset < $length && $header[$offset] === ',') {
if (self::commaStartsNextChallenge($header, $offset + 1, $length)) {
if (Psr7\Utils::caselessEquals($scheme, 'Digest')
&& self::commaStartsKnownDigestParameterWithoutValue($header, $offset + 1, $length)
) {
$invalid = true;
break;
}
++$offset;
break;
}
++$offset;
continue;
}
$name = self::readToken($header, $offset, $length);
if ($name === null) {
if ($offset < $length) {
$invalid = true;
}
break;
}
self::skipWhitespace($header, $offset, $length);
if ($offset >= $length || $header[$offset] !== '=') {
$invalid = true;
break;
}
++$offset;
self::skipWhitespace($header, $offset, $length);
$value = self::readValue($header, $offset, $length);
if ($value === null) {
$invalid = true;
break;
}
$lowerName = Psr7\Utils::asciiToLower($name);
if (\array_key_exists($lowerName, $params)) {
$invalid = true;
}
$params[$lowerName] = $value;
self::skipWhitespace($header, $offset, $length);
if ($offset >= $length) {
break;
}
if ($header[$offset] !== ',') {
$invalid = true;
break;
}
}
$challenges[] = [
'scheme' => Psr7\Utils::asciiToLower($scheme),
'params' => $params,
'invalid' => $invalid,
];
}
return $challenges;
}
/**
* @param array<string, string> $params
*/
private static function createChallenge(array $params): ?DigestChallenge
{
if (!isset($params['nonce']) || $params['nonce'] === '') {
return null;
}
if (isset($params['charset']) && !Psr7\Utils::caselessEquals($params['charset'], 'UTF-8')) {
return null;
}
$algorithm = self::algorithm($params['algorithm'] ?? null);
if ($algorithm === null) {
return null;
}
$qop = self::selectQop($params['qop'] ?? null);
if ($qop === false) {
return null;
}
if ($algorithm['sess'] && $qop === null) {
return null;
}
$challenge = new DigestChallenge();
$challenge->algorithm = $algorithm;
$challenge->realm = $params['realm'] ?? '';
$challenge->nonce = $params['nonce'];
$challenge->opaque = $params['opaque'] ?? null;
if (isset($params['domain'])) {
$domainAreas = \preg_split('/[ \t]+/', $params['domain']);
if ($domainAreas === false) {
throw new \RuntimeException('Unable to split the Digest domain list: '.\preg_last_error_msg());
}
$challenge->domain = \array_values(\array_filter($domainAreas));
} else {
$challenge->domain = [];
}
$challenge->qop = $qop;
$challenge->stale = isset($params['stale']) && Psr7\Utils::caselessEquals($params['stale'], 'true');
$challenge->userhash = isset($params['userhash']) && Psr7\Utils::caselessEquals($params['userhash'], 'true');
return $challenge;
}
/**
* @return array{name: string, hash: string, sess: bool, rank: int, header: string}|null
*/
private static function algorithm(?string $algorithm): ?array
{
$name = Psr7\Utils::asciiToUpper($algorithm ?? 'MD5');
if (!isset(self::ALGORITHMS[$name])) {
return null;
}
$mapped = self::ALGORITHMS[$name];
if (!\in_array($mapped['hash'], \hash_algos(), true)) {
return null;
}
return ['name' => $name] + $mapped;
}
/**
* @return string|false|null
*/
private static function selectQop(?string $qop)
{
if ($qop === null) {
return null;
}
$tokens = \array_map(
static function (string $token): string {
return Psr7\Utils::asciiToLower(\trim($token, " \t"));
},
\explode(',', $qop)
);
return \in_array('auth', $tokens, true) ? 'auth' : false;
}
private static function quote(string $value): string
{
return '"'.\strtr($value, [
'\\' => '\\\\',
'"' => '\\"',
]).'"';
}
private static function isHeaderSafe(string $value): bool
{
return \preg_match('/^[\x20\x09\x21-\x7E\x80-\xFF]*$/D', $value) === 1;
}
private static function isNonceCount(string $nc): bool
{
// Nonce counts start at one.
return $nc !== '00000000' && \preg_match('/^[0-9a-f]{8}$/D', $nc) === 1;
}
private static function commaStartsNextChallenge(string $header, int $offset, int $length): bool
{
self::skipWhitespace($header, $offset, $length);
$nextOffset = $offset;
$token = self::readToken($header, $nextOffset, $length);
if ($token === null) {
return false;
}
self::skipWhitespace($header, $nextOffset, $length);
return $nextOffset >= $length || $header[$nextOffset] !== '=';
}
private static function commaStartsKnownDigestParameterWithoutValue(string $header, int $offset, int $length): bool
{
self::skipWhitespace($header, $offset, $length);
$name = self::readToken($header, $offset, $length);
if ($name === null || !isset(self::DIGEST_CHALLENGE_PARAMETER_NAMES[Psr7\Utils::asciiToLower($name)])) {
return false;
}
self::skipWhitespace($header, $offset, $length);
return $offset >= $length || $header[$offset] !== '=';
}
private static function skipToken68Challenge(string $header, int &$offset, int $length): bool
{
$cursor = $offset;
$hasValue = false;
while ($cursor < $length && self::isToken68Char($header[$cursor])) {
$hasValue = true;
++$cursor;
}
while ($cursor < $length && $header[$cursor] === '=') {
++$cursor;
}
if (!$hasValue) {
return false;
}
$after = $cursor;
self::skipWhitespace($header, $after, $length);
if ($after < $length && $header[$after] !== ',') {
return false;
}
$offset = $after;
return true;
}
private static function skipSeparators(string $header, int &$offset, int $length): void
{
while ($offset < $length) {
$char = $header[$offset];
if ($char !== ',' && !self::isWhitespace($char)) {
return;
}
++$offset;
}
}
private static function skipWhitespace(string $header, int &$offset, int $length): void
{
while ($offset < $length && self::isWhitespace($header[$offset])) {
++$offset;
}
}
private static function isWhitespace(string $char): bool
{
return $char === ' ' || $char === "\t";
}
private static function readToken(string $header, int &$offset, int $length): ?string
{
$start = $offset;
while ($offset < $length && self::isTokenChar($header[$offset])) {
++$offset;
}
if ($offset === $start) {
return null;
}
$token = \substr($header, $start, $offset - $start);
return $token === false ? null : $token;
}
private static function isTokenChar(string $char): bool
{
return \strspn($char, "!#$%&'*+-.^_`|~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") === 1;
}
private static function isToken68Char(string $char): bool
{
return \strspn($char, '-._~+/0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz') === 1;
}
private static function readValue(string $header, int &$offset, int $length): ?string
{
if ($offset >= $length) {
return null;
}
if ($header[$offset] === '"') {
return self::readQuotedString($header, $offset, $length);
}
return self::readToken($header, $offset, $length);
}
private static function readQuotedString(string $header, int &$offset, int $length): ?string
{
++$offset;
$value = '';
$escaped = false;
while ($offset < $length) {
$char = $header[$offset++];
if ($escaped) {
$value .= $char;
$escaped = false;
continue;
}
if ($char === '\\') {
$escaped = true;
continue;
}
if ($char === '"') {
return $value;
}
$value .= $char;
}
return null;
}
}

View file

@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Auth;
/**
* @internal
*/
final class DigestChallenge
{
/** @var array{name: string, hash: string, sess: bool, rank: int, header: string} */
public array $algorithm;
public string $realm = '';
public string $nonce;
public ?string $opaque = null;
/** @var list<string> */
public array $domain = [];
public ?string $qop = null;
public bool $stale = false;
public bool $userhash = false;
}

View file

@ -0,0 +1,843 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp;
use GuzzleHttp\Auth\DigestAuth;
use GuzzleHttp\Auth\DigestChallenge;
use GuzzleHttp\Exception\InvalidArgumentException;
use GuzzleHttp\Exception\ResponseException;
use GuzzleHttp\Promise as P;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\HttpFactory;
use GuzzleHttp\Psr7\LazyOpenStream;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UriInterface;
/**
* Applies built-in Basic authentication and handles Digest authentication
* challenges.
*/
final class AuthMiddleware
{
use NonSerializableTrait;
private const DIGEST_MAX_RETRIES = 2;
private const CHALLENGE_CACHE_LIMIT = 32;
/**
* Request option carrying nonce counts already spent during a Digest
* handshake, so stale retries advance instead of repeating a count.
*/
private const DIGEST_NONCE_COUNTS_OPTION = '__guzzle_digest_nonce_counts';
/**
* Headers that describe the request payload. A probe with an empty body
* must not carry them.
*
* @var list<string>
*/
private const DIGEST_PROBE_PAYLOAD_HEADERS = [
'Transfer-Encoding',
'Expect',
'Trailer',
'Content-Range',
'Content-Encoding',
'Content-MD5',
'Digest',
'Content-Digest',
'Repr-Digest',
];
/**
* @var callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>
*/
private $nextHandler;
/**
* @var callable(): string
*/
private $cnonceGenerator;
private bool $reuseChallenges;
private ?string $credentialHashSecret = null;
/**
* @var array<string, array{challenge: DigestChallenge, credentials: string, nextNc: int}>
*/
private array $digestChallenges = [];
/**
* @param callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed> $nextHandler
* @param (callable(): string)|null $cnonceGenerator
*/
public function __construct(callable $nextHandler, ?callable $cnonceGenerator = null, bool $reuseChallenges = true)
{
$this->nextHandler = $nextHandler;
$this->cnonceGenerator = $cnonceGenerator ?? static function (): string {
return \bin2hex(\random_bytes(16));
};
$this->reuseChallenges = $reuseChallenges;
}
/**
* @return PromiseInterface<ResponseInterface, mixed>
*/
public function __invoke(
#[\SensitiveParameter]
RequestInterface $request,
#[\SensitiveParameter]
array $options
): PromiseInterface {
$auth = $options['auth'] ?? null;
if ($auth === null || $auth === false || $auth === [] || \is_string($auth)) {
return ($this->nextHandler)($request, $options);
}
$normalizedAuth = self::normalizeAuth($auth);
if ($normalizedAuth === null) {
return ($this->nextHandler)($request, $options);
}
[$username, $password, $type] = $normalizedAuth;
if ($type === 'basic') {
return $this->sendBasic($request, $options, $username, $password);
}
return $this->sendDigest($request, $options, $username, $password);
}
/**
* @param array<array-key, mixed> $auth
*
* @return array{0: string, 1: string, 2: 'basic'|'digest'}|null
*/
private static function normalizeAuth(
#[\SensitiveParameter]
array $auth
): ?array {
$type = 'basic';
if (\array_key_exists(2, $auth) && $auth[2] !== null) {
if (!\is_string($auth[2])) {
throw new InvalidArgumentException('auth type must be a string');
}
$type = Psr7\Utils::asciiToLower($auth[2]);
}
if (!\in_array($type, ['basic', 'digest'], true)) {
return null;
}
if (!\array_key_exists(0, $auth) || !\array_key_exists(1, $auth)) {
throw new InvalidArgumentException('auth must contain username and password strings');
}
if (!\is_string($auth[0]) || !\is_string($auth[1])) {
throw new InvalidArgumentException('auth must contain username and password strings');
}
return [$auth[0], $auth[1], $type];
}
/**
* @return PromiseInterface<ResponseInterface, mixed>
*/
private function sendBasic(
#[\SensitiveParameter]
RequestInterface $request,
#[\SensitiveParameter]
array $options,
string $username,
#[\SensitiveParameter]
string $password
): PromiseInterface {
if (\strpos($username, ':') !== false) {
throw new InvalidArgumentException('Basic authentication username must not contain a colon');
}
if (\preg_match('/[\x00-\x1F\x7F]/', $username.$password) !== 0) {
throw new InvalidArgumentException('Basic authentication credentials must not contain ASCII control characters');
}
unset($options['auth']);
return ($this->nextHandler)(
$request->withHeader('Authorization', 'Basic '.\base64_encode($username.':'.$password)),
$options
);
}
/**
* @return PromiseInterface<ResponseInterface, mixed>
*/
private function sendDigest(
#[\SensitiveParameter]
RequestInterface $request,
#[\SensitiveParameter]
array $options,
string $username,
#[\SensitiveParameter]
string $password
): PromiseInterface {
$preemptive = $this->reuseChallenges
? $this->preemptiveDigestRequest($request, $username, $password)
: null;
if ($preemptive !== null) {
$preemptiveOptions = self::withTemporarySink($options);
unset($preemptiveOptions['auth']);
return ($this->nextHandler)($preemptive, $preemptiveOptions)->then(
function (
#[\SensitiveParameter]
ResponseInterface $response
) use ($request, $options, $preemptiveOptions, $username, $password) {
// Clear on 4xx/5xx other than 401 so non-conformant stale-nonce
// errors cannot poison the cache indefinitely.
$status = $response->getStatusCode();
if ($status >= 400 && $status !== 401) {
$this->clearDigestChallenge($request);
}
return $this->handleDigestResponse($request, $options, $preemptiveOptions, $response, $username, $password, false);
},
function (
#[\SensitiveParameter]
$reason
) use ($request, $preemptiveOptions) {
return $this->handleDigestRejection($request, $preemptiveOptions, $reason, true);
}
);
}
$probeOptions = self::withTemporarySink($options);
unset($probeOptions['auth']);
[$probeRequest, $bodyWithheld] = self::probeRequest($request, $options);
if ($bodyWithheld) {
// The probe has no payload, so prepare_body must not add Expect
// if a custom empty stream has unknown size.
$probeOptions[RequestOptions::EXPECT] = false;
}
return ($this->nextHandler)($probeRequest, $probeOptions)->then(
function (
#[\SensitiveParameter]
ResponseInterface $response
) use ($request, $options, $probeOptions, $username, $password, $bodyWithheld) {
return $this->handleDigestResponse($request, $options, $probeOptions, $response, $username, $password, $bodyWithheld);
},
function (
#[\SensitiveParameter]
$reason
) use ($request, $probeOptions) {
return $this->handleDigestRejection($request, $probeOptions, $reason, false);
}
);
}
private function preemptiveDigestRequest(
#[\SensitiveParameter]
RequestInterface $request,
string $username,
#[\SensitiveParameter]
string $password
): ?RequestInterface {
try {
if ($request->getBody()->getSize() !== 0) {
return null;
}
} catch (\Exception $e) {
return null;
}
$key = self::digestCacheKey($request);
if ($key === null) {
return null;
}
$entry = $this->digestChallenges[$key] ?? null;
if ($entry === null
|| $entry['credentials'] !== $this->digestCredentialKey($username, $password)
|| !self::challengeCoversRequest($entry['challenge'], $request)
) {
return null;
}
$authorization = DigestAuth::authorizationHeader(
$request,
$entry['challenge'],
$username,
$password,
($this->cnonceGenerator)(),
\sprintf('%08x', $entry['nextNc'])
);
if ($authorization === null) {
return null;
}
++$this->digestChallenges[$key]['nextNc'];
return $request->withHeader('Authorization', $authorization);
}
/**
* Builds the unauthenticated probe request for a Digest handshake.
*
* @return array{0: RequestInterface, 1: bool}
*/
private static function probeRequest(
#[\SensitiveParameter]
RequestInterface $request,
#[\SensitiveParameter]
array $options
): array {
$probe = $request->withoutHeader('Authorization');
try {
$size = $probe->getBody()->getSize();
} catch (\Exception $e) {
$size = null;
}
if ($size === 0) {
return [$probe, false];
}
$streamFactory = self::requireStreamFactory(
$options[RequestOptions::STREAM_FACTORY] ?? new HttpFactory()
);
$probe = $probe->withBody($streamFactory->createStream(''))
->withHeader('Content-Length', '0');
foreach (self::DIGEST_PROBE_PAYLOAD_HEADERS as $header) {
$probe = $probe->withoutHeader($header);
}
return [$probe, true];
}
/**
* @return ResponseInterface|PromiseInterface<ResponseInterface, mixed>
*/
private function handleDigestResponse(
#[\SensitiveParameter]
RequestInterface $request,
#[\SensitiveParameter]
array $options,
#[\SensitiveParameter]
array $probeOptions,
#[\SensitiveParameter]
ResponseInterface $response,
string $username,
#[\SensitiveParameter]
string $password,
bool $bodyWithheld
) {
$status = $response->getStatusCode();
$previousEntry = null;
if ($this->reuseChallenges && $status === 401) {
$key = self::digestCacheKey($request);
$previousEntry = $key !== null ? ($this->digestChallenges[$key] ?? null) : null;
$this->clearDigestChallenge($request);
}
if ($status !== 401) {
if ($this->reuseChallenges && $response->hasHeader('Authentication-Info')) {
$this->clearDigestChallenge($request);
}
$response = self::restoreOriginalSink($request, $response, $probeOptions);
if ($bodyWithheld && $status !== 407 && !self::isRedirectLikeResponse($response)) {
throw new ResponseException(
'Digest authentication failed because the server did not issue a challenge; the request was probed without its body',
$request,
$response
);
}
return $response;
}
$challenge = DigestAuth::selectChallenge($response);
if ($challenge === null) {
return self::restoreOriginalSink($request, $response, $probeOptions);
}
$retries = $options['__guzzle_digest_retries'] ?? 0;
if (!\is_int($retries)) {
$retries = 0;
}
if (($retries > 0 && !$challenge->stale) || $retries >= self::DIGEST_MAX_RETRIES) {
return self::restoreOriginalSink($request, $response, $probeOptions);
}
try {
self::rewindBodyForRetry($request, $bodyWithheld);
} catch (\Exception $e) {
$response = self::restoreOriginalSink($request, $response, $probeOptions);
throw new ResponseException(
'Digest authentication failed because the request body could not be rewound',
$request,
$response,
$e
);
}
$nonceCounts = self::digestNonceCountsFromOptions($options);
if ($previousEntry !== null
&& $previousEntry['credentials'] === $this->digestCredentialKey($username, $password)
) {
self::rememberDigestNonceCount($nonceCounts, $previousEntry['challenge'], $previousEntry['nextNc']);
}
$nc = $challenge->qop === null ? 1 : ($nonceCounts[self::digestNonceCountKey($challenge)] ?? 1);
$authorization = DigestAuth::authorizationHeader(
$request,
$challenge,
$username,
$password,
($this->cnonceGenerator)(),
\sprintf('%08x', $nc)
);
if ($authorization === null) {
return self::restoreOriginalSink($request, $response, $probeOptions);
}
$response->getBody()->close();
self::rememberDigestNonceCount($nonceCounts, $challenge, $nc + 1);
$retryOptions = $options;
$retryOptions['__guzzle_digest_retries'] = $retries + 1;
$retryOptions[self::DIGEST_NONCE_COUNTS_OPTION] = $nonceCounts;
$downstreamOptions = $retryOptions;
// The nonce-count map only carries handshake state into the retry
// recursion; downstream handlers must not observe it.
unset($downstreamOptions[self::DIGEST_NONCE_COUNTS_OPTION]);
// The caller's delay applies once, before the first Digest leg, not
// before each handshake retry.
unset($downstreamOptions[RequestOptions::DELAY]);
$downstreamOptions = self::withTemporarySink($downstreamOptions);
unset($downstreamOptions['auth']);
$retryRequest = $request->withHeader('Authorization', $authorization);
return ($this->nextHandler)($retryRequest, $downstreamOptions)->then(
function (
#[\SensitiveParameter]
ResponseInterface $retryResponse
) use ($retryRequest, $retryOptions, $downstreamOptions, $username, $password, $challenge, $nc) {
if ($this->reuseChallenges && self::isCacheableDigestSuccess($retryResponse)) {
$this->storeDigestChallenge($retryRequest, $challenge, $username, $password, $nc + 1);
}
return $this->handleDigestResponse($retryRequest, $retryOptions, $downstreamOptions, $retryResponse, $username, $password, false);
},
function (
#[\SensitiveParameter]
$reason
) use ($retryRequest, $downstreamOptions) {
return $this->handleDigestRejection($retryRequest, $downstreamOptions, $reason, false);
}
);
}
private static function isCacheableDigestSuccess(ResponseInterface $response): bool
{
$status = $response->getStatusCode();
return $status >= 200 && $status < 400 && !$response->hasHeader('Authentication-Info');
}
private function storeDigestChallenge(
#[\SensitiveParameter]
RequestInterface $request,
DigestChallenge $challenge,
string $username,
#[\SensitiveParameter]
string $password,
int $nextNc
): void {
$key = self::digestCacheKey($request);
if ($key === null || $challenge->qop === null) {
return;
}
unset($this->digestChallenges[$key]);
if (\count($this->digestChallenges) >= self::CHALLENGE_CACHE_LIMIT) {
\array_shift($this->digestChallenges);
}
$this->digestChallenges[$key] = [
'challenge' => $challenge,
'credentials' => $this->digestCredentialKey($username, $password),
'nextNc' => $nextNc,
];
}
private function clearDigestChallenge(RequestInterface $request): void
{
$key = self::digestCacheKey($request);
if ($key !== null) {
unset($this->digestChallenges[$key]);
}
}
/**
* @param array<array-key, mixed> $options
*
* @return array<string, int>
*/
private static function digestNonceCountsFromOptions(array $options): array
{
$counts = $options[self::DIGEST_NONCE_COUNTS_OPTION] ?? [];
if (!\is_array($counts)) {
return [];
}
$normalized = [];
foreach ($counts as $key => $nextNc) {
if (\is_string($key) && \is_int($nextNc) && $nextNc > 0 && $nextNc < \PHP_INT_MAX) {
$normalized[$key] = $nextNc;
}
}
return $normalized;
}
private static function digestNonceCountKey(DigestChallenge $challenge): string
{
return \implode("\0", [
$challenge->realm,
$challenge->nonce,
$challenge->qop ?? '',
$challenge->algorithm['header'],
]);
}
/**
* @param array<string, int> $counts
*/
private static function rememberDigestNonceCount(array &$counts, DigestChallenge $challenge, int $nextNc): void
{
if ($challenge->qop === null) {
return;
}
$key = self::digestNonceCountKey($challenge);
$counts[$key] = \max($counts[$key] ?? 1, $nextNc);
}
/**
* @param mixed $reason
*
* @return PromiseInterface<ResponseInterface, mixed>
*/
private function handleDigestRejection(
#[\SensitiveParameter]
RequestInterface $request,
#[\SensitiveParameter]
array $options,
#[\SensitiveParameter]
$reason,
bool $preemptive
): PromiseInterface {
if ($this->reuseChallenges && $reason instanceof ResponseException) {
$response = $reason->getResponse();
if ($response->getStatusCode() === 401
|| $response->hasHeader('Authentication-Info')
|| ($preemptive && $response->getStatusCode() >= 400)
) {
$this->clearDigestChallenge($request);
}
}
return self::restoreOriginalSinkOnRejection($options, $reason);
}
private static function digestCacheKey(RequestInterface $request): ?string
{
$uri = $request->getUri();
$scheme = Psr7\Utils::asciiToLower($uri->getScheme());
$host = HostIdentity::canonicalHost($uri->getHost());
if (($scheme !== 'http' && $scheme !== 'https') || $host === '') {
return null;
}
$port = $uri->getPort() ?? ($scheme === 'https' ? 443 : 80);
return $scheme.'://'.$host.':'.$port.'|'.HostIdentity::canonicalHostHeader($request->getHeaderLine('Host'));
}
private function digestCredentialKey(
string $username,
#[\SensitiveParameter]
string $password
): string {
if ($this->credentialHashSecret === null) {
$this->credentialHashSecret = \random_bytes(32);
}
return \hash_hmac('sha256', $username."\0".$password, $this->credentialHashSecret);
}
private static function challengeCoversRequest(DigestChallenge $challenge, RequestInterface $request): bool
{
if ($challenge->domain === []) {
return true;
}
$target = $request->getRequestTarget();
foreach ($challenge->domain as $space) {
$prefix = self::protectionSpacePath($space, $request);
if ($prefix !== null && \str_starts_with($target, $prefix)) {
return true;
}
}
return false;
}
private static function protectionSpacePath(string $space, RequestInterface $request): ?string
{
if ($space === '') {
return null;
}
if ($space[0] === '/') {
return $space;
}
try {
$uri = new Psr7\Uri($space);
} catch (\InvalidArgumentException $e) {
return null;
}
if (Psr7\UriComparator::isCrossOrigin($uri, self::effectiveRequestUri($request))) {
return null;
}
$path = $uri->getPath();
$prefix = $path === '' ? '/' : $path;
if ($uri->getQuery() !== '') {
$prefix .= '?'.$uri->getQuery();
}
return $prefix;
}
private static function effectiveRequestUri(RequestInterface $request): UriInterface
{
$uri = $request->getUri();
$host = $request->getHeaderLine('Host');
if ($host === '' || Psr7\Utils::caselessEquals($host, $uri->getHost())) {
return $uri;
}
try {
$authority = new Psr7\Uri('//'.$host);
if ($authority->getHost() === '') {
return $uri;
}
return $uri->withHost($authority->getHost())->withPort($authority->getPort());
} catch (\InvalidArgumentException $e) {
return $uri;
}
}
private static function isRedirectLikeResponse(ResponseInterface $response): bool
{
return $response->hasHeader('Location')
&& \in_array($response->getStatusCode(), [301, 302, 303, 307, 308], true);
}
private static function rewindBodyForRetry(
#[\SensitiveParameter]
RequestInterface $request,
bool $bodyWithheld
): void {
$body = $request->getBody();
if (!$bodyWithheld) {
try {
if ($body->getSize() === 0) {
return;
}
} catch (\Exception $e) {
// Fall through to the standard rewind path.
}
Psr7\Message::rewindBody($request);
return;
}
if ($body->isSeekable()) {
$body->rewind();
}
}
private static function withTemporarySink(
#[\SensitiveParameter]
array $options
): array {
// The 'stream' option is deliberately not checked here: the cURL
// handlers do not support streaming and write each leg to the sink,
// so a configured sink always needs challenge-body protection.
if (!isset($options[RequestOptions::SINK])) {
return $options;
}
$streamFactory = self::requireStreamFactory(
$options[RequestOptions::STREAM_FACTORY] ?? new HttpFactory()
);
$options['__guzzle_auth_original_sink'] = $options[RequestOptions::SINK];
$options[RequestOptions::SINK] = $streamFactory->createStreamFromResource(
Psr7\Utils::tryFopen('php://temp', 'w+')
);
return $options;
}
private static function restoreOriginalSink(
#[\SensitiveParameter]
RequestInterface $request,
#[\SensitiveParameter]
ResponseInterface $response,
#[\SensitiveParameter]
array $options
): ResponseInterface {
if (!\array_key_exists('__guzzle_auth_original_sink', $options)) {
return $response;
}
try {
$source = $response->getBody();
if ($source->isSeekable()) {
$source->rewind();
}
$target = self::streamForOriginalSink($options['__guzzle_auth_original_sink']);
Psr7\Utils::copyToStream($source, $target);
if ($target->isSeekable()) {
$target->rewind();
}
return $response->withBody($target);
} catch (\Exception $e) {
throw new ResponseException(
$e->getMessage() !== '' ? $e->getMessage() : 'Failed to write the response body',
$request,
$response,
$e
);
}
}
/**
* @param mixed $reason
*
* @return PromiseInterface<ResponseInterface, mixed>
*/
private static function restoreOriginalSinkOnRejection(
#[\SensitiveParameter]
array $options,
#[\SensitiveParameter]
$reason
): PromiseInterface {
if (!$reason instanceof ResponseException || !\array_key_exists('__guzzle_auth_original_sink', $options)) {
/** @var PromiseInterface<ResponseInterface, mixed> */
return P\Create::rejectionFor($reason);
}
try {
$response = self::restoreOriginalSink($reason->getRequest(), $reason->getResponse(), $options);
/** @var PromiseInterface<ResponseInterface, mixed> */
return P\Create::rejectionFor($reason->withResponse($response));
} catch (\Throwable $e) {
/** @var PromiseInterface<ResponseInterface, mixed> */
return P\Create::rejectionFor($e);
}
}
/**
* @param mixed $sink
*/
private static function streamForOriginalSink($sink): StreamInterface
{
if (\is_string($sink)) {
return new LazyOpenStream($sink, 'w+');
}
if (\is_resource($sink)) {
return self::streamForResourceSink(Psr7\Utils::streamFor($sink));
}
if (!$sink instanceof StreamInterface) {
throw new InvalidArgumentException(\sprintf(
'sink must be a resource, string, or %s',
StreamInterface::class
));
}
return Psr7\Utils::streamFor($sink);
}
/**
* Decorates a caller-owned sink stream so that closing the response body
* detaches Guzzle's wrapper without closing the original PHP resource.
*/
private static function streamForResourceSink(StreamInterface $stream): StreamInterface
{
return Psr7\FnStream::decorate($stream, [
'close' => static function () use ($stream): void {
$stream->detach();
},
]);
}
/**
* @param mixed $factory
*/
private static function requireStreamFactory($factory): StreamFactoryInterface
{
if (!$factory instanceof StreamFactoryInterface) {
throw new InvalidArgumentException(\sprintf(
'%s must be an instance of %s',
RequestOptions::STREAM_FACTORY,
StreamFactoryInterface::class
));
}
return $factory;
}
}

View file

@ -1,15 +1,14 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp;
use Psr\Http\Message\MessageInterface;
final class BodySummarizer implements BodySummarizerInterface
{
/**
* @var int|null
*/
private $truncateAt;
private ?int $truncateAt;
public function __construct(?int $truncateAt = null)
{
@ -21,8 +20,10 @@ final class BodySummarizer implements BodySummarizerInterface
*/
public function summarize(MessageInterface $message): ?string
{
return $this->truncateAt === null
? Psr7\Message::bodySummary($message)
: Psr7\Message::bodySummary($message, $this->truncateAt);
try {
return Psr7\Message::bodySummary($message, $this->truncateAt);
} catch (\Exception $e) {
return null;
}
}
}

View file

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp;
use Psr\Http\Message\MessageInterface;

File diff suppressed because it is too large Load diff

View file

@ -1,11 +1,19 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp;
use GuzzleHttp\Cookie\CookieJarInterface;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UriFactoryInterface;
use Psr\Http\Message\UriInterface;
/**
@ -16,14 +24,86 @@ interface ClientInterface
/**
* The Guzzle major version.
*/
public const MAJOR_VERSION = 7;
public const MAJOR_VERSION = 8;
/**
* Send an HTTP request.
*
* @param RequestInterface $request Request to send
* @param array $options Request options to apply to the given
* request and to the transfer.
* @param array{
* base_uri?: string|UriInterface,
* allow_redirects?: bool|array{
* max?: int,
* strict?: bool,
* referer?: bool,
* protocols?: non-empty-array<array-key, string>,
* on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed,
* track_redirects?: bool
* },
* auth?: array{
* 0: string,
* 1: string,
* 2?: string|null
* }|string|false|null,
* body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable,
* cert?: string|array{
* 0: string,
* 1?: string|null
* },
* cert_type?: string,
* connect_timeout?: int|float,
* cookies?: false|CookieJarInterface,
* crypto_method?: int,
* crypto_method_max?: int,
* debug?: bool|resource,
* decode_content?: bool|string,
* delay?: int|float,
* expect?: bool|int,
* form_params?: array<array-key, string|int|float|bool|null|array>,
* force_ip_resolve?: string,
* headers?: array<array-key, string|non-empty-array<array-key, string>>|null,
* http_errors?: bool,
* idn_conversion?: bool|int|null,
* json?: mixed,
* multipart?: array<array-key, array{
* name: string|int,
* contents: mixed,
* headers?: array<array-key, string>,
* filename?: string
* }>,
* multiplex?: string,
* on_headers?: callable(ResponseInterface, RequestInterface): mixed,
* on_stats?: callable(TransferStats): mixed,
* on_trailers?: callable(array<string, list<string>>, ResponseInterface, RequestInterface): mixed,
* progress?: callable(int, int, int, int): mixed,
* protocols?: non-empty-array<array-key, string>,
* proxy?: string|array{
* http?: string|null,
* https?: string|null,
* no?: string|array<array-key, string>|null
* },
* query?: array<array-key, mixed>|string,
* read_timeout?: int|float,
* retries?: int,
* request_factory?: RequestFactoryInterface,
* response_factory?: ResponseFactoryInterface,
* sink?: resource|string|StreamInterface,
* ssl_key?: string|array{
* 0: string,
* 1?: string|null
* },
* ssl_key_type?: string,
* stream?: bool,
* stream_factory?: StreamFactoryInterface,
* stream_context?: array<array-key, mixed>,
* synchronous?: bool,
* timeout?: int|float,
* uri_factory?: UriFactoryInterface,
* verify?: bool|string,
* version?: string|int|float,
* curl?: array<int|string, mixed>,
* ...
* } $options Request options to apply to the given request and to the transfer.
*
* @throws GuzzleException
*/
@ -33,8 +113,82 @@ interface ClientInterface
* Asynchronously send an HTTP request.
*
* @param RequestInterface $request Request to send
* @param array $options Request options to apply to the given
* request and to the transfer.
* @param array{
* base_uri?: string|UriInterface,
* allow_redirects?: bool|array{
* max?: int,
* strict?: bool,
* referer?: bool,
* protocols?: non-empty-array<array-key, string>,
* on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed,
* track_redirects?: bool
* },
* auth?: array{
* 0: string,
* 1: string,
* 2?: string|null
* }|string|false|null,
* body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable,
* cert?: string|array{
* 0: string,
* 1?: string|null
* },
* cert_type?: string,
* connect_timeout?: int|float,
* cookies?: false|CookieJarInterface,
* crypto_method?: int,
* crypto_method_max?: int,
* debug?: bool|resource,
* decode_content?: bool|string,
* delay?: int|float,
* expect?: bool|int,
* form_params?: array<array-key, string|int|float|bool|null|array>,
* force_ip_resolve?: string,
* headers?: array<array-key, string|non-empty-array<array-key, string>>|null,
* http_errors?: bool,
* idn_conversion?: bool|int|null,
* json?: mixed,
* multipart?: array<array-key, array{
* name: string|int,
* contents: mixed,
* headers?: array<array-key, string>,
* filename?: string
* }>,
* multiplex?: string,
* on_headers?: callable(ResponseInterface, RequestInterface): mixed,
* on_stats?: callable(TransferStats): mixed,
* on_trailers?: callable(array<string, list<string>>, ResponseInterface, RequestInterface): mixed,
* progress?: callable(int, int, int, int): mixed,
* protocols?: non-empty-array<array-key, string>,
* proxy?: string|array{
* http?: string|null,
* https?: string|null,
* no?: string|array<array-key, string>|null
* },
* query?: array<array-key, mixed>|string,
* read_timeout?: int|float,
* retries?: int,
* request_factory?: RequestFactoryInterface,
* response_factory?: ResponseFactoryInterface,
* sink?: resource|string|StreamInterface,
* ssl_key?: string|array{
* 0: string,
* 1?: string|null
* },
* ssl_key_type?: string,
* stream?: bool,
* stream_factory?: StreamFactoryInterface,
* stream_context?: array<array-key, mixed>,
* synchronous?: bool,
* timeout?: int|float,
* uri_factory?: UriFactoryInterface,
* verify?: bool|string,
* version?: string|int|float,
* curl?: array<int|string, mixed>,
* ...
* } $options Request options to apply to the given request and to the transfer.
*
* @return PromiseInterface<ResponseInterface, mixed>
*/
public function sendAsync(RequestInterface $request, array $options = []): PromiseInterface;
@ -45,9 +199,82 @@ interface ClientInterface
* relative path to append to the base path of the client. The URL can
* contain the query string as well.
*
* @param string $method HTTP method.
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
* @param string $method HTTP method.
* @param string|UriInterface $uri URI object or string.
* @param array{
* base_uri?: string|UriInterface,
* allow_redirects?: bool|array{
* max?: int,
* strict?: bool,
* referer?: bool,
* protocols?: non-empty-array<array-key, string>,
* on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed,
* track_redirects?: bool
* },
* auth?: array{
* 0: string,
* 1: string,
* 2?: string|null
* }|string|false|null,
* body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable,
* cert?: string|array{
* 0: string,
* 1?: string|null
* },
* cert_type?: string,
* connect_timeout?: int|float,
* cookies?: false|CookieJarInterface,
* crypto_method?: int,
* crypto_method_max?: int,
* debug?: bool|resource,
* decode_content?: bool|string,
* delay?: int|float,
* expect?: bool|int,
* form_params?: array<array-key, string|int|float|bool|null|array>,
* force_ip_resolve?: string,
* headers?: array<array-key, string|non-empty-array<array-key, string>>|null,
* http_errors?: bool,
* idn_conversion?: bool|int|null,
* json?: mixed,
* multipart?: array<array-key, array{
* name: string|int,
* contents: mixed,
* headers?: array<array-key, string>,
* filename?: string
* }>,
* multiplex?: string,
* on_headers?: callable(ResponseInterface, RequestInterface): mixed,
* on_stats?: callable(TransferStats): mixed,
* on_trailers?: callable(array<string, list<string>>, ResponseInterface, RequestInterface): mixed,
* progress?: callable(int, int, int, int): mixed,
* protocols?: non-empty-array<array-key, string>,
* proxy?: string|array{
* http?: string|null,
* https?: string|null,
* no?: string|array<array-key, string>|null
* },
* query?: array<array-key, mixed>|string,
* read_timeout?: int|float,
* retries?: int,
* request_factory?: RequestFactoryInterface,
* response_factory?: ResponseFactoryInterface,
* sink?: resource|string|StreamInterface,
* ssl_key?: string|array{
* 0: string,
* 1?: string|null
* },
* ssl_key_type?: string,
* stream?: bool,
* stream_factory?: StreamFactoryInterface,
* stream_context?: array<array-key, mixed>,
* synchronous?: bool,
* timeout?: int|float,
* uri_factory?: UriFactoryInterface,
* verify?: bool|string,
* version?: string|int|float,
* curl?: array<int|string, mixed>,
* ...
* } $options Request options to apply.
*
* @throws GuzzleException
*/
@ -58,27 +285,86 @@ interface ClientInterface
*
* Use an absolute path to override the base path of the client, or a
* relative path to append to the base path of the client. The URL can
* contain the query string as well. Use an array to provide a URL
* template and additional variables to use in the URL template expansion.
* contain the query string as well.
*
* @param string $method HTTP method
* @param string|UriInterface $uri URI object or string.
* @param array $options Request options to apply.
* @param string $method HTTP method
* @param string|UriInterface $uri URI object or string.
* @param array{
* base_uri?: string|UriInterface,
* allow_redirects?: bool|array{
* max?: int,
* strict?: bool,
* referer?: bool,
* protocols?: non-empty-array<array-key, string>,
* on_redirect?: callable(RequestInterface, ResponseInterface, UriInterface): mixed,
* track_redirects?: bool
* },
* auth?: array{
* 0: string,
* 1: string,
* 2?: string|null
* }|string|false|null,
* body?: resource|string|null|StreamInterface|(callable&object)|\Iterator|\Stringable,
* cert?: string|array{
* 0: string,
* 1?: string|null
* },
* cert_type?: string,
* connect_timeout?: int|float,
* cookies?: false|CookieJarInterface,
* crypto_method?: int,
* crypto_method_max?: int,
* debug?: bool|resource,
* decode_content?: bool|string,
* delay?: int|float,
* expect?: bool|int,
* form_params?: array<array-key, string|int|float|bool|null|array>,
* force_ip_resolve?: string,
* headers?: array<array-key, string|non-empty-array<array-key, string>>|null,
* http_errors?: bool,
* idn_conversion?: bool|int|null,
* json?: mixed,
* multipart?: array<array-key, array{
* name: string|int,
* contents: mixed,
* headers?: array<array-key, string>,
* filename?: string
* }>,
* multiplex?: string,
* on_headers?: callable(ResponseInterface, RequestInterface): mixed,
* on_stats?: callable(TransferStats): mixed,
* on_trailers?: callable(array<string, list<string>>, ResponseInterface, RequestInterface): mixed,
* progress?: callable(int, int, int, int): mixed,
* protocols?: non-empty-array<array-key, string>,
* proxy?: string|array{
* http?: string|null,
* https?: string|null,
* no?: string|array<array-key, string>|null
* },
* query?: array<array-key, mixed>|string,
* read_timeout?: int|float,
* retries?: int,
* request_factory?: RequestFactoryInterface,
* response_factory?: ResponseFactoryInterface,
* sink?: resource|string|StreamInterface,
* ssl_key?: string|array{
* 0: string,
* 1?: string|null
* },
* ssl_key_type?: string,
* stream?: bool,
* stream_factory?: StreamFactoryInterface,
* stream_context?: array<array-key, mixed>,
* synchronous?: bool,
* timeout?: int|float,
* uri_factory?: UriFactoryInterface,
* verify?: bool|string,
* version?: string|int|float,
* curl?: array<int|string, mixed>,
* ...
* } $options Request options to apply.
*
* @return PromiseInterface<ResponseInterface, mixed>
*/
public function requestAsync(string $method, $uri, array $options = []): PromiseInterface;
/**
* Get a client configuration option.
*
* These options include default request options of the client, a "handler"
* (if utilized by the concrete client), and a "base_uri" if utilized by
* the concrete client.
*
* @param string|null $option The config option to retrieve.
*
* @return mixed
*
* @deprecated ClientInterface::getConfig will be removed in guzzlehttp/guzzle:8.0.
*/
public function getConfig(?string $option = null);
}

File diff suppressed because it is too large Load diff

View file

@ -1,7 +1,10 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Cookie;
use GuzzleHttp\HostIdentity;
use GuzzleHttp\Psr7;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
@ -19,12 +22,9 @@ class CookieJar implements CookieJarInterface
/**
* @var SetCookie[] Loaded cookie data
*/
private $cookies = [];
private array $cookies = [];
/**
* @var bool
*/
private $strictMode;
private bool $strictMode;
/**
* @param bool $strictMode Set to true to throw exceptions when invalid
@ -33,8 +33,11 @@ class CookieJar implements CookieJarInterface
* arrays that can be used with the SetCookie
* constructor
*/
public function __construct(bool $strictMode = false, array $cookieArray = [])
{
public function __construct(
bool $strictMode = false,
#[\SensitiveParameter]
array $cookieArray = []
) {
$this->strictMode = $strictMode;
foreach ($cookieArray as $cookie) {
@ -51,14 +54,21 @@ class CookieJar implements CookieJarInterface
* @param array $cookies Cookies to create the jar from
* @param string $domain Domain to set the cookies to
*/
public static function fromArray(array $cookies, string $domain): self
{
public static function fromArray(
#[\SensitiveParameter]
array $cookies,
string $domain
): self {
$cookieJar = new self();
foreach ($cookies as $name => $value) {
if (!\is_scalar($value) && !(\is_object($value) && \method_exists($value, '__toString'))) {
throw new \InvalidArgumentException('Cookie value must be scalar or stringable');
}
$cookieJar->setCookie(new SetCookie([
'Domain' => $domain,
'Name' => $name,
'Value' => $value,
'Name' => (string) $name,
'Value' => (string) $value,
'Discard' => true,
]));
}
@ -94,7 +104,7 @@ class CookieJar implements CookieJarInterface
public function getCookieByName(string $name): ?SetCookie
{
foreach ($this->cookies as $cookie) {
if ($cookie->getName() !== null && Psr7\Utils::caselessEquals($cookie->getName(), $name)) {
if ($cookie->getName() === $name) {
return $cookie;
}
}
@ -134,7 +144,7 @@ class CookieJar implements CookieJarInterface
} else {
$this->cookies = \array_filter(
$this->cookies,
static function (SetCookie $cookie) use ($path, $domain, $name) {
static function (SetCookie $cookie) use ($path, $domain, $name): bool {
return !($cookie->getDomain() !== null
&& $cookie->getName() === $name
&& $cookie->matchesPath($path)
@ -154,8 +164,10 @@ class CookieJar implements CookieJarInterface
);
}
public function setCookie(SetCookie $cookie): bool
{
public function setCookie(
#[\SensitiveParameter]
SetCookie $cookie
): bool {
// If the name string is empty (but not 0), ignore the set-cookie
// string entirely.
$name = $cookie->getName();
@ -237,10 +249,18 @@ class CookieJar implements CookieJarInterface
return new \ArrayIterator(\array_values($this->cookies));
}
public function extractCookies(RequestInterface $request, ResponseInterface $response): void
{
public function extractCookies(
#[\SensitiveParameter]
RequestInterface $request,
#[\SensitiveParameter]
ResponseInterface $response
): void {
if ($cookieHeader = $response->getHeader('Set-Cookie')) {
$uri = $request->getUri();
$requestHost = HostIdentity::canonicalHost($uri->getHost());
$secure = $uri->getScheme() === 'https';
$accepted = 0;
foreach ($cookieHeader as $cookie) {
if (\strlen($cookie) > self::MAX_SET_COOKIE_FIELD_LENGTH) {
continue;
@ -249,11 +269,7 @@ class CookieJar implements CookieJarInterface
$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->setDomain($requestHost);
$sc->setHostOnly(true);
} else {
$sc->setHostOnly(false);
@ -261,7 +277,17 @@ class CookieJar implements CookieJarInterface
if (0 !== \strpos($sc->getPath(), '/')) {
$sc->setPath($this->getCookiePathFromRequest($request));
}
if (!$sc->matchesDomain($request->getUri()->getHost())) {
if (!$sc->matchesDomain($requestHost)) {
continue;
}
if (!$secure && ($sc->getSecure() || $this->overlaysSecureCookie($sc))) {
continue;
}
$prefixName = Psr7\Utils::asciiToLower((string) $sc->getName());
if (\str_starts_with($prefixName, '__secure-') && !$sc->getSecure()) {
continue;
}
if (\str_starts_with($prefixName, '__host-') && (!$sc->getSecure() || !$sc->getHostOnly() || $sc->getPath() !== '/' || !self::hasPathAttribute($cookie))) {
continue;
}
// Note: At this point `$sc->getDomain()` being a public suffix should
@ -273,6 +299,55 @@ class CookieJar implements CookieJarInterface
}
}
private function overlaysSecureCookie(SetCookie $cookie): bool
{
foreach ($this->cookies as $stored) {
if (self::isSecureCookieOverlay($cookie, $stored)) {
return true;
}
}
return false;
}
private static function isSecureCookieOverlay(SetCookie $cookie, SetCookie $stored): bool
{
if ($stored->getName() !== $cookie->getName() || !$stored->getSecure() || $stored->isExpired()) {
return false;
}
$domain = $cookie->getDomain();
$storedDomain = $stored->getDomain();
if ($domain === null || $storedDomain === null) {
return false;
}
if (!HostIdentity::cookieDomainMatches($storedDomain, $domain) && !HostIdentity::cookieDomainMatches($domain, $storedDomain)) {
return false;
}
return $stored->matchesPath($cookie->getPath());
}
/**
* Mirrors SetCookie::fromString()'s splitting because parsed cookies cannot
* distinguish an absent Path attribute from a defaulted path.
*/
private static function hasPathAttribute(string $header): bool
{
$parts = \explode(';', $header);
\array_shift($parts);
foreach ($parts as $part) {
$separator = \strpos($part, '=');
if ($separator !== false && Psr7\Utils::caselessEquals(\trim(\substr($part, 0, $separator), " \t"), 'Path')) {
return true;
}
}
return false;
}
/**
* Computes cookie path following RFC 6265 section 5.1.4
*
@ -298,13 +373,15 @@ class CookieJar implements CookieJarInterface
return \substr($uriPath, 0, $lastSlashPos);
}
public function withCookieHeader(RequestInterface $request): RequestInterface
{
public function withCookieHeader(
#[\SensitiveParameter]
RequestInterface $request
): RequestInterface {
$values = [];
$headerLength = 8;
$uri = $request->getUri();
$scheme = $uri->getScheme();
$host = $uri->getHost();
$host = HostIdentity::canonicalHost($uri->getHost());
$path = $uri->getPath() ?: '/';
foreach ($this->cookies as $cookie) {
@ -354,25 +431,9 @@ class CookieJar implements CookieJarInterface
static function (SetCookie $stored) use ($cookie): bool {
return !($stored->getName() === $cookie->getName()
&& $stored->getPath() === $cookie->getPath()
&& self::cookieDomainsEqual($stored->getDomain(), $cookie->getDomain())
&& $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

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Cookie;
use Psr\Http\Message\RequestInterface;

View file

@ -1,23 +1,37 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Cookie;
use GuzzleHttp\Exception\InvalidArgumentException;
use GuzzleHttp\NonSerializableTrait;
use GuzzleHttp\Psr7\DiagnosticValue;
/**
* Persists non-session cookies using a JSON formatted file
*/
class FileCookieJar extends CookieJar
{
use NonSerializableTrait;
/**
* @var string filename
*/
private $filename;
private string $filename;
/**
* @var bool Control whether to persist session cookies or not.
*/
private $storeSessionCookies;
private bool $storeSessionCookies;
/**
* @var bool Whether to save the cookie jar on destruction.
*
* Disabled by __wakeup() to prevent FileCookieJar from being used as a
* PHP object injection file-write gadget when an application unserializes
* attacker-controlled data.
*/
private bool $autoSave = false;
/**
* Create a new FileCookieJar object
@ -26,7 +40,7 @@ class FileCookieJar extends CookieJar
* @param bool $storeSessionCookies Set to true to store session cookies
* in the cookie jar.
*
* @throws \RuntimeException if the file cannot be found or created
* @throws \RuntimeException if the file cannot be loaded or is invalid
*/
public function __construct(string $cookieFile, bool $storeSessionCookies = false)
{
@ -37,6 +51,8 @@ class FileCookieJar extends CookieJar
if (\file_exists($cookieFile)) {
$this->load($cookieFile);
}
$this->autoSave = true;
}
/**
@ -44,7 +60,24 @@ class FileCookieJar extends CookieJar
*/
public function __destruct()
{
$this->save($this->filename);
if ($this->autoSave) {
$this->save($this->filename);
}
}
/**
* Disable automatic persistence after unserialization.
*/
public function __wakeup(): void
{
$this->autoSave = false;
}
public function __unserialize(array $data): void
{
$this->autoSave = false;
throw new \LogicException(static::class.' should never be unserialized');
}
/**
@ -52,7 +85,8 @@ class FileCookieJar extends CookieJar
*
* @param string $filename File to save
*
* @throws \RuntimeException if the file cannot be found or created
* @throws \RuntimeException if the cookie data cannot be encoded or the
* file cannot be written
*/
public function save(string $filename): void
{
@ -66,56 +100,69 @@ class FileCookieJar extends CookieJar
}
}
$jsonStr = \json_encode($json);
if (\JSON_ERROR_NONE !== \json_last_error()) {
throw new InvalidArgumentException('json_encode error: '.\json_last_error_msg());
try {
$jsonStr = \json_encode($json, \JSON_HEX_TAG | \JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new \RuntimeException('Unable to encode cookie data', 0, $e);
}
/** @var non-empty-string $jsonStr */
if (false === \file_put_contents($filename, $jsonStr, \LOCK_EX)) {
throw new \RuntimeException("Unable to save file {$filename}");
throw new \RuntimeException(\sprintf('Unable to save file %s', DiagnosticValue::escape($filename)));
}
// Best-effort: restrict the cookie file to the owner so persisted
// cookies are not world-readable.
@\chmod($filename, 0600);
}
/**
* Load cookies from a JSON formatted file.
*
* Old cookies are kept unless overwritten by newly loaded ones.
* Cookie records are constructed before any are passed to setCookie().
*
* @param string $filename Cookie file to load.
*
* @throws \RuntimeException if the file cannot be loaded.
* @throws \RuntimeException if the file cannot be loaded or is invalid
*/
public function load(string $filename): void
{
$json = \file_get_contents($filename);
if (false === $json) {
throw new \RuntimeException("Unable to load file {$filename}");
throw new \RuntimeException(\sprintf('Unable to load file %s', DiagnosticValue::escape($filename)));
}
if ($json === '') {
return;
}
$data = \json_decode($json, true);
if (\JSON_ERROR_NONE !== \json_last_error()) {
throw new InvalidArgumentException('json_decode error: '.\json_last_error_msg());
$message = \sprintf('Invalid cookie file: %s', DiagnosticValue::escape($filename));
try {
$data = \json_decode($json, true, 512, \JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new \RuntimeException($message, 0, $e);
}
if (\is_array($data)) {
$cookies = [];
foreach ($data as $cookie) {
if (!\is_array($cookie) || !\array_key_exists('HostOnly', $cookie) || !\is_bool($cookie['HostOnly'])) {
throw new \RuntimeException("Invalid cookie file: {$filename}");
}
// Associative decoding turns JSON objects into arrays, so inspect the root syntax too.
if (!\is_array($data) || \substr($json, \strspn($json, " \t\n\r"), 1) !== '[') {
throw new \RuntimeException($message);
}
$cookies = [];
foreach ($data as $cookie) {
if (!\is_array($cookie) || !\array_key_exists('HostOnly', $cookie) || !\is_bool($cookie['HostOnly'])) {
throw new \RuntimeException($message);
}
try {
$cookies[] = new SetCookie($cookie);
} catch (\InvalidArgumentException $e) {
throw new \RuntimeException($message, 0, $e);
}
}
foreach ($cookies as $cookie) {
$this->setCookie($cookie);
}
} elseif (\is_scalar($data) && !empty($data)) {
throw new \RuntimeException("Invalid cookie file: {$filename}");
foreach ($cookies as $cookie) {
$this->setCookie($cookie);
}
}
}

View file

@ -1,21 +1,36 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Cookie;
use GuzzleHttp\NonSerializableTrait;
/**
* Persists cookies in the client session
*/
class SessionCookieJar extends CookieJar
{
use NonSerializableTrait;
/**
* @var string session key
*/
private $sessionKey;
private string $sessionKey;
/**
* @var bool Control whether to persist session cookies or not.
*/
private $storeSessionCookies;
private bool $storeSessionCookies;
/**
* @var bool Whether to save the cookie jar on destruction.
*
* Disabled by __wakeup() to prevent SessionCookieJar from being used as a
* PHP object injection $_SESSION-write gadget when an application
* unserializes attacker-controlled data.
*/
private bool $autoSave = false;
/**
* Create a new SessionCookieJar object
@ -24,6 +39,8 @@ class SessionCookieJar extends CookieJar
* data in session
* @param bool $storeSessionCookies Set to true to store session cookies
* in the cookie jar.
*
* @throws \RuntimeException if the session contains invalid cookie data
*/
public function __construct(string $sessionKey, bool $storeSessionCookies = false)
{
@ -31,6 +48,7 @@ class SessionCookieJar extends CookieJar
$this->sessionKey = $sessionKey;
$this->storeSessionCookies = $storeSessionCookies;
$this->load();
$this->autoSave = true;
}
/**
@ -38,11 +56,30 @@ class SessionCookieJar extends CookieJar
*/
public function __destruct()
{
$this->save();
if ($this->autoSave) {
$this->save();
}
}
/**
* Save cookies to the client session
* Disable automatic persistence after unserialization.
*/
public function __wakeup(): void
{
$this->autoSave = false;
}
public function __unserialize(array $data): void
{
$this->autoSave = false;
throw new \LogicException(static::class.' should never be unserialized');
}
/**
* Save cookies to the client session.
*
* @throws \RuntimeException if the cookie data cannot be encoded
*/
public function save(): void
{
@ -56,16 +93,19 @@ class SessionCookieJar extends CookieJar
}
}
$json = \json_encode($json);
if (false === $json) {
throw new \RuntimeException('Unable to encode cookie data');
try {
$json = \json_encode($json, \JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new \RuntimeException('Unable to encode cookie data', 0, $e);
}
$_SESSION[$this->sessionKey] = $json;
}
/**
* Load the contents of the client session into the data array
* Load cookies from the client session.
*
* @throws \RuntimeException if the session contains invalid cookie data
*/
protected function load(): void
{
@ -73,27 +113,38 @@ class SessionCookieJar extends CookieJar
return;
}
$message = 'Invalid cookie data';
$json = $_SESSION[$this->sessionKey];
if (!\is_string($json)) {
throw new \RuntimeException('Invalid cookie data');
throw new \RuntimeException($message);
}
$data = \json_decode($json, true);
if (\is_array($data)) {
$cookies = [];
foreach ($data as $cookie) {
if (!\is_array($cookie) || !\array_key_exists('HostOnly', $cookie) || !\is_bool($cookie['HostOnly'])) {
throw new \RuntimeException('Invalid cookie data');
}
try {
$data = \json_decode($json, true, 512, \JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new \RuntimeException($message, 0, $e);
}
// Associative decoding turns JSON objects into arrays, so inspect the root syntax too.
if (!\is_array($data) || \substr($json, \strspn($json, " \t\n\r"), 1) !== '[') {
throw new \RuntimeException($message);
}
$cookies = [];
foreach ($data as $cookie) {
if (!\is_array($cookie) || !\array_key_exists('HostOnly', $cookie) || !\is_bool($cookie['HostOnly'])) {
throw new \RuntimeException($message);
}
try {
$cookies[] = new SetCookie($cookie);
} catch (\InvalidArgumentException $e) {
throw new \RuntimeException($message, 0, $e);
}
}
foreach ($cookies as $cookie) {
$this->setCookie($cookie);
}
} elseif (\is_scalar($data) && \strlen((string) $data)) {
throw new \RuntimeException('Invalid cookie data');
foreach ($cookies as $cookie) {
$this->setCookie($cookie);
}
}
}

View file

@ -1,8 +1,10 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Cookie;
use GuzzleHttp\Handler\HostValidator;
use GuzzleHttp\HostIdentity;
use GuzzleHttp\Psr7;
/**
@ -13,7 +15,7 @@ class SetCookie
/**
* @var array
*/
private static $defaults = [
private const DEFAULTS = [
'Name' => null,
'Value' => null,
'Domain' => null,
@ -28,25 +30,27 @@ class SetCookie
/**
* @var array Cookie data
*/
private $data;
private array $data;
/**
* @var bool Whether this cookie was set without a Domain attribute
* @var bool Whether this cookie was set without a Domain attribute.
*/
private $hostOnly = false;
private bool $hostOnly = false;
/**
* Create a new SetCookie object from a string.
*
* @param string $cookie Set-Cookie header string
*/
public static function fromString(string $cookie): self
{
public static function fromString(
#[\SensitiveParameter]
string $cookie
): self {
// Create the default return array
$data = self::$defaults;
$data = self::DEFAULTS;
// Explode the cookie string using a series of semicolons
$pieces = \array_filter(\array_map(static function (string $piece): string {
return \trim($piece, " \n\r\t\0\x0B");
return \trim($piece, " \t");
}, \explode(';', $cookie)));
// The name of the cookie (first kvp) must exist and include an equal sign.
if (!isset($pieces[0]) || \strpos($pieces[0], '=') === false) {
@ -56,9 +60,9 @@ class SetCookie
// Add the cookie pieces into the parsed data array
foreach ($pieces as $part) {
$cookieParts = \explode('=', $part, 2);
$key = \trim($cookieParts[0], " \n\r\t\0\x0B");
$key = \trim($cookieParts[0], " \t");
$value = isset($cookieParts[1])
? \trim($cookieParts[1], " \n\r\t\0\x0B")
? \trim($cookieParts[1], " \t")
: true;
// Only check for non-cookies when cookies have been found
@ -66,17 +70,20 @@ class SetCookie
$data['Name'] = $key;
$data['Value'] = $value;
} else {
foreach (\array_keys(self::$defaults) as $search) {
foreach (\array_keys(self::DEFAULTS) as $search) {
if (Psr7\Utils::caselessEquals($search, $key)) {
if ($search === 'Max-Age') {
if (is_numeric($value)) {
$data[$search] = (int) $value;
if (\is_string($value) && \preg_match('/^[+-]?[0-9]+$/D', $value) === 1) {
$maxAge = self::parseNumericInteger($value);
if ($maxAge !== null) {
$data[$search] = $maxAge;
}
}
} elseif ($search === 'Secure' || $search === 'Discard' || $search === 'HttpOnly') {
if ($value) {
$data[$search] = true;
}
} else {
} elseif (\is_string($value)) {
$data[$search] = $value;
}
continue 2;
@ -95,14 +102,14 @@ class SetCookie
/**
* @param array $data Array of cookie data provided by a Cookie parser
*/
public function __construct(array $data = [])
{
$this->data = self::$defaults;
public function __construct(
#[\SensitiveParameter]
array $data = []
) {
$this->data = self::DEFAULTS;
self::validateFieldTypes($data);
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']);
}
@ -144,33 +151,18 @@ class SetCookie
}
// Set the remaining values that don't have extra validation logic
foreach (array_diff(array_keys($data), array_keys(self::$defaults)) as $key) {
foreach (array_diff(array_keys($data), array_keys(self::DEFAULTS)) as $key) {
$this->data[$key] = $data[$key];
}
// Extract the Expires value and turn it into a UNIX timestamp if needed
$maxAge = $this->getMaxAge();
if (!$this->getExpires() && $maxAge !== null) {
// Calculate the Expires date
if ($maxAge !== null) {
$this->setExpires(self::maxAgeToExpires($maxAge, \time()));
} elseif (null !== ($expires = $this->getExpires()) && !\is_numeric($expires)) {
$this->setExpires($expires);
}
}
private static function maxAgeToExpires(int $maxAge, int $now): int
{
if ($maxAge <= 0) {
return $now - 1;
}
if ($maxAge > \PHP_INT_MAX - $now) {
return \PHP_INT_MAX;
}
return $now + $maxAge;
}
public function __toString()
public function __toString(): string
{
$str = $this->data['Name'].'='.($this->data['Value'] ?? '').'; ';
foreach ($this->data as $k => $v) {
@ -201,10 +193,8 @@ class SetCookie
/**
* Get the cookie name.
*
* @return string
*/
public function getName()
public function getName(): ?string
{
return $this->data['Name'];
}
@ -214,21 +204,15 @@ class SetCookie
*
* @param string $name Cookie name
*/
public function setName($name): void
public function setName(string $name): void
{
if (!is_string($name)) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Name'] = (string) $name;
$this->data['Name'] = $name;
}
/**
* Get the cookie value.
*
* @return string|null
*/
public function getValue()
public function getValue(): ?string
{
return $this->data['Value'];
}
@ -238,21 +222,15 @@ class SetCookie
*
* @param string $value Cookie value
*/
public function setValue($value): void
public function setValue(string $value): void
{
if (!is_string($value)) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Value'] = (string) $value;
$this->data['Value'] = $value;
}
/**
* Get the domain.
*
* @return string|null
*/
public function getDomain()
public function getDomain(): ?string
{
return $this->data['Domain'];
}
@ -260,23 +238,17 @@ class SetCookie
/**
* Set the domain of the cookie.
*
* @param string|null $domain
* @param string|null $domain Domain of the cookie
*/
public function setDomain($domain): void
public function setDomain(?string $domain): void
{
if (!is_string($domain) && null !== $domain) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Domain'] = null === $domain ? null : (string) $domain;
$this->data['Domain'] = null === $domain ? null : self::normalizeDomain($domain);
}
/**
* Get whether this cookie is scoped to the origin host only.
*
* @return bool
*/
public function getHostOnly()
public function getHostOnly(): bool
{
return $this->hostOnly;
}
@ -293,10 +265,8 @@ class SetCookie
/**
* Get the path.
*
* @return string
*/
public function getPath()
public function getPath(): string
{
return $this->data['Path'];
}
@ -306,21 +276,15 @@ class SetCookie
*
* @param string $path Path of the cookie
*/
public function setPath($path): void
public function setPath(string $path): void
{
if (!is_string($path)) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a string to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Path'] = (string) $path;
$this->data['Path'] = $path;
}
/**
* Maximum lifetime of the cookie in seconds.
*
* @return int|null
*/
public function getMaxAge()
public function getMaxAge(): ?int
{
return null === $this->data['Max-Age'] ? null : (int) $this->data['Max-Age'];
}
@ -330,21 +294,15 @@ class SetCookie
*
* @param int|null $maxAge Max age of the cookie in seconds
*/
public function setMaxAge($maxAge): void
public function setMaxAge(?int $maxAge): void
{
if (!is_int($maxAge) && null !== $maxAge) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an int or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Max-Age'] = $maxAge === null ? null : (int) $maxAge;
$this->data['Max-Age'] = $maxAge;
}
/**
* The UNIX timestamp when the cookie Expires.
*
* @return string|int|null
*/
public function getExpires()
public function getExpires(): ?int
{
return $this->data['Expires'];
}
@ -357,26 +315,36 @@ class SetCookie
public function setExpires($timestamp): void
{
if (!is_int($timestamp) && !is_string($timestamp) && null !== $timestamp) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an int, string or null to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
// TODO: Move this to the parameter definition in 9.0.
throw new \TypeError(__METHOD__.'(): Argument #1 ($timestamp) must be of type int|string|null');
}
if (null === $timestamp) {
if ($timestamp === null) {
$this->data['Expires'] = null;
} elseif (\is_numeric($timestamp)) {
$this->data['Expires'] = (int) $timestamp;
} else {
// Store unparseable dates as session cookies, not as expired cookies.
$expires = \strtotime((string) $timestamp);
$this->data['Expires'] = $expires === false ? null : $expires;
return;
}
if (\is_string($timestamp)) {
if (\is_numeric($timestamp)) {
$this->data['Expires'] = self::parseNumericInteger($timestamp);
return;
}
} elseif (\is_int($timestamp)) {
$this->data['Expires'] = $timestamp;
return;
}
$expires = \strtotime($timestamp);
$this->data['Expires'] = $expires === false ? null : $expires;
}
/**
* Get whether or not this is a secure cookie.
*
* @return bool
*/
public function getSecure()
public function getSecure(): bool
{
return $this->data['Secure'];
}
@ -386,21 +354,15 @@ class SetCookie
*
* @param bool $secure Set to true or false if secure
*/
public function setSecure($secure): void
public function setSecure(bool $secure): void
{
if (!is_bool($secure)) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Secure'] = (bool) $secure;
$this->data['Secure'] = $secure;
}
/**
* Get whether or not this is a session cookie.
*
* @return bool|null
*/
public function getDiscard()
public function getDiscard(): bool
{
return $this->data['Discard'];
}
@ -410,21 +372,15 @@ class SetCookie
*
* @param bool $discard Set to true or false if this is a session cookie
*/
public function setDiscard($discard): void
public function setDiscard(bool $discard): void
{
if (!is_bool($discard)) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['Discard'] = (bool) $discard;
$this->data['Discard'] = $discard;
}
/**
* Get whether or not this is an HTTP only cookie.
*
* @return bool
*/
public function getHttpOnly()
public function getHttpOnly(): bool
{
return $this->data['HttpOnly'];
}
@ -434,13 +390,9 @@ class SetCookie
*
* @param bool $httpOnly Set to true or false if this is HTTP only
*/
public function setHttpOnly($httpOnly): void
public function setHttpOnly(bool $httpOnly): void
{
if (!is_bool($httpOnly)) {
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing a bool to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
}
$this->data['HttpOnly'] = (bool) $httpOnly;
$this->data['HttpOnly'] = $httpOnly;
}
/**
@ -489,80 +441,15 @@ class SetCookie
public function matchesDomain(string $domain): bool
{
$cookieDomain = $this->getDomain();
if (null === $cookieDomain) {
return !$this->getHostOnly();
if (null === $cookieDomain || $cookieDomain === '') {
return false;
}
if ($this->getHostOnly()) {
return Psr7\Utils::asciiToLower($domain) === Psr7\Utils::asciiToLower($cookieDomain);
return HostIdentity::canonicalCookieDomain($domain) === HostIdentity::canonicalCookieDomain($cookieDomain);
}
// Remove the leading '.' as per spec in RFC 6265.
// https://datatracker.ietf.org/doc/html/rfc6265#section-5.2.3
$cookieDomain = Psr7\Utils::asciiToLower($cookieDomain);
if ($cookieDomain !== '' && $cookieDomain[0] === '.') {
/** @var string */
$cookieDomain = \substr($cookieDomain, 1);
}
if ('' === $cookieDomain) {
return false;
}
$domain = Psr7\Utils::asciiToLower($domain);
if ($domain === $cookieDomain) {
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)) {
return false;
}
// Matching the subdomain according to RFC 6265.
// https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.3
if (\filter_var($domain, \FILTER_VALIDATE_IP)) {
return false;
}
return (bool) \preg_match('/\.'.\preg_quote($cookieDomain, '/').'$/D', $domain);
}
private static function isIpAddressOrNumericHost(string $host): bool
{
// Strip one root dot before detection so trailing-dot numeric hosts
// still cannot be matched by subdomains.
if ($host !== '' && \str_ends_with($host, '.')) {
$host = \substr($host, 0, -1);
}
if (\str_starts_with($host, '[') && \str_ends_with($host, ']')) {
$host = \substr($host, 1, -1);
}
if (\filter_var($host, \FILTER_VALIDATE_IP) !== false) {
return true;
}
// Public DNS names do not have an all-numeric rightmost label; treat
// those private/internal hosts as exact-match-only too.
$labels = \explode('.', $host);
$last = (string) \end($labels);
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, '.'));
return HostIdentity::cookieDomainMatches($domain, $cookieDomain);
}
/**
@ -576,12 +463,12 @@ class SetCookie
/**
* Check if the cookie is valid according to RFC 6265.
*
* @return bool|string Returns true if valid or an error message if invalid
* @return string|true Returns true if valid or an error message if invalid
*/
public function validate()
{
$name = $this->getName();
if ($name === '') {
if ($name === null || $name === '') {
return 'The cookie name must not be empty';
}
@ -602,10 +489,108 @@ class SetCookie
// Domains must not be empty, but may be omitted. "0" is not a valid
// internet domain, but may be used as server name in a private network.
$domain = $this->getDomain();
if ($domain === '' || (null !== $domain && '' === \ltrim(\trim($domain, " \n\r\t\0\x0B"), '.'))) {
if ($domain === '' || ($domain !== null && \ltrim(\trim($domain, " \n\r\t\0\x0B"), '.') === '')) {
return 'The cookie domain must not be empty';
}
if ($this->getHostOnly() && $domain === null) {
return 'Host-only cookies must have a domain';
}
return true;
}
private static function normalizeDomain(string $domain): string
{
$domain = Psr7\Utils::asciiToLower($domain);
// Treat trailing-dot domains as host-only, but keep pure-dot domains invalid.
if ($domain !== '' && \substr($domain, -1) === '.' && \trim($domain, '.') !== '') {
return '';
}
if ($domain !== '' && $domain !== '.' && $domain[0] === '.') {
$domain = \substr_replace($domain, '', 0, 1);
}
return HostIdentity::canonicalCookieDomain($domain);
}
private static function maxAgeToExpires(int $maxAge, int $now): int
{
if ($maxAge <= 0) {
return $now - 1;
}
// Clamp absurd Max-Age values so addition cannot promote to float
if ($maxAge > \PHP_INT_MAX - $now) {
return \PHP_INT_MAX;
}
return $now + $maxAge;
}
private static function parseNumericInteger(string $value): ?int
{
if (!\is_numeric($value)) {
return null;
}
if (\preg_match('/^[+-]?[0-9]+$/D', $value) === 1) {
$negative = $value[0] === '-';
$digits = \ltrim($value, '+-');
$digits = \ltrim($digits, '0');
$digits = $digits === '' ? '0' : $digits;
$limit = $negative ? \substr((string) \PHP_INT_MIN, 1) : (string) \PHP_INT_MAX;
if (\strlen($digits) > \strlen($limit) || (\strlen($digits) === \strlen($limit) && \strcmp($digits, $limit) > 0)) {
return null;
}
return (int) ($negative ? '-'.$digits : $digits);
}
$number = (float) $value;
if (!\is_finite($number) || $number < \PHP_INT_MIN || $number > \PHP_INT_MAX) {
return null;
}
if (\PHP_INT_SIZE === 8 && ($number <= (float) \PHP_INT_MIN || $number >= (float) \PHP_INT_MAX)) {
return null;
}
return (int) $number;
}
/**
* @param mixed[] $data
*/
private static function validateFieldTypes(
#[\SensitiveParameter]
array $data
): void {
foreach (['Name', 'Value', 'Domain', 'Path'] as $field) {
if (isset($data[$field]) && !\is_string($data[$field])) {
throw new \InvalidArgumentException(\sprintf('Cookie field "%s" must be a string', $field));
}
}
if (isset($data['Max-Age']) && !\is_int($data['Max-Age'])) {
throw new \InvalidArgumentException('Cookie field "Max-Age" must be an integer');
}
if (isset($data['Expires']) && !\is_int($data['Expires']) && !\is_string($data['Expires'])) {
throw new \InvalidArgumentException('Cookie field "Expires" must be an integer or string');
}
foreach (['Secure', 'Discard', 'HttpOnly'] as $field) {
if (isset($data[$field]) && !\is_bool($data[$field])) {
throw new \InvalidArgumentException(\sprintf('Cookie field "%s" must be a boolean', $field));
}
}
if (\array_key_exists('HostOnly', $data) && !\is_bool($data['HostOnly'])) {
throw new \InvalidArgumentException('Cookie field "HostOnly" must be a boolean');
}
}
}

Some files were not shown because too many files have changed in this diff Show more