95 lines
11 KiB
C#
95 lines
11 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 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)=>Task.FromResult<Book?>(new(){BookID=3,ProjectID=1,BookTitle="Fixture book"})));
|
|
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(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.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.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.MapControllers();await app.StartAsync();
|
|
try
|
|
{
|
|
var address=app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses.Single();
|
|
using var browser=new HttpClient(new HttpClientHandler{AllowAutoRedirect=false}){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 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},{"__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");
|
|
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");
|
|
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;
|
|
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();}
|
|
Console.WriteLine("PASS actual HTTP native pairing, antiforgery, bearer/stamp, book/subscription access, canonical AI and idempotency (synthetic provider, no database)");
|
|
}
|
|
}
|