ErrorHandlerMiddlewareTest.php 15 KB

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