PlotDirector/PlotDirector.NativeCompanion/Tests/PersistentConnectionTests.cs

104 lines
12 KiB
C#

using System.Net;
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using PlotDirector.Companion.Agent;
using PlotDirector.Companion.Protocol;
internal static class PersistentConnectionTests
{
public static async Task Run(Action<bool,string> check)
{
var clock=new Clock();var server=new Server(clock);var store=new MemoryStore();int approvals=0;var manuscript=Guid.NewGuid();
using(var cloud=new CloudGateway(server,_=>approvals++,stateStore:store,timeProvider:clock)){
cloud.Connect("https://fixture.invalid/");await Until(()=>cloud.Status().Health?.State=="Connected");
cloud.RememberBinding(manuscript,3);cloud.SavePreferences(new(){AdvancedMode=true,Width=975,Height=725,RememberInDocument=true,LastManuscript=manuscript});await cloud.FlushSettingsAsync();
check(approvals==1&&store.Load().Active!=null,"first pairing saves approved installation, not a four-hour-only sign-in");
check(!JsonSerializer.Serialize(store.Load()).Contains("access:"),"short-lived access tokens are never persisted in settings");
}
check(!server.Revoked&&store.Load().Active!=null,"normal process disposal preserves trust and settings");
server.Offline=true;using(var cloud=new CloudGateway(server,_=>approvals++,stateStore:store,timeProvider:clock)){
using var stop=new CancellationTokenSource();var loop=cloud.RunConnectionLoop(stop.Token);await Until(()=>cloud.Status().Health?.State=="Reconnecting");await Task.Delay(200);check(server.RenewAttempts==1,"offline startup makes a bounded renewal attempt without browser approval");
server.Offline=false;clock.Advance(TimeSpan.FromMinutes(1));await Until(()=>cloud.Status().Health?.State=="Connected");stop.Cancel();await loop;
check(approvals==1&&cloud.RestoreBinding(manuscript)==3&&cloud.Preferences.Width==975&&cloud.Preferences.RememberInDocument&&cloud.Preferences.AdvancedMode,"process/network recovery restores scoped association and preferences without interaction");
var sessions=new SessionManager();using var ai=new ChapterAiWork(cloud);var tray=new TrayCoordinator(sessions,cloud,ai);
var instance=Guid.NewGuid();var session=Guid.NewGuid();var lease=Guid.NewGuid();
sessions.Attach(instance,lease,chapters:true);tray.Attach(instance,lease,chapters:true);
var registration=new Message{Kind="document",WordInstanceId=instance,SessionId=session,Sequence=1,Documents=[new(){SessionId=session,ManuscriptId=manuscript,Title="Synthetic linked manuscript.docx",RememberedBook=3,AssociationSite="https://fixture.invalid/"}]};
tray.Exchange(instance,registration,sessions.Apply(lease,registration),lease);
using var trayStop=new CancellationTokenSource();var ticking=tray.Tick(trayStop.Token);
try{
await Until(()=>tray.Documents.Single().Book==3);
server.Offline=true;clock.Advance(TimeSpan.FromMinutes(11));_ = cloud.Status();await cloud.ReconnectAsync();
check(tray.ChapterProgressForDisplay(session)?.State=="Sign-in required"&&tray.Documents.Single().RememberedBook==3,"expired authentication displays sign-in required and retains the open document's saved association");
server.Offline=false;clock.Advance(TimeSpan.FromMinutes(1));await cloud.ReconnectAsync();
await Until(()=>tray.Documents.Single().Book==3&&cloud.Status().Health?.State=="Connected");
check(tray.Documents.Single().RememberedBook==3&&cloud.RestoreBinding(manuscript)==3,"reauthentication restores the existing open manuscript without writing a new association");
}finally{trayStop.Cancel();try{await ticking;}catch(OperationCanceledException){}}
var context=cloud.Status().AuthenticationContext;clock.Advance(TimeSpan.FromMinutes(11));await cloud.ReconnectAsync();
check(cloud.Status().AuthenticationContext==context&&cloud.Status().Health?.State=="Connected"&&approvals==1,"access expiry renews without changing account context or asking for browser approval");
server.AllowBook=false;await cloud.CheckConnection();check(cloud.RestoreBinding(manuscript)==null,"persisted association is not restored when current book permission is missing");server.AllowBook=true;await cloud.CheckConnection();
server.LoseRenewalResponse=true;clock.Advance(TimeSpan.FromMinutes(11));await cloud.ReconnectAsync();check(store.Load().Active?.Pending!=null,"lost renewal response retains the exact pending rotation securely for recovery");
}
using(var cloud=new CloudGateway(server,_=>approvals++,stateStore:store,timeProvider:clock)){
await cloud.ReconnectAsync();check(cloud.Status().Health?.State=="Connected"&&store.Load().Active?.Pending==null&&approvals==1,"restart recovers committed rotation and acquires a fresh process connection without re-pairing");
server.Offline=true;await cloud.SignOutAsync();check(store.Load().Active==null&&store.Load().Revocations.Count==1,"offline explicit sign-out disables local trust and durably queues server revocation");
}
using(var cloud=new CloudGateway(server,_=>approvals++,stateStore:store,timeProvider:clock)){
await cloud.ReconnectAsync();check(cloud.Status().Health?.State=="Action required"&&approvals==1,"signed-out process restart never silently resumes the old account");server.Offline=false;await cloud.SignOutAsync();check(server.Revoked&&store.Load().Revocations.Count==0,"queued sign-out revokes server approval after connectivity returns");
cloud.Connect("https://fixture.invalid/");await Until(()=>cloud.Status().Health?.State=="Connected");server.Account=8;cloud.ChangeAccount("https://fixture.invalid/");await Until(()=>store.Load().Active?.AccountId==8&&cloud.Status().Health?.State=="Connected");
check(approvals==3&&cloud.RestoreBinding(manuscript)==null,"account change requires explicit approval and cannot reuse another account's manuscript association");
server.Revoked=true;clock.Advance(TimeSpan.FromMinutes(11));await cloud.ReconnectAsync();check(cloud.Status().Health?.State=="Action required"&&store.Load().Active==null,"server revocation stops renewal and requires a genuine new approval");
}
check(server.ProseRequests==0,"startup, renewal, settings, reconnect and sign-out never upload manuscript prose");
await ProtectedFiles(check);
}
private static async Task ProtectedFiles(Action<bool,string> check)
{
var root=Path.Combine(Path.GetTempPath(),"pd-protected-state-"+Guid.NewGuid().ToString("N"));Directory.CreateDirectory(root);var path=Path.Combine(root,"state.dat");var key=RandomNumberGenerator.GetBytes(32);var secret=new string('A',64);
try{
var state=new CompanionState{Server="https://fixture.invalid/",AccountId=7,Active=new(){Site="https://fixture.invalid/",AccountId=7,InstallationId=Guid.NewGuid(),Credential=secret}};
using(var file=new ProtectedCompanionStateStore(path,new Protection(key))){file.Save(state);check(!Encoding.UTF8.GetString(File.ReadAllBytes(path)).Contains(secret),"credential files contain protected bytes, never clear credentials");check(file.Load().Active?.Credential==secret,"protected settings round trip through injected protection on Linux");}
var original=await File.ReadAllBytesAsync(path);using(var other=new ProtectedCompanionStateStore(path,new Protection(RandomNumberGenerator.GetBytes(32)))){bool refused=false;try{other.Load();}catch(CryptographicException){refused=true;}check(refused,"a different user protection key cannot read saved approval");}
var envelope=JsonSerializer.Deserialize<Dictionary<string,JsonElement>>(original)!;var tampered=Encoding.UTF8.GetString(original).Replace("\"Account\":7","\"Account\":8",StringComparison.Ordinal);await File.WriteAllTextAsync(path,tampered);
using(var file=new ProtectedCompanionStateStore(path,new Protection(key))){bool refused=false;try{file.Load();}catch(CryptographicException){refused=true;}check(refused,"tampering with the account scope cannot decrypt or redirect an approval");}
await File.WriteAllBytesAsync(path,original);using(var file=new ProtectedCompanionStateStore(path,new Protection(key,true))){bool failed=false;try{file.Save(state);}catch(IOException){failed=true;}var persisted=await File.ReadAllBytesAsync(path);check(failed&&original.SequenceEqual(persisted),"failed protected write preserves the previous complete settings file");}
if(!OperatingSystem.IsWindows()){bool refused=false;try{new WindowsUserProtection().Protect([1],[2]);}catch(PlatformNotSupportedException){refused=true;}check(refused,"production protection never falls back to plaintext on non-Windows hosts");}
}finally{Directory.Delete(root,true);}
}
private sealed class Protection(byte[] key,bool fail=false):IStateProtection
{
public byte[] Protect(byte[] clear,byte[] entropy){if(fail)throw new IOException("Synthetic write failure");var nonce=RandomNumberGenerator.GetBytes(12);var encrypted=new byte[clear.Length];var tag=new byte[16];using var aes=new AesGcm(key,16);aes.Encrypt(nonce,clear,encrypted,tag,entropy);return nonce.Concat(tag).Concat(encrypted).ToArray();}
public byte[] Unprotect(byte[] cipher,byte[] entropy){var clear=new byte[cipher.Length-28];using var aes=new AesGcm(key,16);aes.Decrypt(cipher[..12],cipher[28..],cipher[12..28],clear,entropy);return clear;}
}
private sealed class MemoryStore:ICompanionStateStore{private readonly object gate=new();private CompanionState state=new();public CompanionState Load(){lock(gate)return JsonSerializer.Deserialize<CompanionState>(JsonSerializer.Serialize(state))!;}public void Save(CompanionState value){lock(gate)state=JsonSerializer.Deserialize<CompanionState>(JsonSerializer.Serialize(value))!;}}
private sealed class Clock:TimeProvider{public DateTimeOffset Time=new(2026,11,6,12,0,0,TimeSpan.Zero);public override DateTimeOffset GetUtcNow()=>Time;public void Advance(TimeSpan elapsed)=>Time+=elapsed;}
private sealed class Server(Clock clock):HttpMessageHandler
{
public bool Offline,Revoked,AllowBook=true,LoseRenewalResponse;public int Account=7,RenewAttempts,ProseRequests;private Guid installation,connection,lastRotation;private string current="",previous="";private Guid pairingConnection;
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellation)
{
var action=request.RequestUri!.AbsolutePath.Split('/').Last();if(action=="renew")RenewAttempts++;if(Offline)throw new HttpRequestException("Synthetic offline");
var payload=request.Content==null?default:JsonDocument.Parse(await request.Content.ReadAsStringAsync(cancellation)).RootElement;
if(action is "manuscript-capture" or "analyse-chapter" or "import-preview")ProseRequests++;
object result;
if(action=="pair"){pairingConnection=payload.GetProperty("connectionId").GetGuid();result=new{code=new string('A',24)};}
else if(action=="token"){installation=Guid.NewGuid();connection=pairingConnection;current=Convert.ToHexString(RandomNumberGenerator.GetBytes(32));previous="";Revoked=false;result=Tokens(true);}
else if(action=="renew"){
var credential=payload.GetProperty("credential").GetString()!;var next=payload.GetProperty("nextCredential").GetString()!;var rotation=payload.GetProperty("rotationId").GetGuid();var runtime=payload.GetProperty("connectionId").GetGuid();
if(Revoked||payload.GetProperty("installationId").GetGuid()!=installation)return Reply(HttpStatusCode.Unauthorized,new{});
if(credential==current){previous=current;current=next;lastRotation=rotation;connection=runtime;}
else if(credential!=previous||next!=current||rotation!=lastRotation||connection!=runtime)return Reply(HttpStatusCode.Unauthorized,new{});
if(LoseRenewalResponse){LoseRenewalResponse=false;throw new HttpRequestException("Synthetic response lost after commit");}result=Tokens(false);
}
else if(action=="revoke"){var credential=payload.GetProperty("credential").GetString();if(credential==current||credential==previous)Revoked=true;return new(HttpStatusCode.NoContent);}
else if(action=="books")result=AllowBook?new[]{new CompanionBook{BookId=Account==7?3:4,Title="Allowed synthetic book"}}:[];
else result=new ConnectionHealth{Server="online",Authentication="verified",ExpiresUtc=clock.Time.AddMinutes(10).UtcDateTime,VerifiedUtc=clock.Time.UtcDateTime};
return Reply(HttpStatusCode.OK,result);
}
private object Tokens(bool secret)=>new{accessToken="access:"+Guid.NewGuid(),expiresUtc=clock.Time.AddMinutes(10),installationId=installation,accountId=Account,accountName="Synthetic account "+Account,refreshExpiresUtc=clock.Time.AddDays(90),connectionId=connection,deviceSecret=secret?current:null};
private static HttpResponseMessage Reply(HttpStatusCode code,object body)=>new(code){Content=JsonContent.Create(body)};
}
private static async Task Until(Func<bool> ready){using var timeout=new CancellationTokenSource(TimeSpan.FromSeconds(15));while(!ready())await Task.Delay(20,timeout.Token);}
}