Skip to content
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
10 changes: 10 additions & 0 deletions src/ReverseProxy/Forwarder/HttpForwarder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -657,6 +657,16 @@ private async ValueTask<ForwarderError> HandleRequestFailureAsync(HttpContext co
requestException = new AggregateException(requestException, requestBodyException!);
}
}

// ASP.NET Core request timeouts cancel RequestAborted, unlike the forwarder's activity timeout,
// so detect them here before treating linked-token cancellation as a client disconnect.
if (context.RequestAborted.IsCancellationRequested &&
context.Features.Get<IHttpRequestTimeoutFeature>()?.RequestTimeoutToken.IsCancellationRequested == true)
{
// YARP reports request timeouts as 504; ASP.NET Core policy status and response customization are not applied.
return await ReportErrorAsync(ForwarderError.RequestTimedOut, StatusCodes.Status504GatewayTimeout);
}

// Either the client went away (HttpContext.RequestAborted) or the CancellationToken provided to SendAsync was signaled.
return await ReportErrorAsync(requestBodyCanceled ? ForwarderError.RequestBodyCanceled : ForwarderError.RequestCanceled,
context.RequestAborted.IsCancellationRequested ? StatusCodes.Status400BadRequest : StatusCodes.Status502BadGateway);
Expand Down
3 changes: 3 additions & 0 deletions test/ReverseProxy.FunctionalTests/Common/TestEnvironment.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ public class TestEnvironment

public Action<IApplicationBuilder> ConfigureProxyApp { get; set; } = _ => { };

public Action<IApplicationBuilder> ConfigureProxyAppAfterRouting { get; set; } = _ => { };

public string ClusterId { get; set; } = "cluster1";

