using System.Data; using System.Diagnostics; using System.Reflection; using System.Security.Claims; using Dapper; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.SignalR; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Logging.Abstractions; using PlotLine.Data; using PlotLine.Hubs; using PlotLine.Services; internal static class WordMarkerSecurityTests { private static void Check(bool condition,string message) {if(!condition)throw new InvalidOperationException(message);} private static T Proxy(Func handler) where T:class {var value=DispatchProxy.Create();((StoryPointProxy)(object)value).Handler=handler;return value;} public static void HubChecks() => HubChecksAsync().GetAwaiter().GetResult(); private static async Task HubChecksAsync() { var allowed=false;var calls=0;var sends=0;var preview=Guid.NewGuid();var guid=Guid.NewGuid(); var repository=Proxy((name,args)=>{ Check(name=="AcknowledgeMarkersAsync","Client acknowledgement bypassed guarded repository path");calls++; Check((int)args![0]! == 4,"Wrong authenticated actor"); return Task.FromResult(allowed?new(){PreviewID=preview,DocumentGuid=guid}:null); }); var client=Proxy((name,args)=>{sends++;return Task.CompletedTask;}); var clients=Proxy((name,args)=>client); var hub=new WordCompanionFollowHub(null!,null!,null!,null!,repository,NullLogger.Instance) {Context=new Caller(),Clients=clients}; foreach(var action in new Func[]{()=>hub.CompleteOnboardingBuildMarkerSync(99),()=>hub.RequireOnboardingBuildManualSave(99,"save"),()=>hub.FailOnboardingBuildMarkerSync(99,"failed")}) { try{await action();throw new Exception("Foreign build acknowledgement accepted");}catch(HubException){} } Check(calls==3&&sends==0,"Rejected build must not broadcast success/progress"); allowed=true; await hub.CompleteOnboardingBuildMarkerSync(99,new(){DocumentGuid=guid.ToString(),PreviewID=preview,MarkerStatus="UserConfirmedSave"}); Check(calls==4&&sends==2,"Owned marker completion must retain legacy events"); var before=calls; try{await hub.FailOnboardingBuildMarkerSync(99,"bad",new(){DocumentGuid="not-a-guid"});throw new Exception("Malformed identity accepted");}catch(HubException){} Check(calls==before,"Malformed document identity must fail before persistence"); var native=new PlotLine.Services.NativeCompanion.NativePresenceStore(TimeProvider.System);var instance=Guid.NewGuid();var session=Guid.NewGuid(); native.Put(4,"grant",DateTimeOffset.UtcNow.AddHours(1),instance,session,new(){BookId=3,Sequence=1,Revision=1,ManuscriptId=Guid.NewGuid(),Active=true,DocumentTitle="Native fixture",ChapterId=10,SceneId=20}); var legacy=new PlotLine.Services.WordCompanionPresenceService(); var books=Proxy((_,_)=>Task.FromResult(new(){BookID=3,ProjectID=1})); var access=Proxy((_,_)=>Task.FromResult(new(){BookId=3})); var combined=new WordCompanionFollowHub(legacy,null!,null!,null!,repository,NullLogger.Instance,nativePresence:native,nativeBooks:books,nativeAccess:access){Context=new Caller(),Groups=Proxy((_,_)=>Task.CompletedTask)}; var status=await combined.WatchCompanionPresence();Check(status.IsConnected&&status.CompanionVersion=="Native"&&status.LinkedBookID==3&&status.CurrentStoryPosition?.SceneId==20,"Existing website status must use the authoritative native session"); native.Remove(4,"grant",instance,session);Check(!(await combined.WatchCompanionPresence()).IsConnected,"Website status cannot keep a native session green after disconnect"); } private sealed class Caller : HubCallerContext { public override string ConnectionId=>"owned-marker-fixture"; public override string? UserIdentifier=>"4"; public override ClaimsPrincipal User=>new(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,"4")],"Fixture")); public override IDictionary Items {get;}=new Dictionary(); public override IFeatureCollection Features {get;}=new FeatureCollection(); public override CancellationToken ConnectionAborted=>CancellationToken.None; public override void Abort() { } } // Explicit specialist command; never uses the running Development DB for mutation. public static async Task DatabaseChecksAsync() { const string target="PlotDirector_Phase2_20261103_2305"; var start=new ProcessStartInfo("sudo"){RedirectStandardOutput=true,RedirectStandardError=true}; foreach(var value in new[]{"-n","cat","/etc/plotdirector/plotdirector.env"})start.ArgumentList.Add(value); using var process=Process.Start(start)!;var settings=await process.StandardOutput.ReadToEndAsync();await process.WaitForExitAsync(); Check(process.ExitCode==0,"Configuration unavailable"); var valueLine=settings.Split('\n').Single(l=>l.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=',2)[1].Trim().Trim('"','\''); var builder=new SqlConnectionStringBuilder(valueLine);Check(builder.InitialCatalog=="PlotDirector_Development","Unexpected configured source");builder.InitialCatalog=target; using var db=new SqlConnection(builder.ConnectionString);await db.OpenAsync(); Check(await db.ExecuteScalarAsync("SELECT DB_NAME()") == target,"Wrong database"); Check(await db.ExecuteScalarAsync("SELECT COUNT(*) FROM sys.extended_properties WHERE class=0 AND name=N'PlotDirector.Phase2.SyntheticOnly' AND CONVERT(nvarchar(20),value)=N'true'")==1,"Synthetic marker missing"); var sql=await File.ReadAllTextAsync("PlotLine/Sql/230_WordMarkerAcknowledgementOwnership.sql"); foreach(var batch in System.Text.RegularExpressions.Regex.Split(sql,@"^\s*GO\s*$",System.Text.RegularExpressions.RegexOptions.Multiline|System.Text.RegularExpressions.RegexOptions.IgnoreCase)) if(!string.IsNullOrWhiteSpace(batch))await db.ExecuteAsync(batch); using var transaction=db.BeginTransaction(); try { var source=await db.QueryFirstAsync("SELECT TOP(1) p.ProjectID,b.BookID,md.ManuscriptDocumentID,md.DocumentGuid,pua.UserID FROM dbo.Projects p JOIN dbo.Books b ON b.ProjectID=p.ProjectID AND b.IsArchived=0 JOIN dbo.ManuscriptDocuments md ON md.BookID=b.BookID AND md.ProjectID=p.ProjectID AND md.IsActive=1 JOIN dbo.ProjectUserAccess pua ON pua.ProjectID=p.ProjectID AND pua.IsActive=1 WHERE p.IsArchived=0 ORDER BY p.ProjectID,b.BookID",transaction:transaction); var other=await db.ExecuteScalarAsync("SELECT TOP(1) UserID FROM dbo.AppUser WHERE UserID<>@UserID ORDER BY UserID",source,transaction); var preview=Guid.NewGuid(); var build=await db.ExecuteScalarAsync("INSERT dbo.OnboardingManuscriptBuilds(PreviewID,UserID,ProjectID,BookID,ManuscriptDocumentID,MarkerStatus) VALUES(@preview,@UserID,@ProjectID,@BookID,@ManuscriptDocumentID,N'Sent');SELECT CONVERT(int,SCOPE_IDENTITY());",new{preview,source.UserID,source.ProjectID,source.BookID,source.ManuscriptDocumentID},transaction); async Task Ack(int actor,Guid? expectedPreview,Guid? expectedGuid,string status="UserSaveRequired") => (await db.QueryAsync("dbo.Onboarding_ManuscriptBuild_AcknowledgeOwnedMarkers",new{UserID=actor,BuildID=build,PreviewID=expectedPreview,DocumentGuid=expectedGuid,MarkerStatus=status,Message="Synthetic marker security check"},transaction,commandType:CommandType.StoredProcedure)).Any(); Check(!await Ack(other,preview,source.DocumentGuid),"Foreign author accepted"); Check(!await Ack(source.UserID,Guid.NewGuid(),source.DocumentGuid),"Wrong preview accepted"); Check(!await Ack(source.UserID,preview,Guid.NewGuid()),"Wrong document accepted"); await db.ExecuteAsync("UPDATE dbo.OnboardingManuscriptBuilds SET UserID=@other WHERE OnboardingManuscriptBuildID=@build",new{other,build},transaction); Check(!await Ack(source.UserID,preview,source.DocumentGuid),"Project access alone allowed another user's build"); await db.ExecuteAsync("UPDATE dbo.OnboardingManuscriptBuilds SET UserID=@UserID WHERE OnboardingManuscriptBuildID=@build",new{source.UserID,build},transaction); await db.ExecuteAsync("UPDATE dbo.ManuscriptDocuments SET IsActive=0 WHERE ManuscriptDocumentID=@ManuscriptDocumentID",source,transaction); Check(!await Ack(source.UserID,preview,source.DocumentGuid),"Inactive manuscript accepted"); await db.ExecuteAsync("UPDATE dbo.ManuscriptDocuments SET IsActive=1 WHERE ManuscriptDocumentID=@ManuscriptDocumentID",source,transaction); await db.ExecuteAsync("UPDATE dbo.ProjectUserAccess SET IsActive=0 WHERE ProjectID=@ProjectID AND UserID=@UserID",source,transaction); Check(!await Ack(source.UserID,preview,source.DocumentGuid),"Revoked access accepted"); await db.ExecuteAsync("UPDATE dbo.ProjectUserAccess SET IsActive=1 WHERE ProjectID=@ProjectID AND UserID=@UserID",source,transaction); var anotherBook=await db.ExecuteScalarAsync("SELECT TOP(1) BookID FROM dbo.Books WHERE BookID<>@BookID",source,transaction); Check(anotherBook>0,"Need a second synthetic book for association test"); await db.ExecuteAsync("UPDATE dbo.OnboardingManuscriptBuilds SET BookID=@anotherBook WHERE OnboardingManuscriptBuildID=@build",new{anotherBook,build},transaction); Check(!await Ack(source.UserID,preview,source.DocumentGuid),"Build/book/document mismatch accepted"); await db.ExecuteAsync("UPDATE dbo.OnboardingManuscriptBuilds SET BookID=@BookID,MarkerStatus=N'Pending' WHERE OnboardingManuscriptBuildID=@build",new{source.BookID,build},transaction); Check(!await Ack(source.UserID,preview,source.DocumentGuid),"Unsent marker command accepted"); await db.ExecuteAsync("UPDATE dbo.OnboardingManuscriptBuilds SET MarkerStatus=N'Sent',Status=N'Failed' WHERE OnboardingManuscriptBuildID=@build",new{build},transaction); Check(!await Ack(source.UserID,preview,source.DocumentGuid),"Failed/non-built structure accepted"); await db.ExecuteAsync("UPDATE dbo.OnboardingManuscriptBuilds SET Status=N'Built' WHERE OnboardingManuscriptBuildID=@build",new{build},transaction); Check(await Ack(source.UserID,null,null),"Legacy owned browser acknowledgement refused"); Check(await Ack(source.UserID,preview,source.DocumentGuid,"UserConfirmedSave"),"Matching explicit document completion refused"); Check(await Ack(source.UserID,preview,source.DocumentGuid,"UserConfirmedSave"),"Idempotent completed retry refused"); Check(!await Ack(source.UserID,preview,source.DocumentGuid,"Failed"),"Late failure regressed completed build"); Check(await db.ExecuteScalarAsync("SELECT MarkerStatus FROM dbo.OnboardingManuscriptBuilds WHERE OnboardingManuscriptBuildID=@build",new{build},transaction)=="UserConfirmedSave","Refused acknowledgement changed state"); } finally{transaction.Rollback();} Console.WriteLine("PASS actual SQL marker acknowledgement: ownership, preview/document binding, active manuscript/access, legacy compatibility, idempotent completion and late failure refusal; all fixture changes rolled back; synthetic DB only."); } private sealed class Source {public int ProjectID{get;set;}public int BookID{get;set;}public int UserID{get;set;}public int ManuscriptDocumentID{get;set;}public Guid DocumentGuid{get;set;}} }