ErrorHandlerMiddlewareTest.php 14 KB

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