CookieCollectionTest.php 16 KB

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