ErrorHandlerMiddlewareTest.php 13 KB

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