From edf4f2fd9dedc81e651b655191fe50bafe01c60c Mon Sep 17 00:00:00 2001 From: Vladislav Bardin Date: Fri, 5 Nov 2021 20:22:14 +0200 Subject: [PATCH] Add html encoding Encode HTML at exception's description and stack trace to avoid exceptions from telegram bot library --- .../TelegramMessageFormatter.cs | 4 +++- .../TelegramLoggingTests.cs | 23 +++++++++++++++++-- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/src/X.Extensions.Logging.Telegram/TelegramMessageFormatter.cs b/src/X.Extensions.Logging.Telegram/TelegramMessageFormatter.cs index 272eb5c..9bb0d64 100644 --- a/src/X.Extensions.Logging.Telegram/TelegramMessageFormatter.cs +++ b/src/X.Extensions.Logging.Telegram/TelegramMessageFormatter.cs @@ -1,5 +1,7 @@ using System; +using System.Net; using System.Text; + using Microsoft.Extensions.Logging; namespace X.Extensions.Logging.Telegram @@ -45,7 +47,7 @@ public string Format( if (exception != null) { sb.AppendLine(); - sb.AppendLine($"
{exception}
"); + sb.AppendLine($"
{WebUtility.HtmlEncode(exception.ToString())}
"); sb.AppendLine(); } diff --git a/tests/X.Extensions.Logging.Telegram.Tests/TelegramLoggingTests.cs b/tests/X.Extensions.Logging.Telegram.Tests/TelegramLoggingTests.cs index a43dd62..8d7c3d3 100644 --- a/tests/X.Extensions.Logging.Telegram.Tests/TelegramLoggingTests.cs +++ b/tests/X.Extensions.Logging.Telegram.Tests/TelegramLoggingTests.cs @@ -1,4 +1,6 @@ -using System; +using System.Net; +using System.Text.Encodings.Web; + using Microsoft.Extensions.Logging; using NUnit.Framework; @@ -13,7 +15,7 @@ public void Setup() } [Test] - public void Test1() + public void Test_MessageFormatter_MessageNotNull() { var options = new TelegramLoggerOptions { @@ -29,5 +31,22 @@ public void Test1() Assert.NotNull(message); } + + [TestCase("

Exception message description

")] + [TestCase("

Exception
message description

")] + public void ExceptionDescriptionWithRawHtmlTest(string description) + { + var encodedHtml = WebUtility.HtmlEncode(description); + + var containsRawHtml = encodedHtml.Contains("

") || + encodedHtml.Contains("

") || + encodedHtml.Contains("
") || + encodedHtml.Contains("") || + encodedHtml.Contains("") || + encodedHtml.Contains("") || + encodedHtml.Contains(""); + + Assert.False(containsRawHtml); + } } } \ No newline at end of file