93 lines
6.5 KiB
C#
93 lines
6.5 KiB
C#
using System.Net;
|
|
using System.Security.Claims;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using Microsoft.AspNetCore.Antiforgery;
|
|
using Microsoft.AspNetCore.Builder;
|
|
using Microsoft.AspNetCore.Hosting;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.Mvc.Filters;
|
|
using Microsoft.AspNetCore.Hosting.Server;
|
|
using Microsoft.AspNetCore.Hosting.Server.Features;
|
|
using Microsoft.AspNetCore.DataProtection;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging;
|
|
using PlotLine.Controllers;
|
|
using PlotLine.Models;
|
|
using PlotLine.Services;
|
|
using PlotLine.ViewModels;
|
|
|
|
// Real MVC model binding, production controller metadata, authentication/antiforgery; no SQL, workers or live sessions.
|
|
internal static class ImportTransportTests
|
|
{
|
|
public static async Task RunAsync()
|
|
{
|
|
var builder=WebApplication.CreateBuilder(new WebApplicationOptions{EnvironmentName="Development"});
|
|
builder.WebHost.UseUrls("http://127.0.0.1:0");builder.Logging.ClearProviders();
|
|
builder.Services.AddDataProtection().UseEphemeralDataProtectionProvider();
|
|
builder.Services.AddAuthentication("TransportFixture").AddCookie("TransportFixture",options=>options.Events.OnRedirectToLogin=context=>{context.Response.StatusCode=401;return Task.CompletedTask;});
|
|
builder.Services.AddAuthorization();
|
|
builder.Services.AddSingleton<IImportService>(new UnusedImportService());
|
|
builder.Services.AddControllersWithViews(options=>options.Filters.Add(new TransportResult())).AddApplicationPart(typeof(ImportsController).Assembly);
|
|
await using var app=builder.Build();
|
|
app.Use(async(context,next)=>{if(!context.Request.Headers.ContainsKey("X-Fixture-Anonymous"))context.User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,"synthetic-transport")],"TransportFixture"));await next();});
|
|
app.UseAuthorization();
|
|
app.MapGet("/_transport/token",(IAntiforgery antiforgery,HttpContext context)=>Results.Text(antiforgery.GetAndStoreTokens(context).RequestToken!));
|
|
app.MapControllerRoute("default","{controller=Imports}/{action=Index}/{id?}");
|
|
await app.StartAsync();
|
|
var address=app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses.Single();
|
|
using var client=new HttpClient(new HttpClientHandler{AllowAutoRedirect=false,UseCookies=true}){BaseAddress=new Uri(address)};
|
|
var token=await client.GetStringAsync("/_transport/token");
|
|
var small=new string('x',1024)+"雪 café 🖋";
|
|
var large=new string('x',5*1024*1024)+"雪 café 🖋";
|
|
var failures=new List<string>();
|
|
foreach(var action in new[]{"Preview","Import","ValidationReport"})
|
|
foreach(var payload in new[]{small,large})
|
|
{
|
|
using var body=new FormUrlEncodedContent(new Dictionary<string,string>{{"JsonText",payload},{"__RequestVerificationToken",token}});
|
|
using var response=await client.PostAsync("/Imports/"+action,body);
|
|
if(response.StatusCode!=HttpStatusCode.OK){failures.Add($"{action}: {payload.Length} characters returned HTTP {(int)response.StatusCode}");continue;}
|
|
var result=JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement;
|
|
if(result.GetProperty("length").GetInt32()!=payload.Length || result.GetProperty("sha256").GetString()!=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload))))failures.Add(action+": bound content differs");
|
|
}
|
|
using(var body=new MultipartFormDataContent())
|
|
{
|
|
body.Add(new StringContent(token),"__RequestVerificationToken");
|
|
body.Add(new ByteArrayContent(Encoding.UTF8.GetBytes(large)),"JsonFile","synthetic.plotdirector");
|
|
using var response=await client.PostAsync("/Imports/Preview",body);
|
|
if(response.StatusCode!=HttpStatusCode.OK || JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.GetProperty("fileLength").GetInt64()!=Encoding.UTF8.GetByteCount(large))failures.Add("Multipart upload did not preserve the 5 MiB input");
|
|
}
|
|
using(var response=await client.PostAsync("/Imports/Import",new FormUrlEncodedContent(new Dictionary<string,string>{{"JsonText",small}})))
|
|
if(response.StatusCode!=HttpStatusCode.BadRequest)failures.Add("Missing antiforgery token was not rejected");
|
|
using(var request=new HttpRequestMessage(HttpMethod.Post,"/Imports/Preview"))
|
|
{
|
|
request.Headers.Add("X-Fixture-Anonymous","true");request.Content=new FormUrlEncodedContent(new Dictionary<string,string>{{"JsonText",small}});
|
|
using var response=await client.SendAsync(request);if(response.StatusCode!=HttpStatusCode.Unauthorized)failures.Add("Anonymous import was not rejected");
|
|
}
|
|
await app.StopAsync();
|
|
if(failures.Count>0)throw new InvalidOperationException(string.Join("; ",failures));
|
|
Console.WriteLine("PASS real MVC import transport: all three POST actions retain 5 MiB pasted/carried content and Unicode; multipart upload, authentication and antiforgery verified. Import service/SQL verification is separate.");
|
|
}
|
|
private sealed class TransportResult:IAsyncActionFilter
|
|
{
|
|
public Task OnActionExecutionAsync(ActionExecutingContext context,ActionExecutionDelegate next)
|
|
{
|
|
if(context.Controller is ImportsController && context.ActionArguments.TryGetValue("model",out var value) && value is ImportIndexViewModel model)
|
|
{
|
|
context.Result=context.ModelState.IsValid ? new JsonResult(new{length=model.JsonText.Length,sha256=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(model.JsonText))),fileLength=model.JsonFile?.Length??0}) : new BadRequestResult();
|
|
return Task.CompletedTask;
|
|
}
|
|
return Continue(next);
|
|
}
|
|
private static async Task Continue(ActionExecutionDelegate next) { await next(); }
|
|
}
|
|
private sealed class UnusedImportService:IImportService
|
|
{
|
|
public Task<ImportIndexViewModel> PreviewAsync(ImportIndexViewModel model)=>throw new InvalidOperationException("Transport filter must intercept execution.");
|
|
public Task<ImportResult> ImportAsync(ImportIndexViewModel model)=>throw new InvalidOperationException("Transport filter must intercept execution.");
|
|
public Task<string> BuildValidationReportAsync(ImportIndexViewModel model)=>throw new InvalidOperationException("Transport filter must intercept execution.");
|
|
}
|
|
}
|