ErrorHandlerMiddlewareTest.php 16 KB

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