ErrorHandlerMiddlewareTest.php 13 KB

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