NormalizerFormatterTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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. $reflMethod->setAccessible(true);
  200. $res = $reflMethod->invoke($formatter, [$foo, $bar], true);
  201. restore_error_handler();
  202. $this->assertEquals('[{"bar":{"foo":null}},{"foo":{"bar":null}}]', $res);
  203. }
  204. public function testCanNormalizeReferences()
  205. {
  206. $formatter = new NormalizerFormatter();
  207. $x = ['foo' => 'bar'];
  208. $y = ['x' => &$x];
  209. $x['y'] = &$y;
  210. $formatter->normalizeValue($y);
  211. }
  212. public function testToJsonIgnoresInvalidTypes()
  213. {
  214. // set up the invalid data
  215. $resource = fopen(__FILE__, 'r');
  216. // set an error handler to assert that the error is not raised anymore
  217. $that = $this;
  218. set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
  219. if (error_reporting() & $level) {
  220. restore_error_handler();
  221. $that->fail("$message should not be raised");
  222. }
  223. return true;
  224. });
  225. $formatter = new NormalizerFormatter();
  226. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  227. $reflMethod->setAccessible(true);
  228. $res = $reflMethod->invoke($formatter, [$resource], true);
  229. restore_error_handler();
  230. $this->assertEquals('[null]', $res);
  231. }
  232. public function testNormalizeHandleLargeArraysWithExactly1000Items()
  233. {
  234. $formatter = new NormalizerFormatter();
  235. $largeArray = range(1, 1000);
  236. $res = $formatter->format($this->getRecord(
  237. Level::Critical,
  238. 'bar',
  239. channel: 'test',
  240. context: [$largeArray],
  241. ));
  242. $this->assertCount(1000, $res['context'][0]);
  243. $this->assertArrayNotHasKey('...', $res['context'][0]);
  244. }
  245. public function testNormalizeHandleLargeArrays()
  246. {
  247. $formatter = new NormalizerFormatter();
  248. $largeArray = range(1, 2000);
  249. $res = $formatter->format($this->getRecord(
  250. Level::Critical,
  251. 'bar',
  252. channel: 'test',
  253. context: [$largeArray],
  254. ));
  255. $this->assertCount(1001, $res['context'][0]);
  256. $this->assertEquals('Over 1000 items (2000 total), aborting normalization', $res['context'][0]['...']);
  257. }
  258. public function testIgnoresInvalidEncoding()
  259. {
  260. $formatter = new NormalizerFormatter();
  261. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  262. $reflMethod->setAccessible(true);
  263. // send an invalid unicode sequence as a object that can't be cleaned
  264. $record = new \stdClass;
  265. $record->message = "\xB1\x31";
  266. $this->assertsame('{"message":"�1"}', $reflMethod->invoke($formatter, $record));
  267. }
  268. public function testConvertsInvalidEncodingAsLatin9()
  269. {
  270. $formatter = new NormalizerFormatter();
  271. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  272. $reflMethod->setAccessible(true);
  273. $res = $reflMethod->invoke($formatter, ['message' => "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE"]);
  274. $this->assertSame('{"message":"��������"}', $res);
  275. }
  276. public function testMaxNormalizeDepth()
  277. {
  278. $formatter = new NormalizerFormatter();
  279. $formatter->setMaxNormalizeDepth(1);
  280. $throwable = new \Error('Foo');
  281. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  282. $this->assertEquals(
  283. 'Over 1 levels deep, aborting normalization',
  284. $message['context']['exception']
  285. );
  286. }
  287. public function testMaxNormalizeItemCountWith0ItemsMax()
  288. {
  289. $formatter = new NormalizerFormatter();
  290. $formatter->setMaxNormalizeDepth(9);
  291. $formatter->setMaxNormalizeItemCount(0);
  292. $throwable = new \Error('Foo');
  293. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  294. $this->assertEquals(
  295. ["..." => "Over 0 items (7 total), aborting normalization"],
  296. $message
  297. );
  298. }
  299. public function testMaxNormalizeItemCountWith2ItemsMax()
  300. {
  301. $formatter = new NormalizerFormatter();
  302. $formatter->setMaxNormalizeDepth(9);
  303. $formatter->setMaxNormalizeItemCount(2);
  304. $throwable = new \Error('Foo');
  305. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  306. unset($message['context']['exception']['trace']);
  307. unset($message['context']['exception']['file']);
  308. $this->assertEquals(
  309. [
  310. "message" => "foobar",
  311. "context" => ['exception' => [
  312. 'class' => 'Error',
  313. 'message' => 'Foo',
  314. 'code' => 0,
  315. ]],
  316. "..." => "Over 2 items (7 total), aborting normalization",
  317. ],
  318. $message
  319. );
  320. }
  321. public function testExceptionTraceWithArgs()
  322. {
  323. try {
  324. // This will contain $resource and $wrappedResource as arguments in the trace item
  325. $resource = fopen('php://memory', 'rw+');
  326. fwrite($resource, 'test_resource');
  327. $wrappedResource = new TestFooNorm;
  328. $wrappedResource->foo = $resource;
  329. // Just do something stupid with a resource/wrapped resource as argument
  330. $arr = [$wrappedResource, $resource];
  331. // modifying the array inside throws a "usort(): Array was modified by the user comparison function"
  332. usort($arr, function ($a, $b) {
  333. throw new \ErrorException('Foo');
  334. });
  335. } catch (\Throwable $e) {
  336. }
  337. $formatter = new NormalizerFormatter();
  338. $record = $this->getRecord(context: ['exception' => $e]);
  339. $result = $formatter->format($record);
  340. // See https://github.com/php/php-src/issues/8810 fixed in PHP 8.2
  341. $offset = PHP_VERSION_ID >= 80200 ? 13 : 11;
  342. $this->assertSame(
  343. __FILE__.':'.(__LINE__ - $offset),
  344. $result['context']['exception']['trace'][0]
  345. );
  346. }
  347. private function formatRecordWithExceptionInContext(NormalizerFormatter $formatter, \Throwable $exception): array
  348. {
  349. $message = $formatter->format($this->getRecord(
  350. Level::Critical,
  351. 'foobar',
  352. channel: 'core',
  353. context: ['exception' => $exception],
  354. ));
  355. return $message;
  356. }
  357. public function testExceptionTraceDoesNotLeakCallUserFuncArgs()
  358. {
  359. try {
  360. $arg = new TestInfoLeak;
  361. call_user_func([$this, 'throwHelper'], $arg, $dt = new \DateTime());
  362. } catch (\Exception $e) {
  363. }
  364. $formatter = new NormalizerFormatter();
  365. $record = $this->getRecord(context: ['exception' => $e]);
  366. $result = $formatter->format($record);
  367. $this->assertSame(
  368. __FILE__ .':'.(__LINE__-9),
  369. $result['context']['exception']['trace'][0]
  370. );
  371. }
  372. public function testCanNormalizeIncompleteObject(): void
  373. {
  374. $serialized = "O:17:\"Monolog\TestClass\":1:{s:23:\"\x00Monolog\TestClass\x00name\";s:4:\"test\";}";
  375. $object = unserialize($serialized);
  376. $formatter = new NormalizerFormatter();
  377. $record = $this->getRecord(context: ['object' => $object]);
  378. $result = $formatter->format($record);
  379. $this->assertEquals([
  380. '__PHP_Incomplete_Class' => 'Monolog\\TestClass',
  381. ], $result['context']['object']);
  382. }
  383. private function throwHelper($arg)
  384. {
  385. throw new \RuntimeException('Thrown');
  386. }
  387. }
  388. class TestFooNorm
  389. {
  390. public $foo = 'fooValue';
  391. }
  392. class TestBarNorm
  393. {
  394. public function __toString()
  395. {
  396. return 'bar';
  397. }
  398. }
  399. class TestStreamFoo
  400. {
  401. public $foo;
  402. public $resource;
  403. public function __construct($resource)
  404. {
  405. $this->resource = $resource;
  406. $this->foo = 'BAR';
  407. }
  408. public function __toString()
  409. {
  410. fseek($this->resource, 0);
  411. return $this->foo . ' - ' . (string) stream_get_contents($this->resource);
  412. }
  413. }
  414. class TestToStringError
  415. {
  416. public function __toString()
  417. {
  418. throw new \RuntimeException('Could not convert to string');
  419. }
  420. }
  421. class TestInfoLeak
  422. {
  423. public function __toString()
  424. {
  425. return 'Sensitive information';
  426. }
  427. }