| | | 1 | | using ArturRios.Data.Relational.Core.DependencyInjection; |
| | | 2 | | using ArturRios.Heimdall.WebApi.Security; |
| | | 3 | | using ArturRios.Util.WebApi.Configuration; |
| | | 4 | | using ArturRios.Util.WebApi.Security.Extensions; |
| | | 5 | | using Serilog; |
| | | 6 | | |
| | | 7 | | namespace ArturRios.Heimdall.WebApi; |
| | | 8 | | |
| | | 9 | | public static class ForwardedHeadersRegistrationExtensions |
| | | 10 | | { |
| | | 11 | | /// <summary> |
| | | 12 | | /// Believes <c>X-Forwarded-For</c> and <c>X-Forwarded-Proto</c> from the proxies |
| | | 13 | | /// <c>HEIMDALL_TRUSTED_PROXIES</c> names, and from no one else — see |
| | | 14 | | /// <see cref="TrustedProxyOptions" />. Applied by <c>UseForwardedHeaders</c>, which runs |
| | | 15 | | /// ahead of everything that reads the client address: the rate limiter, and the request log. |
| | | 16 | | /// </summary> |
| | | 17 | | public static IServiceCollection AddTrustedForwardedHeaders(this IServiceCollection services) |
| | | 18 | | { |
| | 966 | 19 | | var proxies = TrustedProxyOptions.FromEnvironment(); |
| | | 20 | | |
| | 966 | 21 | | if (proxies.InvalidEntries.Count > 0) |
| | | 22 | | { |
| | 0 | 23 | | Log.Warning( |
| | 0 | 24 | | "Ignoring unusable {Variable} entries {Entries}; they are neither an address nor a CIDR network", |
| | 0 | 25 | | TrustedProxyOptions.ProxiesVariable, proxies.InvalidEntries); |
| | | 26 | | } |
| | | 27 | | |
| | 966 | 28 | | if (!proxies.Configured) |
| | | 29 | | { |
| | 966 | 30 | | Log.Warning( |
| | 966 | 31 | | "No trusted proxy is configured ({Variable}); behind a reverse proxy every caller will " + |
| | 966 | 32 | | "be rate limited and logged under the proxy's address", |
| | 966 | 33 | | TrustedProxyOptions.ProxiesVariable); |
| | | 34 | | |
| | 966 | 35 | | return services; |
| | | 36 | | } |
| | | 37 | | |
| | 0 | 38 | | Log.Information( |
| | 0 | 39 | | "Trusting forwarded headers from {Proxies} and {Networks}", |
| | 0 | 40 | | proxies.Proxies.Select(proxy => proxy.ToString()), |
| | 0 | 41 | | proxies.Networks.Select(network => network.ToString())); |
| | | 42 | | |
| | 0 | 43 | | services.Configure<ForwardedHeadersOptions>(proxies.Apply); |
| | | 44 | | |
| | 0 | 45 | | return services; |
| | | 46 | | } |
| | | 47 | | } |