ErrorHandlerMiddlewareTest.php 13 KB

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