Skip to content

Commit

Permalink
Add html encoding
Browse files Browse the repository at this point in the history
Encode HTML at exception's description and stack trace to avoid exceptions from telegram bot library
  • Loading branch information
Bardin08 committed Nov 5, 2021
1 parent 0c0a449 commit edf4f2f
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
using System;
using System.Net;
using System.Text;

using Microsoft.Extensions.Logging;

namespace X.Extensions.Logging.Telegram
Expand Down Expand Up @@ -45,7 +47,7 @@ public string Format<TState>(
if (exception != null)
{
sb.AppendLine();
sb.AppendLine($"<pre>{exception}</pre>");
sb.AppendLine($"<pre>{WebUtility.HtmlEncode(exception.ToString())}</pre>");
sb.AppendLine();
}

Expand Down
23 changes: 21 additions & 2 deletions tests/X.Extensions.Logging.Telegram.Tests/TelegramLoggingTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System;
using System.Net;
using System.Text.Encodings.Web;

using Microsoft.Extensions.Logging;
using NUnit.Framework;

Expand All @@ -13,7 +15,7 @@ public void Setup()
}

[Test]
public void Test1()
public void Test_MessageFormatter_MessageNotNull()
{
var options = new TelegramLoggerOptions
{
Expand All @@ -29,5 +31,22 @@ public void Test1()

Assert.NotNull(message);
}

[TestCase("<p style=\"font-family='Lucida Console'\">Exception message description</p>")]
[TestCase("<p style=\"font-family='Lucida Console';width:100%\">Exception <br/><i><b>message</b></i> description</p>")]
public void ExceptionDescriptionWithRawHtmlTest(string description)
{
var encodedHtml = WebUtility.HtmlEncode(description);

var containsRawHtml = encodedHtml.Contains("<p style=\"font-family='Lucida Console'\">") ||
encodedHtml.Contains("</p>") ||
encodedHtml.Contains("<br/>") ||
encodedHtml.Contains("<i>") ||
encodedHtml.Contains("</i>") ||
encodedHtml.Contains("<b>") ||
encodedHtml.Contains("</b>");

Assert.False(containsRawHtml);
}
}
}

0 comments on commit edf4f2f

Please sign in to comment.