RoutingMiddlewareTest.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.3.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\Routing\Middleware;
  16. use Cake\Cache\Cache;
  17. use Cake\Core\Configure;
  18. use Cake\Routing\Middleware\RoutingMiddleware;
  19. use Cake\Routing\RouteBuilder;
  20. use Cake\Routing\RouteCollection;
  21. use Cake\Routing\Router;
  22. use Cake\TestSuite\TestCase;
  23. use TestApp\Application;
  24. use TestApp\Middleware\DumbMiddleware;
  25. use Zend\Diactoros\Response;
  26. use Zend\Diactoros\ServerRequestFactory;
  27. /**
  28. * Test for RoutingMiddleware
  29. */
  30. class RoutingMiddlewareTest extends TestCase
  31. {
  32. protected $log = [];
  33. /**
  34. * Setup method
  35. *
  36. * @return void
  37. */
  38. public function setUp()
  39. {
  40. parent::setUp();
  41. Router::reload();
  42. Router::connect('/articles', ['controller' => 'Articles', 'action' => 'index']);
  43. $this->log = [];
  44. }
  45. /**
  46. * Test redirect responses from redirect routes
  47. *
  48. * @return void
  49. */
  50. public function testRedirectResponse()
  51. {
  52. Router::scope('/', function ($routes) {
  53. $routes->redirect('/testpath', '/pages');
  54. });
  55. $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/testpath']);
  56. $request = $request->withAttribute('base', '/subdir');
  57. $response = new Response();
  58. $next = function ($req, $res) {
  59. };
  60. $middleware = new RoutingMiddleware();
  61. $response = $middleware($request, $response, $next);
  62. $this->assertEquals(301, $response->getStatusCode());
  63. $this->assertEquals('http://localhost/subdir/pages', $response->getHeaderLine('Location'));
  64. }
  65. /**
  66. * Test redirects with additional headers
  67. *
  68. * @return void
  69. */
  70. public function testRedirectResponseWithHeaders()
  71. {
  72. Router::scope('/', function ($routes) {
  73. $routes->redirect('/testpath', '/pages');
  74. });
  75. $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/testpath']);
  76. $response = new Response('php://memory', 200, ['X-testing' => 'Yes']);
  77. $next = function ($req, $res) {
  78. };
  79. $middleware = new RoutingMiddleware();
  80. $response = $middleware($request, $response, $next);
  81. $this->assertEquals(301, $response->getStatusCode());
  82. $this->assertEquals('http://localhost/pages', $response->getHeaderLine('Location'));
  83. $this->assertEquals('Yes', $response->getHeaderLine('X-testing'));
  84. }
  85. /**
  86. * Test that Router sets parameters
  87. *
  88. * @return void
  89. */
  90. public function testRouterSetParams()
  91. {
  92. $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/articles']);
  93. $response = new Response();
  94. $next = function ($req, $res) {
  95. $expected = [
  96. 'controller' => 'Articles',
  97. 'action' => 'index',
  98. 'plugin' => null,
  99. 'pass' => [],
  100. '_matchedRoute' => '/articles'
  101. ];
  102. $this->assertEquals($expected, $req->getAttribute('params'));
  103. };
  104. $middleware = new RoutingMiddleware();
  105. $middleware($request, $response, $next);
  106. }
  107. /**
  108. * Test routing middleware does wipe off existing params keys.
  109. *
  110. * @return void
  111. */
  112. public function testPreservingExistingParams()
  113. {
  114. $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/articles']);
  115. $request = $request->withAttribute('params', ['_csrfToken' => 'i-am-groot']);
  116. $response = new Response();
  117. $next = function ($req, $res) {
  118. $expected = [
  119. 'controller' => 'Articles',
  120. 'action' => 'index',
  121. 'plugin' => null,
  122. 'pass' => [],
  123. '_matchedRoute' => '/articles',
  124. '_csrfToken' => 'i-am-groot'
  125. ];
  126. $this->assertEquals($expected, $req->getAttribute('params'));
  127. };
  128. $middleware = new RoutingMiddleware();
  129. $middleware($request, $response, $next);
  130. }
  131. /**
  132. * Test middleware invoking hook method
  133. *
  134. * @return void
  135. */
  136. public function testRoutesHookInvokedOnApp()
  137. {
  138. Router::reload();
  139. $this->assertFalse(Router::$initialized, 'Router precondition failed');
  140. $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/app/articles']);
  141. $response = new Response();
  142. $next = function ($req, $res) {
  143. $expected = [
  144. 'controller' => 'Articles',
  145. 'action' => 'index',
  146. 'plugin' => null,
  147. 'pass' => [],
  148. '_matchedRoute' => '/app/articles'
  149. ];
  150. $this->assertEquals($expected, $req->getAttribute('params'));
  151. $this->assertTrue(Router::$initialized, 'Router state should indicate routes loaded');
  152. $this->assertNotEmpty(Router::routes());
  153. $this->assertEquals('/app/articles', Router::routes()[0]->template);
  154. };
  155. $app = new Application(CONFIG);
  156. $middleware = new RoutingMiddleware($app);
  157. $middleware($request, $response, $next);
  158. }
  159. /**
  160. * Test that pluginRoutes hook is called
  161. *
  162. * @return void
  163. */
  164. public function testRoutesHookCallsPluginHook()
  165. {
  166. Router::reload();
  167. $this->assertFalse(Router::$initialized, 'Router precondition failed');
  168. $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/app/articles']);
  169. $response = new Response();
  170. $next = function ($req, $res) {
  171. return $res;
  172. };
  173. $app = $this->getMockBuilder(Application::class)
  174. ->setMethods(['pluginRoutes'])
  175. ->setConstructorArgs([CONFIG])
  176. ->getMock();
  177. $app->expects($this->once())
  178. ->method('pluginRoutes')
  179. ->with($this->isInstanceOf(RouteBuilder::class));
  180. $middleware = new RoutingMiddleware($app);
  181. $middleware($request, $response, $next);
  182. }
  183. /**
  184. * Test that routing is not applied if a controller exists already
  185. *
  186. * @return void
  187. */
  188. public function testRouterNoopOnController()
  189. {
  190. $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/articles']);
  191. $request = $request->withAttribute('params', ['controller' => 'Articles']);
  192. $response = new Response();
  193. $next = function ($req, $res) {
  194. $this->assertEquals(['controller' => 'Articles'], $req->getAttribute('params'));
  195. };
  196. $middleware = new RoutingMiddleware();
  197. $middleware($request, $response, $next);
  198. }
  199. /**
  200. * Test missing routes not being caught.
  201. *
  202. */
  203. public function testMissingRouteNotCaught()
  204. {
  205. $this->expectException(\Cake\Routing\Exception\MissingRouteException::class);
  206. $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/missing']);
  207. $response = new Response();
  208. $next = function ($req, $res) {
  209. };
  210. $middleware = new RoutingMiddleware();
  211. $middleware($request, $response, $next);
  212. }
  213. /**
  214. * Test route with _method being parsed correctly.
  215. *
  216. * @return void
  217. */
  218. public function testFakedRequestMethodParsed()
  219. {
  220. Router::connect('/articles-patch', [
  221. 'controller' => 'Articles',
  222. 'action' => 'index',
  223. '_method' => 'PATCH'
  224. ]);
  225. $request = ServerRequestFactory::fromGlobals(
  226. [
  227. 'REQUEST_METHOD' => 'POST',
  228. 'REQUEST_URI' => '/articles-patch'
  229. ],
  230. null,
  231. ['_method' => 'PATCH']
  232. );
  233. $response = new Response();
  234. $next = function ($req, $res) {
  235. $expected = [
  236. 'controller' => 'Articles',
  237. 'action' => 'index',
  238. '_method' => 'PATCH',
  239. 'plugin' => null,
  240. 'pass' => [],
  241. '_matchedRoute' => '/articles-patch'
  242. ];
  243. $this->assertEquals($expected, $req->getAttribute('params'));
  244. $this->assertEquals('PATCH', $req->getMethod());
  245. };
  246. $middleware = new RoutingMiddleware();
  247. $middleware($request, $response, $next);
  248. }
  249. /**
  250. * Test invoking simple scoped middleware
  251. *
  252. * @return void
  253. */
  254. public function testInvokeScopedMiddleware()
  255. {
  256. Router::scope('/api', function ($routes) {
  257. $routes->registerMiddleware('first', function ($req, $res, $next) {
  258. $this->log[] = 'first';
  259. return $next($req, $res);
  260. });
  261. $routes->registerMiddleware('second', function ($req, $res, $next) {
  262. $this->log[] = 'second';
  263. return $next($req, $res);
  264. });
  265. $routes->registerMiddleware('dumb', DumbMiddleware::class);
  266. // Connect middleware in reverse to test ordering.
  267. $routes->applyMiddleware('second', 'first', 'dumb');
  268. $routes->connect('/ping', ['controller' => 'Pings']);
  269. });
  270. $request = ServerRequestFactory::fromGlobals([
  271. 'REQUEST_METHOD' => 'GET',
  272. 'REQUEST_URI' => '/api/ping'
  273. ]);
  274. $response = new Response();
  275. $next = function ($req, $res) {
  276. $this->log[] = 'last';
  277. return $res;
  278. };
  279. $middleware = new RoutingMiddleware();
  280. $result = $middleware($request, $response, $next);
  281. $this->assertSame($response, $result, 'Should return result');
  282. $this->assertSame(['second', 'first', 'last'], $this->log);
  283. }
  284. /**
  285. * Test control flow in scoped middleware.
  286. *
  287. * Scoped middleware should be able to generate a response
  288. * and abort lower layers.
  289. *
  290. * @return void
  291. */
  292. public function testInvokeScopedMiddlewareReturnResponse()
  293. {
  294. Router::scope('/', function ($routes) {
  295. $routes->registerMiddleware('first', function ($req, $res, $next) {
  296. $this->log[] = 'first';
  297. return $next($req, $res);
  298. });
  299. $routes->registerMiddleware('second', function ($req, $res, $next) {
  300. $this->log[] = 'second';
  301. return $res;
  302. });
  303. $routes->applyMiddleware('first');
  304. $routes->connect('/', ['controller' => 'Home']);
  305. $routes->scope('/api', function ($routes) {
  306. $routes->applyMiddleware('second');
  307. $routes->connect('/articles', ['controller' => 'Articles']);
  308. });
  309. });
  310. $request = ServerRequestFactory::fromGlobals([
  311. 'REQUEST_METHOD' => 'GET',
  312. 'REQUEST_URI' => '/api/articles'
  313. ]);
  314. $response = new Response();
  315. $next = function ($req, $res) {
  316. $this->fail('Should not be invoked as first should be ignored.');
  317. };
  318. $middleware = new RoutingMiddleware();
  319. $result = $middleware($request, $response, $next);
  320. $this->assertSame($response, $result, 'Should return result');
  321. $this->assertSame(['first', 'second'], $this->log);
  322. }
  323. /**
  324. * Test control flow in scoped middleware.
  325. *
  326. * @return void
  327. */
  328. public function testInvokeScopedMiddlewareReturnResponseMainScope()
  329. {
  330. Router::scope('/', function ($routes) {
  331. $routes->registerMiddleware('first', function ($req, $res, $next) {
  332. $this->log[] = 'first';
  333. return $res;
  334. });
  335. $routes->registerMiddleware('second', function ($req, $res, $next) {
  336. $this->log[] = 'second';
  337. return $next($req, $res);
  338. });
  339. $routes->applyMiddleware('first');
  340. $routes->connect('/', ['controller' => 'Home']);
  341. $routes->scope('/api', function ($routes) {
  342. $routes->applyMiddleware('second');
  343. $routes->connect('/articles', ['controller' => 'Articles']);
  344. });
  345. });
  346. $request = ServerRequestFactory::fromGlobals([
  347. 'REQUEST_METHOD' => 'GET',
  348. 'REQUEST_URI' => '/'
  349. ]);
  350. $response = new Response();
  351. $next = function ($req, $res) {
  352. $this->fail('Should not be invoked as second should be ignored.');
  353. };
  354. $middleware = new RoutingMiddleware();
  355. $result = $middleware($request, $response, $next);
  356. $this->assertSame($response, $result, 'Should return result');
  357. $this->assertSame(['first'], $this->log);
  358. }
  359. /**
  360. * Test invoking middleware & scope separation
  361. *
  362. * Re-opening a scope should not inherit middleware declared
  363. * in the first context.
  364. *
  365. * @dataProvider scopedMiddlewareUrlProvider
  366. * @return void
  367. */
  368. public function testInvokeScopedMiddlewareIsolatedScopes($url, $expected)
  369. {
  370. Router::scope('/', function ($routes) {
  371. $routes->registerMiddleware('first', function ($req, $res, $next) {
  372. $this->log[] = 'first';
  373. return $next($req, $res);
  374. });
  375. $routes->registerMiddleware('second', function ($req, $res, $next) {
  376. $this->log[] = 'second';
  377. return $next($req, $res);
  378. });
  379. $routes->scope('/api', function ($routes) {
  380. $routes->applyMiddleware('first');
  381. $routes->connect('/ping', ['controller' => 'Pings']);
  382. });
  383. $routes->scope('/api', function ($routes) {
  384. $routes->applyMiddleware('second');
  385. $routes->connect('/version', ['controller' => 'Version']);
  386. });
  387. });
  388. $request = ServerRequestFactory::fromGlobals([
  389. 'REQUEST_METHOD' => 'GET',
  390. 'REQUEST_URI' => $url
  391. ]);
  392. $response = new Response();
  393. $next = function ($req, $res) {
  394. $this->log[] = 'last';
  395. return $res;
  396. };
  397. $middleware = new RoutingMiddleware();
  398. $result = $middleware($request, $response, $next);
  399. $this->assertSame($response, $result, 'Should return result');
  400. $this->assertSame($expected, $this->log);
  401. }
  402. /**
  403. * Provider for scope isolation test.
  404. *
  405. * @return array
  406. */
  407. public function scopedMiddlewareUrlProvider()
  408. {
  409. return [
  410. ['/api/ping', ['first', 'last']],
  411. ['/api/version', ['second', 'last']],
  412. ];
  413. }
  414. /**
  415. * Test we store route collection in cache.
  416. *
  417. * @return void
  418. */
  419. public function testCacheRoutes()
  420. {
  421. Configure::write('Router.cache', true);
  422. Cache::setConfig('_cake_router_', [
  423. 'engine' => 'File',
  424. 'path' => TMP,
  425. ]);
  426. Router::$initialized = false;
  427. $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/articles']);
  428. $response = new Response();
  429. $next = function ($req, $res) {
  430. $routeCollection = Cache::read('routeCollection', '_cake_router_');
  431. $this->assertInstanceOf(RouteCollection::class, $routeCollection);
  432. return $res;
  433. };
  434. $app = new Application(CONFIG);
  435. $middleware = new RoutingMiddleware($app);
  436. $middleware($request, $response, $next);
  437. Cache::clear(false, '_cake_router_');
  438. Cache::drop('_cake_router_');
  439. }
  440. /**
  441. * Test we don't cache routes if cache is disabled.
  442. *
  443. * @return void
  444. */
  445. public function testCacheNotUsedIfCacheDisabled()
  446. {
  447. Configure::write('Router.cache', true);
  448. Cache::disable();
  449. Cache::setConfig('_cake_router_', [
  450. 'engine' => 'File',
  451. 'path' => TMP,
  452. ]);
  453. Router::$initialized = false;
  454. $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/articles']);
  455. $response = new Response();
  456. $next = function ($req, $res) {
  457. $routeCollection = Cache::read('routeCollection', '_cake_router_');
  458. $this->assertFalse($routeCollection);
  459. return $res;
  460. };
  461. $app = new Application(CONFIG);
  462. $middleware = new RoutingMiddleware($app);
  463. $middleware($request, $response, $next);
  464. Cache::drop('_cake_router_');
  465. Cache::enable();
  466. }
  467. /**
  468. * Test cache name is used
  469. *
  470. * @return void
  471. */
  472. public function testCacheConfigNotFound()
  473. {
  474. $this->expectException(\InvalidArgumentException::class);
  475. $this->expectExceptionMessage('The "notfound" cache configuration does not exist');
  476. Configure::write('Router.cache', true);
  477. Configure::write('Router.cacheConfig', 'notfound');
  478. Cache::setConfig('_cake_router_', [
  479. 'engine' => 'File',
  480. 'path' => TMP,
  481. ]);
  482. Router::$initialized = false;
  483. $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/articles']);
  484. $response = new Response();
  485. $next = function ($req, $res) {
  486. return $res;
  487. };
  488. $app = new Application(CONFIG);
  489. $middleware = new RoutingMiddleware($app);
  490. $middleware($request, $response, $next);
  491. Cache::drop('_cake_router_');
  492. }
  493. }