PlotDirector/PlotLine.Tests/NativeInstallationTests.cs

66 lines
8.1 KiB
C#

using System.Security.Claims;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using PlotLine.Controllers;
using PlotLine.Data;
using PlotLine.Models;
using PlotLine.Services;
using PlotLine.Services.NativeCompanion;
internal static class NativeInstallationTests
{
public static async Task Run()
{
static void Check(bool value,string message){if(!value)throw new Exception(message);}
var user=new AppUser{UserID=7,SecurityStamp=Guid.NewGuid(),DisplayName="Synthetic author"};var repo=new MemoryNativeInstallations(user);var protection=new EphemeralDataProtectionProvider();var pairing=new DesktopPairing(protection,TimeProvider.System);var presence=new NativePresenceStore(TimeProvider.System);var service=new NativeInstallationService(repo,pairing,presence,TimeProvider.System);
var first=await service.Create(new(7,user.SecurityStamp,true,true,Guid.NewGuid(),"Synthetic Windows installation"));
Check(first.ExpiresUtc<=DateTimeOffset.UtcNow.AddMinutes(10)&&first.DeviceSecret?.Length==64,"Installation approval issues a short-lived access token and separate refresh credential");
Check(first.ToString()=="NativeDeviceTokens [redacted]","Tokens cannot be exposed by default record diagnostic formatting");
var users=NativeWorkflowTests.Proxy<IUserRepository>((_,_)=>Task.FromResult<AppUser?>(user));var services=new ServiceCollection().AddLogging().AddSingleton(pairing).AddSingleton(users).AddSingleton<INativeInstallationRepository>(repo);services.AddAuthentication(DesktopPairing.Scheme).AddScheme<AuthenticationSchemeOptions,DesktopAuthentication>(DesktopPairing.Scheme,_=>{});await using var provider=services.BuildServiceProvider();
async Task<bool> Auth(string token){await using var scope=provider.CreateAsyncScope();var context=new DefaultHttpContext{RequestServices=scope.ServiceProvider};context.Request.Headers.Authorization="Bearer "+token;return(await context.AuthenticateAsync(DesktopPairing.Scheme)).Succeeded;}
Check(await Auth(first.AccessToken),"Trusted access requires both protected token and active installation record");
var instance=Guid.NewGuid();var session=Guid.NewGuid();var grant=pairing.Read(first.AccessToken)!;var key=NativeInstallationService.GrantKey(first.InstallationId,first.ConnectionId);presence.Put(7,key,first.ExpiresUtc,instance,session,new(){BookId=3,ManuscriptId=Guid.NewGuid(),Sequence=1});
var next=Convert.ToHexString(RandomNumberGenerator.GetBytes(32));var request=new NativeDeviceRenew(first.InstallationId,first.DeviceSecret!,next,Guid.NewGuid(),Guid.NewGuid());
var renewed=await service.Renew(request)??throw new Exception("Renewal failed");Check(renewed.AccountId==7&&renewed.ConnectionId==request.ConnectionId&&renewed.DeviceSecret==null,"Renewal remains bound to its original account and carries no standing bearer token");
Check(!await Auth(first.AccessToken)&&await Auth(renewed.AccessToken)&&presence.Read(7,3).Length==0,"Restart invalidates old process access/liveness while retaining installation trust");
Check(await service.Renew(request)!=null,"Lost-response retry requires the identical persisted rotation and next credential");
Check(await service.Renew(request with{RotationId=Guid.NewGuid()})==null,"Old refresh credential cannot create another renewal after rotation");
Check(!await service.RevokeUser(8,first.InstallationId)&&await Auth(renewed.AccessToken),"Other account cannot revoke this installation");
var current=new NativeDeviceRenew(first.InstallationId,next,new string('B',64),Guid.NewGuid(),request.ConnectionId);
user.SecurityStamp=Guid.NewGuid();Check(!await Auth(renewed.AccessToken)&&await service.Renew(current)==null,"Account security-stamp changes invalidate access and installation renewal");user.SecurityStamp=grant.Stamp;
user.IsLocked=true;Check(!await Auth(renewed.AccessToken)&&await service.Renew(current)==null,"Locked accounts cannot renew or use trusted installations");user.IsLocked=false;
var recreatedPairing=new DesktopPairing(protection,TimeProvider.System);var restarted=new NativeInstallationService(repo,recreatedPairing,presence,TimeProvider.System);Check(await restarted.Renew(current)!=null,"Server process restart does not erase persisted installation approval");
var logout=new AccountController(NativeWorkflowTests.Proxy<IAuthService>((name,_)=>name=="LogoutAsync"?Task.CompletedTask:throw new Exception(name)),service){ControllerContext=new(){HttpContext=new DefaultHttpContext{User=new(new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,"7")],"fixture"))}}};
await logout.Logout();Check(!await Auth(renewed.AccessToken)&&await service.Renew(current)==null,"Explicit website logout revokes device approval, including future renewal");
var second=await service.Create(new(7,user.SecurityStamp,false,true,Guid.NewGuid(),"Another fixture"));await service.RevokeSecret(new(second.InstallationId,second.DeviceSecret!,"",Guid.Empty,Guid.Empty));Check(!await Auth(second.AccessToken),"Device sign-out immediately invalidates otherwise unexpired access");
}
}
internal sealed class MemoryNativeInstallations(AppUser user):INativeInstallationRepository
{
private sealed record Secret(NativeInstallation Row,byte[] Current,byte[]? Previous=null,Guid? Rotation=null);
private readonly Dictionary<Guid,Secret> rows=[];private readonly object gate=new();
private bool Valid(NativeInstallation row)=>row.SecurityStamp==user.SecurityStamp&&!user.IsLocked&&row.RevokedUtc==null&&row.RefreshExpiresUtc>DateTimeOffset.UtcNow;
public Task<bool> Validate(Guid id,int actor,Guid stamp,Guid connection){lock(gate){if(!rows.TryGetValue(id,out var entry)||entry.Row.UserID!=actor||entry.Row.SecurityStamp!=stamp||entry.Row.ConnectionID!=connection||!Valid(entry.Row))return Task.FromResult(false);entry.Row.LastSeenUtc=DateTimeOffset.UtcNow;entry.Row.DisconnectedUtc=null;return Task.FromResult(true);}}
public Task<IReadOnlyList<NativeInstallation>> Run(string action,Guid? id=null,int? actor=null,Guid? stamp=null,string? name=null,bool retain=false,byte[]? hash=null,byte[]? nextHash=null,Guid? rotation=null,Guid? connection=null)
{
lock(gate){
if(action=="create"){if(actor!=user.UserID||stamp!=user.SecurityStamp)throw new UnauthorizedAccessException();rows[id!.Value]=new(new(){InstallationID=id.Value,UserID=actor.Value,SecurityStamp=stamp!.Value,AccountName=user.DisplayName??"Fixture",DeviceName=name!,RetainImport=retain,ConnectionID=connection!.Value,CreatedUtc=DateTimeOffset.UtcNow,RefreshExpiresUtc=DateTimeOffset.UtcNow.AddDays(90)},hash!);}
else if(action=="rotate"){
if(!rows.TryGetValue(id!.Value,out var entry)||!Valid(entry.Row))return Task.FromResult<IReadOnlyList<NativeInstallation>>([]);
if(entry.Current.SequenceEqual(hash!)){entry.Row.PreviousConnectionID=entry.Row.ConnectionID;entry.Row.ConnectionID=connection!.Value;rows[id.Value]=entry with{Previous=entry.Current,Current=nextHash!,Rotation=rotation};}
else if(entry.Previous==null||!entry.Previous.SequenceEqual(hash!)||!entry.Current.SequenceEqual(nextHash!)||entry.Rotation!=rotation||entry.Row.ConnectionID!=connection)return Task.FromResult<IReadOnlyList<NativeInstallation>>([]);
}
else if(action=="revoke-secret"){
if(!rows.TryGetValue(id!.Value,out var entry)||!(entry.Current.SequenceEqual(hash!)||(entry.Previous?.SequenceEqual(hash!)==true&&entry.Rotation==rotation&&entry.Current.SequenceEqual(nextHash!))))return Task.FromResult<IReadOnlyList<NativeInstallation>>([]);entry.Row.RevokedUtc=DateTimeOffset.UtcNow;
}
else if(action is "revoke-user" or "revoke-all"){foreach(var entry in rows.Values.Where(s=>s.Row.UserID==actor&&(!id.HasValue||s.Row.InstallationID==id)))entry.Row.RevokedUtc=DateTimeOffset.UtcNow;}
else if(action=="disconnect"){if(rows.TryGetValue(id!.Value,out var entry)&&entry.Row.UserID==actor&&entry.Row.ConnectionID==connection){entry.Row.DisconnectedUtc=DateTimeOffset.UtcNow;}}
else if(action!="list")throw new InvalidOperationException(action);
return Task.FromResult<IReadOnlyList<NativeInstallation>>(rows.Values.Select(s=>s.Row).Where(r=>(!id.HasValue||r.InstallationID==id)&&(!actor.HasValue||r.UserID==actor)).ToArray());
}
}
}