Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,15 @@ and the README's [Hypervel Fork](README.md#hypervel-fork) section.
Please refer to [UPGRADING](UPGRADING.md) guide for upgrading to a major version.


## 8.3.1 - 2026-10-25

### Fixed

- Fix `CookieJar` storing already expired cookies instead of removing the stored cookie
- Fix `CookieJar` ignoring a same-value cookie that changes its expiry or its `Discard`, `Secure`, or `HttpOnly` flag
- Fix `SetCookie` renewing the lifetime of `Max-Age` cookies rebuilt from an array, so persisted cookies never expired


## 8.3.0 - 2026-10-18

### Changed
Expand Down
10 changes: 6 additions & 4 deletions UPGRADING.md
Original file line number Diff line number Diff line change
Expand Up @@ -1251,10 +1251,12 @@ Cookies parsed from normal `Set-Cookie` headers continue to be normalized by

#### SetCookie Max-Age Precedence

`SetCookie` now follows RFC cookie precedence when both `Max-Age` and `Expires`
are present. A valid `Max-Age` value controls the effective expiration time,
including `Max-Age=0` expiring the cookie immediately, even when `Expires` is a
future date.
`SetCookie::fromString()` now follows RFC cookie precedence when a `Set-Cookie`
header carries both `Max-Age` and `Expires`. A valid `Max-Age` value controls
the effective expiration time, including `Max-Age=0` expiring the cookie
immediately, even when `Expires` is a future date. Cookies built from an array
keep a supplied `Expires`, as in Guzzle 7, so persisted cookies do not restart
their lifetime when a jar is loaded.

#### Cookie Max-Age Parsing

Expand Down
25 changes: 8 additions & 17 deletions src/Cookie/CookieJar.php
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ public function setCookie(
}

$maxAge = $cookie->getMaxAge();
if ($maxAge !== null && $maxAge <= 0) {
if (($maxAge !== null && $maxAge <= 0) || $cookie->isExpired()) {
if ($cookie->getDomain() !== null) {
$this->removeCookie($cookie);
}
Expand All @@ -207,22 +207,13 @@ public function setCookie(
continue;
}

// The previously set cookie is a discard cookie and this one is
// not so allow the new cookie to be set
if (!$cookie->getDiscard() && $c->getDiscard()) {
unset($this->cookies[$i]);
continue;
}

// If the new cookie's expiration is further into the future, then
// replace the old cookie
if ($cookie->getExpires() > $c->getExpires()) {
unset($this->cookies[$i]);
continue;
}

// If the value has changed, we better change it
if ($cookie->getValue() !== $c->getValue()) {
// Replace the old cookie when its value, expiry or flags changed
if ($cookie->getValue() !== $c->getValue()
|| $cookie->getExpires() !== $c->getExpires()
|| $cookie->getDiscard() !== $c->getDiscard()
|| $cookie->getSecure() !== $c->getSecure()
|| $cookie->getHttpOnly() !== $c->getHttpOnly()
) {
unset($this->cookies[$i]);
continue;
}
Expand Down
9 changes: 7 additions & 2 deletions src/Cookie/SetCookie.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,11 @@ public static function fromString(
}
}

// Max-Age takes precedence over Expires, RFC 6265 section 5.3
if ($data['Max-Age'] !== null) {
$data['Expires'] = null;
}

return new self($data);
}

Expand Down Expand Up @@ -155,9 +160,9 @@ public function __construct(
$this->data[$key] = $data[$key];
}

// Extract the Expires value and turn it into a UNIX timestamp if needed
// Derive Expires from Max-Age unless the data already carries one
$maxAge = $this->getMaxAge();
if ($maxAge !== null) {
if ($maxAge !== null && $this->getExpires() === null) {
$this->setExpires(self::maxAgeToExpires($maxAge, \time()));
}
}
Expand Down
85 changes: 83 additions & 2 deletions tests/Cookie/CookieJarTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ protected function getTestCookies(): array
{
return [
new SetCookie(['Name' => 'foo', 'Value' => 'bar', 'Domain' => 'foo.com', 'Path' => '/', 'Discard' => true]),
new SetCookie(['Name' => 'test', 'Value' => '123', 'Domain' => 'baz.com', 'Path' => '/foo', 'Expires' => 2]),
new SetCookie(['Name' => 'test', 'Value' => '123', 'Domain' => 'baz.com', 'Path' => '/foo', 'Expires' => 2139722880]),
new SetCookie(['Name' => 'you', 'Value' => '123', 'Domain' => 'bar.com', 'Path' => '/boo', 'Expires' => \time() + 1000]),
];
}
Expand Down Expand Up @@ -592,6 +592,33 @@ public function testOverwritesCookiesThatHaveChanged(): void
self::assertSame('zoo', $c[0]->getValue());
}

