CookieTest.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. * Licensed under The MIT License
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  10. * @link https://cakephp.org CakePHP(tm) Project
  11. * @since 3.5.0
  12. * @license https://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace Cake\Test\TestCase\Http\Cookie;
  15. use Cake\Chronos\Chronos;
  16. use Cake\Http\Cookie\Cookie;
  17. use Cake\Http\Cookie\CookieInterface;
  18. use Cake\Http\Cookie\SameSiteEnum;
  19. use Cake\TestSuite\TestCase;
  20. use DateTimeInterface;
  21. use InvalidArgumentException;
  22. use PHPUnit\Framework\Attributes\DataProvider;
  23. use ValueError;
  24. /**
  25. * HTTP cookies test.
  26. */
  27. class CookieTest extends TestCase
  28. {
  29. /**
  30. * Generate invalid cookie names.
  31. *
  32. * @return array
  33. */
  34. public static function invalidNameProvider(): array
  35. {
  36. return [
  37. ['no='],
  38. ["no\rnewline"],
  39. ["no\nnewline"],
  40. ["no\ttab"],
  41. ['no,comma'],
  42. ['no;semi'],
  43. ];
  44. }
  45. /**
  46. * Test invalid cookie name
  47. */
  48. #[DataProvider('invalidNameProvider')]
  49. public function testValidateNameInvalidChars(string $name): void
  50. {
  51. $this->expectException(InvalidArgumentException::class);
  52. $this->expectExceptionMessage('contains invalid characters.');
  53. new Cookie($name, 'value');
  54. }
  55. /**
  56. * Test empty cookie name
  57. */
  58. public function testValidateNameEmptyName(): void
  59. {
  60. $this->expectException(InvalidArgumentException::class);
  61. $this->expectExceptionMessage('The cookie name cannot be empty.');
  62. new Cookie('', '');
  63. }
  64. /**
  65. * Tests the header value
  66. */
  67. public function testToHeaderValue(): void
  68. {
  69. $cookie = new Cookie('cakephp', 'cakephp-rocks');
  70. $result = $cookie->toHeaderValue();
  71. $this->assertSame('cakephp=cakephp-rocks; path=/', $result);
  72. $date = Chronos::createFromFormat('m/d/Y h:i:s', '12/1/2027 12:00:00');
  73. $cookie = new Cookie('cakephp', 'cakephp-rocks');
  74. $cookie = $cookie->withDomain('cakephp.org')
  75. ->withExpiry($date)
  76. ->withHttpOnly(true)
  77. ->withSameSite(CookieInterface::SAMESITE_STRICT)
  78. ->withSecure(true);
  79. $result = $cookie->toHeaderValue();
  80. $expected = 'cakephp=cakephp-rocks; expires=Wed, 01-Dec-2027 12:00:00 GMT; path=/; domain=cakephp.org; samesite=Strict; secure; httponly';
  81. $this->assertSame($expected, $result);
  82. }
  83. /**
  84. * Test getting the value from the cookie
  85. */
  86. public function testGetValue(): void
  87. {
  88. $cookie = new Cookie('cakephp', 'cakephp-rocks');
  89. $result = $cookie->getValue();
  90. $this->assertSame('cakephp-rocks', $result);
  91. $cookie = new Cookie('cakephp', '');
  92. $result = $cookie->getValue();
  93. $this->assertSame('', $result);
  94. }
  95. /**
  96. * Test setting values in cookies
  97. */
  98. public function testWithValue(): void
  99. {
  100. $cookie = new Cookie('cakephp', 'cakephp-rocks');
  101. $new = $cookie->withValue('new');
  102. $this->assertNotSame($new, $cookie, 'Should make a clone');
  103. $this->assertSame('cakephp-rocks', $cookie->getValue(), 'old instance not modified');
  104. $this->assertSame('new', $new->getValue());
  105. }
  106. /**
  107. * Test setting domain in cookies
  108. */
  109. public function testWithDomain(): void
  110. {
  111. $cookie = new Cookie('cakephp', 'cakephp-rocks');
  112. $new = $cookie->withDomain('example.com');
  113. $this->assertNotSame($new, $cookie, 'Should make a clone');
  114. $this->assertStringNotContainsString('example.com', $cookie->toHeaderValue(), 'old instance not modified');
  115. $this->assertStringContainsString('domain=example.com', $new->toHeaderValue());
  116. }
  117. /**
  118. * Test setting path in cookies
  119. */
  120. public function testWithPath(): void
  121. {
  122. $cookie = new Cookie('cakephp', 'cakephp-rocks');
  123. $new = $cookie->withPath('/api');
  124. $this->assertNotSame($new, $cookie, 'Should make a clone');
  125. $this->assertStringNotContainsString('path=/api', $cookie->toHeaderValue(), 'old instance not modified');
  126. $this->assertStringContainsString('path=/api', $new->toHeaderValue());
  127. }
  128. /**
  129. * Test setting SameSite in cookies
  130. */
  131. public function testWithSameSite(): void
  132. {
  133. $cookie = new Cookie('cakephp', 'cakephp-rocks');
  134. $new = $cookie->withSameSite(CookieInterface::SAMESITE_LAX);
  135. $this->assertNotSame($new, $cookie, 'Should make a clone');
  136. $this->assertStringNotContainsString('samesite=Lax', $cookie->toHeaderValue(), 'old instance not modified');
  137. $this->assertStringContainsString('samesite=Lax', $new->toHeaderValue());
  138. $new = $cookie->withSameSite(SameSiteEnum::STRICT);
  139. $this->assertStringContainsString('samesite=Strict', $new->toHeaderValue());
  140. }
  141. /**
  142. * Test setting SameSite in cookies
  143. */
  144. public function testWithSameSiteException(): void
  145. {
  146. $this->expectException(ValueError::class);
  147. $cookie = new Cookie('cakephp', 'cakephp-rocks');
  148. $cookie->withSameSite('invalid');
  149. }
  150. public function testGetSameSite(): void
  151. {
  152. $cookie = new Cookie(name: 'cakephp', value: 'cakephp-rocks', sameSite: 'NONE');
  153. $this->assertSame(SameSiteEnum::NONE, $cookie->getSameSite());
  154. }
  155. /**
  156. * Test default path in cookies
  157. */
  158. public function testDefaultPath(): void
  159. {
  160. $cookie = new Cookie('cakephp', 'cakephp-rocks');
  161. $this->assertStringContainsString('path=/', $cookie->toHeaderValue());
  162. }
  163. /**
  164. * Test setting httponly in cookies
  165. */
  166. public function testWithHttpOnly(): void
  167. {
  168. $cookie = new Cookie('cakephp', 'cakephp-rocks');
  169. $new = $cookie->withHttpOnly(true);
  170. $this->assertNotSame($new, $cookie, 'Should clone');
  171. $this->assertFalse($cookie->isHttpOnly());
  172. $this->assertTrue($new->isHttpOnly());
  173. }
  174. /**
  175. * Test setting secure in cookies
  176. */
  177. public function testWithSecure(): void
  178. {
  179. $cookie = new Cookie('cakephp', 'cakephp-rocks');
  180. $new = $cookie->withSecure(true);
  181. $this->assertNotSame($new, $cookie, 'Should clone');
  182. $this->assertFalse($cookie->isSecure());
  183. $this->assertTrue($new->isSecure());
  184. }
  185. /**
  186. * Test the never expiry method
  187. */
  188. public function testWithNeverExpire(): void
  189. {
  190. $cookie = new Cookie('cakephp', 'cakephp-rocks');
  191. $new = $cookie->withNeverExpire();
  192. $this->assertNotSame($new, $cookie, 'Should clone');
  193. $this->assertStringContainsString('01-Jan-2038', $new->toHeaderValue());
  194. }
  195. /**
  196. * Test the expired method
  197. */
  198. public function testWithExpired(): void
  199. {
  200. $cookie = new Cookie('cakephp', 'cakephp-rocks');
  201. $new = $cookie->withExpired();
  202. $this->assertNotSame($new, $cookie, 'Should clone');
  203. $this->assertStringNotContainsString('expiry', $cookie->toHeaderValue());
  204. $this->assertStringContainsString('01-Jan-1970', $new->toHeaderValue());
  205. }
  206. /**
  207. * Test the expired method
  208. */
  209. public function testWithExpiredNotUtc(): void
  210. {
  211. date_default_timezone_set('Europe/Paris');
  212. $cookie = new Cookie('cakephp', 'cakephp-rocks');
  213. $new = $cookie->withExpired();
  214. date_default_timezone_set('UTC');
  215. $this->assertStringContainsString('01-Jan-1970 00:00:01 GMT+0000', $new->toHeaderValue());
  216. }
  217. /**
  218. * Test the withExpiry method
  219. */
  220. public function testWithExpiry(): void
  221. {
  222. $cookie = new Cookie('cakephp', 'cakephp-rocks');
  223. $new = $cookie->withExpiry(Chronos::createFromDate(2022, 6, 15));
  224. $this->assertNotSame($new, $cookie, 'Should clone');
  225. $this->assertStringNotContainsString('expires', $cookie->toHeaderValue());
  226. $this->assertStringContainsString('expires=Wed, 15-Jun-2022', $new->toHeaderValue());
  227. }
  228. /**
  229. * Test the withExpiry method changes timezone
  230. */
  231. public function testWithExpiryChangesTimezone(): void
  232. {
  233. $cookie = new Cookie('cakephp', 'cakephp-rocks');
  234. $date = Chronos::createFromDate(2022, 6, 15);
  235. $date = $date->setTimezone('America/New_York');
  236. $new = $cookie->withExpiry($date);
  237. $this->assertNotSame($new, $cookie, 'Should clone');
  238. $this->assertStringNotContainsString('expires', $cookie->toHeaderValue());
  239. $this->assertStringContainsString('expires=Wed, 15-Jun-2022', $new->toHeaderValue());
  240. $this->assertStringContainsString('GMT', $new->toHeaderValue());
  241. $this->assertSame((int)$date->format('U'), $new->getExpiresTimestamp());
  242. }
  243. /**
  244. * Test the isExpired method
  245. */
  246. public function testIsExpired(): void
  247. {
  248. $date = Chronos::now();
  249. $cookie = new Cookie('cakephp', 'yay');
  250. $this->assertFalse($cookie->isExpired($date));
  251. $cookie = new Cookie('cakephp', 'yay', $date);
  252. $this->assertFalse($cookie->isExpired($date), 'same time, not expired');
  253. $date = $date->modify('+10 seconds');
  254. $this->assertTrue($cookie->isExpired($date), 'future now');
  255. $date = $date->modify('-1 minute');
  256. $this->assertFalse($cookie->isExpired($date), 'expires later');
  257. }
  258. /**
  259. * Test the withName method
  260. */
  261. public function testWithName(): void
  262. {
  263. $cookie = new Cookie('cakephp', 'cakephp-rocks');
  264. $new = $cookie->withName('user');
  265. $this->assertNotSame($new, $cookie, 'Should clone');
  266. $this->assertNotSame('user', $cookie->getName());
  267. $this->assertSame('user', $new->getName());
  268. }
  269. /**
  270. * Test the withAddedValue method
  271. */
  272. public function testWithAddedValue(): void
  273. {
  274. $cookie = new Cookie('cakephp', '{"type":"mvc", "icing": true}');
  275. $new = $cookie->withAddedValue('type', 'mvc')
  276. ->withAddedValue('user.name', 'mark');
  277. $this->assertNotSame($new, $cookie, 'Should clone');
  278. $this->assertNull($cookie->read('user.name'));
  279. $this->assertSame('mvc', $new->read('type'));
  280. $this->assertSame('mark', $new->read('user.name'));
  281. }
  282. /**
  283. * Test the withoutAddedValue method
  284. */
  285. public function testWithoutAddedValue(): void
  286. {
  287. $cookie = new Cookie('cakephp', '{"type":"mvc", "user": {"name":"mark"}}');
  288. $new = $cookie->withoutAddedValue('type')
  289. ->withoutAddedValue('user.name');
  290. $this->assertNotSame($new, $cookie, 'Should clone');
  291. $this->assertNotNull($cookie->read('type'));
  292. $this->assertNull($new->read('type'));
  293. $this->assertNull($new->read('user.name'));
  294. }
  295. /**
  296. * Test check() with serialized source data.
  297. */
  298. public function testCheckStringSourceData(): void
  299. {
  300. $cookie = new Cookie('cakephp', '{"type":"mvc", "user": {"name":"mark"}}');
  301. $this->assertTrue($cookie->check('type'));
  302. $this->assertTrue($cookie->check('user.name'));
  303. $this->assertFalse($cookie->check('nope'));
  304. $this->assertFalse($cookie->check('user.nope'));
  305. }
  306. /**
  307. * Test check() with array source data.
  308. */
  309. public function testCheckArraySourceData(): void
  310. {
  311. $data = [
  312. 'type' => 'mvc',
  313. 'user' => ['name' => 'mark'],
  314. ];
  315. $cookie = new Cookie('cakephp', $data);
  316. $this->assertTrue($cookie->check('type'));
  317. $this->assertTrue($cookie->check('user.name'));
  318. $this->assertFalse($cookie->check('nope'));
  319. $this->assertFalse($cookie->check('user.nope'));
  320. }
  321. /**
  322. * test read() and set on different types
  323. */
  324. public function testReadExpandsOnDemand(): void
  325. {
  326. $data = [
  327. 'username' => 'florian',
  328. 'profile' => [
  329. 'profession' => 'developer',
  330. ],
  331. ];
  332. $cookie = new Cookie('cakephp', json_encode($data));
  333. $this->assertFalse($cookie->isExpanded());
  334. $this->assertSame('developer', $cookie->read('profile.profession'));
  335. $this->assertTrue($cookie->isExpanded(), 'Cookies expand when read.');
  336. $cookie = $cookie->withValue(json_encode($data));
  337. $this->assertTrue($cookie->check('profile.profession'), 'Cookies expand when read.');
  338. $this->assertTrue($cookie->isExpanded());
  339. $cookie = $cookie->withValue(json_encode($data))
  340. ->withAddedValue('face', 'punch');
  341. $this->assertTrue($cookie->isExpanded());
  342. $this->assertSame('punch', $cookie->read('face'));
  343. }
  344. /**
  345. * test read() on structured data.
  346. */
  347. public function testReadComplexData(): void
  348. {
  349. $data = [
  350. 'username' => 'florian',
  351. 'profile' => [
  352. 'profession' => 'developer',
  353. ],
  354. ];
  355. $cookie = new Cookie('cakephp', $data);
  356. $result = $cookie->getValue();
  357. $this->assertEquals($data, $result);
  358. $result = $cookie->read('foo');
  359. $this->assertNull($result);
  360. $result = $cookie->read();
  361. $this->assertEquals($data, $result);
  362. $result = $cookie->read('profile.profession');
  363. $this->assertSame('developer', $result);
  364. }
  365. /**
  366. * Test reading complex data serialized in 1.x and early 2.x
  367. */
  368. public function testReadLegacyComplexData(): void
  369. {
  370. $data = 'key|value,key2|value2';
  371. $cookie = new Cookie('cakephp', $data);
  372. $this->assertSame('value', $cookie->read('key'));
  373. $this->assertNull($cookie->read('nope'));
  374. }
  375. /**
  376. * Test that toHeaderValue() collapses data.
  377. */
  378. public function testToHeaderValueCollapsesComplexData(): void
  379. {
  380. $data = [
  381. 'username' => 'florian',
  382. 'profile' => [
  383. 'profession' => 'developer',
  384. ],
  385. ];
  386. $cookie = new Cookie('cakephp', $data);
  387. $this->assertSame('developer', $cookie->read('profile.profession'));
  388. $expected = '{"username":"florian","profile":{"profession":"developer"}}';
  389. $this->assertStringContainsString(urlencode($expected), $cookie->toHeaderValue());
  390. }
  391. /**
  392. * Tests getting the id
  393. */
  394. public function testGetId(): void
  395. {
  396. $cookie = new Cookie('cakephp', 'cakephp-rocks');
  397. $this->assertSame('cakephp;;/', $cookie->getId());
  398. $cookie = new Cookie('CAKEPHP', 'cakephp-rocks');
  399. $this->assertSame('CAKEPHP;;/', $cookie->getId());
  400. $cookie = new Cookie('test', 'val', null, '/path', 'example.com');
  401. $this->assertSame('test;example.com;/path', $cookie->getId());
  402. }
  403. public function testCreateFromHeaderStringInvalidSamesite(): void
  404. {
  405. $header = 'cakephp=cakephp-rocks; expires=Wed, 01-Dec-2027 12:00:00 GMT; path=/; domain=cakephp.org; samesite=invalid; secure; httponly';
  406. $result = Cookie::createFromHeaderString($header);
  407. // Ignore invalid value when parsing headers
  408. // https://tools.ietf.org/html/draft-west-first-party-cookies-07#section-4.1
  409. $this->assertNull($result->getSameSite());
  410. }
  411. public function testCreateFromHeaderStringEmptyValue(): void
  412. {
  413. // Invalid cookie with no = separator or value.
  414. $header = 'cakephp; expires=Wed, 01-Dec-2027 12:00:00 GMT; path=/; domain=cakephp.org;';
  415. $result = Cookie::createFromHeaderString($header);
  416. $this->assertSame('', $result->getValue());
  417. }
  418. public function testDefaults(): void
  419. {
  420. Cookie::setDefaults(['path' => '/cakephp', 'expires' => time()]);
  421. $cookie = new Cookie('cakephp', 'cakephp-rocks');
  422. $this->assertSame('/cakephp', $cookie->getPath());
  423. $this->assertInstanceOf(DateTimeInterface::class, $cookie->getExpiry());
  424. Cookie::setDefaults(['path' => '/', 'expires' => null]);
  425. $cookie = new Cookie('cakephp', 'cakephp-rocks');
  426. $this->assertSame('/', $cookie->getPath());
  427. $this->assertNull($cookie->getExpiry());
  428. }
  429. public function testInvalidSameSiteForDefaults(): void
  430. {
  431. $this->expectException(ValueError::class);
  432. Cookie::setDefaults(['samesite' => 'ompalompa']);
  433. new Cookie('cakephp', 'cakephp-rocks');
  434. }
  435. }