PlotDirector/PlotLine.Tests/ApplicationDomainBoundaryTests.cs

35 lines
2.9 KiB
C#

using System.Security.Claims;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using PlotLine.Controllers;
using PlotLine.Services;
internal static class ApplicationDomainBoundaryTests
{
public static void Run()
{
using var services=new ServiceCollection().AddSingleton<IConfiguration>(new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string,string?> { ["Site:WebsiteBaseUrl"]="https://plotdirector.com" }).Build()).BuildServiceProvider();
var builder=new ApplicationBuilder(services);builder.UseApplicationDomainBoundary();builder.Run(c=>{c.Response.StatusCode=204;return Task.CompletedTask;});var pipeline=builder.Build();
foreach(var path in new[]{"/features","/features/timeline","/problem-solver","/privacy","/pricing"})
{
var c=new DefaultHttpContext{RequestServices=services};c.Request.Path=path;c.Request.QueryString=new("?from=test");pipeline(c).GetAwaiter().GetResult();
Check(c.Response.StatusCode==308 && c.Response.Headers.Location=="https://plotdirector.com"+path+"?from=test","Public route redirect");
Check(c.Response.Headers["X-Robots-Tag"]=="noindex, nofollow","Application noindex");
}
foreach(var path in new[]{"/Projects","/Pricing/Checkout","/help/getting-started/first-book","/word-companion","/api/native-companion","/hubs/word-companion-follow","/problem-solver/workspace/characters"})
{var c=new DefaultHttpContext{RequestServices=services};c.Request.Path=path;pipeline(c).GetAwaiter().GetResult();Check(c.Response.StatusCode==204,"Preserve application route "+path);}
Check(new HomeController().Index() is RedirectToActionResult {ControllerName:"Projects",ActionName:"Index"},"Root lands on Projects");
var http=new DefaultHttpContext();http.User=new ClaimsPrincipal(new ClaimsIdentity(new[]{new Claim(ClaimTypes.NameIdentifier,"1")},"Test"));
var controller=new AccountController(null!){ControllerContext=new(new ActionContext(http,new Microsoft.AspNetCore.Routing.RouteData(),new Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor()))};controller.Url=new UrlHelper(controller.ControllerContext);
Check(controller.Login() is RedirectToActionResult {ControllerName:"Projects"},"Authenticated sign in opens Projects");
Check(controller.Login("/Books/Details/123") is LocalRedirectResult {Url:"/Books/Details/123"},"Safe deep link survives");
foreach(var url in new[]{"https://example.com/","//example.com/","/\\example.com/"})Check(controller.Login(url) is RedirectToActionResult {ControllerName:"Projects"},"Reject open redirect");
Console.WriteLine("PASS Application domain boundary, Projects landing, authenticated sign in and safe deep links");
}
private static void Check(bool ok,string message){if(!ok)throw new InvalidOperationException(message);}
}