Files
Alphaeus Mote 844c044d08
CI / build-test (push) Failing after 11m47s
CI / images (push) Has been skipped
Release / release (push) Failing after 1m24s
Release / images (push) Has been skipped
test(screen): wait for the recorded session outcome and audit rows
The socket learns an outcome a moment before the server records it; under
CI load the tests read the session too early.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 22:52:18 -05:00

517 lines
25 KiB
C#

using System.Collections.Concurrent;
using System.Net;
using System.Net.Http.Json;
using System.Net.WebSockets;
using System.Text;
using Backend.Auth;
using Backend.Data;
using Backend.Screen;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Shared.Contracts.Api;
using Shared.Contracts.Messages;
using Shared.Contracts.Models;
using Shared.Contracts.Serialization;
using Xunit;
namespace Backend.Tests;
/// <summary>
/// A device's agent for Remote View: answers each open with <see cref="Reply"/>,
/// remembers what it was asked, and (when ok) runs a screen host that echoes
/// every byte back and reports one monitor.
/// </summary>
public sealed class FakeScreenAgents : IScreenAgentClient
{
public ConcurrentQueue<ScreenOpenRequest> Opened { get; } = new();
public ConcurrentQueue<(Guid Session, string Reason)> Closed { get; } = new();
public Func<ScreenOpenRequest, ScreenOpenReply> Reply { get; set; } = _ => new ScreenOpenReply(ScreenOpenStatuses.Ok, Consent: ScreenConsentResults.Notified);
public bool Offline { get; set; }
/// <summary>Sessions whose user at the device presses Stop on the banner right after the stream opens.</summary>
public ConcurrentDictionary<Guid, bool> StopAtDevice { get; } = new();
public Task<IScreenAgentStream> OpenAsync(string clientId, ScreenOpenRequest request, CancellationToken cancellationToken)
{
if (Offline)
{
throw new ScreenAgentUnavailableException("The device did not answer.");
}
Opened.Enqueue(request);
var reply = Reply(request);
ScreenStreamPump? device = null;
var server = new ScreenStreamPump(
(frame, _) => { device!.Deliver(frame); return ValueTask.CompletedTask; },
ScreenStreamDefaults.InputWindowBytes, ScreenStreamDefaults.WindowBytes * 2);
device = new ScreenStreamPump(
(frame, _) => { server.Deliver(frame); return ValueTask.CompletedTask; },
ScreenStreamDefaults.WindowBytes, ScreenStreamDefaults.InputWindowBytes * 2);
if (reply.Status == ScreenOpenStatuses.Ok)
{
_ = Task.Run(async () =>
{
await device.SendEventAsync(new ScreenStatePayload(
ScreenSessionState.Open, Monitors: [new ScreenMonitor(0, "FAKE1", 0, 0, 1024, 768, true), new ScreenMonitor(1, "FAKE2", 1024, 0, 800, 600, false)],
Desktop: "default", ViewOnly: request.ViewOnly), CancellationToken.None);
if (StopAtDevice.ContainsKey(request.SessionId))
{
// What the agent sends when the banner's Stop is pressed: a final state, then the end.
await device.SendEventAsync(new ScreenStatePayload(
ScreenSessionState.Closed, "anything the device says", StoppedAtDevice: true), CancellationToken.None);
await device.EndAsync("Stopped by the user at the device.");
return;
}
await device.ReceiveAsync((bytes, ct) => new ValueTask(device.SendAsync(bytes.ToArray(), ct)), null, CancellationToken.None);
});
}
return Task.FromResult<IScreenAgentStream>(new Stream(reply, server));
}
public Task CloseAsync(string clientId, Guid sessionId, string reason, CancellationToken cancellationToken)
{
Closed.Enqueue((sessionId, reason));
return Task.CompletedTask;
}
private sealed class Stream(ScreenOpenReply reply, ScreenStreamPump pump) : IScreenAgentStream
{
public ScreenOpenReply Reply => reply;
public ScreenStreamPump Pump => pump;
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}
/// <summary>Remote View: who may open what, the one-time socket ticket, the relay and the audit trail.</summary>
public class ScreenEndpointTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private static StringContent Json(object body) => new(JsonDefaults.Serialize(body), Encoding.UTF8, "application/json");
/// <summary>An online device whose agent reports Remote View (or not, or unavailable).</summary>
private async Task<string> DeviceAsync(string name, bool online = true, bool reports = true, bool available = true)
{
var clientId = await fixture.SeedDeviceAsync(name, online);
if (!reports && available)
{
return clientId;
}
var report = new InventoryReport(
new InventoryIdentity(clientId, name, null, null, null, null, null, null, false, null),
new InventoryOs("Windows 11", "10.0.26100", null, null, null, null, null),
new InventoryCpu(null, 1, 1), [], 0, [], [], [], DateTimeOffset.UtcNow,
reports
? new InventoryRemoteView(available, available ? null : "Screen capture is unavailable on this device.", true, available, available, false,
"windows", "1.0.0", "default", [new ScreenMonitor(0, "FAKE1", 0, 0, 1024, 768, true)], ScreenSessionPolicy.Default)
: null);
await fixture.WithDbAsync(async db =>
{
db.DeviceInventory.Add(new DeviceInventoryEntity { ClientId = clientId, ReportJson = JsonDefaults.Serialize(report), UpdatedUtc = DateTimeOffset.UtcNow });
await db.SaveChangesAsync();
});
return clientId;
}
/// <summary>A client signed in with its cookies in hand, so the WebSocket can carry them too.</summary>
private async Task<(HttpClient Client, string Cookies)> SignInAsync(string user, string role = "Admin", Guid? roleId = null)
{
(await fixture.SignedInAsync(user, role, roleId)).Dispose();
var client = fixture.CreateClient(new WebApplicationFactoryClientOptions { HandleCookies = false });
var response = await client.SignInAsync(user, TestClients.Password);
response.EnsureSuccessStatusCode();
var cookies = string.Join("; ", response.Headers.GetValues("Set-Cookie").Select(c => c.Split(';')[0]));
client.DefaultRequestHeaders.Add("Cookie", cookies);
return (client, cookies);
}
private async Task<CreateScreenResponse> OpenAsync(HttpClient client, string clientId, bool viewOnly = false)
{
var response = await client.PostAsync(ApiRoutes.For.DeviceScreen(clientId), Json(new { viewOnly }), Ct);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
return (await response.Content.ReadFromJsonAsync<CreateScreenResponse>(JsonDefaults.Options, Ct))!;
}
private async Task<WebSocket> ConnectAsync(string cookies, string socketPath, string? origin = null)
{
var client = fixture.Server.CreateWebSocketClient();
client.ConfigureRequest = request =>
{
request.Headers.Cookie = cookies;
if (origin is not null)
{
request.Headers.Origin = origin;
}
};
return await client.ConnectAsync(new Uri($"ws://localhost{socketPath}"), Ct);
}
private static async Task<byte[]> ReceiveAsync(WebSocket socket, int count)
{
var received = new MemoryStream();
var buffer = new byte[64 * 1024];
while (received.Length < count)
{
var result = await socket.ReceiveAsync(buffer, Ct);
Assert.NotEqual(WebSocketMessageType.Close, result.MessageType);
received.Write(buffer, 0, result.Count);
}
return received.ToArray();
}
private Task<List<AuditEventEntity>> AuditAsync(string clientId) => fixture.WithDbAsync(db => db.AuditEvents.AsNoTracking()
.Where(e => e.ClientId == clientId && e.Category == "screen")
.OrderBy(e => e.Id)
.ToListAsync());
/// <summary>The session once it reads <paramref name="expected"/>: the server records an outcome a moment after the socket learns it.</summary>
private async Task<ScreenSessionDto> StateAsync(HttpClient admin, string device, Guid sessionId, ScreenSessionState expected)
{
var path = ApiRoutes.For.DeviceScreenSession(device, sessionId);
var deadline = DateTime.UtcNow.AddSeconds(20);
var state = (await admin.GetFromJsonAsync<ScreenSessionDto>(path, JsonDefaults.Options, Ct))!;
while (state.State != expected && DateTime.UtcNow < deadline)
{
await Task.Delay(50, Ct);
state = (await admin.GetFromJsonAsync<ScreenSessionDto>(path, JsonDefaults.Options, Ct))!;
}
return state;
}
/// <summary>The device's screen audit rows once there are at least <paramref name="count"/>.</summary>
private async Task<List<AuditEventEntity>> AuditAsync(string clientId, int count)
{
var deadline = DateTime.UtcNow.AddSeconds(20);
var audit = await AuditAsync(clientId);
while (audit.Count < count && DateTime.UtcNow < deadline)
{
await Task.Delay(50, Ct);
audit = await AuditAsync(clientId);
}
return audit;
}
private Task<Guid> RoleAsync(params string[] permissions) => fixture.WithDbAsync(async db =>
{
var role = new RoleEntity
{
Id = Guid.NewGuid(), Name = $"screen-{Guid.NewGuid():N}", PermissionsJson = JsonDefaults.Serialize(permissions),
CreatedUtc = DateTimeOffset.UtcNow, UpdatedUtc = DateTimeOffset.UtcNow,
};
db.Roles.Add(role);
await db.SaveChangesAsync();
return role.Id;
});
[Fact]
public void TheBuiltInRolesGetRemoteView_ExceptViewersAndScriptAuthors()
{
foreach (var set in new[] { Permissions.OperatorSet, Permissions.HelpDeskSet })
{
Assert.Contains(Permissions.ScreenView, set);
Assert.Contains(Permissions.ScreenControl, set);
}
Assert.DoesNotContain(Permissions.ViewerSet, p => p.StartsWith("screen.", StringComparison.Ordinal));
Assert.DoesNotContain(Permissions.ScriptAuthorSet, p => p.StartsWith("screen.", StringComparison.Ordinal));
}
[Fact]
public async Task ViewersCannotOpen_HelpDeskCan_AndViewOnlyNeedsLess()
{
var device = await DeviceAsync("SCREEN-ROLES");
var (viewer, _) = await SignInAsync("screen-viewer", "Viewer");
var (helpDesk, _) = await SignInAsync("screen-helpdesk", RoleService.HelpDesk);
var (watcher, _) = await SignInAsync("screen-watcher", roleId: await RoleAsync(Permissions.DevicesView, Permissions.ScreenView));
Assert.Equal(HttpStatusCode.Forbidden, (await viewer.PostAsync(ApiRoutes.For.DeviceScreen(device), Json(new { viewOnly = true }), Ct)).StatusCode);
Assert.Equal(HttpStatusCode.OK, (await helpDesk.PostAsync(ApiRoutes.For.DeviceScreen(device), Json(new { viewOnly = false }), Ct)).StatusCode);
Assert.Equal(HttpStatusCode.Forbidden, (await watcher.PostAsync(ApiRoutes.For.DeviceScreen(device), Json(new { viewOnly = false }), Ct)).StatusCode);
Assert.Equal(HttpStatusCode.OK, (await watcher.PostAsync(ApiRoutes.For.DeviceScreen(device), Json(new { viewOnly = true }), Ct)).StatusCode);
}
[Fact]
public async Task ADeviceOutOfScopeIsNotThere()
{
var mine = await DeviceAsync("SCREEN-MINE");
var theirs = await DeviceAsync("SCREEN-THEIRS");
using var scoped = await fixture.ScopedSignedInAsync("screen-scoped", mine);
Assert.Equal(HttpStatusCode.OK, (await scoped.PostAsync(ApiRoutes.For.DeviceScreen(mine), Json(new { }), Ct)).StatusCode);
Assert.Equal(HttpStatusCode.NotFound, (await scoped.PostAsync(ApiRoutes.For.DeviceScreen(theirs), Json(new { }), Ct)).StatusCode);
Assert.Equal(HttpStatusCode.NotFound, (await scoped.GetAsync(ApiRoutes.For.DeviceScreen(theirs), Ct)).StatusCode);
}
[Fact]
public async Task OfflineOldAndIncapableDevicesSaySo()
{
var (admin, _) = await SignInAsync("screen-admin");
var offline = await DeviceAsync("SCREEN-OFFLINE", online: false);
var old = await DeviceAsync("SCREEN-OLD", reports: false);
var incapable = await DeviceAsync("SCREEN-NOCAPTURE", available: false);
var response = await admin.PostAsync(ApiRoutes.For.DeviceScreen(offline), Json(new { }), Ct);
Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);
Assert.Contains("not online", await response.Content.ReadAsStringAsync(Ct));
response = await admin.PostAsync(ApiRoutes.For.DeviceScreen(old), Json(new { }), Ct);
Assert.Equal(HttpStatusCode.NotImplemented, response.StatusCode);
Assert.Contains("Requires a newer agent.", await response.Content.ReadAsStringAsync(Ct));
response = await admin.PostAsync(ApiRoutes.For.DeviceScreen(incapable), Json(new { }), Ct);
Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);
Assert.Contains("Screen capture is unavailable", await response.Content.ReadAsStringAsync(Ct));
}
[Fact]
public async Task TheRelayPumpsBytesBothWays_AndViewOnlyReachesTheAgent()
{
var device = await DeviceAsync("SCREEN-RELAY");
var (admin, cookies) = await SignInAsync("screen-relay");
var opened = await OpenAsync(admin, device, viewOnly: true);
using var socket = await ConnectAsync(cookies, opened.Ticket.SocketPath);
var payload = Enumerable.Range(0, 300_000).Select(i => (byte)(i % 251)).ToArray();
var receiving = ReceiveAsync(socket, payload.Length);
await socket.SendAsync(payload, WebSocketMessageType.Binary, true, Ct);
Assert.Equal(payload, await receiving.WaitAsync(TimeSpan.FromSeconds(30), Ct));
var request = fixture.ScreenAgents.Opened.Single(r => r.SessionId == opened.Session.Id);
Assert.True(request.ViewOnly);
Assert.Equal("screen-relay", request.Operator);
Assert.Equal("screen-relay", request.OperatorName);
var state = await StateAsync(admin, device, opened.Session.Id, ScreenSessionState.Open);
Assert.Equal(ScreenSessionState.Open, state.State);
Assert.Equal(2, state.Monitors!.Count);
Assert.Equal(ScreenConsentResults.Notified, state.Consent);
await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "bye", Ct);
}
[Fact]
public async Task ATicketWorksOnce_ForItsUser()
{
var device = await DeviceAsync("SCREEN-TICKET");
var (owner, ownerCookies) = await SignInAsync("screen-owner");
var (_, otherCookies) = await SignInAsync("screen-other");
var opened = await OpenAsync(owner, device);
var stranger = await Assert.ThrowsAnyAsync<Exception>(() => ConnectAsync(otherCookies, opened.Ticket.SocketPath));
Assert.Contains("404", stranger.Message);
using (var first = await ConnectAsync(ownerCookies, opened.Ticket.SocketPath))
{
await first.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "bye", Ct);
}
var again = await Assert.ThrowsAnyAsync<Exception>(() => ConnectAsync(ownerCookies, opened.Ticket.SocketPath));
Assert.Contains("401", again.Message);
// A fresh ticket for the same session (a reconnect, or another monitor).
var ticket = await (await owner.PostAsync(ApiRoutes.For.DeviceScreenTicket(device, opened.Session.Id), Json(new { monitor = 1 }), Ct))
.Content.ReadFromJsonAsync<ScreenTicketDto>(JsonDefaults.Options, Ct);
using var reconnected = await ConnectAsync(ownerCookies, ticket!.SocketPath);
var deadline = DateTime.UtcNow.AddSeconds(20);
while (fixture.ScreenAgents.Opened.Count(r => r.SessionId == opened.Session.Id) < 2)
{
Assert.True(DateTime.UtcNow < deadline, "The reconnect never reached the agent.");
await Task.Delay(20, Ct);
}
Assert.Equal(1, fixture.ScreenAgents.Opened.Last(r => r.SessionId == opened.Session.Id).Monitor);
await reconnected.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "bye", Ct);
}
[Fact]
public async Task ACookieAloneDoesNotOpenTheSocket_NorDoesAnotherSite()
{
var device = await DeviceAsync("SCREEN-CSWSH");
var (admin, cookies) = await SignInAsync("screen-cswsh");
var opened = await OpenAsync(admin, device);
var bare = ApiRoutes.For.DeviceScreenSocket(device, opened.Session.Id);
Assert.Contains("401", (await Assert.ThrowsAnyAsync<Exception>(() => ConnectAsync(cookies, bare))).Message);
Assert.Contains("403", (await Assert.ThrowsAnyAsync<Exception>(() => ConnectAsync(cookies, opened.Ticket.SocketPath, "https://evil.example"))).Message);
}
[Fact]
public void ATicketExpires()
{
var clock = new ManualClock(DateTimeOffset.UtcNow);
var registry = new ScreenSessionRegistry(clock);
var session = registry.Create("dev1", "DEV1", "ann", viewOnly: false, monitor: -1);
var stale = registry.IssueTicket(session);
clock.Advance(ScreenStreamDefaults.TokenLifetime + TimeSpan.FromSeconds(1));
Assert.False(registry.Redeem(session.Id, "ann", stale.Token));
var fresh = registry.IssueTicket(session);
Assert.False(registry.Redeem(session.Id, "bob", fresh.Token));
Assert.False(registry.Redeem(session.Id, "ann", fresh.Token));
var good = registry.IssueTicket(session);
Assert.False(registry.Redeem(Guid.NewGuid(), "ann", good.Token));
var last = registry.IssueTicket(session);
Assert.True(registry.Redeem(session.Id, "ANN", last.Token));
Assert.False(registry.Redeem(session.Id, "ann", last.Token));
Assert.DoesNotContain(last.Token, registry.IssueTicket(session).SocketPath.Replace(last.Token, "", StringComparison.Ordinal));
}
[Fact]
public void ASessionNobodyReconnectsToExpires()
{
var clock = new ManualClock(DateTimeOffset.UtcNow);
var registry = new ScreenSessionRegistry(clock);
var session = registry.Create("dev1", "DEV1", "ann", false, -1);
Assert.Empty(registry.Expired());
clock.Advance(ScreenStreamDefaults.ReconnectGrace + TimeSpan.FromSeconds(1));
Assert.Equal(session.Id, Assert.Single(registry.Expired()).Session.Id);
}
[Fact]
public async Task StartAndEndAreAudited()
{
var device = await DeviceAsync("SCREEN-AUDIT");
var (admin, cookies) = await SignInAsync("screen-auditor");
var opened = await OpenAsync(admin, device);
using (var socket = await ConnectAsync(cookies, opened.Ticket.SocketPath))
{
await socket.SendAsync(new byte[] { 1, 2, 3 }, WebSocketMessageType.Binary, true, Ct);
await ReceiveAsync(socket, 3);
var deleted = await admin.DeleteAsync(ApiRoutes.For.DeviceScreenSession(device, opened.Session.Id), Ct);
Assert.Equal(HttpStatusCode.NoContent, deleted.StatusCode);
}
var audit = await AuditAsync(device, 2);
Assert.Equal(["started", "ended"], audit.Select(a => a.Action));
Assert.All(audit, a => Assert.Equal("screen-auditor", a.Actor));
Assert.Contains("mode=control", audit[0].Detail);
Assert.Contains("consent=notified", audit[0].Detail);
Assert.Contains("duration=", audit[1].Detail);
Assert.Contains("reason=Closed from the console.", audit[1].Detail);
Assert.Contains(fixture.ScreenAgents.Closed, c => c.Session == opened.Session.Id);
var ended = await StateAsync(admin, device, opened.Session.Id, ScreenSessionState.Closed);
Assert.Equal(ScreenSessionState.Closed, ended.State);
Assert.Empty((await admin.GetFromJsonAsync<List<ScreenSessionDto>>(ApiRoutes.For.DeviceScreen(device), JsonDefaults.Options, Ct))!);
}
[Fact]
public async Task ADeclineEndsTheSession_AndIsAudited()
{
var device = await DeviceAsync("SCREEN-DECLINE");
var (admin, cookies) = await SignInAsync("screen-declined");
var opened = await OpenAsync(admin, device);
var before = fixture.ScreenAgents.Reply;
fixture.ScreenAgents.Reply = r => r.SessionId == opened.Session.Id
? new ScreenOpenReply(ScreenOpenStatuses.Declined, "The user declined.", ScreenConsentResults.Declined)
: before(r);
using var socket = await ConnectAsync(cookies, opened.Ticket.SocketPath);
var result = await socket.ReceiveAsync(new byte[16], Ct);
Assert.Equal(WebSocketMessageType.Close, result.MessageType);
Assert.Equal(WebSocketCloseStatus.PolicyViolation, socket.CloseStatus);
Assert.Equal("The user declined.", socket.CloseStatusDescription);
var state = await StateAsync(admin, device, opened.Session.Id, ScreenSessionState.Declined);
Assert.Equal(ScreenSessionState.Declined, state.State);
var audit = Assert.Single(await AuditAsync(device, 1));
Assert.Equal("refused", audit.Action);
Assert.Contains("consent=declined", audit.Detail);
}
[Fact]
public async Task StopAtTheDeviceEndsTheSession_AndIsAudited()
{
var device = await DeviceAsync("SCREEN-STOPPED");
var (admin, cookies) = await SignInAsync("screen-stopped");
var opened = await OpenAsync(admin, device);
fixture.ScreenAgents.StopAtDevice[opened.Session.Id] = true;
using var socket = await ConnectAsync(cookies, opened.Ticket.SocketPath);
var buffer = new byte[64 * 1024];
WebSocketReceiveResult result;
do
{
result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), Ct).WaitAsync(TimeSpan.FromSeconds(30), Ct);
}
while (result.MessageType != WebSocketMessageType.Close);
var deadline = DateTime.UtcNow.AddSeconds(20);
var path = ApiRoutes.For.DeviceScreenSession(device, opened.Session.Id);
var state = (await admin.GetFromJsonAsync<ScreenSessionDto>(path, JsonDefaults.Options, Ct))!;
while (state.State != ScreenSessionState.Closed)
{
Assert.True(DateTime.UtcNow < deadline, "The session never ended.");
await Task.Delay(50, Ct);
state = (await admin.GetFromJsonAsync<ScreenSessionDto>(path, JsonDefaults.Options, Ct))!;
}
// The server's words, not the device's.
Assert.Equal(ScreenEndReasons.StoppedAtDevice, state.Message);
Assert.Empty((await admin.GetFromJsonAsync<List<ScreenSessionDto>>(ApiRoutes.For.DeviceScreen(device), JsonDefaults.Options, Ct))!);
// The ended row is written as the session closes, which can land a moment after it reads Closed.
var audit = await AuditAsync(device);
while (audit.Count < 2 && DateTime.UtcNow < deadline)
{
await Task.Delay(50, Ct);
audit = await AuditAsync(device);
}
Assert.Equal(["started", "ended"], audit.Select(a => a.Action));
Assert.Contains("reason=Stopped by the user at the device.", audit[1].Detail);
Assert.DoesNotContain("anything the device says", audit[1].Detail);
}
[Fact]
public async Task AReconnectToASessionStoppedAtTheDeviceEndsIt()
{
var device = await DeviceAsync("SCREEN-STOPPED-AGAIN");
var (admin, cookies) = await SignInAsync("screen-stopped-again");
var opened = await OpenAsync(admin, device);
using (var first = await ConnectAsync(cookies, opened.Ticket.SocketPath))
{
await first.SendAsync(new byte[] { 1 }, WebSocketMessageType.Binary, true, Ct);
await ReceiveAsync(first, 1);
await first.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "bye", Ct);
}
var before = fixture.ScreenAgents.Reply;
fixture.ScreenAgents.Reply = r => r.SessionId == opened.Session.Id
? new ScreenOpenReply(ScreenOpenStatuses.Stopped, "Stopped by the user at the device.")
: before(r);
var ticket = await (await admin.PostAsync(ApiRoutes.For.DeviceScreenTicket(device, opened.Session.Id), Json(new { monitor = -1 }), Ct))
.Content.ReadFromJsonAsync<ScreenTicketDto>(JsonDefaults.Options, Ct);
using var again = await ConnectAsync(cookies, ticket!.SocketPath);
var result = await again.ReceiveAsync(new byte[16], Ct);
Assert.Equal(WebSocketMessageType.Close, result.MessageType);
var state = await StateAsync(admin, device, opened.Session.Id, ScreenSessionState.Closed);
Assert.Equal(ScreenSessionState.Closed, state.State);
Assert.Equal(ScreenEndReasons.StoppedAtDevice, state.Message);
Assert.Contains("reason=Stopped by the user at the device.", (await AuditAsync(device)).Last().Detail);
}
private sealed class ManualClock(DateTimeOffset now) : TimeProvider
{
private DateTimeOffset now = now;
public override DateTimeOffset GetUtcNow() => now;
public void Advance(TimeSpan by) => now += by;
}
}