CookieCollectionTest.php 18 KB

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