/**
* @dataProvider changedAttributeProvider
*
* @param int|bool|null $expected
*/
public function testReplacesCookieWhenAttributeChanges(string $header, string $attribute, $expected): void
{
$request = new Request('GET', 'https://example.com/');
$this->jar->extractCookies($request, new Response(200, ['Set-Cookie' => 'sid=abc; Expires=Wed, 21 Oct 2037 07:28:00 GMT; Path=/']));

$this->jar->extractCookies($request, new Response(200, ['Set-Cookie' => $header]));

self::assertCount(1, $this->jar);
self::assertSame($expected, $this->jar->toArray()[0][$attribute]);
}

public static function changedAttributeProvider(): array
{
return [
'earlier expiry' => ['sid=abc; Expires=Tue, 21 Oct 2036 07:28:00 GMT; Path=/', 'Expires', 2108186880],
'session cookie' => ['sid=abc; Path=/', 'Expires', null],
'discard' => ['sid=abc; Expires=Wed, 21 Oct 2037 07:28:00 GMT; Path=/; Discard', 'Discard', true],
'secure' => ['sid=abc; Expires=Wed, 21 Oct 2037 07:28:00 GMT; Path=/; Secure', 'Secure', true],
'http only' => ['sid=abc; Expires=Wed, 21 Oct 2037 07:28:00 GMT; Path=/; HttpOnly', 'HttpOnly', true],
];
}

