PlotDirector/PlotLine.Tests/NativeCompanionHttpTests.cs

142 lines
22 KiB
C#

using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Reflection;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using PlotDirector.Companion.Protocol;
using PlotLine.Controllers;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.Services.NativeCompanion;
internal static class NativeCompanionHttpTests
{
private static T Proxy<T>(Func<string,object?[]?,object?> handler)where T:class{var item=DispatchProxy.Create<T,StoryPointProxy>();((StoryPointProxy)(object)item).Handler=handler;return item;}
public static async Task Run()
{
void Check(bool condition,string message){if(!condition)throw new Exception(message);}
var user=new AppUser{UserID=7,SecurityStamp=Guid.NewGuid()};var allowed=true;
var users=Proxy<IUserRepository>((name,args)=>Task.FromResult<AppUser?>(user));
var repo=Proxy<IWordCompanionRepository>((name,args)=>name switch{
"ListProjectsAsync"=>Task.FromResult<IReadOnlyList<WordCompanionProjectDto>>([new(){ProjectId=1,Title="Fixture"}]),
"ListBooksAsync"=>Task.FromResult<IReadOnlyList<WordCompanionBookDto>>([new(){BookId=3,Title="Test book"}]),
"GetBookStructureAsync"=>Task.FromResult((int)args![0]! ==3?new WordCompanionBookStructureResponse{BookId=3}:null),
_=>throw new Exception(name)});
var subscriptions=Proxy<ISubscriptionService>((name,args)=>Task.FromResult(new EntitlementDecision{Allowed=allowed}));
var json="""{"schemaVersion":"1.0","chapterSummary":"A fictional chapter.","sceneBoundaries":[{"sceneNumber":1,"startParagraph":1,"endParagraph":1,"suggestedTitle":"A narrative scene","structuralSummary":"The characters encounter a new problem and make a decision to resolve the immediate situation.","confidence":0.8,"reason":"A coherent dramatic unit."}]}""";
var provider=new FakeStoryIntelligenceClient(JsonSerializer.Serialize(new{output=new[]{new{content=new[]{new{type="output_text",text=json}}}}}));
var coverFile=Path.Combine(Path.GetTempPath(),"pd-native-cover-"+Guid.NewGuid()+".png");
using(var bitmap=new SkiaSharp.SKBitmap(20,30)){using var image=SkiaSharp.SKImage.FromBitmap(bitmap);using var png=image.Encode(SkiaSharp.SKEncodedImageFormat.Png,90);File.WriteAllBytes(coverFile,png.ToArray());}
var coverReads=0;
var builder=WebApplication.CreateBuilder(new WebApplicationOptions{EnvironmentName="Development"});builder.Logging.ClearProviders();builder.WebHost.UseUrls("http://127.0.0.1:0");
builder.Services.AddSingleton<IStoryIntelligenceClient>(provider);
builder.Services.AddSingleton(NativeWorkflowTests.Proxy<IBookRepository>((n,a)=>{if(n=="GetCoverPathsAsync")coverReads++;return Task.FromResult<Book?>(new(){BookID=3,ProjectID=1,BookTitle="Fixture book",CoverThumbnailPath="/uploads/books/3/cover.webp"});}));
builder.Services.AddSingleton(Proxy<IUploadStorageService>((n,a)=>n=="TryResolvePublicPath"&&Equals(a![1],"uploads/books/3")?coverFile:throw new Exception("Unexpected cover path lookup")));
builder.Services.AddSingleton(NativeWorkflowTests.Proxy<IWordCompanionService>((n,a)=>n=="AnalyseManuscriptAsync"?Task.FromResult<WordCompanionManuscriptAnalyseResponse?>(new(){CanImport=true,Message="Preview eligible"}):throw new Exception("Unexpected write "+n)));
builder.Services.AddSingleton(NativeWorkflowTests.Proxy<IStoryContextService>((n,a)=>Task.FromResult<StoryContextViewModel?>(null)));
builder.Services.AddSingleton(NativeWorkflowTests.Proxy<IWriterWorkspaceService>((n,a)=>Task.FromResult<PlotLine.ViewModels.ChapterWorkflowViewModel?>(null)));
builder.Services.AddSingleton<INativeInstallationRepository>(new MemoryNativeInstallations(user));builder.Services.AddScoped<NativeInstallationService>();builder.Services.AddSingleton(users);builder.Services.AddSingleton(repo);builder.Services.AddSingleton(subscriptions);
builder.Services.AddSingleton<IDataProtectionProvider>(new EphemeralDataProtectionProvider());builder.Services.AddSingleton(TimeProvider.System);builder.Services.AddSingleton<DesktopPairing>();builder.Services.AddSingleton<NativeAnalysisCache>();builder.Services.AddSingleton(NativeWorkflowTests.Proxy<INativeImportRepository>((n,a)=>n=="List"?Task.FromResult<IReadOnlyList<NativeImportedChapter>>([]):throw new Exception("Unexpected import write "+n)));builder.Services.AddScoped<NativeImportService>();builder.Services.AddSingleton<NativePresenceStore>();builder.Services.AddSingleton<INativeReviewRepository>(new MemoryNativeReviews());
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options=>{options.LoginPath="/fixture-login";options.Cookie.SecurePolicy=Microsoft.AspNetCore.Http.CookieSecurePolicy.None;})
.AddScheme<AuthenticationSchemeOptions,DesktopAuthentication>(DesktopPairing.Scheme,_=>{});
builder.Services.AddRateLimiter(o=>o.AddPolicy("native-pair",_=>System.Threading.RateLimiting.RateLimitPartition.GetNoLimiter("fixture")));
builder.Services.AddSignalR();builder.Services.AddAuthorization();builder.Services.AddControllersWithViews().AddApplicationPart(typeof(NativeCompanionController).Assembly);
builder.Services.AddSingleton<IManuscriptStructureAnalysisService>(new ManuscriptStructureAnalysisService(new FakeStoryPromptRepository(),new FakeStoryPromptVersionService(),provider,new ChapterStructureValidator(),NullLogger<ManuscriptStructureAnalysisService>.Instance));
await using var app=builder.Build();app.UseRouting();app.UseRateLimiter();app.UseAuthentication();app.UseAuthorization();
app.MapGet("/fixture-login",async (Microsoft.AspNetCore.Http.HttpContext context)=>{await context.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity([new(ClaimTypes.NameIdentifier,"7"),new("PlotLine.SecurityStamp",user.SecurityStamp.ToString())],CookieAuthenticationDefaults.AuthenticationScheme)));return "Fixture login";});
app.MapGet("/fixture-antiforgery",(IAntiforgery xsrf,Microsoft.AspNetCore.Http.HttpContext context)=>xsrf.GetAndStoreTokens(context).RequestToken);
app.MapGet("/fixture-render-review/{id:guid}",async (Guid id,Microsoft.AspNetCore.Http.HttpContext context)=>{
var row=await context.RequestServices.GetRequiredService<INativeReviewRepository>().Get(7,id);if(row==null)return Microsoft.AspNetCore.Http.Results.NotFound();
var action=new Microsoft.AspNetCore.Mvc.ActionContext(context,new Microsoft.AspNetCore.Routing.RouteData(),new Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor());
var views=context.RequestServices.GetRequiredService<Microsoft.AspNetCore.Mvc.ViewEngines.ICompositeViewEngine>();var view=views.GetView(null,"/Views/NativeWorkspace/Review.cshtml",false);if(!view.Success)throw new Exception("Native review Razor view unavailable");
using var writer=new StringWriter();var data=new Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary(new Microsoft.AspNetCore.Mvc.ModelBinding.EmptyModelMetadataProvider(),new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary()){Model=new NativeReviewModel(row,JsonSerializer.Deserialize<AiChapterResult>(row.ResultJson)!,string.IsNullOrEmpty(row.DecisionsJson)?[]:JsonSerializer.Deserialize<NativeSceneDecision[]>(row.DecisionsJson)!,[],1)};
var temp=new Microsoft.AspNetCore.Mvc.ViewFeatures.TempDataDictionary(context,context.RequestServices.GetRequiredService<Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataProvider>());
await view.View.RenderAsync(new Microsoft.AspNetCore.Mvc.Rendering.ViewContext(action,view.View,data,temp,writer,new Microsoft.AspNetCore.Mvc.ViewFeatures.HtmlHelperOptions()));return Microsoft.AspNetCore.Http.Results.Content(writer.ToString(),"text/html");
}).RequireAuthorization();
app.MapHub<PlotLine.Hubs.NativeCompanionPresenceHub>("/hubs/native-companion");app.MapControllers();await app.StartAsync();
try
{
var address=app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses.Single();
using var browserHandler=new HttpClientHandler{AllowAutoRedirect=false};using var browser=new HttpClient(browserHandler){BaseAddress=new Uri(address)};
using var agent=new HttpClient(new HttpClientHandler{AllowAutoRedirect=false,UseCookies=false}){BaseAddress=new Uri(address)};
Check((await agent.GetAsync("/api/native-companion/books")).StatusCode==HttpStatusCode.Unauthorized,"Native API is not anonymous");
var anonymousHub=(await agent.PostAsync("/hubs/native-companion/negotiate?negotiateVersion=1",null)).StatusCode;Check(anonymousHub is HttpStatusCode.Unauthorized or HttpStatusCode.Redirect,"Anonymous native hub subscription refused");
var verifier=new string('d',64);var challenge=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(verifier)));
var oversized=await agent.PostAsJsonAsync("/api/native-companion/pair",new{challenge=new string('A',64),padding=new string('x',5000)});Check(!oversized.IsSuccessStatusCode,"Oversized pairing bodies are refused before pairing state creation");
var paired=await agent.PostAsJsonAsync("/api/native-companion/pair",new{challenge});Check(paired.IsSuccessStatusCode,"Pairing start accepts verifier challenge");
var code=(await paired.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("code").GetString()!;
Check((await browser.GetAsync("/native-companion/authorize?code="+code)).StatusCode==HttpStatusCode.Redirect,"Browser approval requires existing site sign-in");
await browser.GetAsync("/fixture-login");
var approval=await browser.GetAsync("/native-companion/authorize?code="+code);Check(approval.IsSuccessStatusCode&&(await approval.Content.ReadAsStringAsync()).Contains("Approve this Word Companion connection"),"Actual approval view renders before any upload");
Check((await browser.PostAsync("/native-companion/authorize",new FormUrlEncodedContent(new Dictionary<string,string>{{"code",code}}))).StatusCode==HttpStatusCode.BadRequest,"Approval enforces antiforgery");
var antiforgery=await browser.GetStringAsync("/fixture-antiforgery");
Check((await browser.PostAsync("/native-companion/authorize",new FormUrlEncodedContent(new Dictionary<string,string>{{"code",code},{"retainImport","true"},{"__RequestVerificationToken",antiforgery}}))).IsSuccessStatusCode,"Authenticated antiforgery approval succeeds");
var redeemed=await agent.PostAsJsonAsync("/api/native-companion/token",new{code,verifier});Check(redeemed.IsSuccessStatusCode,"Agent redeems approved pairing");
var token=(await redeemed.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("accessToken").GetString();agent.DefaultRequestHeaders.Authorization=new AuthenticationHeaderValue("Bearer",token);
Check((await agent.GetFromJsonAsync<CompanionBook[]>("/api/native-companion/books"))!.Single().BookId==3,"Grant loads authorized books through actual routing");
var listed=(await agent.GetFromJsonAsync<CompanionBook[]>("/api/native-companion/books"))!.Single();Check(listed.ProjectTitle=="Fixture"&&listed.BookTitle=="Test book","Native book selection includes author-facing project and book names");
Check((await agent.GetAsync("/api/native-companion/books/999/cover")).StatusCode==HttpStatusCode.Forbidden&&coverReads==0,"Foreign book cover denied before private file lookup");
var cover=await agent.GetFromJsonAsync<BookCoverReply>("/api/native-companion/books/3/cover");Check(coverReads==1&&Convert.FromBase64String(cover!.Png).Take(4).SequenceEqual(new byte[]{137,80,78,71}),"Authorised cover uses an actual bounded PNG suitable for Windows");
Check((await agent.GetFromJsonAsync<ConnectionHealth>("/api/native-companion/connection"))?.Authentication=="verified","Authenticated health verifies current session and configuration without paid AI request");
Check((await agent.GetFromJsonAsync<SavedWorkspace>("/api/native-companion/books/3/workspace"))?.State=="saved-book","Saved workspace is scoped to accessible book over actual HTTP");
var preview=await agent.PostAsJsonAsync("/api/native-companion/import-preview",NativeWorkflowTests.Selection());Check(preview.IsSuccessStatusCode&&(await preview.Content.ReadFromJsonAsync<PlotDirector.Companion.Protocol.ImportPreview>())?.CommitAvailable==false,"HTTP import preview is read-only with commit explicitly unavailable");
var request=new AiChapterRequest{BookId=3,ManuscriptId=Guid.NewGuid(),SessionId=Guid.NewGuid(),RequestId=Guid.NewGuid(),ChapterStart=20,ChapterEnd=40,Paragraphs=[new(){Index=1,Start=20,End=40,Text="A fictional narrative paragraph."}]};
var response=await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request);Check(response.IsSuccessStatusCode,"Authenticated chapter API calls canonical service");
var result=await response.Content.ReadFromJsonAsync<AiChapterResult>();Check(result?.State=="complete"&&result.Scenes.Single().Start==20&&provider.Prompts.Count==1,"Actual HTTP response maps scene to Word position");
Check((await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request)).IsSuccessStatusCode&&provider.Prompts.Count==1,"HTTP retry reuses successful provider result");
Check(result!.ReviewPath.StartsWith("/native-companion/reviews/")&&!string.IsNullOrWhiteSpace(result.Scenes.Single().Summary),"AI summary is preserved and saved PWA review handoff returned");
var reviewId=Guid.Parse(result.ReviewPath.Split('/').Last());var reviewHtml=await browser.GetStringAsync("/fixture-render-review/"+reviewId);Check(reviewHtml.Contains("Save review decisions")&&reviewHtml.Contains("Summary")&&reviewHtml.Contains("scene"),"Actual compiled Razor review renders AI title/summary form");
var decisionFields=new Dictionary<string,string>{{"version","1"},{"scenes[0].Index","0"},{"scenes[0].State","approved"},{"scenes[0].Title","<script>not-executable</script>"},{"scenes[0].Summary","Edited summary"},{"__RequestVerificationToken",antiforgery}};
Check((await browser.PostAsync(result.ReviewPath,new FormUrlEncodedContent(decisionFields))).StatusCode==HttpStatusCode.Redirect,"Actual antiforgery-protected form binds and saves review decisions");
Check((await browser.PostAsync(result.ReviewPath,new FormUrlEncodedContent(decisionFields))).StatusCode==HttpStatusCode.Conflict,"Actual stale review form receives conflict without overwriting");reviewHtml=await browser.GetStringAsync("/fixture-render-review/"+reviewId);Check(!reviewHtml.Contains("<script>not-executable</script>")&&reviewHtml.Contains("Edited summary"),"Saved title is encoded while edited summary remains reviewable");
request.RequestId=Guid.NewGuid();var reused=await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request);Check(reused.IsSuccessStatusCode&&provider.Prompts.Count==1,"Unchanged chapter content reuses durable suggestion across new request identifiers");
Check((await reused.Content.ReadFromJsonAsync<AiChapterResult>())?.SourceRetained==true,"Retaining source requires explicit opt-in and reuses analysis without another provider call");
using(var previewScope=app.Services.CreateScope()){var plan=await previewScope.ServiceProvider.GetRequiredService<NativeImportService>().Preview(7,3,[reviewId]);Check(plan.Conflicts.Length==0&&plan.Items.Single().Scenes.Single().Text==request.Paragraphs.Single().Text,"Actual HTTP retained source and approved decisions produce an exact-prose import preview");}
var negotiation=await browser.PostAsync("/hubs/native-companion/negotiate?negotiateVersion=1",null);Check(negotiation.IsSuccessStatusCode,"Native presence hub requires normal browser authentication and negotiates after sign-in");
var connectionToken=(await negotiation.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("connectionToken").GetString();
using var socket=new System.Net.WebSockets.ClientWebSocket();socket.Options.Cookies=browserHandler.CookieContainer;using var socketTimeout=new CancellationTokenSource(TimeSpan.FromSeconds(10));
await socket.ConnectAsync(new Uri(address.Replace("http://","ws://")+"/hubs/native-companion?id="+Uri.EscapeDataString(connectionToken!)),socketTimeout.Token);
await socket.SendAsync(Encoding.UTF8.GetBytes("{\"protocol\":\"json\",\"version\":1}\u001e"),System.Net.WebSockets.WebSocketMessageType.Text,true,socketTimeout.Token);
var socketBuffer=new byte[4096];await socket.ReceiveAsync(socketBuffer,socketTimeout.Token);
var instance=Guid.NewGuid();var document=Guid.NewGuid();var live=new NativePresence{BookId=3,ManuscriptId=request.ManuscriptId,Sequence=1,DocumentTitle="Synthetic manuscript"};
Check((await agent.PostAsJsonAsync($"/api/native-companion/instances/{instance}/documents/{document}/presence",live)).IsSuccessStatusCode,"Actual bearer-scoped presence accepted");
var notification=await socket.ReceiveAsync(socketBuffer,socketTimeout.Token);Check(Encoding.UTF8.GetString(socketBuffer,0,notification.Count).Contains("NativePresenceChanged"),"Authenticated native hub pushes only invalidation, not prose or navigation feedback");socket.Abort();
var leases=await browser.GetFromJsonAsync<JsonElement[]>("/native-companion/presence?bookId=3");Check(leases?.Length==1,"Authenticated browser sees scoped native session without prose");
Check((await agent.PostAsJsonAsync($"/api/native-companion/instances/{instance}/documents/{document}/presence",live)).StatusCode==HttpStatusCode.Conflict,"Actual HTTP stale sequence refused");
Check((await browser.PostAsync(result.ReviewPath,new FormUrlEncodedContent(new Dictionary<string,string>{{"version","1"}}))).StatusCode==HttpStatusCode.BadRequest,"Review decisions require antiforgery");
Check((await agent.PostAsync("/api/native-companion/presence/disconnect",null)).IsSuccessStatusCode,"Signout disconnect revokes grant presence");
live.Sequence=2;Check((await agent.PostAsJsonAsync($"/api/native-companion/instances/{instance}/documents/{document}/presence",live)).StatusCode==HttpStatusCode.Conflict,"Late heartbeat cannot restore signed-out presence");
request.BookId=999;Check((await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request)).StatusCode==HttpStatusCode.Forbidden&&provider.Prompts.Count==1,"Foreign book rejected without provider charge");request.BookId=3;
allowed=false;Check((await agent.PostAsJsonAsync("/api/native-companion/analyse-chapter",request)).StatusCode==HttpStatusCode.Forbidden,"Subscription access enforced on HTTP path");allowed=true;
var runtime=Guid.NewGuid();var devicePair=await agent.PostAsJsonAsync("/api/native-companion/pair",new{challenge,persistent=true,connectionId=runtime,deviceName="HTTP fixture installation"});var deviceCode=(await devicePair.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("code").GetString()!;
await browser.PostAsync("/native-companion/authorize",new FormUrlEncodedContent(new Dictionary<string,string>{{"code",deviceCode},{"__RequestVerificationToken",antiforgery}}));
var device=(await(await agent.PostAsJsonAsync("/api/native-companion/token",new{code=deviceCode,verifier})).Content.ReadFromJsonAsync<NativeDeviceTokens>())!;
agent.DefaultRequestHeaders.Authorization=new("Bearer",device.AccessToken);Check((await agent.GetAsync("/api/native-companion/books")).IsSuccessStatusCode,"Actual HTTP trusted installation authenticates");
var rotate=new NativeDeviceRenew(device.InstallationId,device.DeviceSecret!,new string('C',64),Guid.NewGuid(),runtime);var rotatedResponse=await agent.PostAsJsonAsync("/api/native-companion/renew",rotate);Check(rotatedResponse.IsSuccessStatusCode,"Actual HTTP access renewal does not need browser approval");
var renewed=(await rotatedResponse.Content.ReadFromJsonAsync<NativeDeviceTokens>())!;Check((await agent.PostAsJsonAsync("/api/native-companion/renew",rotate)).IsSuccessStatusCode,"Actual HTTP rotation retry is idempotent");
Check((await agent.PostAsJsonAsync("/api/native-companion/renew",rotate with{RotationId=Guid.NewGuid()})).StatusCode==HttpStatusCode.Unauthorized,"Actual HTTP stale credential cannot start another rotation");
agent.DefaultRequestHeaders.Authorization=new("Bearer",renewed.AccessToken);Check((await agent.PostAsJsonAsync("/api/native-companion/revoke",rotate with{Credential=new string('C',64),NextCredential=""})).IsSuccessStatusCode,"Explicit trusted sign-out revokes installation over HTTP");Check((await agent.GetAsync("/api/native-companion/books")).StatusCode==HttpStatusCode.Unauthorized,"Actual HTTP revocation invalidates unexpired access immediately");
agent.DefaultRequestHeaders.Authorization=new("Bearer",token);
user.SecurityStamp=Guid.NewGuid();Check((await agent.GetAsync("/api/native-companion/books")).StatusCode==HttpStatusCode.Unauthorized,"Revoked grant rejected through HTTP handler");
}
finally{await app.StopAsync();File.Delete(coverFile);}
Console.WriteLine("PASS actual HTTP native pairing, antiforgery, bearer/stamp, book/subscription access, canonical AI/idempotency, persistent review and live WebSocket invalidation (synthetic provider, no database)");
}
}