CookieCollectionTest.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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\Client\Response as ClientResponse;
  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 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. * @expectedException \InvalidArgumentException
  163. * @expectedExceptionMessage Expected `Cake\Http\Cookie\CookieCollection[]` as $cookies but instead got `array` at index 1
  164. * @return void
  165. */
  166. public function testConstructorWithInvalidCookieObjects()
  167. {
  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, 09-Jun-2021 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. '2021-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. * @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 expired cookies
  238. *
  239. * @return void
  240. */
  241. public function testAddFromResponseIgnoreExpired()
  242. {
  243. $collection = new CookieCollection();
  244. $request = new ServerRequest([
  245. 'url' => '/app'
  246. ]);
  247. $response = (new Response())
  248. ->withAddedHeader('Set-Cookie', 'test=value')
  249. ->withAddedHeader('Set-Cookie', 'expired=soon; Expires=Wed, 09-Jun-2012 10:18:14 GMT; Path=/;');
  250. $new = $collection->addFromResponse($response, $request);
  251. $this->assertFalse($new->has('expired'), 'Should drop expired cookies');
  252. }
  253. /**
  254. * Test adding cookies from a response removes existing cookies if
  255. * the new response marks them as expired.
  256. *
  257. * @return void
  258. */
  259. public function testAddFromResponseRemoveExpired()
  260. {
  261. $collection = new CookieCollection([
  262. new Cookie('expired', 'not yet', null, '/', 'example.com')
  263. ]);
  264. $request = new ServerRequest([
  265. 'url' => '/app',
  266. 'environment' => [
  267. 'HTTP_HOST' => 'example.com'
  268. ]
  269. ]);
  270. $response = (new Response())
  271. ->withAddedHeader('Set-Cookie', 'test=value')
  272. ->withAddedHeader('Set-Cookie', 'expired=soon; Expires=Wed, 09-Jun-2012 10:18:14 GMT; Path=/;');
  273. $new = $collection->addFromResponse($response, $request);
  274. $this->assertFalse($new->has('expired'), 'Should drop expired cookies');
  275. }
  276. /**
  277. * Test adding cookies from responses updates cookie values.
  278. *
  279. * @return void
  280. */
  281. public function testAddFromResponseUpdateExisting()
  282. {
  283. $collection = new CookieCollection([
  284. new Cookie('key', 'old value', null, '/', 'example.com')
  285. ]);
  286. $request = new ServerRequest([
  287. 'url' => '/',
  288. 'environment' => [
  289. 'HTTP_HOST' => 'example.com'
  290. ]
  291. ]);
  292. $response = (new Response())->withAddedHeader('Set-Cookie', 'key=new value');
  293. $new = $collection->addFromResponse($response, $request);
  294. $this->assertTrue($new->has('key'));
  295. $this->assertSame('new value', $new->get('key')->getValue());
  296. }
  297. /**
  298. * Test adding cookies from the collection to request.
  299. *
  300. * @return void
  301. */
  302. public function testAddToRequest()
  303. {
  304. $collection = new CookieCollection();
  305. $collection = $collection
  306. ->add(new Cookie('api', 'A', null, '/api', 'example.com'))
  307. ->add(new Cookie('blog', 'b', null, '/blog', 'blog.example.com'))
  308. ->add(new Cookie('expired', 'ex', new DateTime('-2 seconds'), '/', 'example.com'));
  309. $request = new ClientRequest('http://example.com/api');
  310. $request = $collection->addToRequest($request);
  311. $this->assertSame('api=A', $request->getHeaderLine('Cookie'));
  312. $request = new ClientRequest('http://example.com/');
  313. $request = $collection->addToRequest($request);
  314. $this->assertSame('', $request->getHeaderLine(''));
  315. $request = new ClientRequest('http://example.com/blog');
  316. $request = $collection->addToRequest($request);
  317. $this->assertSame('', $request->getHeaderLine('Cookie'), 'domain matching should apply');
  318. $request = new ClientRequest('http://foo.blog.example.com/blog');
  319. $request = $collection->addToRequest($request);
  320. $this->assertSame('blog=b', $request->getHeaderLine('Cookie'));
  321. }
  322. /**
  323. * Test adding no cookies
  324. *
  325. * @return void
  326. */
  327. public function testAddToRequestNoCookies()
  328. {
  329. $collection = new CookieCollection();
  330. $request = new ClientRequest('http://example.com/api');
  331. $request = $collection->addToRequest($request);
  332. $this->assertFalse($request->hasHeader('Cookie'), 'No header should be set.');
  333. }
  334. /**
  335. * Test adding cookies from the collection to request.
  336. *
  337. * @return void
  338. */
  339. public function testAddToRequestExtraCookies()
  340. {
  341. $collection = new CookieCollection();
  342. $collection = $collection
  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, ['b' => 'B']);
  348. $this->assertSame('api=A; b=B', $request->getHeaderLine('Cookie'));
  349. $request = new ClientRequest('http://example.com/api');
  350. $request = $collection->addToRequest($request, ['api' => 'custom']);
  351. $this->assertSame('api=custom', $request->getHeaderLine('Cookie'), 'Extra cookies overwrite values in jar');
  352. }
  353. /**
  354. * Test adding cookies ignores leading dot
  355. *
  356. * @return void
  357. */
  358. public function testAddToRequestLeadingDot()
  359. {
  360. $collection = new CookieCollection();
  361. $collection = $collection
  362. ->add(new Cookie('public', 'b', null, '/', '.example.com'));
  363. $request = new ClientRequest('http://example.com/blog');
  364. $request = $collection->addToRequest($request);
  365. $this->assertSame('public=b', $request->getHeaderLine('Cookie'));
  366. }
  367. /**
  368. * Test adding cookies checks the secure crumb
  369. *
  370. * @return void
  371. */
  372. public function testAddToRequestSecureCrumb()
  373. {
  374. $collection = new CookieCollection();
  375. $collection = $collection
  376. ->add(new Cookie('secret', 'A', null, '/', 'example.com', true))
  377. ->add(new Cookie('public', 'b', null, '/', '.example.com', false));
  378. $request = new ClientRequest('https://example.com/api');
  379. $request = $collection->addToRequest($request);
  380. $this->assertSame('secret=A; public=b', $request->getHeaderLine('Cookie'));
  381. // no HTTPS set.
  382. $request = new ClientRequest('http://example.com/api');
  383. $request = $collection->addToRequest($request);
  384. $this->assertSame('public=b', $request->getHeaderLine('Cookie'));
  385. }
  386. /**
  387. * test createFromHeader() building cookies from a header string.
  388. *
  389. * @return void
  390. */
  391. public function testCreateFromHeader()
  392. {
  393. $header = [
  394. 'http=name; HttpOnly; Secure;',
  395. 'expires=expiring; Expires=Wed, 15-Jun-2022 10:22:22; Path=/api; HttpOnly; Secure;',
  396. 'expired=expired; version=1; Expires=Wed, 15-Jun-2015 10:22:22;',
  397. ];
  398. $cookies = CookieCollection::createFromHeader($header);
  399. $this->assertCount(3, $cookies);
  400. $this->assertTrue($cookies->has('http'));
  401. $this->assertTrue($cookies->has('expires'));
  402. $this->assertFalse($cookies->has('version'));
  403. $this->assertTrue($cookies->has('expired'), 'Expired cookies should be present');
  404. }
  405. /**
  406. * test createFromServerRequest() building cookies from a header string.
  407. *
  408. * @return void
  409. */
  410. public function testCreateFromServerRequest()
  411. {
  412. $request = new ServerRequest(['cookies' => ['name' => 'val', 'cakephp' => 'rocks']]);
  413. $cookies = CookieCollection::createFromServerRequest($request);
  414. $this->assertCount(2, $cookies);
  415. $this->assertTrue($cookies->has('name'));
  416. $this->assertTrue($cookies->has('cakephp'));
  417. $cookie = $cookies->get('name');
  418. $this->assertSame('val', $cookie->getValue());
  419. $this->assertSame('', $cookie->getPath(), 'No path on request cookies');
  420. $this->assertSame('', $cookie->getDomain(), 'No domain on request cookies');
  421. }
  422. }