public function testDistinctNumericStringCookieNamesCoexist(): void
{
$this->jar->setCookie(new SetCookie([
Expand Down Expand Up @@ -661,7 +688,7 @@ public function testNullValueCookieStillDeletesMatchingCookie(): void
public function testAddsCookiesFromResponseWithRequest(): void
{
$response = new Response(200, [
'Set-Cookie' => 'fpc=d=.Hm.yh4.1XmJWjJfs4orLQzKzPImxklQoxXSHOZATHUSEFciRueW_7704iYUtsXNEXq0M92Px2glMdWypmJ7HIQl6XIUvrZimWjQ3vIdeuRbI.FNQMAfcxu_XN1zSx7l.AcPdKL6guHc2V7hIQFhnjRW0rxm2oHY1P4bGQxFNz7f.tHm12ZD3DbdMDiDy7TBXsuP4DM-&v=2; expires=Fri, 02-Mar-2019 02:17:40 GMT;',
'Set-Cookie' => 'fpc=d=.Hm.yh4.1XmJWjJfs4orLQzKzPImxklQoxXSHOZATHUSEFciRueW_7704iYUtsXNEXq0M92Px2glMdWypmJ7HIQl6XIUvrZimWjQ3vIdeuRbI.FNQMAfcxu_XN1zSx7l.AcPdKL6guHc2V7hIQFhnjRW0rxm2oHY1P4bGQxFNz7f.tHm12ZD3DbdMDiDy7TBXsuP4DM-&v=2; expires=Wed, 21-Oct-2037 07:28:00 GMT;',
]);
$request = new Request('GET', 'http://www.example.com');
$this->jar->extractCookies($request, $response);
Expand Down Expand Up @@ -980,6 +1007,60 @@ public function testMaxAgeZeroCookieFromResponseOverridesFutureExpires(): void
self::assertCount(0, $this->jar);
}

public function testMaxAgeZeroSetAfterConstructionRemovesExistingCookie(): void
{
$data = ['Name' => 'sid', 'Value' => 'abc', 'Domain' => 'example.com', 'Path' => '/', 'Expires' => 2139722880];
self::assertTrue($this->jar->setCookie(new SetCookie($data)));

$deletion = new SetCookie($data);
$deletion->setMaxAge(0);

self::assertFalse($this->jar->setCookie($deletion));
self::assertCount(0, $this->jar);
}

public function testDoesNotStoreExpiredCookieFromResponse(): void
{
$this->jar->extractCookies(
new Request('GET', 'https://example.com/'),
new Response(200, ['Set-Cookie' => 'sid=abc; Expires=Thu, 01 Jan 1970 00:00:01 GMT; Path=/'])
);

self::assertCount(0, $this->jar);
}

/**
* @dataProvider expiredCookieProvider
*/
public function testExpiredCookieFromResponseRemovesExistingCookie(string $header): void
{
$request = new Request('GET', 'https://example.com/');
$this->jar->extractCookies($request, new Response(200, ['Set-Cookie' => 'sid=abc; Expires=Wed, 21 Oct 2037 07:28:00 GMT; Path=/']));
self::assertCount(1, $this->jar);

$this->jar->extractCookies($request, new Response(200, ['Set-Cookie' => $header]));

self::assertCount(0, $this->jar);
self::assertFalse($this->jar->withCookieHeader($request)->hasHeader('Cookie'));
}

public static function expiredCookieProvider(): array
{
return [
'same value' => ['sid=abc; Expires=Thu, 01 Jan 1970 00:00:01 GMT; Path=/'],
'changed value' => ['sid=deleted; Expires=Thu, 01 Jan 1970 00:00:01 GMT; Path=/'],
];
}

public function testConstructorDropsExpiredCookies(): void
{
$jar = new CookieJar(false, [
['Name' => 'sid', 'Value' => 'abc', 'Domain' => 'example.com', 'Path' => '/', 'Expires' => 1],
]);

self::assertCount(0, $jar);
}

public function testDoesNotSendHostOnlyCookieToSubdomain(): void
{
$this->jar->extractCookies(
Expand Down
21 changes: 21 additions & 0 deletions tests/Cookie/FileCookieJarTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use GuzzleHttp\Cookie\FileCookieJar;
use GuzzleHttp\Cookie\SetCookie;
use GuzzleHttp\Psr7\Request;
use PHPUnit\Framework\TestCase;

/**
Expand Down Expand Up @@ -112,6 +113,26 @@ public function testLoadDoesNotChangeJarWhenLaterRecordIsInvalid(): void
}
}

public function testLoadDoesNotExtendMaxAgeCookies(): void
{
\file_put_contents($this->file, \json_encode([[
'Name' => 'sid',
'Value' => 'abc',
'Domain' => 'example.com',
'Path' => '/',
'Max-Age' => 3600,
'Expires' => 1,
'Secure' => false,
'Discard' => false,
'HttpOnly' => false,
'HostOnly' => true,
]]));

$jar = new FileCookieJar($this->file);

self::assertFalse($jar->withCookieHeader(new Request('GET', 'https://example.com/'))->hasHeader('Cookie'));
}

public function testRejectsCookieDataThatCannotBeEncoded(): void
{
$jar = new FileCookieJar($this->file, true);
Expand Down
35 changes: 22 additions & 13 deletions tests/Cookie/SetCookieTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,24 @@ public function testAddsExpiresBasedOnMaxAge(): void
self::assertLessThanOrEqual($after + 100, $expires);
}

public function testKeepsExpiresFromDataWithMaxAge(): void
{
$cookie = new SetCookie(['Max-Age' => 60, 'Expires' => 1]);

self::assertSame(1, $cookie->getExpires());
self::assertTrue($cookie->isExpired());
}

public function testMaxAgeOverridesExpiresInSetCookieString(): void
{
$before = \time();
$cookie = SetCookie::fromString('sid=abc; Expires=Wed, 21 Oct 2037 07:28:00 GMT; Max-Age=60');
$after = \time();

self::assertGreaterThanOrEqual($before + 60, $cookie->getExpires());
self::assertLessThanOrEqual($after + 60, $cookie->getExpires());
}

public function testMaxAgeZeroExpiresCookie(): void
{
$cookie = SetCookie::fromString('sid=abc; Max-Age=0');
Expand Down Expand Up @@ -119,13 +137,13 @@ public function testFromStringIgnoresValuelessTypedAttributes(): void

public function testHoldsValues(): void
{
$before = \time();
$t = \time();
$data = [
'Name' => 'foo',
'Value' => 'baz',
'Path' => '/bar',
'Domain' => 'baz.com',
'Expires' => $before,
'Expires' => $t,
'Max-Age' => 100,
'Secure' => true,
'Discard' => true,
Expand All @@ -135,22 +153,13 @@ public function testHoldsValues(): void
];

$cookie = new SetCookie($data);
$after = \time();
$expires = $cookie->getExpires();

self::assertIsInt($expires);
self::assertGreaterThanOrEqual($before + 100, $expires);
self::assertLessThanOrEqual($after + 100, $expires);

$expected = $data;
$expected['Expires'] = $expires;
self::assertEquals($expected, $cookie->toArray());
self::assertEquals($data, $cookie->toArray());

self::assertSame('foo', $cookie->getName());
self::assertSame('baz', $cookie->getValue());
self::assertSame('baz.com', $cookie->getDomain());
self::assertSame('/bar', $cookie->getPath());
self::assertSame($expires, $cookie->getExpires());
self::assertSame($t, $cookie->getExpires());
self::assertSame(100, $cookie->getMaxAge());
self::assertTrue($cookie->getSecure());
self::assertTrue($cookie->getDiscard());
Expand Down
8 changes: 5 additions & 3 deletions tests/Handler/CurlMultiHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -324,16 +324,18 @@ public function testDelayedRequestAttachesBeforeSiblingSelectTimeoutWhenTicking(

$delayed = $handler(new Request('GET', Server::$url), ['delay' => 100]);

// Stop at the attach: the tick that completes the delayed transfer may
// still select for the sibling's full timeout.
$start = \microtime(true);
$deadline = $start + 10;
while (P\State::isPending($delayed) && \microtime(true) < $deadline) {
while (self::readMultiProperty($handler, 'delays') !== [] && \microtime(true) < $deadline) {
$handler->tick();
}
$elapsed = \microtime(true) - $start;

self::assertTrue(P\State::isFulfilled($delayed));
self::assertSame(200, $delayed->wait()->getStatusCode());
self::assertSame([], self::readMultiProperty($handler, 'delays'), 'Timed out waiting for the delayed request to attach.');
self::assertLessThan(2.5, $elapsed, 'The delayed request waited for an unrelated transfer before attaching.');
self::assertSame(200, $delayed->wait()->getStatusCode());
self::assertTrue(P\State::isPending($sibling));
} finally {
$sibling->cancel();
Expand Down