45 lines
2.1 KiB
C#
45 lines
2.1 KiB
C#
using System.Net;
|
|
using Microsoft.AspNetCore.Authentication;
|
|
using Microsoft.AspNetCore.Builder;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using PlotLine.Services;
|
|
|
|
internal static class TrustedProxySchemeTests
|
|
{
|
|
public static void LoginRedirectScheme() => Run().GetAwaiter().GetResult();
|
|
private static async Task Run()
|
|
{
|
|
using var services = new ServiceCollection().AddLogging().AddOptions()
|
|
.AddAuthentication("Test").AddCookie("Test", options => {
|
|
options.LoginPath = "/Account/Login";
|
|
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
|
|
}).Services.BuildServiceProvider();
|
|
var builder = new ApplicationBuilder(services);
|
|
builder.UseTrustedProxyScheme();
|
|
builder.UseAuthentication();
|
|
builder.Run(context => context.ChallengeAsync("Test"));
|
|
var pipeline = builder.Build();
|
|
foreach (var (remote, forwarded, expected) in new[] {
|
|
(IPAddress.Loopback, "https", "https"),
|
|
(IPAddress.IPv6Loopback, "https", "https"),
|
|
(IPAddress.Loopback, "http", "http"),
|
|
(IPAddress.Parse("203.0.113.10"), "https", "http")
|
|
})
|
|
{
|
|
using var requestScope = services.CreateScope();
|
|
var context = new DefaultHttpContext { RequestServices = requestScope.ServiceProvider };
|
|
context.Connection.RemoteIpAddress = remote;
|
|
context.Request.Scheme = "http";
|
|
context.Request.Host = new HostString("dev.plotdirector.test");
|
|
context.Request.Path = "/private";
|
|
context.Request.Headers["X-Forwarded-Proto"] = forwarded;
|
|
context.Request.Headers["X-Forwarded-Host"] = "untrusted.example";
|
|
await pipeline(context);
|
|
var location = context.Response.Headers.Location.ToString();
|
|
if (context.Response.StatusCode != 302 || !location.StartsWith(expected + "://dev.plotdirector.test/Account/Login?", StringComparison.Ordinal))
|
|
throw new Exception("Login redirects must preserve the trusted proxy scheme and ignore untrusted forwarded headers.");
|
|
}
|
|
}
|
|
}
|