ErrorHandlerMiddlewareTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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\Error\Middleware;
  17. use Cake\Core\Configure;
  18. use Cake\Datasource\Exception\RecordNotFoundException;
  19. use Cake\Error\ExceptionRendererInterface;
  20. use Cake\Error\ExceptionTrap;
  21. use Cake\Error\Middleware\ErrorHandlerMiddleware;
  22. use Cake\Error\Renderer\WebExceptionRenderer;
  23. use Cake\Event\EventInterface;
  24. use Cake\Event\EventManager;
  25. use Cake\Http\Exception\MissingControllerException;
  26. use Cake\Http\Exception\NotFoundException;
  27. use Cake\Http\Exception\RedirectException;
  28. use Cake\Http\Exception\ServiceUnavailableException;
  29. use Cake\Http\Response;
  30. use Cake\Http\ServerRequestFactory;
  31. use Cake\Log\Log;
  32. use Cake\Routing\Router;
  33. use Cake\TestSuite\TestCase;
  34. use Error;
  35. use LogicException;
  36. use Psr\Http\Message\ResponseInterface;
  37. use Psr\Http\Message\ServerRequestInterface;
  38. use TestApp\Application;
  39. use TestApp\Http\TestRequestHandler;
  40. use Throwable;
  41. /**
  42. * Test for ErrorHandlerMiddleware
  43. */
  44. class ErrorHandlerMiddlewareTest extends TestCase
  45. {
  46. /**
  47. * @var \Cake\Log\Engine\ArrayLog
  48. */
  49. protected $logger;
  50. /**
  51. * setup
  52. */
  53. public function setUp(): void
  54. {
  55. parent::setUp();
  56. static::setAppNamespace();
  57. Log::reset();
  58. Log::setConfig('error_test', [
  59. 'className' => 'Array',
  60. ]);
  61. $this->logger = Log::engine('error_test');
  62. }
  63. /**
  64. * Teardown
  65. */
  66. public function tearDown(): void
  67. {
  68. parent::tearDown();
  69. Log::drop('error_test');
  70. }
  71. /**
  72. * Test returning a response works ok.
  73. */
  74. public function testNoErrorResponse(): void
  75. {
  76. $request = ServerRequestFactory::fromGlobals();
  77. $middleware = new ErrorHandlerMiddleware();
  78. $result = $middleware->process($request, new TestRequestHandler());
  79. $this->assertInstanceOf(Response::class, $result);
  80. $this->assertCount(0, $this->logger->read());
  81. }
  82. /**
  83. * Test using a factory method to make a renderer.
  84. */
  85. public function testRendererFactory(): void
  86. {
  87. $request = ServerRequestFactory::fromGlobals();
  88. $factory = function ($exception) {
  89. $this->assertInstanceOf('LogicException', $exception);
  90. return new class implements ExceptionRendererInterface
  91. {
  92. public function render(): ResponseInterface|string
  93. {
  94. return new Response();
  95. }
  96. public function write(string|ResponseInterface $output): void
  97. {
  98. }
  99. };
  100. };
  101. $middleware = new ErrorHandlerMiddleware(new ExceptionTrap([
  102. 'exceptionRenderer' => $factory,
  103. ]));
  104. $handler = new TestRequestHandler(function (): void {
  105. throw new LogicException('Something bad');
  106. });
  107. $middleware->process($request, $handler);
  108. }
  109. /**
  110. * Test rendering an error page
  111. */
  112. public function testHandleException(): void
  113. {
  114. $request = ServerRequestFactory::fromGlobals();
  115. $middleware = new ErrorHandlerMiddleware();
  116. $handler = new TestRequestHandler(function (): void {
  117. throw new NotFoundException('whoops');
  118. });
  119. $result = $middleware->process($request, $handler);
  120. $this->assertInstanceOf(Response::class, $result);
  121. $this->assertSame(404, $result->getStatusCode());
  122. $this->assertStringContainsString('was not found', '' . $result->getBody());
  123. }
  124. /**
  125. * Test rendering an error page with an exception trap
  126. */
  127. public function testHandleExceptionWithExceptionTrap(): void
  128. {
  129. $request = ServerRequestFactory::fromGlobals();
  130. $middleware = new ErrorHandlerMiddleware(new ExceptionTrap([
  131. 'exceptionRenderer' => WebExceptionRenderer::class,
  132. ]));
  133. $handler = new TestRequestHandler(function (): void {
  134. throw new NotFoundException('whoops');
  135. });
  136. $result = $middleware->process($request, $handler);
  137. $this->assertInstanceOf(Response::class, $result);
  138. $this->assertSame(404, $result->getStatusCode());
  139. $this->assertStringContainsString('was not found', '' . $result->getBody());
  140. }
  141. /**
  142. * Test creating a redirect response
  143. */
  144. public function testHandleRedirectException(): void
  145. {
  146. $request = ServerRequestFactory::fromGlobals();
  147. $middleware = new ErrorHandlerMiddleware();
  148. $handler = new TestRequestHandler(function (): void {
  149. throw new RedirectException('http://example.org/login');
  150. });
  151. $result = $middleware->process($request, $handler);
  152. $this->assertInstanceOf(ResponseInterface::class, $result);
  153. $this->assertSame(302, $result->getStatusCode());
  154. $this->assertEmpty((string)$result->getBody());
  155. $expected = [
  156. 'location' => ['http://example.org/login'],
  157. ];
  158. $this->assertSame($expected, $result->getHeaders());
  159. }
  160. /**
  161. * Test creating a redirect response
  162. */
  163. public function testHandleRedirectExceptionHeaders(): void
  164. {
  165. $request = ServerRequestFactory::fromGlobals();
  166. $middleware = new ErrorHandlerMiddleware();
  167. $handler = new TestRequestHandler(function (): void {
  168. $err = new RedirectException('http://example.org/login', 301, ['Constructor' => 'yes', 'Method' => 'yes']);
  169. throw $err;
  170. });
  171. $result = $middleware->process($request, $handler);
  172. $this->assertInstanceOf(ResponseInterface::class, $result);
  173. $this->assertSame(301, $result->getStatusCode());
  174. $this->assertEmpty('' . $result->getBody());
  175. $expected = [
  176. 'location' => ['http://example.org/login'],
  177. 'Constructor' => ['yes'],
  178. 'Method' => ['yes'],
  179. ];
  180. $this->assertEquals($expected, $result->getHeaders());
  181. }
  182. /**
  183. * Test rendering an error page holds onto the original request.
  184. */
  185. public function testHandleExceptionPreserveRequest(): void
  186. {
  187. $request = ServerRequestFactory::fromGlobals();
  188. $request = $request->withHeader('Accept', 'application/json');
  189. $middleware = new ErrorHandlerMiddleware();
  190. $handler = new TestRequestHandler(function (): void {
  191. throw new NotFoundException('whoops');
  192. });
  193. $result = $middleware->process($request, $handler);
  194. $this->assertInstanceOf(Response::class, $result);
  195. $this->assertSame(404, $result->getStatusCode());
  196. $this->assertStringContainsString('"message": "whoops"', (string)$result->getBody());
  197. $this->assertStringContainsString('application/json', $result->getHeaderLine('Content-type'));
  198. }
  199. /**
  200. * Test handling PHP 7's Error instance.
  201. */
  202. public function testHandlePHP7Error(): void
  203. {
  204. $middleware = new ErrorHandlerMiddleware();
  205. $request = ServerRequestFactory::fromGlobals();
  206. $error = new Error();
  207. $result = $middleware->handleException($error, $request);
  208. $this->assertInstanceOf(Response::class, $result);
  209. }
  210. /**
  211. * Test rendering an error page logs errors
  212. */
  213. public function testHandleExceptionLogAndTrace(): void
  214. {
  215. $request = ServerRequestFactory::fromGlobals([
  216. 'REQUEST_URI' => '/target/url',
  217. 'HTTP_REFERER' => '/other/path',
  218. ]);
  219. $middleware = new ErrorHandlerMiddleware(['log' => true, 'trace' => true]);
  220. $handler = new TestRequestHandler(function (): void {
  221. throw new NotFoundException('Kaboom!');
  222. });
  223. $result = $middleware->process($request, $handler);
  224. $this->assertSame(404, $result->getStatusCode());
  225. $this->assertStringContainsString('was not found', '' . $result->getBody());
  226. $logs = $this->logger->read();
  227. $this->assertCount(1, $logs);
  228. $this->assertStringContainsString('error', $logs[0]);
  229. $this->assertStringContainsString('[Cake\Http\Exception\NotFoundException] Kaboom!', $logs[0]);
  230. $this->assertStringContainsString(
  231. str_replace('/', DS, 'vendor/phpunit/phpunit/src/Framework/TestCase.php'),
  232. $logs[0]
  233. );
  234. $this->assertStringContainsString('Request URL: /target/url', $logs[0]);
  235. $this->assertStringContainsString('Referer URL: /other/path', $logs[0]);
  236. $this->assertStringNotContainsString('Previous:', $logs[0]);
  237. }
  238. /**
  239. * Test rendering an error page logs errors with previous
  240. */
  241. public function testHandleExceptionLogAndTraceWithPrevious(): void
  242. {
  243. $request = ServerRequestFactory::fromGlobals([
  244. 'REQUEST_URI' => '/target/url',
  245. 'HTTP_REFERER' => '/other/path',
  246. ]);
  247. $middleware = new ErrorHandlerMiddleware(['log' => true, 'trace' => true]);
  248. $handler = new TestRequestHandler(function ($req): void {
  249. $previous = new RecordNotFoundException('Previous logged');
  250. throw new NotFoundException('Kaboom!', null, $previous);
  251. });
  252. $result = $middleware->process($request, $handler);
  253. $this->assertSame(404, $result->getStatusCode());
  254. $this->assertStringContainsString('was not found', '' . $result->getBody());
  255. $logs = $this->logger->read();
  256. $this->assertCount(1, $logs);
  257. $this->assertStringContainsString('error', $logs[0]);
  258. $this->assertStringContainsString('[Cake\Http\Exception\NotFoundException] Kaboom!', $logs[0]);
  259. $this->assertStringContainsString(
  260. 'Caused by: [Cake\Datasource\Exception\RecordNotFoundException]',
  261. $logs[0]
  262. );
  263. $this->assertStringContainsString(
  264. str_replace('/', DS, 'vendor/phpunit/phpunit/src/Framework/TestCase.php'),
  265. $logs[0]
  266. );
  267. $this->assertStringContainsString('Request URL: /target/url', $logs[0]);
  268. $this->assertStringContainsString('Referer URL: /other/path', $logs[0]);
  269. }
  270. /**
  271. * Test rendering an error page skips logging for specific classes
  272. */
  273. public function testHandleExceptionSkipLog(): void
  274. {
  275. $request = ServerRequestFactory::fromGlobals();
  276. $middleware = new ErrorHandlerMiddleware([
  277. 'log' => true,
  278. 'skipLog' => [NotFoundException::class],
  279. ]);
  280. $handler = new TestRequestHandler(function (): void {
  281. throw new NotFoundException('Kaboom!');
  282. });
  283. $result = $middleware->process($request, $handler);
  284. $this->assertSame(404, $result->getStatusCode());
  285. $this->assertStringContainsString('was not found', '' . $result->getBody());
  286. $this->assertCount(0, $this->logger->read());
  287. }
  288. /**
  289. * Test rendering an error page logs exception attributes
  290. */
  291. public function testHandleExceptionLogAttributes(): void
  292. {
  293. $request = ServerRequestFactory::fromGlobals();
  294. $middleware = new ErrorHandlerMiddleware(['log' => true]);
  295. $handler = new TestRequestHandler(function (): void {
  296. throw new MissingControllerException(['controller' => 'Articles']);
  297. });
  298. $result = $middleware->process($request, $handler);
  299. $this->assertSame(404, $result->getStatusCode());
  300. $logs = $this->logger->read();
  301. $this->assertStringContainsString(
  302. '[Cake\Http\Exception\MissingControllerException] Controller class `Articles` could not be found.',
  303. $logs[0]
  304. );
  305. $this->assertStringContainsString('Exception Attributes:', $logs[0]);
  306. $this->assertStringContainsString("'controller' => 'Articles'", $logs[0]);
  307. $this->assertStringContainsString('Request URL:', $logs[0]);
  308. }
  309. public function testExceptionBeforeRenderEvent(): void
  310. {
  311. $request = ServerRequestFactory::fromGlobals();
  312. $middleware = new ErrorHandlerMiddleware(new ExceptionTrap([
  313. 'exceptionRenderer' => WebExceptionRenderer::class,
  314. ]));
  315. $handler = new TestRequestHandler(function (): void {
  316. throw new NotFoundException('whoops');
  317. });
  318. EventManager::instance()->on(
  319. 'Exception.beforeRender',
  320. function (EventInterface $event, Throwable $e, ServerRequestInterface $req) {
  321. return 'Response string from event';
  322. }
  323. );
  324. $result = $middleware->process($request, $handler);
  325. $this->assertInstanceOf(Response::class, $result);
  326. $this->assertSame('Response string from event', (string)$result->getBody());
  327. }
  328. /**
  329. * Test handling an error and having rendering fail.
  330. */
  331. public function testHandleExceptionRenderingFails(): void
  332. {
  333. $request = ServerRequestFactory::fromGlobals();
  334. $factory = function () {
  335. return new class implements ExceptionRendererInterface
  336. {
  337. public function render(): ResponseInterface|string
  338. {
  339. throw new LogicException('Rendering failed');
  340. }
  341. public function write(string|ResponseInterface $output): void
  342. {
  343. }
  344. };
  345. };
  346. $middleware = new ErrorHandlerMiddleware(new ExceptionTrap([
  347. 'exceptionRenderer' => $factory,
  348. ]));
  349. $handler = new TestRequestHandler(function (): void {
  350. throw new ServiceUnavailableException('whoops');
  351. });
  352. $response = $middleware->process($request, $handler);
  353. $this->assertSame(500, $response->getStatusCode());
  354. $this->assertSame('An Internal Server Error Occurred', '' . $response->getBody());
  355. }
  356. /**
  357. * Test that the middleware loads routes if not already loaded, which is the
  358. * case when an exception occurs before RoutingMiddleware is run.
  359. *
  360. * @return void
  361. */
  362. public function testRoutesLoading(): void
  363. {
  364. $request = ServerRequestFactory::fromGlobals();
  365. $app = new Application(CONFIG);
  366. $middleware = new ErrorHandlerMiddleware(
  367. new ExceptionTrap([
  368. 'exceptionRenderer' => WebExceptionRenderer::class,
  369. ]),
  370. $app
  371. );
  372. $this->assertSame([], Router::routes());
  373. $middleware->process($request, $app);
  374. $this->assertNotEmpty(Router::routes());
  375. }
  376. /**
  377. * Test exception args are not ignored in php7.4 with debug enabled.
  378. */
  379. public function testExceptionArgs(): void
  380. {
  381. // Force exception_ignore_args to true for test
  382. ini_set('zend.exception_ignore_args', '1');
  383. // Debug disabled
  384. Configure::write('debug', false);
  385. new ErrorHandlerMiddleware();
  386. $this->assertSame('1', ini_get('zend.exception_ignore_args'));
  387. // Debug enabled
  388. Configure::write('debug', true);
  389. new ErrorHandlerMiddleware();
  390. $this->assertSame('0', ini_get('zend.exception_ignore_args'));
  391. }
  392. }