NormalizerFormatterTest.php 14 KB

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