NormalizerFormatterTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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 testFormatExceptionWithBasePath(): void
  76. {
  77. $formatter = new NormalizerFormatter('Y-m-d');
  78. $formatter->setBasePath(\dirname(\dirname(\dirname(__DIR__))));
  79. $e = new \LogicException('bar');
  80. $formatted = $formatter->normalizeValue([
  81. 'exception' => $e,
  82. ]);
  83. self::assertSame('tests/Monolog/Formatter/NormalizerFormatterTest.php:' . (__LINE__ - 5), $formatted['exception']['file']);
  84. self::assertStringStartsWith('vendor/phpunit/phpunit/src/Framework/TestCase.php:', $formatted['exception']['trace'][0]);
  85. self::assertStringStartsWith('vendor/phpunit/phpunit/src/Framework/TestCase.php:', $formatted['exception']['trace'][1]);
  86. }
  87. public function testFormatSoapFaultException()
  88. {
  89. if (!class_exists('SoapFault')) {
  90. $this->markTestSkipped('Requires the soap extension');
  91. }
  92. $formatter = new NormalizerFormatter('Y-m-d');
  93. $e = new \SoapFault('foo', 'bar', 'hello', 'world');
  94. $formatted = $formatter->normalizeValue([
  95. 'exception' => $e,
  96. ]);
  97. unset($formatted['exception']['trace']);
  98. $this->assertEquals([
  99. 'exception' => [
  100. 'class' => 'SoapFault',
  101. 'message' => 'bar',
  102. 'code' => 0,
  103. 'file' => $e->getFile().':'.$e->getLine(),
  104. 'faultcode' => 'foo',
  105. 'faultactor' => 'hello',
  106. 'detail' => 'world',
  107. ],
  108. ], $formatted);
  109. $formatter = new NormalizerFormatter('Y-m-d');
  110. $e = new \SoapFault('foo', 'bar', 'hello', (object) ['bar' => (object) ['biz' => 'baz'], 'foo' => 'world']);
  111. $formatted = $formatter->normalizeValue([
  112. 'exception' => $e,
  113. ]);
  114. unset($formatted['exception']['trace']);
  115. $this->assertEquals([
  116. 'exception' => [
  117. 'class' => 'SoapFault',
  118. 'message' => 'bar',
  119. 'code' => 0,
  120. 'file' => $e->getFile().':'.$e->getLine(),
  121. 'faultcode' => 'foo',
  122. 'faultactor' => 'hello',
  123. 'detail' => '{"bar":{"biz":"baz"},"foo":"world"}',
  124. ],
  125. ], $formatted);
  126. }
  127. public function testFormatToStringExceptionHandle()
  128. {
  129. $formatter = new NormalizerFormatter('Y-m-d');
  130. $formatted = $formatter->format($this->getRecord(context: [
  131. 'myObject' => new TestToStringError(),
  132. ]));
  133. $this->assertEquals(
  134. [
  135. 'level_name' => Level::Warning->getName(),
  136. 'level' => Level::Warning->value,
  137. 'channel' => 'test',
  138. 'message' => 'test',
  139. 'context' => [
  140. 'myObject' => [
  141. TestToStringError::class => [],
  142. ],
  143. ],
  144. 'datetime' => date('Y-m-d'),
  145. 'extra' => [],
  146. ],
  147. $formatted
  148. );
  149. }
  150. public function testBatchFormat()
  151. {
  152. $formatter = new NormalizerFormatter('Y-m-d');
  153. $formatted = $formatter->formatBatch([
  154. $this->getRecord(Level::Critical, 'bar', channel: 'test'),
  155. $this->getRecord(Level::Warning, 'foo', channel: 'log'),
  156. ]);
  157. $this->assertEquals([
  158. [
  159. 'level_name' => Level::Critical->getName(),
  160. 'level' => Level::Critical->value,
  161. 'channel' => 'test',
  162. 'message' => 'bar',
  163. 'context' => [],
  164. 'datetime' => date('Y-m-d'),
  165. 'extra' => [],
  166. ],
  167. [
  168. 'level_name' => Level::Warning->getName(),
  169. 'level' => Level::Warning->value,
  170. 'channel' => 'log',
  171. 'message' => 'foo',
  172. 'context' => [],
  173. 'datetime' => date('Y-m-d'),
  174. 'extra' => [],
  175. ],
  176. ], $formatted);
  177. }
  178. /**
  179. * Test issue #137
  180. */
  181. public function testIgnoresRecursiveObjectReferences()
  182. {
  183. // set up the recursion
  184. $foo = new \stdClass();
  185. $bar = new \stdClass();
  186. $foo->bar = $bar;
  187. $bar->foo = $foo;
  188. // set an error handler to assert that the error is not raised anymore
  189. $that = $this;
  190. set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
  191. if (error_reporting() & $level) {
  192. restore_error_handler();
  193. $that->fail("$message should not be raised");
  194. }
  195. return true;
  196. });
  197. $formatter = new NormalizerFormatter();
  198. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  199. $res = $reflMethod->invoke($formatter, [$foo, $bar], true);
  200. restore_error_handler();
  201. $this->assertEquals('[{"bar":{"foo":null}},{"foo":{"bar":null}}]', $res);
  202. }
  203. public function testCanNormalizeReferences()
  204. {
  205. $formatter = new NormalizerFormatter();
  206. $x = ['foo' => 'bar'];
  207. $y = ['x' => &$x];
  208. $x['y'] = &$y;
  209. $formatter->normalizeValue($y);
  210. }
  211. public function testToJsonIgnoresInvalidTypes()
  212. {
  213. // set up the invalid data
  214. $resource = fopen(__FILE__, 'r');
  215. // set an error handler to assert that the error is not raised anymore
  216. $that = $this;
  217. set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
  218. if (error_reporting() & $level) {
  219. restore_error_handler();
  220. $that->fail("$message should not be raised");
  221. }
  222. return true;
  223. });
  224. $formatter = new NormalizerFormatter();
  225. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  226. $res = $reflMethod->invoke($formatter, [$resource], true);
  227. restore_error_handler();
  228. $this->assertEquals('[null]', $res);
  229. }
  230. public function testNormalizeHandleLargeArraysWithExactly1000Items()
  231. {
  232. $formatter = new NormalizerFormatter();
  233. $largeArray = range(1, 1000);
  234. $res = $formatter->format($this->getRecord(
  235. Level::Critical,
  236. 'bar',
  237. channel: 'test',
  238. context: [$largeArray],
  239. ));
  240. $this->assertCount(1000, $res['context'][0]);
  241. $this->assertArrayNotHasKey('...', $res['context'][0]);
  242. }
  243. public function testNormalizeHandleLargeArrays()
  244. {
  245. $formatter = new NormalizerFormatter();
  246. $largeArray = range(1, 2000);
  247. $res = $formatter->format($this->getRecord(
  248. Level::Critical,
  249. 'bar',
  250. channel: 'test',
  251. context: [$largeArray],
  252. ));
  253. $this->assertCount(1001, $res['context'][0]);
  254. $this->assertEquals('Over 1000 items (2000 total), aborting normalization', $res['context'][0]['...']);
  255. }
  256. public function testIgnoresInvalidEncoding()
  257. {
  258. $formatter = new NormalizerFormatter();
  259. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  260. // send an invalid unicode sequence as a object that can't be cleaned
  261. $record = new \stdClass;
  262. $record->message = "\xB1\x31";
  263. $this->assertsame('{"message":"�1"}', $reflMethod->invoke($formatter, $record));
  264. }
  265. public function testConvertsInvalidEncodingAsLatin9()
  266. {
  267. $formatter = new NormalizerFormatter();
  268. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  269. $res = $reflMethod->invoke($formatter, ['message' => "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE"]);
  270. $this->assertSame('{"message":"��������"}', $res);
  271. }
  272. public function testMaxNormalizeDepth()
  273. {
  274. $formatter = new NormalizerFormatter();
  275. $formatter->setMaxNormalizeDepth(1);
  276. $throwable = new \Error('Foo');
  277. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  278. $this->assertEquals(
  279. 'Over 1 levels deep, aborting normalization',
  280. $message['context']['exception']
  281. );
  282. }
  283. public function testMaxNormalizeItemCountWith0ItemsMax()
  284. {
  285. $formatter = new NormalizerFormatter();
  286. $formatter->setMaxNormalizeDepth(9);
  287. $formatter->setMaxNormalizeItemCount(0);
  288. $throwable = new \Error('Foo');
  289. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  290. $this->assertEquals(
  291. ["..." => "Over 0 items (7 total), aborting normalization"],
  292. $message
  293. );
  294. }
  295. public function testMaxNormalizeItemCountWith2ItemsMax()
  296. {
  297. $formatter = new NormalizerFormatter();
  298. $formatter->setMaxNormalizeDepth(9);
  299. $formatter->setMaxNormalizeItemCount(2);
  300. $throwable = new \Error('Foo');
  301. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  302. unset($message['context']['exception']['trace']);
  303. unset($message['context']['exception']['file']);
  304. $this->assertEquals(
  305. [
  306. "message" => "foobar",
  307. "context" => ['exception' => [
  308. 'class' => 'Error',
  309. 'message' => 'Foo',
  310. 'code' => 0,
  311. ]],
  312. "..." => "Over 2 items (7 total), aborting normalization",
  313. ],
  314. $message
  315. );
  316. }
  317. public function testExceptionTraceWithArgs()
  318. {
  319. try {
  320. // This will contain $resource and $wrappedResource as arguments in the trace item
  321. $resource = fopen('php://memory', 'rw+');
  322. fwrite($resource, 'test_resource');
  323. $wrappedResource = new TestFooNorm;
  324. $wrappedResource->foo = $resource;
  325. // Just do something stupid with a resource/wrapped resource as argument
  326. $arr = [$wrappedResource, $resource];
  327. // modifying the array inside throws a "usort(): Array was modified by the user comparison function"
  328. usort($arr, function ($a, $b) {
  329. throw new \ErrorException('Foo');
  330. });
  331. } catch (\Throwable $e) {
  332. }
  333. $formatter = new NormalizerFormatter();
  334. $record = $this->getRecord(context: ['exception' => $e]);
  335. $result = $formatter->format($record);
  336. // See https://github.com/php/php-src/issues/8810 fixed in PHP 8.2
  337. $offset = PHP_VERSION_ID >= 80200 ? 13 : 11;
  338. $this->assertSame(
  339. __FILE__.':'.(__LINE__ - $offset),
  340. $result['context']['exception']['trace'][0]
  341. );
  342. }
  343. private function formatRecordWithExceptionInContext(NormalizerFormatter $formatter, \Throwable $exception): array
  344. {
  345. $message = $formatter->format($this->getRecord(
  346. Level::Critical,
  347. 'foobar',
  348. channel: 'core',
  349. context: ['exception' => $exception],
  350. ));
  351. return $message;
  352. }
  353. public function testExceptionTraceDoesNotLeakCallUserFuncArgs()
  354. {
  355. try {
  356. $arg = new TestInfoLeak;
  357. \call_user_func([$this, 'throwHelper'], $arg, $dt = new \DateTime());
  358. } catch (\Exception $e) {
  359. }
  360. $formatter = new NormalizerFormatter();
  361. $record = $this->getRecord(context: ['exception' => $e]);
  362. $result = $formatter->format($record);
  363. $this->assertSame(
  364. __FILE__ .':'.(__LINE__-9),
  365. $result['context']['exception']['trace'][0]
  366. );
  367. }
  368. public function testCanNormalizeIncompleteObject(): void
  369. {
  370. $serialized = "O:17:\"Monolog\TestClass\":1:{s:23:\"\x00Monolog\TestClass\x00name\";s:4:\"test\";}";
  371. $object = unserialize($serialized);
  372. $formatter = new NormalizerFormatter();
  373. $record = $this->getRecord(context: ['object' => $object]);
  374. $result = $formatter->format($record);
  375. $this->assertEquals([
  376. '__PHP_Incomplete_Class' => 'Monolog\\TestClass',
  377. ], $result['context']['object']);
  378. }
  379. private function throwHelper($arg)
  380. {
  381. throw new \RuntimeException('Thrown');
  382. }
  383. }
  384. class TestFooNorm
  385. {
  386. public $foo = 'fooValue';
  387. }
  388. class TestBarNorm
  389. {
  390. public function __toString()
  391. {
  392. return 'bar';
  393. }
  394. }
  395. class TestStreamFoo
  396. {
  397. public $foo;
  398. public $resource;
  399. public function __construct($resource)
  400. {
  401. $this->resource = $resource;
  402. $this->foo = 'BAR';
  403. }
  404. public function __toString()
  405. {
  406. fseek($this->resource, 0);
  407. return $this->foo . ' - ' . (string) stream_get_contents($this->resource);
  408. }
  409. }
  410. class TestToStringError
  411. {
  412. public function __toString()
  413. {
  414. throw new \RuntimeException('Could not convert to string');
  415. }
  416. }
  417. class TestInfoLeak
  418. {
  419. public function __toString()
  420. {
  421. return 'Sensitive information';
  422. }
  423. }