diff --git a/Docs/Sprints/2026-11-03-phase2.md b/Docs/Sprints/2026-11-03-phase2.md index 78fd93b4..9fed2015 100644 --- a/Docs/Sprints/2026-11-03-phase2.md +++ b/Docs/Sprints/2026-11-03-phase2.md @@ -16,11 +16,11 @@ 2. COMPLETE: Writer/shared surface spacing, requested icon changes, Locations conventional commands/grips, mobile Chapter table repair and rendered coverage inventory (9d78a63, 016b58f, 869e305). 3. DEFERRED ACCEPTANCE: authenticated live Writer/PWA testing; no session is available. Real full-layout browser/Hub fixture results are recorded separately. 4. DEFERRED DEPLOYMENT: two illustration records were Generating at restart preflight. No interruption authorised; expanded gate b523a86 refuses restart. Recheck only at the next meaningful deployment checkpoint. -5. CURRENT: persistent-data inventory (167 schema tables / 114 project candidates / 55 existing serialized entity sets); initial isolated map/asset/book-metadata/rollback repairs under broader verification. -6. NEXT: extend backed-up authoritative manuscript sources, writing plans and other confirmed persistent omissions; populate and compare all supported entity sets in isolated SQL, including same-project restore, references, assets and failure recovery. Human SI review/audit data is persistent under its runtime contract, not an expendable cache. -7. PENDING: complete table/file classification and historical-backup fixture discovery; do not claim comprehensive backup coverage from the initial map/core cases. -8. PENDING: inventory every import/export workflow and intended fidelity; run applicable synthetic semantic round trips and repair confirmed defects. -9. PENDING: final serial build/harness, focused integration/browser/visual verification; safe Development deployment and concise handover. +5. COMPLETE CHECKPOINT: serialized backup/restore coverage now has 69 collections (65 persistent plus 4 diagnostic/shared vocabulary), 70 SQL entities / 838 columns with no missing non-computed model properties. All 65 persistent collections have populated stored-value copy/in-place comparisons; 12 uploaded files and embedded map image bytes are verified. Commits f12ad43, dbb2e2d, 6ae3715, 571f670, 28397ff. +6. CURRENT: HTTP Import/Export transport and workflow/format inventory. Reproduced 5 MiB carried-forward JSON rejection across three POST actions; per-field limit repair under HTTP verification. Next: actual SQL export packets in all supported formats, then legacy JSON and manuscript import semantics. +7. PENDING: remaining persistent table classification and historical fixture discovery. Unrepresented SI review/audit/provenance is persistent under its runtime contract, not an expendable cache; project-derived illustration catalogue/files also remain outside verified backup coverage. Do not claim a complete 167-table audit. +8. PENDING: finish independently safe data gaps and meaningful format round trips; record concrete limits/deferred work. No historical compatibility claim without actual fixtures. +9. PENDING: final serial build/harness and focused browser/integration checks; meaningful restart-gate recheck, safe Development deployment if idle, concise handover. ## Execution record @@ -175,3 +175,9 @@ Twenty malformed previews fail before allocation, including missing file records Evidence: `/tmp/plotdirector-phase2-transfer-files.log` passed; solution build zero warnings/errors. Broader harness is running before commit. Full authenticated browser transfer of large embedded backups is not yet tested; Import/Export workflow/format verification remains next. Remaining unrepresented SI/review/provenance data and project-derived illustration-library files are explicitly outside this checkpoint. No running Development schema/data writes or deployment. The asset checkpoint's full regression harness passed: 405 checks, exit 0 (`/tmp/plotdirector-phase2-tests-files.log`). Latest expanded SQL run also verifies complete safety-backup refusal when active file bytes are missing. Source-field inventory regenerated for gallery metadata. A separate HTTP transport fixture is now under development; its results are not included in this checkpoint. + +### HTTP import carry-forward limit + +A real isolated MVC host reproduced HTTP 400 for 5 MiB JSON carried as a form value on Preview, Import and ValidationReport. Small values and a 5 MiB multipart file succeeded; the default per-value form parser limit was the blocker after upload/preview. ImportsController now allows 32 MiB per form value, leaving existing request-body/upstream limits unchanged. This is not a claim that arbitrary-size backups can pass the deployed reverse proxy. + +After repair, all three production POST actions bind the complete 5 MiB payload and Unicode suffix with matching SHA-256; multipart bytes also match. Missing antiforgery tokens return 400 and anonymous requests return 401. The fixture exercises production controller metadata/model binding with an action filter that reports bound data; service/SQL behavior is covered separately, and no live authenticated acceptance is implied. Evidence: `/tmp/plotdirector-phase2-import-transport-before.log` (three failures), `/tmp/plotdirector-phase2-import-transport-after.log` (pass). Build zero warnings/errors; preceding asset checkpoint's 405-check harness passed. No Development changes. diff --git a/PlotLine.Tests/ImportTransportTests.cs b/PlotLine.Tests/ImportTransportTests.cs new file mode 100644 index 00000000..152779da --- /dev/null +++ b/PlotLine.Tests/ImportTransportTests.cs @@ -0,0 +1,92 @@ +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(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().Features.Get()!.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(); + foreach(var action in new[]{"Preview","Import","ValidationReport"}) + foreach(var payload in new[]{small,large}) + { + using var body=new FormUrlEncodedContent(new Dictionary{{"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{{"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{{"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 PreviewAsync(ImportIndexViewModel model)=>throw new InvalidOperationException("Transport filter must intercept execution."); + public Task ImportAsync(ImportIndexViewModel model)=>throw new InvalidOperationException("Transport filter must intercept execution."); + public Task BuildValidationReportAsync(ImportIndexViewModel model)=>throw new InvalidOperationException("Transport filter must intercept execution."); + } +} diff --git a/PlotLine.Tests/Program.cs b/PlotLine.Tests/Program.cs index e68086d8..b7ff389f 100644 --- a/PlotLine.Tests/Program.cs +++ b/PlotLine.Tests/Program.cs @@ -17,6 +17,13 @@ using PlotLine.ViewModels; #pragma warning disable CS8321 +if (args.Contains("--import-transport")) +{ + try { await ImportTransportTests.RunAsync(); } + catch(Exception ex) { Console.Error.WriteLine(ex.Message); Environment.ExitCode=1; } + return; +} + if (args.Contains("--writing-solver-dead-ends")) { WritingSolverDeadEndTests.Run(args); diff --git a/PlotLine/Controllers/ImportsController.cs b/PlotLine/Controllers/ImportsController.cs index 5c718cbe..a44e5171 100644 --- a/PlotLine/Controllers/ImportsController.cs +++ b/PlotLine/Controllers/ImportsController.cs @@ -7,6 +7,7 @@ using System.Text; namespace PlotLine.Controllers; [Authorize] +[RequestFormLimits(ValueLengthLimit = 32 * 1024 * 1024)] public sealed class ImportsController(IImportService imports) : Controller { public IActionResult Index() => View(new ImportIndexViewModel