RoutingMiddlewareTest.php 20 KB

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