Skip to content

Commit f892103

Browse files
committed
fix(Session): send SameSite attribute in BaseHandler::destroyCookie()
1 parent c431aa1 commit f892103

3 files changed

Lines changed: 250 additions & 4 deletions

File tree

‎docs/changelogs/v4.7.7.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ Release Date: Unreleased
1919
- **CORS:** Fixed a bug where `Cors::hasResponseHeaders()` matched header substrings via `str_contains()`, causing false positives when existing exposed headers shared a prefix with configured exposed headers.
2020
- **HTTP:** Fixed a bug where `UploadedFile::move()` and `UploadedFile::store()` on Windows could store a file under a different name than `getName()` reported, or write its contents to an NTFS alternate data stream. Filenames ending in a period or space or containing a colon are now rejected, including explicitly supplied names.
2121
- **Security:** Fixed a bug where `Security::__construct()` threw a `TypeError` when the CSRF cookie was an array, causing an HTTP 500 response for affected requests.
22+
- **Session:** Fixed a bug where `BaseHandler::destroyCookie()` did not send the `SameSite` attribute in the `Set-Cookie` header, which could prevent browsers from properly clearing the session cookie.
2223
- **Worker Mode:** Fixed a bug where every request that ended with an uncaught exception, including a `404 Page Not Found` without a 404 override, called `exit()` in the exception handler. This ended the worker script, so FrankenPHP booted a new one, and the worker loop skipped its cleanup after the request. The exception handler now returns to the worker loop.
2324

2425
See the repo's [CHANGELOG.md](https://github.com/codeigniter4/CodeIgniter4/blob/develop/CHANGELOG.md) for a complete list of bugs fixed.

‎system/Session/Handlers/BaseHandler.php‎

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
namespace CodeIgniter\Session\Handlers;
1515

16+
use CodeIgniter\Cookie\Cookie;
1617
use Config\Cookie as CookieConfig;
1718
use Config\Session as SessionConfig;
1819
use Psr\Log\LoggerAwareTrait;
@@ -70,6 +71,13 @@ abstract class BaseHandler implements SessionHandlerInterface
7071
*/
7172
protected $cookieSecure = false;
7273

