NormalizerFormatterTest.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Monolog\Formatter;
  11. use Monolog\Test\TestCase;
  12. use Monolog\Level;
  13. /**
  14. * @covers Monolog\Formatter\NormalizerFormatter
  15. */
  16. class NormalizerFormatterTest extends TestCase
  17. {
  18. public function testFormat()
  19. {
  20. $formatter = new NormalizerFormatter('Y-m-d');
  21. $formatted = $formatter->format($this->getRecord(
  22. Level::Error,
  23. 'foo',
  24. channel: 'meh',
  25. extra: ['foo' => new TestFooNorm, 'bar' => new TestBarNorm, 'baz' => [], 'res' => fopen('php://memory', 'rb')],
  26. context: [
  27. 'foo' => 'bar',
  28. 'baz' => 'qux',
  29. 'inf' => INF,
  30. '-inf' => -INF,
  31. 'nan' => acos(4),
  32. ],
  33. ));
  34. $this->assertEquals([
  35. 'level_name' => Level::Error->getName(),
  36. 'level' => Level::Error->value,
  37. 'channel' => 'meh',
  38. 'message' => 'foo',
  39. 'datetime' => date('Y-m-d'),
  40. 'extra' => [
  41. 'foo' => ['Monolog\\Formatter\\TestFooNorm' => ["foo" => "fooValue"]],
  42. 'bar' => ['Monolog\\Formatter\\TestBarNorm' => 'bar'],
  43. 'baz' => [],
  44. 'res' => '[resource(stream)]',
  45. ],
  46. 'context' => [
  47. 'foo' => 'bar',
  48. 'baz' => 'qux',
  49. 'inf' => 'INF',
  50. '-inf' => '-INF',
  51. 'nan' => 'NaN',
  52. ],
  53. ], $formatted);
  54. }
  55. public function testFormatExceptions()
  56. {
  57. $formatter = new NormalizerFormatter('Y-m-d');
  58. $e = new \LogicException('bar');
  59. $e2 = new \RuntimeException('foo', 0, $e);
  60. $formatted = $formatter->normalizeValue([
  61. 'exception' => $e2,
  62. ]);
  63. $this->assertGreaterThan(5, count($formatted['exception']['trace']));
  64. $this->assertTrue(isset($formatted['exception']['previous']));
  65. unset($formatted['exception']['trace'], $formatted['exception']['previous']);
  66. $this->assertEquals([
  67. 'exception' => [
  68. 'class' => get_class($e2),
  69. 'message' => $e2->getMessage(),
  70. 'code' => $e2->getCode(),
  71. 'file' => $e2->getFile().':'.$e2->getLine(),
  72. ],
  73. ], $formatted);
  74. }
  75. public function testFormatSoapFaultException()
  76. {
  77. if (!class_exists('SoapFault')) {
  78. $this->markTestSkipped('Requires the soap extension');
  79. }
  80. $formatter = new NormalizerFormatter('Y-m-d');
  81. $e = new \SoapFault('foo', 'bar', 'hello', 'world');
  82. $formatted = $formatter->normalizeValue([
  83. 'exception' => $e,
  84. ]);
  85. unset($formatted['exception']['trace']);
  86. $this->assertEquals([
  87. 'exception' => [
  88. 'class' => 'SoapFault',
  89. 'message' => 'bar',
  90. 'code' => 0,
  91. 'file' => $e->getFile().':'.$e->getLine(),
  92. 'faultcode' => 'foo',
  93. 'faultactor' => 'hello',
  94. 'detail' => 'world',
  95. ],
  96. ], $formatted);
  97. $formatter = new NormalizerFormatter('Y-m-d');
  98. $e = new \SoapFault('foo', 'bar', 'hello', (object) ['bar' => (object) ['biz' => 'baz'], 'foo' => 'world']);
  99. $formatted = $formatter->normalizeValue([
  100. 'exception' => $e,
  101. ]);
  102. unset($formatted['exception']['trace']);
  103. $this->assertEquals([
  104. 'exception' => [
  105. 'class' => 'SoapFault',
  106. 'message' => 'bar',
  107. 'code' => 0,
  108. 'file' => $e->getFile().':'.$e->getLine(),
  109. 'faultcode' => 'foo',
  110. 'faultactor' => 'hello',
  111. 'detail' => '{"bar":{"biz":"baz"},"foo":"world"}',
  112. ],
  113. ], $formatted);
  114. }
  115. public function testFormatToStringExceptionHandle()
  116. {
  117. $formatter = new NormalizerFormatter('Y-m-d');
  118. $this->expectException('RuntimeException');
  119. $this->expectExceptionMessage('Could not convert to string');
  120. $formatter->format($this->getRecord(context: [
  121. 'myObject' => new TestToStringError(),
  122. ]));
  123. }
  124. public function testBatchFormat()
  125. {
  126. $formatter = new NormalizerFormatter('Y-m-d');
  127. $formatted = $formatter->formatBatch([
  128. $this->getRecord(Level::Critical, 'bar', channel: 'test'),
  129. $this->getRecord(Level::Warning, 'foo', channel: 'log'),
  130. ]);
  131. $this->assertEquals([
  132. [
  133. 'level_name' => Level::Critical->getName(),
  134. 'level' => Level::Critical->value,
  135. 'channel' => 'test',
  136. 'message' => 'bar',
  137. 'context' => [],
  138. 'datetime' => date('Y-m-d'),
  139. 'extra' => [],
  140. ],
  141. [
  142. 'level_name' => Level::Warning->getName(),
  143. 'level' => Level::Warning->value,
  144. 'channel' => 'log',
  145. 'message' => 'foo',
  146. 'context' => [],
  147. 'datetime' => date('Y-m-d'),
  148. 'extra' => [],
  149. ],
  150. ], $formatted);
  151. }
  152. /**
  153. * Test issue #137
  154. */
  155. public function testIgnoresRecursiveObjectReferences()
  156. {
  157. // set up the recursion
  158. $foo = new \stdClass();
  159. $bar = new \stdClass();
  160. $foo->bar = $bar;
  161. $bar->foo = $foo;
  162. // set an error handler to assert that the error is not raised anymore
  163. $that = $this;
  164. set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
  165. if (error_reporting() & $level) {
  166. restore_error_handler();
  167. $that->fail("$message should not be raised");
  168. }
  169. return true;
  170. });
  171. $formatter = new NormalizerFormatter();
  172. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  173. $reflMethod->setAccessible(true);
  174. $res = $reflMethod->invoke($formatter, [$foo, $bar], true);
  175. restore_error_handler();
  176. $this->assertEquals('[{"bar":{"foo":null}},{"foo":{"bar":null}}]', $res);
  177. }
  178. public function testCanNormalizeReferences()
  179. {
  180. $formatter = new NormalizerFormatter();
  181. $x = ['foo' => 'bar'];
  182. $y = ['x' => &$x];
  183. $x['y'] = &$y;
  184. $formatter->normalizeValue($y);
  185. }
  186. public function testToJsonIgnoresInvalidTypes()
  187. {
  188. // set up the invalid data
  189. $resource = fopen(__FILE__, 'r');
  190. // set an error handler to assert that the error is not raised anymore
  191. $that = $this;
  192. set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
  193. if (error_reporting() & $level) {
  194. restore_error_handler();
  195. $that->fail("$message should not be raised");
  196. }
  197. return true;
  198. });
  199. $formatter = new NormalizerFormatter();
  200. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  201. $reflMethod->setAccessible(true);
  202. $res = $reflMethod->invoke($formatter, [$resource], true);
  203. restore_error_handler();
  204. $this->assertEquals('[null]', $res);
  205. }
  206. public function testNormalizeHandleLargeArraysWithExactly1000Items()
  207. {
  208. $formatter = new NormalizerFormatter();
  209. $largeArray = range(1, 1000);
  210. $res = $formatter->format($this->getRecord(
  211. Level::Critical,
  212. 'bar',
  213. channel: 'test',
  214. context: [$largeArray],
  215. ));
  216. $this->assertCount(1000, $res['context'][0]);
  217. $this->assertArrayNotHasKey('...', $res['context'][0]);
  218. }
  219. public function testNormalizeHandleLargeArrays()
  220. {
  221. $formatter = new NormalizerFormatter();
  222. $largeArray = range(1, 2000);
  223. $res = $formatter->format($this->getRecord(
  224. Level::Critical,
  225. 'bar',
  226. channel: 'test',
  227. context: [$largeArray],
  228. ));
  229. $this->assertCount(1001, $res['context'][0]);
  230. $this->assertEquals('Over 1000 items (2000 total), aborting normalization', $res['context'][0]['...']);
  231. }
  232. public function testIgnoresInvalidEncoding()
  233. {
  234. $formatter = new NormalizerFormatter();
  235. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  236. $reflMethod->setAccessible(true);
  237. // send an invalid unicode sequence as a object that can't be cleaned
  238. $record = new \stdClass;
  239. $record->message = "\xB1\x31";
  240. $this->assertsame('{"message":"�1"}', $reflMethod->invoke($formatter, $record));
  241. }
  242. public function testConvertsInvalidEncodingAsLatin9()
  243. {
  244. $formatter = new NormalizerFormatter();
  245. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  246. $reflMethod->setAccessible(true);
  247. $res = $reflMethod->invoke($formatter, ['message' => "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE"]);
  248. $this->assertSame('{"message":"��������"}', $res);
  249. }
  250. public function testMaxNormalizeDepth()
  251. {
  252. $formatter = new NormalizerFormatter();
  253. $formatter->setMaxNormalizeDepth(1);
  254. $throwable = new \Error('Foo');
  255. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  256. $this->assertEquals(
  257. 'Over 1 levels deep, aborting normalization',
  258. $message['context']['exception']
  259. );
  260. }
  261. public function testMaxNormalizeItemCountWith0ItemsMax()
  262. {
  263. $formatter = new NormalizerFormatter();
  264. $formatter->setMaxNormalizeDepth(9);
  265. $formatter->setMaxNormalizeItemCount(0);
  266. $throwable = new \Error('Foo');
  267. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  268. $this->assertEquals(
  269. ["..." => "Over 0 items (7 total), aborting normalization"],
  270. $message
  271. );
  272. }
  273. public function testMaxNormalizeItemCountWith2ItemsMax()
  274. {
  275. $formatter = new NormalizerFormatter();
  276. $formatter->setMaxNormalizeDepth(9);
  277. $formatter->setMaxNormalizeItemCount(2);
  278. $throwable = new \Error('Foo');
  279. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  280. unset($message['context']['exception']['trace']);
  281. unset($message['context']['exception']['file']);
  282. $this->assertEquals(
  283. [
  284. "message" => "foobar",
  285. "context" => ['exception' => [
  286. 'class' => 'Error',
  287. 'message' => 'Foo',
  288. 'code' => 0,
  289. ]],
  290. "..." => "Over 2 items (7 total), aborting normalization",
  291. ],
  292. $message
  293. );
  294. }
  295. public function testExceptionTraceWithArgs()
  296. {
  297. try {
  298. // This will contain $resource and $wrappedResource as arguments in the trace item
  299. $resource = fopen('php://memory', 'rw+');
  300. fwrite($resource, 'test_resource');
  301. $wrappedResource = new TestFooNorm;
  302. $wrappedResource->foo = $resource;
  303. // Just do something stupid with a resource/wrapped resource as argument
  304. $arr = [$wrappedResource, $resource];
  305. // modifying the array inside throws a "usort(): Array was modified by the user comparison function"
  306. usort($arr, function ($a, $b) {
  307. throw new \ErrorException('Foo');
  308. });
  309. } catch (\Throwable $e) {
  310. }
  311. $formatter = new NormalizerFormatter();
  312. $record = $this->getRecord(context: ['exception' => $e]);
  313. $result = $formatter->format($record);
  314. // See https://github.com/php/php-src/issues/8810 fixed in PHP 8.2
  315. $offset = PHP_VERSION_ID >= 80200 ? 13 : 11;
  316. $this->assertSame(
  317. __FILE__.':'.(__LINE__ - $offset),
  318. $result['context']['exception']['trace'][0]
  319. );
  320. }
  321. private function formatRecordWithExceptionInContext(NormalizerFormatter $formatter, \Throwable $exception): array
  322. {
  323. $message = $formatter->format($this->getRecord(
  324. Level::Critical,
  325. 'foobar',
  326. channel: 'core',
  327. context: ['exception' => $exception],
  328. ));
  329. return $message;
  330. }
  331. public function testExceptionTraceDoesNotLeakCallUserFuncArgs()
  332. {
  333. try {
  334. $arg = new TestInfoLeak;
  335. call_user_func([$this, 'throwHelper'], $arg, $dt = new \DateTime());
  336. } catch (\Exception $e) {
  337. }
  338. $formatter = new NormalizerFormatter();
  339. $record = $this->getRecord(context: ['exception' => $e]);
  340. $result = $formatter->format($record);
  341. $this->assertSame(
  342. __FILE__ .':'.(__LINE__-9),
  343. $result['context']['exception']['trace'][0]
  344. );
  345. }
  346. private function throwHelper($arg)
  347. {
  348. throw new \RuntimeException('Thrown');
  349. }
  350. }
  351. class TestFooNorm
  352. {
  353. public $foo = 'fooValue';
  354. }
  355. class TestBarNorm
  356. {
  357. public function __toString()
  358. {
  359. return 'bar';
  360. }
  361. }
  362. class TestStreamFoo
  363. {
  364. public $foo;
  365. public $resource;
  366. public function __construct($resource)
  367. {
  368. $this->resource = $resource;
  369. $this->foo = 'BAR';
  370. }
  371. public function __toString()
  372. {
  373. fseek($this->resource, 0);
  374. return $this->foo . ' - ' . (string) stream_get_contents($this->resource);
  375. }
  376. }
  377. class TestToStringError
  378. {
  379. public function __toString()
  380. {
  381. throw new \RuntimeException('Could not convert to string');
  382. }
  383. }
  384. class TestInfoLeak
  385. {
  386. public function __toString()
  387. {
  388. return 'Sensitive information';
  389. }
  390. }