Skip to content

Commit ebb4547

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

3 files changed

Lines changed: 223 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: 198 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,198 @@
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+
* @param array<string, mixed> $options
27+
*/
28+
function setcookie(string $name, string $value = '', array $options = []): bool
29+
{
30+
BaseHandlerTest::$lastSetCookieArgs = [
31+
'name' => $name,
32+
'value' => $value,
33+
'options' => $options,
34+
];
35+
36+
return true;
37+
}
38+
39+
/**
40+
* @internal
41+
*/
42+
#[Group('Others')]
43+
final class BaseHandlerTest extends CIUnitTestCase
44+
{
45+
/**
46+
* @var array{name: string, value: string, options: array<string, mixed>}|null
47+
*/
48+
public static ?array $lastSetCookieArgs = null;
49+
50+
protected function setUp(): void
51+
{
52+
parent::setUp();
53+
54+
self::$lastSetCookieArgs = null;
55+
Factories::reset('config');
56+
}
57+
58+
protected function tearDown(): void
59+
{
60+
parent::tearDown();
61+
62+
self::$lastSetCookieArgs = null;
63+
Factories::reset('config');
64+
}
65+
66+
private function createHandler(?CookieConfig $cookieConfig = null): BaseHandler
67+
{
68+
if ($cookieConfig instanceof CookieConfig) {
69+
Factories::injectMock('config', CookieConfig::class, $cookieConfig);
70+
}
71+
72+
$sessionConfig = new SessionConfig();
73+
$sessionConfig->cookieName = 'ci_session';
74+
75+
return new class ($sessionConfig, '127.0.0.1') extends BaseHandler {
76+
public function open(string $path, string $name): bool
77+
{
78+
return true;
79+
}
80+
81+
public function close(): bool
82+
{
83+
return true;
84+
}
85+
86+
public function read(string $id): string
87+
{
88+
return '';
89+
}
90+
91+
public function write(string $id, string $data): bool
92+
{
93+
return true;
94+
}
95+
96+
public function destroy(string $id): bool
97+
{
98+
return $this->destroyCookie();
99+
}
100+
101+
public function gc(int $maxLifetime): int
102+
{
103+
return 1;
104+
}
105+
};
106+
}
107+
108+
public function testConstructorInitializesCookieSameSiteFromConfig(): void
109+
{
110+
$cookieConfig = new CookieConfig();
111+
$cookieConfig->samesite = 'Strict';
112+
113+
$handler = $this->createHandler($cookieConfig);
114+
115+
$this->assertSame('Strict', $this->getPrivateProperty($handler, 'cookieSameSite'));
116+
}
117+
118+
public function testConstructorDefaultsToCookieConfigSameSite(): void
119+
{
120+
$handler = $this->createHandler();
121+
122+
$this->assertSame('Lax', $this->getPrivateProperty($handler, 'cookieSameSite'));
123+
}
124+
125+
public function testDestroyCookiePassesSameSiteInOptions(): void
126+
{
127+
$cookieConfig = new CookieConfig();
128+
$cookieConfig->domain = 'example.com';
129+
$cookieConfig->path = '/app';
130+
$cookieConfig->secure = true;
131+
$cookieConfig->samesite = 'Strict';
132+
133+
$handler = $this->createHandler($cookieConfig);
134+
$result = $handler->destroy('ci_session');
135+
136+
$this->assertTrue($result);
137+
$this->assertNotNull(self::$lastSetCookieArgs);
138+
$this->assertSame('ci_session', self::$lastSetCookieArgs['name']);
139+
$this->assertSame('', self::$lastSetCookieArgs['value']);
140+
141+
$options = self::$lastSetCookieArgs['options'];
142+
$this->assertSame(1, $options['expires']);
143+
$this->assertSame('/app', $options['path']);
144+
$this->assertSame('example.com', $options['domain']);
145+
$this->assertTrue($options['secure']);
146+
$this->assertTrue($options['httponly']);
147+
$this->assertSame('Strict', $options['samesite']);
148+
}
149+
150+
public function testDestroyCookieNormalizesEmptySameSiteToLax(): void
151+
{
152+
$cookieConfig = new CookieConfig();
153+
$cookieConfig->samesite = '';
154+
155+
$handler = $this->createHandler($cookieConfig);
156+
$handler->destroy('ci_session');
157+
158+
$this->assertNotNull(self::$lastSetCookieArgs);
159+
$this->assertSame('Lax', self::$lastSetCookieArgs['options']['samesite']);
160+
}
161+
162+
public function testDestroyCookieNormalizesLowercaseSameSite(): void
163+
{
164+
$handler = $this->createHandler();
165+
$this->setPrivateProperty($handler, 'cookieSameSite', 'none');
166+
$handler->destroy('ci_session');
167+
168+
$this->assertNotNull(self::$lastSetCookieArgs);
169+
$this->assertSame('None', self::$lastSetCookieArgs['options']['samesite']);
170+
}
171+
172+
#[DataProvider('provideDestroyCookieNormalizesSameSiteCase')]
173+
public function testDestroyCookieNormalizesSameSiteCase(string $input, string $expected): void
174+
{
175+
$handler = $this->createHandler();
176+
$this->setPrivateProperty($handler, 'cookieSameSite', $input);
177+
$handler->destroy('ci_session');
178+
179+
$this->assertNotNull(self::$lastSetCookieArgs);
180+
$this->assertSame($expected, self::$lastSetCookieArgs['options']['samesite']);
181+
}
182+
183+
/**
184+
* @return iterable<string, array{string, string}>
185+
*/
186+
public static function provideDestroyCookieNormalizesSameSiteCase(): iterable
187+
{
188+
yield 'uppercase LAX' => ['LAX', 'Lax'];
189+
190+
yield 'uppercase STRICT' => ['STRICT', 'Strict'];
191+
192+
yield 'uppercase NONE' => ['NONE', 'None'];
193+
194+
yield 'mixed case sTrIcT' => ['sTrIcT', 'Strict'];
195+
196+
yield 'empty string' => ['', 'Lax'];
197+
}
198+
}

0 commit comments

Comments
 (0)