74+
/**
75+
* Cookie SameSite setting.
76+
*
77+
* @var ''|'Lax'|'None'|'Strict'
78+
*/
79+
protected string $cookieSameSite = '';
80+
7381
/**
7482
* Cookie name to use.
7583
*
@@ -116,9 +124,10 @@ public function __construct(SessionConfig $config, string $ipAddress)
116124
$cookie = config(CookieConfig::class);
117125

118126
// Session cookies have no prefix.
119-
$this->cookieDomain = $cookie->domain;
120-
$this->cookiePath = $cookie->path;
121-
$this->cookieSecure = $cookie->secure;
127+
$this->cookieDomain = $cookie->domain;
128+
$this->cookiePath = $cookie->path;
129+
$this->cookieSecure = $cookie->secure;
130+
$this->cookieSameSite = $cookie->samesite;
122131

123132
$this->ipAddress = $ipAddress;
124133
}
@@ -129,10 +138,21 @@ public function __construct(SessionConfig $config, string $ipAddress)
129138
*/
130139
protected function destroyCookie(): bool
131140
{
141+
$samesite = $this->cookieSameSite === ''
142+
? Cookie::SAMESITE_LAX
143+
: ucfirst(strtolower($this->cookieSameSite));
144+
132145
return setcookie(
133146
$this->cookieName,
134147
'',
135-
['expires' => 1, 'path' => $this->cookiePath, 'domain' => $this->cookieDomain, 'secure' => $this->cookieSecure, 'httponly' => true],
148+
[
149+
'expires' => 1,
150+
'path' => $this->cookiePath,
151+
'domain' => $this->cookieDomain,
152+
'secure' => $this->cookieSecure,
153+
'httponly' => true,
154+
'samesite' => $samesite,
155+
],
136156
);
137157
}
138158

Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
namespace CodeIgniter\Session\Handlers;
15+
16+
use CodeIgniter\Config\Factories;
17+
use CodeIgniter\Test\CIUnitTestCase;
18+
use Config\Cookie as CookieConfig;
19+
use Config\Session as SessionConfig;
20+
use PHPUnit\Framework\Attributes\DataProvider;
21+
use PHPUnit\Framework\Attributes\Group;
22+
23+
/**
24+
* Mock setcookie function in CodeIgniter\Session\Handlers namespace.
25+
*
26+
* The mock is only active while BaseHandlerTest is running, so that calls
27+
* from other handler tests are delegated to the native function.
28+
*
29+
* @param array<string, mixed> $options
30+
*/
31+
function setcookie(string $name, string $value = '', array $options = []): bool
32+
{
33+
if (! BaseHandlerTest::$interceptSetCookie) {
34+
return \setcookie($name, $value, $options);
35+
}
36+
37+
BaseHandlerTest::$lastSetCookieArgs = [
38+
'name' => $name,
39+
'value' => $value,
40+
'options' => $options,
41+
];
42+
43+
return true;
44+
}
45+
46+
/**
47+
* @internal
48+
*/
49+
#[Group('Others')]
50+
final class BaseHandlerTest extends CIUnitTestCase
51+
{
52+
/**
53+
* Whether the setcookie() mock in this namespace should intercept calls.
54+
*/
55+
public static bool $interceptSetCookie = false;
56+
57+
/**
58+
* @var array{name: string, value: string, options: array<string, mixed>}|null
59+
*/
60+
public static ?array $lastSetCookieArgs = null;
61+
62+
protected function setUp(): void
63+
{
64+
parent::setUp();
65+
66+
self::$interceptSetCookie = true;
67+
self::$lastSetCookieArgs = null;
68+
Factories::reset('config');
69+
}
70+
71+
protected function tearDown(): void
72+
{
73+
// Reset before parent::tearDown() so a failure in the parent does not
74+
// leave the setcookie() mock intercepting calls in later tests.
75+
self::$interceptSetCookie = false;
76+
self::$lastSetCookieArgs = null;
77+
78+
parent::tearDown();
79+
80+
Factories::reset('config');
81+
}
82+
83+
private function createHandler(?CookieConfig $cookieConfig = null): BaseHandler
84+
{
85+
if ($cookieConfig instanceof CookieConfig) {
86+
Factories::injectMock('config', CookieConfig::class, $cookieConfig);
87+
}
88+
89+
$sessionConfig = new SessionConfig();
90+
$sessionConfig->cookieName = 'ci_session';
91+
92+
return new class ($sessionConfig, '127.0.0.1') extends BaseHandler {
93+
public function open(string $path, string $name): bool
94+
{
95+
return true;
96+
}
97+
98+
public function close(): bool
99+
{
100+
return true;
101+
}
102+
103+
public function read(string $id): string
104+
{
105+
return '';
106+
}
107+
108+
public function write(string $id, string $data): bool
109+
{
110+
return true;
111+
}
112+
113+
public function destroy(string $id): bool
114+
{
115+
return $this->destroyCookie();
116+
}
117+
118+
public function gc(int $maxLifetime): int
119+
{
120+
return 1;
121+
}
122+
};
123+
}
124+
125+
public function testConstructorInitializesCookieSameSiteFromConfig(): void
126+
{
127+
$cookieConfig = new CookieConfig();
128+
$cookieConfig->samesite = 'Strict';
129+
130+
$handler = $this->createHandler($cookieConfig);
131+
132+
$this->assertSame('Strict', $this->getPrivateProperty($handler, 'cookieSameSite'));
133+
}
134+
135+
public function testConstructorDefaultsToCookieConfigSameSite(): void
136+
{
137+
$handler = $this->createHandler();
138+
139+
$this->assertSame('Lax', $this->getPrivateProperty($handler, 'cookieSameSite'));
140+
}
141+
142+
public function testDestroyCookiePassesSameSiteInOptions(): void
143+
{
144+
$cookieConfig = new CookieConfig();
145+
$cookieConfig->domain = 'example.com';
146+
$cookieConfig->path = '/app';
147+
$cookieConfig->secure = true;
148+
$cookieConfig->samesite = 'Strict';
149+
150+
$handler = $this->createHandler($cookieConfig);
151+
$result = $handler->destroy('ci_session');
152+
153+
$this->assertTrue($result);
154+
$this->assertNotNull(self::$lastSetCookieArgs);
155+
$this->assertSame('ci_session', self::$lastSetCookieArgs['name']);
156+
$this->assertSame('', self::$lastSetCookieArgs['value']);
157+
158+
$options = self::$lastSetCookieArgs['options'];
159+
$this->assertSame(1, $options['expires']);
160+
$this->assertSame('/app', $options['path']);
161+
$this->assertSame('example.com', $options['domain']);
162+
$this->assertTrue($options['secure']);
163+
$this->assertTrue($options['httponly']);
164+
$this->assertSame('Strict', $options['samesite']);
165+
}
166+
167+
public function testSetCookieMockDelegatesWhenInterceptDisabled(): void
168+
{
169+
self::$interceptSetCookie = false;
170+
171+
$handler = $this->createHandler();
172+
$handler->destroy('ci_session');
173+
174+
$this->assertNull(self::$lastSetCookieArgs);
175+
}
176+
177+
public function testDestroyCookieNormalizesEmptySameSiteToLax(): void
178+
{
179+
$cookieConfig = new CookieConfig();
180+
$cookieConfig->samesite = '';
181+
182+
$handler = $this->createHandler($cookieConfig);
183+
$handler->destroy('ci_session');
184+
185+
$this->assertNotNull(self::$lastSetCookieArgs);
186+
$this->assertSame('Lax', self::$lastSetCookieArgs['options']['samesite']);
187+
}
188+
189+
public function testDestroyCookieNormalizesLowercaseSameSite(): void
190+
{
191+
$handler = $this->createHandler();
192+
$this->setPrivateProperty($handler, 'cookieSameSite', 'none');
193+
$handler->destroy('ci_session');
194+
195+
$this->assertNotNull(self::$lastSetCookieArgs);
196+
$this->assertSame('None', self::$lastSetCookieArgs['options']['samesite']);
197+
}
198+
199+
#[DataProvider('provideDestroyCookieNormalizesSameSiteCase')]
200+
public function testDestroyCookieNormalizesSameSiteCase(string $input, string $expected): void
201+
{
202+
$handler = $this->createHandler();
203+
$this->setPrivateProperty($handler, 'cookieSameSite', $input);
204+
$handler->destroy('ci_session');
205+
206+
$this->assertNotNull(self::$lastSetCookieArgs);
207+
$this->assertSame($expected, self::$lastSetCookieArgs['options']['samesite']);
208+
}
209+
210+
/**
211+
* @return iterable<string, array{string, string}>
212+
*/
213+
public static function provideDestroyCookieNormalizesSameSiteCase(): iterable
214+
{
215+
yield 'uppercase LAX' => ['LAX', 'Lax'];
216+
217+
yield 'uppercase STRICT' => ['STRICT', 'Strict'];
218+
219+
yield 'uppercase NONE' => ['NONE', 'None'];
220+
221+
yield 'mixed case sTrIcT' => ['sTrIcT', 'Strict'];
222+
223+
yield 'empty string' => ['', 'Lax'];
224+
}
225+
}

0 commit comments

Comments
 (0)