PlotDirector/PlotLine.Tests/NativeCompanionTests.cs

91 lines
9.6 KiB
C#

using System.Reflection;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using PlotLine.Controllers;
using PlotLine.Data;
using PlotLine.Models;
using System.Security.Cryptography;
using System.Text;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.Logging.Abstractions;
using PlotDirector.Companion.Protocol;
using PlotLine.Services;
using PlotLine.Services.NativeCompanion;
internal static class NativeCompanionTests
{
public static async Task Run()
{
void Check(bool value,string name){if(!value)throw new Exception(name);}
var clock=new Clock();var pairing=new DesktopPairing(new EphemeralDataProtectionProvider(),clock);
var verifier=new string('a',64);var challenge=Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(verifier)));
var code=pairing.Start(challenge);
Check(pairing.Redeem(code,verifier)==null,"Pairing needs browser approval");
var stamp=Guid.NewGuid();Check(pairing.Approve(code,7,stamp),"First browser approval");Check(!pairing.Approve(code,9,Guid.NewGuid()),"Cannot change approved owner");
Check(pairing.Redeem(code,new string('b',64))==null,"Wrong verifier refused");
var token=pairing.Redeem(code,verifier)!;var grant=pairing.Read(token)!;
Check(grant.UserId==7&&grant.Stamp==stamp&&pairing.Redeem(code,verifier)==null,"One-use code yields correct protected subject");
Check(pairing.Read("tampered"+token)==null,"Tampered grant refused");clock.Now=clock.Now.AddHours(5);Check(pairing.Read(token)==null,"Expired grant refused");
var expires=pairing.Start(challenge);clock.Now=clock.Now.AddMinutes(6);Check(!pairing.Approve(expires,7,stamp),"Expired browser request refused");
var request=new AiChapterRequest{RequestId=Guid.NewGuid(),BookId=3,ManuscriptId=Guid.NewGuid(),SessionId=Guid.NewGuid(),ChapterStart=100,ChapterEnd=135,Paragraphs=[new(){Index=1,Start=100,End=110,Text="First scene."},new(){Index=2,Start=110,End=111,Text="\r"},new(){Index=3,Start=111,End=135,Text="Second scene begins."}]};
var mapped=NativeChapterMapping.Build(request);
Check(mapped.ParagraphMap.Count==2&&mapped.ParagraphMap[1].WordParagraphIndex==3&&mapped.PrivateAnalysis,"Blank paragraphs retain reversible Word mapping and private logging");
var chapterJson="""{"schemaVersion":"1.0","chapterSummary":"A transition between arrival and departure.","sceneBoundaries":[{"sceneNumber":1,"startParagraph":1,"endParagraph":1,"suggestedTitle":"Arrival","confidence":0.9,"reason":"Opening","structuralSummary":"The opening scene establishes a clear dramatic moment and situation for the characters."},{"sceneNumber":2,"startParagraph":2,"endParagraph":2,"suggestedTitle":"Departure","confidence":0.8,"reason":"Transition","structuralSummary":"The next scene shifts the dramatic situation to a new moment and a different goal."}]}""";
var fake=new FakeStoryIntelligenceClient(System.Text.Json.JsonSerializer.Serialize(new{output=new[]{new{content=new[]{new{type="output_text",text=chapterJson}}}}}));
var service=new ManuscriptStructureAnalysisService(new FakeStoryPromptRepository(),new FakeStoryPromptVersionService(),fake,new ChapterStructureValidator(),NullLogger<ManuscriptStructureAnalysisService>.Instance);
var result=await service.AnalyseChapterAsync(mapped);
Check(result.Success,result.ErrorMessage??"Existing chapter AI pipeline accepts native paragraph map");
var answer=NativeChapterMapping.Map(request,result);
Check(answer.Scenes.Length==2&&answer.Scenes[0].Start==100&&answer.Scenes[1].Start==111&&answer.Scenes[1].End==135&&answer.Scenes.All(s=>s.Origin=="AI"),"AI boundaries map to exact Word ranges with explicit origin");
Check(fake.Prompts.Single().Contains("First scene.")&&fake.Prompts.Single().Contains("Second scene begins."),"Existing prompt receives one chapter");
request.Paragraphs[1].Start=109;try{NativeChapterMapping.Build(request);throw new Exception("Accepted bad map");}catch(ArgumentException){}
var cache=new NativeAnalysisCache(clock);var calls=0;var id=Guid.NewGuid();var done=new TaskCompletionSource<AiChapterResult>();
var first=cache.Run(7,id,"same",_=>{calls++;return done.Task;});var duplicate=cache.Run(7,id,"same",_=>throw new Exception("duplicate"));
Check(ReferenceEquals(first,duplicate)&&calls==1,"In-flight duplicate shares provider call");
try{_ = cache.Run(7,id,"different",_=>done.Task);throw new Exception("Accepted changed request ID");}catch(ArgumentException){}
try{_ = cache.Run(7,Guid.NewGuid(),"other",_=>done.Task);throw new Exception("Accepted concurrent chapter");}catch(InvalidOperationException){}
done.SetResult(new(){RequestId=id,State="complete"});await first;
Check((await cache.Run(7,id,"same",_=>throw new Exception())).State=="complete","Successful duplicate reuses result");
var cancelId=Guid.NewGuid();var pending=cache.Run(7,cancelId,"cancel",async c=>{await Task.Delay(Timeout.Infinite,c);return new();});cache.Cancel(8,cancelId);Check(!pending.IsCompleted,"Other user's cancellation isolated");cache.Cancel(7,cancelId);Check((await pending).State=="cancelled","Cancellation isolated to owned chapter");
Check((await cache.Run(7,Guid.NewGuid(),"fail",_=>throw new IOException())).State=="failed","One failed chapter isolated");
Check((await cache.Run(7,id,"same",_=>throw new Exception())).State=="complete","Success survives another chapter's failure");
var limiter=new StoryIntelligenceRequestLimiter(Microsoft.Extensions.Options.Options.Create(new PlotLine.Models.StoryIntelligenceOptions{MaxGlobalConcurrentAiRequests=1}));
var lease=await limiter.EnterAsync(CancellationToken.None);var waiting=limiter.EnterAsync(CancellationToken.None);
Check(!waiting.IsCompleted,"Configured shared provider concurrency is enforced");lease.Dispose();(await waiting).Dispose();
using var stopped=new CancellationTokenSource();stopped.Cancel();try{using var cancelledLease=await limiter.EnterAsync(stopped.Token);throw new Exception("Ignored cancellation");}catch(OperationCanceledException){}
await Security();
}
private static T Proxy<T>(Func<string,object?[]?,object?> handler) where T:class
{var value=DispatchProxy.Create<T,StoryPointProxy>();((StoryPointProxy)(object)value).Handler=handler;return value;}
private static async Task Security()
{
void Check(bool value,string name){if(!value)throw new Exception(name);}
var pairing=new DesktopPairing(new EphemeralDataProtectionProvider(),TimeProvider.System);var stamp=Guid.NewGuid();var verifier=new string('c',64);
var code=pairing.Start(Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(verifier))));pairing.Approve(code,7,stamp);var grant=pairing.Redeem(code,verifier)!;
var user=new AppUser{UserID=7,SecurityStamp=stamp};
var users=Proxy<IUserRepository>((name,args)=>name=="GetByIdAsync"?Task.FromResult<AppUser?>(user):throw new Exception(name));
var services=new ServiceCollection();services.AddLogging();services.AddSingleton(pairing);services.AddSingleton(users);
services.AddAuthentication(DesktopPairing.Scheme).AddScheme<AuthenticationSchemeOptions,DesktopAuthentication>(DesktopPairing.Scheme,_=>{});
await using var provider=services.BuildServiceProvider();
async Task<AuthenticateResult> Auth(string? bearer)
{await using var scope=provider.CreateAsyncScope();var context=new DefaultHttpContext{RequestServices=scope.ServiceProvider};if(bearer!=null)context.Request.Headers.Authorization="Bearer "+bearer;return await context.AuthenticateAsync(DesktopPairing.Scheme);}
Check((await Auth(null)).None,"Native API requires an explicit bearer grant");
Check((await Auth(grant)).Principal?.FindFirstValue(ClaimTypes.NameIdentifier)=="7","Native handler authenticates protected grant");
user.SecurityStamp=Guid.NewGuid();Check(!(await Auth(grant)).Succeeded,"Password/security-stamp change revokes desktop access");user.SecurityStamp=stamp;user.IsLocked=true;Check(!(await Auth(grant)).Succeeded,"Locked account cannot use native API");
var access=false;var allowed=true;var accesses=0;
var repo=Proxy<IWordCompanionRepository>((name,args)=>{
if(name!="GetBookStructureAsync")throw new Exception(name);accesses++;Check((int)args![1]! == 7,"Book access uses authenticated subject");return Task.FromResult(access?new WordCompanionBookStructureResponse{BookId=(int)args[0]!}:null);
});
var subscriptions=Proxy<ISubscriptionService>((name,args)=>Task.FromResult(new EntitlementDecision{Allowed=allowed}));
var scopeFactory=provider.GetRequiredService<IServiceScopeFactory>();
var api=new NativeCompanionController(repo,new NativeAnalysisCache(TimeProvider.System),scopeFactory,new ConfigurationBuilder().Build(),subscriptions){ControllerContext=new ControllerContext{HttpContext=new DefaultHttpContext{User=new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,"7")],DesktopPairing.Scheme))}}};
Check(await api.Analyse(new(){BookId=999}) is ForbidResult&&accesses==1,"Foreign book denied before constructing or charging an AI request");
allowed=false;Check(await api.Analyse(new(){BookId=999}) is ForbidResult&&accesses==1,"Story Intelligence entitlement enforced before AI work");
}
private sealed class Clock:TimeProvider{public DateTimeOffset Now=DateTimeOffset.UtcNow;public override DateTimeOffset GetUtcNow()=>Now;}
}