Skip to content

Commit b331224

Browse files
Review feedback
1 parent f413b79 commit b331224

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

src/Sentry.AspNetCore/SentryTunnelMiddleware.cs

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using Microsoft.AspNetCore.Http;
22
using Microsoft.Extensions.DependencyInjection;
3+
using Microsoft.Extensions.Primitives;
34
using Sentry.Internal.Extensions;
45

56
namespace Sentry.AspNetCore;
@@ -98,13 +99,8 @@ public async Task InvokeAsync(HttpContext context, RequestDelegate next)
9899
Method = HttpMethod.Post,
99100
Content = new StreamContent(memoryStream),
100101
};
101-
var existingForwardedFor = context.Request.Headers["X-Forwarded-For"];
102-
var clientIp = context.Connection?.RemoteIpAddress?.ToString();
103-
if (clientIp != null)
102+
if (CreateXForwardedForHeader(context) is { } forwardedFor)
104103
{
105-
var forwardedFor = string.IsNullOrEmpty(existingForwardedFor)
106-
? clientIp
107-
: $"{existingForwardedFor}, {clientIp}";
108104
sentryRequest.Headers.Add("X-Forwarded-For", forwardedFor);
109105
}
110106
var responseMessage = await client.SendAsync(sentryRequest).ConfigureAwait(false);
@@ -126,6 +122,25 @@ public async Task InvokeAsync(HttpContext context, RequestDelegate next)
126122
}
127123
}
128124

125+
private static string? CreateXForwardedForHeader(HttpContext context)
126+
{
127+
var existingForwardedFor = context.Request.Headers["X-Forwarded-For"];
128+
var clientIp = context.Connection?.RemoteIpAddress?.ToString();
129+
if (clientIp is null)
130+
{
131+
return existingForwardedFor.Count > 0 ? existingForwardedFor.ToString() : null;
132+
}
133+
134+
if (existingForwardedFor.Count == 0)
135+
{
136+
return clientIp;
137+
}
138+
139+
return string.IsNullOrEmpty(existingForwardedFor)
140+
? clientIp
141+
: $"{existingForwardedFor}, {clientIp}";
142+
}
143+
129144
private bool IsHostAllowed(string host) =>
130145
host.EndsWith(".sentry.io", StringComparison.OrdinalIgnoreCase) ||
131146
host.Equals("sentry.io", StringComparison.OrdinalIgnoreCase) ||

0 commit comments

Comments
 (0)