public Func<ClusterConfig, RouteConfig, (ClusterConfig Cluster, RouteConfig Route)> ConfigTransformer { get; set; } = (a, b) => (a, b);
Expand Down Expand Up @@ -143,6 +145,7 @@ public IHost CreateProxy(string destinationAddress, Action<Exception> onProxyExc

ConfigureProxyApp(app);
app.UseRouting();
ConfigureProxyAppAfterRouting(app);
app.UseEndpoints(builder =>
{
builder.MapReverseProxy();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,12 @@
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
using Yarp.ReverseProxy.Common;
using Yarp.ReverseProxy.Forwarder;
using Yarp.ReverseProxy.Utilities;

namespace Yarp.ReverseProxy;
Expand All @@ -22,6 +25,53 @@ public class HttpForwarderCancellationTests
// See https://github.com/dotnet/runtime/issues/27727
public static bool Http2OverTlsSupported => !RuntimeInformation.IsOSPlatform(OSPlatform.OSX);

[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task RouteTimeout_Returns504(bool useNamedPolicy)
{
var error = ForwarderError.None;
var statusCode = HttpStatusCode.OK;
// The timeout may fire before or after the destination is reached; either way it must be reported as a timeout.
var test = new TestEnvironment(async context =>
{
try
{
await Task.Delay(Timeout.Infinite, context.RequestAborted);
}
catch (OperationCanceledException)
{
}
})
{
ConfigureProxyServices = services => services.AddRequestTimeouts(options =>
options.AddPolicy("test", TimeSpan.FromMilliseconds(10))),
ConfigureProxyApp = app =>
{
app.Use(async (context, next) =>
{
await next();
error = context.Features.Get<IForwarderErrorFeature>()?.Error ?? ForwarderError.None;
});
},
ConfigureProxyAppAfterRouting = app => app.UseRequestTimeouts(),
ConfigTransformer = (cluster, route) => (cluster, useNamedPolicy
? route with { TimeoutPolicy = "test" }
: route with { Timeout = TimeSpan.FromMilliseconds(10) }),
};

await test.Invoke(async uri =>
{
using var client = new HttpClient();
using var response = await client.GetAsync(uri);

statusCode = response.StatusCode;
});

Assert.Equal(HttpStatusCode.GatewayTimeout, statusCode);
Assert.Equal(ForwarderError.RequestTimedOut, error);
}

[Fact(Skip = "Condition not met", SkipUnless = nameof(Http2OverTlsSupported))]
public async Task ServerSendsHttp2Reset_ReadToClientIsCanceled()
{
Expand Down
89 changes: 89 additions & 0 deletions test/ReverseProxy.Tests/Forwarder/HttpForwarderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Http.Timeouts;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -1535,6 +1536,94 @@ public async Task RequestCanceled_Returns400()
Assert.Equal(0, proxyResponseStream.Length);
}

[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task RouteTimeout_Returns504(bool copyRequestBody)
{
TestEventListener.Collect();
TestLogger.Collect();

using var timeoutCts = new CancellationTokenSource();
var httpContext = new DefaultHttpContext();
httpContext.Request.Method = copyRequestBody ? "POST" : "GET";
httpContext.Request.Host = new HostString("example.com:3456");
httpContext.RequestAborted = timeoutCts.Token;
if (copyRequestBody)
{
httpContext.Request.Body = new CallbackReadStream(async (memory, ct) =>
{
timeoutCts.Cancel();
await Task.Delay(Timeout.Infinite, ct);
return 0;
});
httpContext.Request.ContentLength = 1;
}

var timeoutFeature = new Mock<IHttpRequestTimeoutFeature>();
timeoutFeature.SetupGet(f => f.RequestTimeoutToken).Returns(timeoutCts.Token);
httpContext.Features.Set(timeoutFeature.Object);

var destinationPrefix = "https://localhost:123/";
var client = MockHttpHandler.CreateClient(async (HttpRequestMessage request, CancellationToken cancellationToken) =>
{
if (copyRequestBody)
{
await request.Content.CopyToWithCancellationAsync(Stream.Null);
}
else
{
timeoutCts.Cancel();
}

cancellationToken.ThrowIfCancellationRequested();
return new HttpResponseMessage();
});

var proxyError = await CreateProxy().SendAsync(httpContext, destinationPrefix, client);

if (copyRequestBody)
{
AssertErrorInfoAndStages<AggregateException>(ForwarderError.RequestTimedOut, StatusCodes.Status504GatewayTimeout,
proxyError, httpContext, destinationPrefix, ForwarderStage.RequestContentTransferStart);
}
else
{
AssertErrorInfoAndStages<OperationCanceledException>(ForwarderError.RequestTimedOut, StatusCodes.Status504GatewayTimeout,
proxyError, httpContext, destinationPrefix);
}
}

[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task LinkedCancellation_WithRouteTimeoutFeature_IsNotTimedOut(bool manualCancellation)
{
TestEventListener.Collect();
TestLogger.Collect();

var httpContext = new DefaultHttpContext();
httpContext.Request.Method = "GET";
httpContext.RequestAborted = new CancellationToken(canceled: !manualCancellation);
var timeoutFeature = new Mock<IHttpRequestTimeoutFeature>();
timeoutFeature.SetupGet(f => f.RequestTimeoutToken).Returns(new CancellationToken(canceled: manualCancellation));
httpContext.Features.Set(timeoutFeature.Object);

var destinationPrefix = "https://localhost:123/";
var client = MockHttpHandler.CreateClient((HttpRequestMessage request, CancellationToken cancellationToken) =>
{
cancellationToken.ThrowIfCancellationRequested();
return Task.FromResult(new HttpResponseMessage());
});

var proxyError = await CreateProxy().SendAsync(httpContext, destinationPrefix, client, ForwarderRequestConfig.Empty,
HttpTransformer.Default, new CancellationToken(canceled: manualCancellation));

AssertErrorInfoAndStages<OperationCanceledException>(ForwarderError.RequestCanceled,
manualCancellation ? StatusCodes.Status502BadGateway : StatusCodes.Status400BadRequest,
proxyError, httpContext, destinationPrefix);
}

[Fact]
public async Task RequestWithBodyTimedOut_Returns504()
{
Expand Down
Loading