CookieCollectionTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. $new = $collection->addFromResponse($response, $request);
  190. $this->assertNotSame($new, $collection, 'Should clone collection');
  191. $this->assertTrue($new->has('test'));
  192. $this->assertTrue($new->has('session'));
  193. $this->assertTrue($new->has('expiring'));
  194. $this->assertSame('value', $new->get('test')->getValue());
  195. $this->assertSame('123abc', $new->get('session')->getValue());
  196. $this->assertSame('soon', $new->get('expiring')->getValue());
  197. $this->assertSame('/app', $new->get('test')->getPath(), 'cookies should inherit request path');
  198. $this->assertSame('/', $new->get('expiring')->getPath(), 'path attribute should be used.');
  199. $this->assertSame(0, $new->get('test')->getExpiry(), 'No expiry');
  200. $this->assertSame(
  201. '2021-06-09 10:18:14',
  202. date('Y-m-d H:i:s', $new->get('expiring')->getExpiry()),
  203. 'Has expiry'
  204. );
  205. $session = $new->get('session');
  206. $this->assertSame(0, $session->getExpiry(), 'No expiry');
  207. $this->assertSame('www.example.com', $session->getDomain(), 'Has domain');
  208. }
  209. /**
  210. * Test adding cookies that contain URL encoded data
  211. *
  212. * @return void
  213. */
  214. public function testAddFromResponseValueUrldecodeData()
  215. {
  216. $collection = new CookieCollection();
  217. $request = new ServerRequest([
  218. 'url' => '/app'
  219. ]);
  220. $response = (new Response())
  221. ->withAddedHeader('Set-Cookie', 'test=val%3Bue; Path=/example; Secure;');
  222. $new = $collection->addFromResponse($response, $request);
  223. $this->assertTrue($new->has('test'));
  224. $test = $new->get('test');
  225. $this->assertSame('val;ue', $test->getValue());
  226. $this->assertSame('/example', $test->getPath());
  227. }
  228. /**
  229. * Test adding cookies from a response ignores expired cookies
  230. *
  231. * @return void
  232. */
  233. public function testAddFromResponseIgnoreExpired()
  234. {
  235. $collection = new CookieCollection();
  236. $request = new ServerRequest([
  237. 'url' => '/app'
  238. ]);
  239. $response = (new Response())
  240. ->withAddedHeader('Set-Cookie', 'test=value')
  241. ->withAddedHeader('Set-Cookie', 'expired=soon; Expires=Wed, 09-Jun-2012 10:18:14 GMT; Path=/;');
  242. $new = $collection->addFromResponse($response, $request);
  243. $this->assertFalse($new->has('expired'), 'Should drop expired cookies');
  244. }
  245. /**
  246. * Test adding cookies from a response removes existing cookies if
  247. * the new response marks them as expired.
  248. *
  249. * @return void
  250. */
  251. public function testAddFromResponseRemoveExpired()
  252. {
  253. $collection = new CookieCollection([
  254. new Cookie('expired', 'not yet', null, '/', 'example.com')
  255. ]);
  256. $request = new ServerRequest([
  257. 'url' => '/app',
  258. 'environment' => [
  259. 'HTTP_HOST' => 'example.com'
  260. ]
  261. ]);
  262. $response = (new Response())
  263. ->withAddedHeader('Set-Cookie', 'test=value')
  264. ->withAddedHeader('Set-Cookie', 'expired=soon; Expires=Wed, 09-Jun-2012 10:18:14 GMT; Path=/;');
  265. $new = $collection->addFromResponse($response, $request);
  266. $this->assertFalse($new->has('expired'), 'Should drop expired cookies');
  267. }
  268. /**
  269. * Test adding cookies from responses updates cookie values.
  270. *
  271. * @return void
  272. */
  273. public function testAddFromResponseUpdateExisting()
  274. {
  275. $collection = new CookieCollection([
  276. new Cookie('key', 'old value', null, '/', 'example.com')
  277. ]);
  278. $request = new ServerRequest([
  279. 'url' => '/',
  280. 'environment' => [
  281. 'HTTP_HOST' => 'example.com'
  282. ]
  283. ]);
  284. $response = (new Response())->withAddedHeader('Set-Cookie', 'key=new value');
  285. $new = $collection->addFromResponse($response, $request);
  286. $this->assertTrue($new->has('key'));
  287. $this->assertSame('new value', $new->get('key')->getValue());
  288. }
  289. /**
  290. * Test adding cookies from the collection to request.
  291. *
  292. * @return void
  293. */
  294. public function testAddToRequest()
  295. {
  296. $collection = new CookieCollection();
  297. $collection = $collection
  298. ->add(new Cookie('api', 'A', null, '/api', 'example.com'))
  299. ->add(new Cookie('blog', 'b', null, '/blog', 'blog.example.com'))
  300. ->add(new Cookie('expired', 'ex', new DateTime('-2 seconds'), '/', 'example.com'));
  301. $request = new ClientRequest('http://example.com/api');
  302. $request = $collection->addToRequest($request);
  303. $this->assertSame('api=A', $request->getHeaderLine('Cookie'));
  304. $request = new ClientRequest('http://example.com/');
  305. $request = $collection->addToRequest($request);
  306. $this->assertSame('', $request->getHeaderLine(''));
  307. $request = new ClientRequest('http://example.com/blog');
  308. $request = $collection->addToRequest($request);
  309. $this->assertSame('', $request->getHeaderLine('Cookie'), 'domain matching should apply');
  310. $request = new ClientRequest('http://foo.blog.example.com/blog');
  311. $request = $collection->addToRequest($request);
  312. $this->assertSame('blog=b', $request->getHeaderLine('Cookie'));
  313. }
  314. /**
  315. * Test adding cookies from the collection to request.
  316. *
  317. * @return void
  318. */
  319. public function testAddToRequestExtraCookies()
  320. {
  321. $collection = new CookieCollection();
  322. $collection = $collection
  323. ->add(new Cookie('api', 'A', null, '/api', 'example.com'))
  324. ->add(new Cookie('blog', 'b', null, '/blog', 'blog.example.com'))
  325. ->add(new Cookie('expired', 'ex', new DateTime('-2 seconds'), '/', 'example.com'));
  326. $request = new ClientRequest('http://example.com/api');
  327. $request = $collection->addToRequest($request, ['b' => 'B']);
  328. $this->assertSame('api=A; b=B', $request->getHeaderLine('Cookie'));
  329. $request = new ClientRequest('http://example.com/api');
  330. $request = $collection->addToRequest($request, ['api' => 'custom']);
  331. $this->assertSame('api=custom', $request->getHeaderLine('Cookie'), 'Extra cookies overwrite values in jar');
  332. }
  333. /**
  334. * Test adding cookies ignores leading dot
  335. *
  336. * @return void
  337. */
  338. public function testAddToRequestLeadingDot()
  339. {
  340. $collection = new CookieCollection();
  341. $collection = $collection
  342. ->add(new Cookie('public', 'b', null, '/', '.example.com'));
  343. $request = new ClientRequest('http://example.com/blog');
  344. $request = $collection->addToRequest($request);
  345. $this->assertSame('public=b', $request->getHeaderLine('Cookie'));
  346. }
  347. /**
  348. * Test adding cookies checks the secure crumb
  349. *
  350. * @return void
  351. */
  352. public function testAddToRequestSecureCrumb()
  353. {
  354. $collection = new CookieCollection();
  355. $collection = $collection
  356. ->add(new Cookie('secret', 'A', null, '/', 'example.com', true))
  357. ->add(new Cookie('public', 'b', null, '/', '.example.com', false));
  358. $request = new ClientRequest('https://example.com/api');
  359. $request = $collection->addToRequest($request);
  360. $this->assertSame('secret=A; public=b', $request->getHeaderLine('Cookie'));
  361. // no HTTPS set.
  362. $request = new ClientRequest('http://example.com/api');
  363. $request = $collection->addToRequest($request);
  364. $this->assertSame('public=b', $request->getHeaderLine('Cookie'));
  365. }
  366. /**
  367. * test createFromHeader() building cookies from a header string.
  368. *
  369. * @return void
  370. */
  371. public function testCreateFromHeader()
  372. {
  373. $header = [
  374. 'http=name; HttpOnly; Secure;',
  375. 'expires=expiring; Expires=Wed, 15-Jun-2022 10:22:22; Path=/api; HttpOnly; Secure;',
  376. 'expired=expired; Expires=Wed, 15-Jun-2015 10:22:22;',
  377. ];
  378. $cookies = CookieCollection::createFromHeader($header);
  379. $this->assertCount(3, $cookies);
  380. $this->assertTrue($cookies->has('http'));
  381. $this->assertTrue($cookies->has('expires'));
  382. $this->assertTrue($cookies->has('expired'), 'Expired cookies should be present');
  383. }
  384. /**
  385. * test createFromServerRequest() building cookies from a header string.
  386. *
  387. * @return void
  388. */
  389. public function testCreateFromServerRequest()
  390. {
  391. $request = new ServerRequest(['cookies' => ['name' => 'val', 'cakephp' => 'rocks']]);
  392. $cookies = CookieCollection::createFromServerRequest($request);
  393. $this->assertCount(2, $cookies);
  394. $this->assertTrue($cookies->has('name'));
  395. $this->assertTrue($cookies->has('cakephp'));
  396. $cookie = $cookies->get('name');
  397. $this->assertSame('val', $cookie->getValue());
  398. $this->assertSame('', $cookie->getPath(), 'No path on request cookies');
  399. $this->assertSame('', $cookie->getDomain(), 'No domain on request cookies');
  400. }
  401. }