NormalizerFormatterTest.php 15 KB

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