From 8b620cdf25eba7eab490de55d9a8901fcf9c836b Mon Sep 17 00:00:00 2001 From: Miha Zupan Date: Wed, 18 Nov 2026 08:27:25 +0100 Subject: [PATCH] Report ASP.NET Core route timeouts as 504 responses --- src/ReverseProxy/Forwarder/HttpForwarder.cs | 10 +++ .../Common/TestEnvironment.cs | 3 + .../HttpForwarderCancellationTests.cs | 50 +++++++++++ .../Forwarder/HttpForwarderTests.cs | 89 +++++++++++++++++++ 4 files changed, 152 insertions(+) diff --git a/src/ReverseProxy/Forwarder/HttpForwarder.cs b/src/ReverseProxy/Forwarder/HttpForwarder.cs index 923ce65755..d41a94d5dc 100644 --- a/src/ReverseProxy/Forwarder/HttpForwarder.cs +++ b/src/ReverseProxy/Forwarder/HttpForwarder.cs @@ -657,6 +657,16 @@ private async ValueTask 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()?.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); diff --git a/test/ReverseProxy.FunctionalTests/Common/TestEnvironment.cs b/test/ReverseProxy.FunctionalTests/Common/TestEnvironment.cs index f36afbea5b..88f476e64f 100644 --- a/test/ReverseProxy.FunctionalTests/Common/TestEnvironment.cs +++ b/test/ReverseProxy.FunctionalTests/Common/TestEnvironment.cs @@ -39,6 +39,8 @@ public class TestEnvironment public Action ConfigureProxyApp { get; set; } = _ => { }; + public Action ConfigureProxyAppAfterRouting { get; set; } = _ => { }; + public string ClusterId { get; set; } = "cluster1"; public Func ConfigTransformer { get; set; } = (a, b) => (a, b); @@ -143,6 +145,7 @@ public IHost CreateProxy(string destinationAddress, Action onProxyExc ConfigureProxyApp(app); app.UseRouting(); + ConfigureProxyAppAfterRouting(app); app.UseEndpoints(builder => { builder.MapReverseProxy(); diff --git a/test/ReverseProxy.FunctionalTests/HttpForwarderCancellationTests.cs b/test/ReverseProxy.FunctionalTests/HttpForwarderCancellationTests.cs index 0830b0b31e..6ede18a069 100644 --- a/test/ReverseProxy.FunctionalTests/HttpForwarderCancellationTests.cs +++ b/test/ReverseProxy.FunctionalTests/HttpForwarderCancellationTests.cs @@ -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; @@ -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()?.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() { diff --git a/test/ReverseProxy.Tests/Forwarder/HttpForwarderTests.cs b/test/ReverseProxy.Tests/Forwarder/HttpForwarderTests.cs index 2efb07137e..01d94161b5 100644 --- a/test/ReverseProxy.Tests/Forwarder/HttpForwarderTests.cs +++ b/test/ReverseProxy.Tests/Forwarder/HttpForwarderTests.cs @@ -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; @@ -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(); + 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(ForwarderError.RequestTimedOut, StatusCodes.Status504GatewayTimeout, + proxyError, httpContext, destinationPrefix, ForwarderStage.RequestContentTransferStart); + } + else + { + AssertErrorInfoAndStages(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(); + 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(ForwarderError.RequestCanceled, + manualCancellation ? StatusCodes.Status502BadGateway : StatusCodes.Status400BadRequest, + proxyError, httpContext, destinationPrefix); + } + [Fact] public async Task RequestWithBodyTimedOut_Returns504() {