CookieCollectionTest.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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\Http\Client\Request as ClientRequest;
  16. use Cake\Http\Cookie\Cookie;
  17. use Cake\Http\Cookie\CookieCollection;
  18. use Cake\Http\Response;
  19. use Cake\Http\ServerRequest;
  20. use Cake\TestSuite\TestCase;
  21. use Cake\Utility\Security;
  22. use DateTime;
  23. use InvalidArgumentException;
  24. /**
  25. * Cookie collection test.
  26. */
  27. class CookieCollectionTest extends TestCase
  28. {
  29. /**
  30. * Test constructor
  31. */
  32. public function testConstructorWithEmptyArray(): void
  33. {
  34. $collection = new CookieCollection([]);
  35. $this->assertCount(0, $collection);
  36. }
  37. /**
  38. * Test valid cookies
  39. */
  40. public function testConstructorWithCookieArray(): void
  41. {
  42. $cookies = [
  43. new Cookie('one', 'one'),
  44. new Cookie('two', 'two'),
  45. ];
  46. $collection = new CookieCollection($cookies);
  47. $this->assertCount(2, $collection);
  48. }
  49. /**
  50. * Test iteration
  51. */
  52. public function testIteration(): void
  53. {
  54. $cookies = [
  55. new Cookie('remember_me', 'a'),
  56. new Cookie('gtm', 'b'),
  57. new Cookie('three', 'tree'),
  58. ];
  59. $collection = new CookieCollection($cookies);
  60. $names = [];
  61. foreach ($collection as $cookie) {
  62. $names[] = $cookie->getName();
  63. }
  64. $this->assertSame(['remember_me', 'gtm', 'three'], $names);
  65. }
  66. /**
  67. * Test adding cookies
  68. */
  69. public function testAdd(): void
  70. {
  71. $cookies = [];
  72. $collection = new CookieCollection($cookies);
  73. $this->assertCount(0, $collection);
  74. $remember = new Cookie('remember_me', 'a');
  75. $new = $collection->add($remember);
  76. $this->assertNotSame($new, $collection->add($remember));
  77. $this->assertCount(0, $collection, 'Original instance not modified');
  78. $this->assertCount(1, $new);
  79. $this->assertFalse($collection->has('remember_me'), 'Original instance not modified');
  80. $this->assertTrue($new->has('remember_me'));
  81. $this->assertSame($remember, $new->get('remember_me'));
  82. }
  83. /**
  84. * Cookie collections need to support duplicate cookie names because
  85. * of use cases in Http\Client
  86. */
  87. public function testAddDuplicates(): void
  88. {
  89. $remember = new Cookie('remember_me', 'yes');
  90. $rememberNo = new Cookie('remember_me', 'no', null, '/path2');
  91. $this->assertNotEquals($remember->getId(), $rememberNo->getId(), 'Cookies should have different ids');
  92. $collection = new CookieCollection([]);
  93. $new = $collection->add($remember)->add($rememberNo);
  94. $this->assertCount(2, $new, 'Cookies with different ids create duplicates.');
  95. $this->assertNotSame($new, $collection);
  96. $this->assertSame($remember, $new->get('remember_me'), 'get() fetches first cookie');
  97. }
  98. /**
  99. * Test has()
  100. */
  101. public function testHas(): void
  102. {
  103. $cookies = [
  104. new Cookie('remember_me', 'a'),
  105. new Cookie('gtm', 'b'),
  106. ];
  107. $collection = new CookieCollection($cookies);
  108. $this->assertFalse($collection->has('nope'));
  109. $this->assertTrue($collection->has('remember_me'));
  110. $this->assertTrue($collection->has('REMEMBER_me'), 'case insensitive cookie names');
  111. }
  112. /**
  113. * Tests the magic __isset() and __get() methods
  114. */
  115. public function testMagicIssetAndGet(): void
  116. {
  117. $cookies = [
  118. new Cookie('remember_me', 'a'),
  119. new Cookie('gtm', 'b'),
  120. ];
  121. $collection = new CookieCollection($cookies);
  122. $this->assertFalse(isset($collection->nope));
  123. $this->assertTrue(isset($collection->remember_me));
  124. $this->assertTrue(isset($collection->REMEMBER_me));
  125. $this->assertEquals('a', $collection->remember_me->getValue());
  126. $this->assertEquals('b', $collection->GTM->getValue());
  127. $this->assertNull($collection->nope);
  128. }
  129. /**
  130. * Test removing cookies
  131. */
  132. public function testRemove(): void
  133. {
  134. $cookies = [
  135. new Cookie('remember_me', 'a'),
  136. new Cookie('gtm', 'b'),
  137. ];
  138. $collection = new CookieCollection($cookies);
  139. $this->assertInstanceOf(Cookie::class, $collection->get('REMEMBER_me'), 'case insensitive cookie names');
  140. $new = $collection->remove('remember_me');
  141. $this->assertTrue($collection->has('remember_me'), 'old instance not modified');
  142. $this->assertNotSame($new, $collection);
  143. $this->assertFalse($new->has('remember_me'), 'should be removed');
  144. $this->expectException(InvalidArgumentException::class);
  145. $new->get('remember_me');
  146. }
  147. /**
  148. * Test getting cookies by name
  149. */
  150. public function testGetByName(): void
  151. {
  152. $cookies = [
  153. new Cookie('remember_me', 'a'),
  154. new Cookie('gtm', 'b'),
  155. ];
  156. $collection = new CookieCollection($cookies);
  157. $this->assertFalse($collection->has('nope'));
  158. $this->assertInstanceOf(Cookie::class, $collection->get('REMEMBER_me'), 'case insensitive cookie names');
  159. $this->assertInstanceOf(Cookie::class, $collection->get('remember_me'));
  160. $this->assertSame($cookies[0], $collection->get('remember_me'));
  161. }
  162. /**
  163. * Test that the constructor takes only an array of objects implementing
  164. * the CookieInterface
  165. */
  166. public function testConstructorWithInvalidCookieObjects(): void
  167. {
  168. $this->expectException(InvalidArgumentException::class);
  169. $this->expectExceptionMessage('Expected `Cake\Http\Cookie\CookieCollection[]` as $cookies but instead got `array` at index 1');
  170. $array = [
  171. new Cookie('one', 'one'),
  172. [],
  173. ];
  174. new CookieCollection($array);
  175. }
  176. /**
  177. * Test adding cookies from a response.
  178. */
  179. public function testAddFromResponse(): void
  180. {
  181. $collection = new CookieCollection();
  182. $request = new ServerRequest([
  183. 'url' => '/app',
  184. ]);
  185. $response = (new Response())
  186. ->withAddedHeader('Set-Cookie', 'test=value')
  187. ->withAddedHeader('Set-Cookie', 'expiring=soon; Expires=Mon, 09-Jun-2031 10:18:14 GMT; Path=/; HttpOnly; Secure;')
  188. ->withAddedHeader('Set-Cookie', 'session=123abc; Domain=www.example.com')
  189. ->withAddedHeader('Set-Cookie', 'maxage=value; Max-Age=60; Expires=Mon, 09-Jun-2031 10:18:14 GMT;');
  190. $new = $collection->addFromResponse($response, $request);
  191. $this->assertNotSame($new, $collection, 'Should clone collection');
  192. $this->assertTrue($new->has('test'));
  193. $this->assertTrue($new->has('session'));
  194. $this->assertTrue($new->has('expiring'));
  195. $this->assertSame('value', $new->get('test')->getValue());
  196. $this->assertSame('123abc', $new->get('session')->getValue());
  197. $this->assertSame('soon', $new->get('expiring')->getValue());
  198. $this->assertSame('value', $new->get('maxage')->getValue());
  199. $this->assertSame('/app', $new->get('test')->getPath(), 'cookies should inherit request path');
  200. $this->assertSame('/', $new->get('expiring')->getPath(), 'path attribute should be used.');
  201. $this->assertNull($new->get('test')->getExpiry(), 'No expiry');
  202. $this->assertSame(
  203. '2031-06-09 10:18:14',
  204. $new->get('expiring')->getExpiry()->format('Y-m-d H:i:s'),
  205. 'Has expiry'
  206. );
  207. $session = $new->get('session');
  208. $this->assertNull($session->getExpiry(), 'No expiry');
  209. $this->assertSame('www.example.com', $session->getDomain(), 'Has domain');
  210. $maxage = $new->get('maxage');
  211. $this->assertLessThanOrEqual(
  212. (new DateTime('60 seconds'))->format('Y-m-d H:i:s'),
  213. $maxage->getExpiry()->format('Y-m-d H:i:s'),
  214. 'Has max age'
  215. );
  216. }
  217. /**
  218. * Test adding cookies that contain URL encoded data
  219. */
  220. public function testAddFromResponseValueUrldecodeData(): void
  221. {
  222. $collection = new CookieCollection();
  223. $request = new ServerRequest([
  224. 'url' => '/app',
  225. ]);
  226. $response = (new Response())
  227. ->withAddedHeader('Set-Cookie', 'test=val%3Bue; Path=/example; Secure;');
  228. $new = $collection->addFromResponse($response, $request);
  229. $this->assertTrue($new->has('test'));
  230. $test = $new->get('test');
  231. $this->assertSame('val;ue', $test->getValue());
  232. $this->assertSame('/example', $test->getPath());
  233. }
  234. /**
  235. * Test adding cookies from a response ignores empty headers
  236. */
  237. public function testAddFromResponseIgnoreEmpty(): void
  238. {
  239. $collection = new CookieCollection();
  240. $request = new ServerRequest([
  241. 'url' => '/app',
  242. ]);
  243. $response = (new Response())
  244. ->withAddedHeader('Set-Cookie', '');
  245. $new = $collection->addFromResponse($response, $request);
  246. $this->assertCount(0, $new, 'no cookies parsed');
  247. }
  248. /**
  249. * Test adding cookies from a response ignores expired cookies
  250. */
  251. public function testAddFromResponseIgnoreExpired(): void
  252. {
  253. $collection = new CookieCollection();
  254. $request = new ServerRequest([
  255. 'url' => '/app',
  256. ]);
  257. $response = (new Response())
  258. ->withAddedHeader('Set-Cookie', 'test=value')
  259. ->withAddedHeader('Set-Cookie', 'expired=soon; Expires=Wed, 09-Jun-2012 10:18:14 GMT; Path=/;');
  260. $new = $collection->addFromResponse($response, $request);
  261. $this->assertFalse($new->has('expired'), 'Should drop expired cookies');
  262. }
  263. /**
  264. * Test adding cookies from a response removes existing cookies if
  265. * the new response marks them as expired.
  266. */
  267. public function testAddFromResponseRemoveExpired(): void
  268. {
  269. $collection = new CookieCollection([
  270. new Cookie('expired', 'not yet', null, '/', 'example.com'),
  271. ]);
  272. $request = new ServerRequest([
  273. 'url' => '/app',
  274. 'environment' => [
  275. 'HTTP_HOST' => 'example.com',
  276. ],
  277. ]);
  278. $response = (new Response())
  279. ->withAddedHeader('Set-Cookie', 'test=value')
  280. ->withAddedHeader('Set-Cookie', 'expired=soon; Expires=Wed, 09-Jun-2012 10:18:14 GMT; Path=/;');
  281. $new = $collection->addFromResponse($response, $request);
  282. $this->assertFalse($new->has('expired'), 'Should drop expired cookies');
  283. }
  284. /**
  285. * Test adding cookies from a response with bad expires values
  286. */
  287. public function testAddFromResponseInvalidExpires(): void
  288. {
  289. $collection = new CookieCollection();
  290. $request = new ServerRequest([
  291. 'url' => '/app',
  292. ]);
  293. $response = (new Response())
  294. ->withAddedHeader('Set-Cookie', 'test=value')
  295. ->withAddedHeader('Set-Cookie', 'expired=no; Expires=1w; Path=/; HttpOnly; Secure;');
  296. $new = $collection->addFromResponse($response, $request);
  297. $this->assertTrue($new->has('test'));
  298. $this->assertTrue($new->has('expired'));
  299. $expired = $new->get('expired');
  300. $this->assertNull($expired->getExpiry());
  301. }
  302. /**
  303. * Test adding cookies from responses updates cookie values.
  304. */
  305. public function testAddFromResponseUpdateExisting(): void
  306. {
  307. $collection = new CookieCollection([
  308. new Cookie('key', 'old value', null, '/', 'example.com'),
  309. ]);
  310. $request = new ServerRequest([
  311. 'url' => '/',
  312. 'environment' => [
  313. 'HTTP_HOST' => 'example.com',
  314. ],
  315. ]);
  316. $response = (new Response())->withAddedHeader('Set-Cookie', 'key=new value');
  317. $new = $collection->addFromResponse($response, $request);
  318. $this->assertTrue($new->has('key'));
  319. $this->assertSame('new value', $new->get('key')->getValue());
  320. }
  321. /**
  322. * Test adding cookies from the collection to request.
  323. */
  324. public function testAddToRequest(): void
  325. {
  326. $collection = new CookieCollection();
  327. $collection = $collection
  328. ->add(new Cookie('default', '1', null, '/', 'example.com'))
  329. ->add(new Cookie('api', 'A', null, '/api', 'example.com'))
  330. ->add(new Cookie('blog', 'b', null, '/blog', 'blog.example.com'))
  331. ->add(new Cookie('expired', 'ex', new DateTime('-2 seconds'), '/', 'example.com'));
  332. $request = new ClientRequest('http://example.com/api');
  333. $request = $collection->addToRequest($request);
  334. $this->assertSame('default=1; api=A', $request->getHeaderLine('Cookie'));
  335. $request = new ClientRequest('http://example.com/');
  336. $request = $collection->addToRequest($request);
  337. $this->assertSame('default=1', $request->getHeaderLine('Cookie'));
  338. $request = new ClientRequest('http://example.com');
  339. $request = $collection->addToRequest($request);
  340. $this->assertSame('default=1', $request->getHeaderLine('Cookie'));
  341. $request = new ClientRequest('http://example.com/blog');
  342. $request = $collection->addToRequest($request);
  343. $this->assertSame('default=1', $request->getHeaderLine('Cookie'), 'domain matching should apply');
  344. $request = new ClientRequest('http://foo.blog.example.com/blog');
  345. $request = $collection->addToRequest($request);
  346. $this->assertSame('default=1; blog=b', $request->getHeaderLine('Cookie'));
  347. }
  348. /**
  349. * Test adding no cookies
  350. */
  351. public function testAddToRequestNoCookies(): void
  352. {
  353. $collection = new CookieCollection();
  354. $request = new ClientRequest('http://example.com/api');
  355. $request = $collection->addToRequest($request);
  356. $this->assertFalse($request->hasHeader('Cookie'), 'No header should be set.');
  357. }
  358. /**
  359. * Testing the cookie size limit warning
  360. */
  361. public function testCookieSizeWarning(): void
  362. {
  363. $this->expectWarningMessageMatches('/The cookie `default` exceeds the recommended maximum cookie length of 4096 bytes.*/', function (): void {
  364. $string = Security::insecureRandomBytes(9000);
  365. $collection = new CookieCollection();
  366. $collection = $collection
  367. ->add(new Cookie('default', $string, null, '/', 'example.com'));
  368. $request = new ClientRequest('http://example.com/api');
  369. $collection->addToRequest($request);
  370. });
  371. }
  372. /**
  373. * Test adding cookies from the collection to request.
  374. */
  375. public function testAddToRequestExtraCookies(): void
  376. {
  377. $collection = new CookieCollection();
  378. $collection = $collection
  379. ->add(new Cookie('api', 'A', null, '/api', 'example.com'))
  380. ->add(new Cookie('blog', 'b', null, '/blog', 'blog.example.com'))
  381. ->add(new Cookie('expired', 'ex', new DateTime('-2 seconds'), '/', 'example.com'));
  382. $request = new ClientRequest('http://example.com/api');
  383. $request = $collection->addToRequest($request, ['b' => 'B']);
  384. $this->assertSame('b=B; api=A', $request->getHeaderLine('Cookie'));
  385. $request = new ClientRequest('http://example.com/api');
  386. $request = $collection->addToRequest($request, ['api' => 'custom']);
  387. $this->assertSame('api=custom', $request->getHeaderLine('Cookie'), 'Extra cookies overwrite values in jar');
  388. }
  389. /**
  390. * Test adding cookies ignores leading dot
  391. */
  392. public function testAddToRequestLeadingDot(): void
  393. {
  394. $collection = new CookieCollection();
  395. $collection = $collection
  396. ->add(new Cookie('public', 'b', null, '/', '.example.com'));
  397. $request = new ClientRequest('http://example.com/blog');
  398. $request = $collection->addToRequest($request);
  399. $this->assertSame('public=b', $request->getHeaderLine('Cookie'));
  400. }
  401. /**
  402. * Test adding cookies checks the secure crumb
  403. */
  404. public function testAddToRequestSecureCrumb(): void
  405. {
  406. $collection = new CookieCollection();
  407. $collection = $collection
  408. ->add(new Cookie('secret', 'A', null, '/', 'example.com', true))
  409. ->add(new Cookie('public', 'b', null, '/', '.example.com', false));
  410. $request = new ClientRequest('https://example.com/api');
  411. $request = $collection->addToRequest($request);
  412. $this->assertSame('secret=A; public=b', $request->getHeaderLine('Cookie'));
  413. // no HTTPS set.
  414. $request = new ClientRequest('http://example.com/api');
  415. $request = $collection->addToRequest($request);
  416. $this->assertSame('public=b', $request->getHeaderLine('Cookie'));
  417. }
  418. /**
  419. * test createFromHeader() building cookies from a header string.
  420. */
  421. public function testCreateFromHeader(): void
  422. {
  423. $header = [
  424. 'http=name; HttpOnly; Secure;',
  425. 'expires=expiring; Expires=Mon, 17-Apr-2023 10:22:22; Path=/api; HttpOnly; Secure;',
  426. 'expired=expired; version=1; Expires=Wed, 15-Jun-2015 10:22:22;',
  427. 'invalid=invalid-secure; Expires=Mon, 17-Apr-2023 10:22:22; Secure=true; SameSite=none',
  428. '7=numeric',
  429. ];
  430. $cookies = CookieCollection::createFromHeader($header);
  431. $this->assertCount(4, $cookies);
  432. $this->assertTrue($cookies->has('http'));
  433. $this->assertTrue($cookies->has('expires'));
  434. $this->assertFalse($cookies->has('version'));
  435. $this->assertTrue($cookies->has('expired'), 'Expired cookies should be present');
  436. $this->assertFalse($cookies->has('invalid'), 'Invalid cookies should not be present');
  437. $this->assertTrue($cookies->has('7'));
  438. }
  439. /**
  440. * test createFromServerRequest() building cookies from a header string.
  441. */
  442. public function testCreateFromServerRequest(): void
  443. {
  444. $request = new ServerRequest([
  445. 'cookies' => [
  446. 'name' => 'val',
  447. 'cakephp' => 'rocks',
  448. '123' => 'a integer key cookie',
  449. ],
  450. ]);
  451. $cookies = CookieCollection::createFromServerRequest($request);
  452. $this->assertCount(3, $cookies);
  453. $this->assertTrue($cookies->has('name'));
  454. $this->assertTrue($cookies->has('cakephp'));
  455. $this->assertTrue($cookies->has('123'));
  456. $cookie = $cookies->get('name');
  457. $this->assertSame('val', $cookie->getValue());
  458. $this->assertSame('/', $cookie->getPath());
  459. $this->assertSame('', $cookie->getDomain(), 'No domain on request cookies');
  460. $cookie = $cookies->get('123');
  461. $this->assertSame('a integer key cookie', $cookie->getValue());
  462. }
  463. }