TelegramBots / Telegram.Bot.Examples

Examples for the Telegram.Bot C# Library
MIT License
630 stars 289 forks source link

Using HttpClientFactory should be discouraged? #529

Closed mazharenko closed 2 months ago

mazharenko commented 6 months ago

When getting HttpClient from HttpClientFactory, e.g. via Typed clients as shown in Telegram.Bot.Examples.Polling, the HttpClient returned is configured to log every request. And since there is the token value in request urls, this can lead to disclosure of sensitive data.

C:\Users\mazharenko\AppData\Local\JetBrains\Toolbox\apps\Rider\ch-0\223.8836.53\plugins\dpa\DotFiles\JetBrains.DPA.Runner.exe --handle=9660 --backend-pid=10348 --etw-collect-flags=3 --detach-event-name=dpa.detach.9660 C:/Workspace/Telegram.Bot.Examples/Telegram.Bot.Examples.Polling/bin/Debug/net6.0/Telegram.Bot.Examples.Polling.exe
info: Telegram.Bot.Services.PollingService[0]
      Starting polling service
info: System.Net.Http.HttpClient.telegram_bot_client.LogicalHandler[100]
      Start processing HTTP request POST https://api.telegram.org/bot190■■■■■■■:■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■/getMe
info: System.Net.Http.HttpClient.telegram_bot_client.ClientHandler[100]
      Sending HTTP request POST https://api.telegram.org/bot190■■■■■■■:■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■/getMe
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.

Known workarounds:

  1. As suggested in Guidelines for using HttpClient, one can manually set the Handler for their HttpClient with some PooledConnectionLifetime value.
  2. After adding the Typed client to the service collection, one can remove IHttpMessageHandlerBuilderFilter from it. This is gonna have impact on other Typed clients in the application though.
    builder.RemoveAll<IHttpMessageHandlerBuilderFilter>();

I personally think these logs can be quite useful sometimes, but the mechanism is not configurable enough.

wiz0u commented 2 months ago

examples have been updated to using RemoveAllLoggers (.NET 8) to fix this