Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Filter OperationCanceled instead of TaskCanceled logs #1671

Merged
merged 1 commit into from
Dec 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -70,5 +70,10 @@ public class LoggingOptions
/// Called when the IdentityServer middleware detects an unhandled exception, and is used to determine if the exception is logged.
/// Returns true to emit the log, false to suppress.
/// </summary>
public Func<HttpContext, Exception, bool> UnhandledExceptionLoggingFilter = (context, exception) => !(context.RequestAborted.IsCancellationRequested && exception is TaskCanceledException);
public Func<HttpContext, Exception, bool> UnhandledExceptionLoggingFilter = (context, exception) =>
{
var result = !(context.RequestAborted.IsCancellationRequested && exception is OperationCanceledException);
return result;
};

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@

using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Duende.IdentityServer.Hosting;
using FluentAssertions;
using IntegrationTests.Common;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Xunit;


namespace IntegrationTests.Hosting;

public class FailRouter : IEndpointRouter
{
private readonly Type _exceptionType;
public FailRouter(Type exceptionType)
{
_exceptionType = exceptionType;
}

public IEndpointHandler Find(HttpContext context)
{
throw (Exception) _exceptionType.GetConstructor([]).Invoke(null);
}
}

public class IdentityServerMiddlewareTests
{
private IdentityServerPipeline _pipeline = new IdentityServerPipeline();
public static readonly TheoryData<Type, bool> ExceptionFilteringTestCases = new TheoryData<Type, bool>
{
{ typeof(TaskCanceledException), true },
{ typeof(OperationCanceledException), true },
{ typeof(Exception), false },
{ typeof(InvalidOperationException), false },
{ typeof(ArgumentException), false },
{ typeof(NullReferenceException), false }

};

[Theory]
[MemberData(nameof(ExceptionFilteringTestCases))]
public async Task expected_exception_types_are_filtered_from_logs_when_incoming_requests_are_canceled(Type t, bool filteringExpected)
{
// Set up the pipeline so that we will throw some exception. Throwing in
// the router specifically is not important - that is just a convenient
// place to throw an exception.
_pipeline.OnPostConfigureServices += svcs =>
{
svcs.AddTransient<IEndpointRouter>(_ => new FailRouter(t));
};
_pipeline.Initialize(enableLogging: true);

// First we make a request that is canceled. Filtered exception types are only filtered for canceled Http requests.
var source = new CancellationTokenSource();
var token = source.Token;
source.Cancel();
var canceledHttpRequest = async () => await _pipeline.BackChannelClient.GetAsync(IdentityServerPipeline.DiscoveryEndpoint, token);

// The middleware will always throw
var exceptionShould = await canceledHttpRequest.Should().ThrowAsync<Exception>();

// The middleware will log most exceptions, but not TaskCanceled or OperationCanceled
if (filteringExpected)
{
_pipeline.MockLogger.LogMessages.Should().NotContain(m => m.StartsWith("Unhandled exception: "));
}
else
{
_pipeline.MockLogger.LogMessages.Should().Contain(m => m.StartsWith("Unhandled exception: "));
}

// Now reset the log messages so that we can verify that we always log for requests that are not canceled
_pipeline.MockLogger.LogMessages.Clear();
var notCanceledRequest = async () => await _pipeline.BackChannelClient.GetAsync(IdentityServerPipeline.DiscoveryKeysEndpoint, CancellationToken.None);
await notCanceledRequest.Should().ThrowAsync<Exception>();
_pipeline.MockLogger.LogMessages.Should().Contain(m => m.StartsWith("Unhandled exception: "));
}
}
Loading