890bab034b
- PUBLIC_SERVER_URL and TRUSTED_HOSTS left at .env.example's sample
(control.example.com, any RFC 2606 name) are ignored with a startup
warning: links follow the forwarded headers and devices download from
the server URL they already use. .env.example ships them empty and
deploy.sh clears sample values from an existing .env.
- The screen host is built from its own folder so .cargo/config.toml's
+crt-static applies; the shipped exe imported VCRUNTIME140.dll and died
without output on devices without the Visual C++ runtime ("the screen
host gave no answer"). The build now refuses an exe with CRT imports.
- A failed screen host probe is retried with backoff (30 s up to 10 min)
and the inventory is republished once it answers; the warning and the
reason carry the exit code.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
786 lines
34 KiB
C#
786 lines
34 KiB
C#
using System.Security.AccessControl;
|
|
using System.Security.Principal;
|
|
using System.Text;
|
|
using Agent.Screen;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using Shared.Contracts.Messages;
|
|
using Shared.Contracts.Models;
|
|
using Xunit;
|
|
|
|
namespace Agent.Tests;
|
|
|
|
/// <summary>The person at the device, as the tests want them.</summary>
|
|
internal sealed class FakeDesktop : IScreenDesktop
|
|
{
|
|
public bool CanPrompt { get; set; } = true;
|
|
public int? Session { get; set; } = 1;
|
|
public string? User { get; set; } = @"CONTOSO\ann";
|
|
public bool? Answer { get; set; } = true;
|
|
public List<string> Asked { get; } = [];
|
|
public List<string> Notified { get; } = [];
|
|
|
|
public int? ActiveConsoleSession() => Session;
|
|
|
|
public string? SignedInUser(int? session) => User;
|
|
|
|
public Task<bool?> AskAsync(int? session, string title, string message, TimeSpan timeout, CancellationToken cancellationToken)
|
|
{
|
|
lock (Asked)
|
|
{
|
|
Asked.Add(message);
|
|
}
|
|
|
|
return Task.FromResult(Answer);
|
|
}
|
|
|
|
public void Notify(int? session, string title, string message, TimeSpan showFor)
|
|
{
|
|
lock (Notified)
|
|
{
|
|
Notified.Add(message);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>Starts the fake screen host for real, noting each command line and (optionally) a console session.</summary>
|
|
internal sealed class RecordingLauncher(Func<int?>? session = null) : IScreenProcessLauncher
|
|
{
|
|
private readonly DirectScreenProcessLauncher inner = new();
|
|
|
|
public List<IReadOnlyList<string>> Started { get; } = [];
|
|
|
|
public IScreenProcess Start(string fileName, IReadOnlyList<string> arguments)
|
|
{
|
|
lock (Started)
|
|
{
|
|
Started.Add(arguments);
|
|
}
|
|
|
|
var process = inner.Start(fileName, arguments);
|
|
return session is null ? process : new InSession(process, session());
|
|
}
|
|
|
|
private sealed class InSession(IScreenProcess inner, int? session) : IScreenProcess
|
|
{
|
|
public Stream Input => inner.Input;
|
|
public Stream Output => inner.Output;
|
|
public Stream Error => inner.Error;
|
|
public int? SessionId => session;
|
|
public Task<int> Exited => inner.Exited;
|
|
public void Kill() => inner.Kill();
|
|
public ValueTask DisposeAsync() => inner.DisposeAsync();
|
|
}
|
|
}
|
|
|
|
/// <summary>The fake screen host (tests/FakeScreenHost), and a server end wired to an agent's sessions.</summary>
|
|
internal static class ScreenHostTestKit
|
|
{
|
|
public static ScreenHostCommand FakeHost(params string[] prefix)
|
|
{
|
|
// tests/Agent.Tests/bin/<config>/<tfm>/ → tests/FakeScreenHost/bin/<config>/net10.0/
|
|
var baseDirectory = new DirectoryInfo(AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar));
|
|
var configuration = baseDirectory.Parent!.Name;
|
|
var tests = baseDirectory.Parent.Parent!.Parent!.Parent!.FullName;
|
|
var output = Path.Combine(tests, "FakeScreenHost", "bin", configuration, "net10.0");
|
|
var exe = Path.Combine(output, OperatingSystem.IsWindows() ? "FakeScreenHost.exe" : "FakeScreenHost");
|
|
if (File.Exists(exe))
|
|
{
|
|
return new ScreenHostCommand(exe, prefix);
|
|
}
|
|
|
|
var dotnet = Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet";
|
|
return new ScreenHostCommand(dotnet, [Path.Combine(output, "FakeScreenHost.dll"), .. prefix]);
|
|
}
|
|
|
|
public static ScreenHost Host(ScreenHostCommand? command, IScreenProcessLauncher launcher, IScreenDesktop desktop, bool winPe = false)
|
|
=> new(command, launcher, desktop, winPe, NullLogger.Instance);
|
|
|
|
/// <summary>The server's end of one stream: what the agent publishes lands here; what it sends goes to the agent.</summary>
|
|
public sealed class Server
|
|
{
|
|
private readonly List<ScreenStatePayload> states = [];
|
|
|
|
public Server(ScreenSessions sessions, Guid streamId)
|
|
{
|
|
Pump = new ScreenStreamPump(
|
|
(frame, _) =>
|
|
{
|
|
sessions.Deliver(streamId, frame);
|
|
return ValueTask.CompletedTask;
|
|
},
|
|
ScreenStreamDefaults.InputWindowBytes,
|
|
ScreenStreamDefaults.WindowBytes * 2);
|
|
}
|
|
|
|
public ScreenStreamPump Pump { get; }
|
|
|
|
public MemoryStream Received { get; } = new();
|
|
|
|
public IReadOnlyList<ScreenStatePayload> States
|
|
{
|
|
get
|
|
{
|
|
lock (states)
|
|
{
|
|
return [.. states];
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>The agent's publish: frames go straight to this end.</summary>
|
|
public ValueTask Publish(byte[] frame, CancellationToken cancellationToken)
|
|
{
|
|
Pump.Deliver(frame);
|
|
return ValueTask.CompletedTask;
|
|
}
|
|
|
|
public Task<string> ReceiveAsync(CancellationToken cancellationToken)
|
|
=> Pump.ReceiveAsync(
|
|
(bytes, _) =>
|
|
{
|
|
lock (Received)
|
|
{
|
|
Received.Write(bytes.Span);
|
|
}
|
|
|
|
return ValueTask.CompletedTask;
|
|
},
|
|
(state, _) =>
|
|
{
|
|
lock (states)
|
|
{
|
|
states.Add(state);
|
|
}
|
|
|
|
return ValueTask.CompletedTask;
|
|
},
|
|
cancellationToken);
|
|
|
|
public long ReceivedLength
|
|
{
|
|
get
|
|
{
|
|
lock (Received)
|
|
{
|
|
return Received.Length;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
public static async Task WaitUntilAsync(Func<bool> condition, TimeSpan? timeout = null)
|
|
{
|
|
var deadline = DateTime.UtcNow + (timeout ?? TimeSpan.FromSeconds(20));
|
|
while (!condition())
|
|
{
|
|
if (DateTime.UtcNow > deadline)
|
|
{
|
|
throw new TimeoutException("The condition was not met in time.");
|
|
}
|
|
|
|
await Task.Delay(25);
|
|
}
|
|
}
|
|
}
|
|
|
|
public class ScreenConsentPolicyTests
|
|
{
|
|
private static readonly ScreenSessionPolicy Defaults = ScreenSessionPolicy.Default;
|
|
|
|
[Fact]
|
|
public void TheDefaultsNotifyWithoutAsking_AndAllowUnattended()
|
|
{
|
|
Assert.True(Defaults.Notify);
|
|
Assert.False(Defaults.AskFirst);
|
|
Assert.True(Defaults.AllowUnattended);
|
|
Assert.Equal(30, Defaults.AskTimeoutSeconds);
|
|
}
|
|
|
|
[Fact]
|
|
public void OffRefusesWhateverElseIsSet()
|
|
{
|
|
var decision = ScreenConsentPolicy.Decide(enabled: false, Defaults, winPe: true, canPrompt: true, "ann");
|
|
Assert.Equal(ScreenConsentAction.Refuse, decision.Action);
|
|
Assert.Equal(ScreenOpenStatuses.Disabled, decision.Status);
|
|
}
|
|
|
|
[Fact]
|
|
public void WindowsPeNeverAsks()
|
|
{
|
|
var decision = ScreenConsentPolicy.Decide(true, Defaults with { AskFirst = true, AllowUnattended = false }, winPe: true, canPrompt: false, null);
|
|
Assert.Equal(ScreenConsentAction.Allow, decision.Action);
|
|
Assert.Equal(ScreenConsentResults.WinPe, decision.Consent);
|
|
}
|
|
|
|
[Fact]
|
|
public void NobodySignedIn_NeedsUnattended()
|
|
{
|
|
var refused = ScreenConsentPolicy.Decide(true, Defaults with { AllowUnattended = false }, false, true, null);
|
|
Assert.Equal(ScreenConsentAction.Refuse, refused.Action);
|
|
Assert.Equal(ScreenOpenStatuses.Unattended, refused.Status);
|
|
|
|
var allowed = ScreenConsentPolicy.Decide(true, Defaults with { AskFirst = true }, false, true, "");
|
|
Assert.Equal(ScreenConsentAction.Allow, allowed.Action);
|
|
Assert.Equal(ScreenConsentResults.Unattended, allowed.Consent);
|
|
}
|
|
|
|
[Fact]
|
|
public void SomeoneSignedIn_IsAsked_OrTold_OrNot()
|
|
{
|
|
Assert.Equal(ScreenConsentAction.Ask, ScreenConsentPolicy.Decide(true, Defaults with { AskFirst = true }, false, true, "ann").Action);
|
|
Assert.Equal(ScreenConsentAction.Notify, ScreenConsentPolicy.Decide(true, Defaults, false, true, "ann").Action);
|
|
|
|
var silent = ScreenConsentPolicy.Decide(true, Defaults with { Notify = false }, false, true, "ann");
|
|
Assert.Equal(ScreenConsentAction.Allow, silent.Action);
|
|
Assert.Equal(ScreenConsentResults.Silent, silent.Consent);
|
|
}
|
|
|
|
[Fact]
|
|
public void WithoutAPrompt_AskFirstRefuses()
|
|
{
|
|
var decision = ScreenConsentPolicy.Decide(true, Defaults with { AskFirst = true }, false, canPrompt: false, null);
|
|
Assert.Equal(ScreenConsentAction.Refuse, decision.Action);
|
|
}
|
|
|
|
[Fact]
|
|
public void TheAskTimeoutIsClamped()
|
|
{
|
|
Assert.Equal(TimeSpan.FromSeconds(10), ScreenConsentPolicy.AskTimeout(Defaults with { AskTimeoutSeconds = 1 }));
|
|
Assert.Equal(TimeSpan.FromSeconds(120), ScreenConsentPolicy.AskTimeout(Defaults with { AskTimeoutSeconds = 9999 }));
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData(true, null, ScreenConsentResults.Accepted)]
|
|
[InlineData(false, ScreenOpenStatuses.Declined, ScreenConsentResults.Declined)]
|
|
[InlineData(null, ScreenOpenStatuses.Declined, ScreenConsentResults.TimedOut)]
|
|
public async Task TheAnswerDecides(bool? answer, string? refusal, string consent)
|
|
{
|
|
var desktop = new FakeDesktop { Answer = answer };
|
|
var gate = new ScreenConsentGate(desktop, () => Defaults with { AskFirst = true }, () => true, winPe: false);
|
|
|
|
var (reply, result) = await gate.SettleAsync(new ScreenOpenRequest(Guid.NewGuid(), Guid.NewGuid(), false, -1, "bob"), CancellationToken.None);
|
|
|
|
Assert.Equal(refusal, reply?.Status);
|
|
Assert.Equal(consent, reply?.Consent ?? result);
|
|
Assert.Contains("bob wants to view and control your screen", Assert.Single(desktop.Asked));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task NotifySaysWhoAndWhat()
|
|
{
|
|
var desktop = new FakeDesktop();
|
|
var gate = new ScreenConsentGate(desktop, () => Defaults, () => true, winPe: false);
|
|
|
|
var (reply, consent) = await gate.SettleAsync(new ScreenOpenRequest(Guid.NewGuid(), Guid.NewGuid(), true, -1, "bob"), CancellationToken.None);
|
|
|
|
Assert.Null(reply);
|
|
Assert.Equal(ScreenConsentResults.Notified, consent);
|
|
Assert.Contains("bob is starting to view your screen", Assert.Single(desktop.Notified));
|
|
Assert.Empty(desktop.Asked);
|
|
}
|
|
}
|
|
|
|
public class ScreenHostProtocolTests
|
|
{
|
|
[Fact]
|
|
public void StateEventsCarryTheMonitors()
|
|
{
|
|
const string line = """@event {"type":"state","monitors":[{"index":1,"name":"DISPLAY2","x":1920,"y":0,"width":1280,"height":1024,"primary":false}],"desktop":"winlogon","viewOnly":true,"winpe":false}""";
|
|
|
|
Assert.True(ScreenHostProtocol.TryParseEvent(line, out var hostEvent));
|
|
Assert.Equal("state", hostEvent!.Type);
|
|
var monitor = Assert.Single(hostEvent.Monitors!);
|
|
Assert.Equal(new ScreenMonitor(1, "DISPLAY2", 1920, 0, 1280, 1024, false), monitor);
|
|
Assert.Equal("winlogon", hostEvent.Desktop);
|
|
Assert.True(hostEvent.ViewOnly);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("""@event {"type":"closed","reason":"bye"}""", "closed")]
|
|
[InlineData("""@event {"type":"ready"}""", "ready")]
|
|
public void OtherEvents(string line, string type)
|
|
{
|
|
Assert.True(ScreenHostProtocol.TryParseEvent(line, out var hostEvent));
|
|
Assert.Equal(type, hostEvent!.Type);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("2026-11-06 INFO listening")]
|
|
[InlineData("@event not json")]
|
|
[InlineData("@event {}")]
|
|
[InlineData("@eventual {\"type\":\"ready\"}")]
|
|
[InlineData(null)]
|
|
public void AnythingElseIsALogLine(string? line)
|
|
{
|
|
Assert.False(ScreenHostProtocol.TryParseEvent(line, out _));
|
|
}
|
|
|
|
[Fact]
|
|
public void TheProbeIsItsJsonLine()
|
|
{
|
|
const string output = "warming up\n{\"version\":\"1.2.3\",\"capture\":false,\"input\":false,\"monitors\":[],\"desktop\":\"default\",\"winpe\":true,\"platform\":\"windows\",\"reason\":\"no GPU\"}\n";
|
|
|
|
Assert.True(ScreenHostProtocol.TryParseProbe(output, out var probe));
|
|
Assert.Equal("1.2.3", probe!.Version);
|
|
Assert.False(probe.Capture);
|
|
Assert.True(probe.WinPe);
|
|
Assert.Equal("windows", probe.Platform);
|
|
Assert.Equal("no GPU", probe.Reason);
|
|
Assert.False(ScreenHostProtocol.TryParseProbe("nothing to see", out _));
|
|
Assert.False(ScreenHostProtocol.TryParseProbe("{broken", out _));
|
|
}
|
|
|
|
[Fact]
|
|
public void ServeArguments()
|
|
{
|
|
Assert.Equal(["serve", "--stdio", "--view-only", "--monitor", "1", "--max-fps", "60", "--log-level", "debug"],
|
|
ScreenHostProtocol.ServeArguments(viewOnly: true, monitor: 1, maxFps: 200, logLevel: "debug"));
|
|
Assert.Equal(["serve", "--stdio", "--monitor", "-1"], ScreenHostProtocol.ServeArguments(false, -7, null, null));
|
|
}
|
|
|
|
[Fact]
|
|
public void ExitCodesExplainThemselves()
|
|
{
|
|
Assert.Contains("capture is unavailable", ScreenHostProtocol.DescribeExit(2));
|
|
Assert.Contains("arguments", ScreenHostProtocol.DescribeExit(3));
|
|
Assert.Contains("exit code 1", ScreenHostProtocol.DescribeExit(1));
|
|
}
|
|
|
|
#if WINDOWS
|
|
[Fact]
|
|
public void TheWindowsCommandLineQuotesWhatNeedsIt()
|
|
{
|
|
Assert.Equal(
|
|
"\"C:\\Program Files\\ExecuteR\\Agent\\ExecuteR-Screen.exe\" serve --stdio --log-level \"a b\" \"\" \"q\\\"x\"",
|
|
WindowsScreenProcessLauncher.CommandLine(@"C:\Program Files\ExecuteR\Agent\ExecuteR-Screen.exe", ["serve", "--stdio", "--log-level", "a b", "", "q\"x"]));
|
|
}
|
|
|
|
[Fact]
|
|
public void AFolderUsersMayWriteToIsNotTrusted()
|
|
{
|
|
var users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
|
|
var system = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);
|
|
|
|
var locked = new DirectorySecurity();
|
|
locked.AddAccessRule(new FileSystemAccessRule(users, FileSystemRights.ReadAndExecute, AccessControlType.Allow));
|
|
locked.AddAccessRule(new FileSystemAccessRule(system, FileSystemRights.FullControl, AccessControlType.Allow));
|
|
Assert.False(ScreenHostTrust.Writable(locked));
|
|
|
|
var open = new DirectorySecurity();
|
|
open.AddAccessRule(new FileSystemAccessRule(users, FileSystemRights.Modify, AccessControlType.Allow));
|
|
Assert.True(ScreenHostTrust.Writable(open));
|
|
}
|
|
#endif
|
|
|
|
[Fact]
|
|
public void TheHostIsOnlyFoundBesideTheAgent()
|
|
{
|
|
var folder = Directory.CreateTempSubdirectory("screen-locate-");
|
|
try
|
|
{
|
|
Assert.Null(ScreenHost.Locate(folder.FullName, requireProtectedFolder: false));
|
|
|
|
File.WriteAllBytes(Path.Combine(folder.FullName, ScreenHostProtocol.ExecutableName), [0]);
|
|
var found = ScreenHost.Locate(folder.FullName, requireProtectedFolder: false);
|
|
Assert.Equal(Path.Combine(folder.FullName, ScreenHostProtocol.ExecutableName), found!.FileName);
|
|
Assert.Null(found.Problem);
|
|
Assert.Empty(found.PrefixArguments);
|
|
}
|
|
finally
|
|
{
|
|
folder.Delete(recursive: true);
|
|
}
|
|
}
|
|
}
|
|
|
|
public class ScreenSessionTests
|
|
{
|
|
private static readonly ScreenSessionPolicy Policy = ScreenSessionPolicy.Default;
|
|
|
|
private static ScreenSessions Sessions(
|
|
ScreenHost host, bool enabled = true, ScreenSessionPolicy? policy = null, TimeSpan? heartbeat = null, TimeSpan? idle = null)
|
|
=> new(host, () => enabled, () => policy ?? Policy, NullLogger.Instance, heartbeat: heartbeat, idle: idle);
|
|
|
|
private static ScreenOpenRequest Request(Guid? session = null, bool viewOnly = false, int monitor = -1)
|
|
=> new(session ?? Guid.NewGuid(), Guid.NewGuid(), viewOnly, monitor, "bob");
|
|
|
|
[Fact]
|
|
public async Task BytesGoBothWays_AndTheStateComesBack()
|
|
{
|
|
var launcher = new RecordingLauncher();
|
|
var desktop = new FakeDesktop();
|
|
await using var sessions = Sessions(ScreenHostTestKit.Host(ScreenHostTestKit.FakeHost(), launcher, desktop));
|
|
var request = Request(viewOnly: true, monitor: 0);
|
|
var server = new ScreenHostTestKit.Server(sessions, request.StreamId);
|
|
|
|
var reply = await sessions.OpenAsync(request, server.Publish, CancellationToken.None);
|
|
|
|
Assert.Equal(ScreenOpenStatuses.Ok, reply.Status);
|
|
Assert.Equal(ScreenConsentResults.Notified, reply.Consent);
|
|
var arguments = Assert.Single(launcher.Started);
|
|
Assert.Contains("--view-only", arguments);
|
|
Assert.Equal("0", arguments[arguments.ToList().IndexOf("--monitor") + 1]);
|
|
|
|
var receiving = server.ReceiveAsync(CancellationToken.None);
|
|
var payload = Encoding.ASCII.GetBytes(new string('x', 200_000));
|
|
await server.Pump.SendAsync(payload, CancellationToken.None);
|
|
await ScreenHostTestKit.WaitUntilAsync(() => server.ReceivedLength == payload.Length);
|
|
Assert.Equal(payload, server.Received.ToArray());
|
|
|
|
await ScreenHostTestKit.WaitUntilAsync(() => server.States.Any(s => s.Monitors is { Count: 1 }));
|
|
var state = server.States.First(s => s.Monitors is { Count: 1 });
|
|
Assert.True(state.ViewOnly);
|
|
Assert.Equal("default", state.Desktop);
|
|
|
|
// The server ends the stream: stdin closes, the host says why and exits.
|
|
await server.Pump.EndAsync("done");
|
|
await ScreenHostTestKit.WaitUntilAsync(() => sessions.ActiveStreams == 0);
|
|
await receiving;
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ASlowServerHoldsTheHostBack()
|
|
{
|
|
var desktop = new FakeDesktop();
|
|
const int flood = 6 * 1024 * 1024;
|
|
await using var sessions = Sessions(ScreenHostTestKit.Host(
|
|
ScreenHostTestKit.FakeHost("--flood", flood.ToString(System.Globalization.CultureInfo.InvariantCulture)),
|
|
new RecordingLauncher(), desktop));
|
|
var request = Request();
|
|
long published = 0;
|
|
ScreenHostTestKit.Server? server = null;
|
|
server = new ScreenHostTestKit.Server(sessions, request.StreamId);
|
|
|
|
var reply = await sessions.OpenAsync(request, (frame, ct) =>
|
|
{
|
|
if (frame[0] == ScreenFrame.Data)
|
|
{
|
|
Interlocked.Add(ref published, frame.Length - ScreenFrame.HeaderBytes);
|
|
}
|
|
|
|
return server.Publish(frame, ct);
|
|
}, CancellationToken.None);
|
|
Assert.Equal(ScreenOpenStatuses.Ok, reply.Status);
|
|
|
|
// Nobody acknowledges: the agent stops at its window, whatever the host has to say.
|
|
await ScreenHostTestKit.WaitUntilAsync(() => Interlocked.Read(ref published) >= ScreenStreamDefaults.WindowBytes - ScreenStreamDefaults.ChunkBytes);
|
|
await Task.Delay(500);
|
|
Assert.InRange(Interlocked.Read(ref published), 1, ScreenStreamDefaults.WindowBytes);
|
|
|
|
// Reading resumes it, to the last byte.
|
|
_ = server.ReceiveAsync(CancellationToken.None);
|
|
await ScreenHostTestKit.WaitUntilAsync(() => server.ReceivedLength == flood);
|
|
sessions.Close(request.SessionId, "test over");
|
|
await ScreenHostTestKit.WaitUntilAsync(() => sessions.ActiveStreams == 0);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task CloseStopsTheHost_AndTellsTheServerWhy()
|
|
{
|
|
await using var sessions = Sessions(ScreenHostTestKit.Host(ScreenHostTestKit.FakeHost(), new RecordingLauncher(), new FakeDesktop()));
|
|
var request = Request();
|
|
var server = new ScreenHostTestKit.Server(sessions, request.StreamId);
|
|
Assert.Equal(ScreenOpenStatuses.Ok, (await sessions.OpenAsync(request, server.Publish, CancellationToken.None)).Status);
|
|
var receiving = server.ReceiveAsync(CancellationToken.None);
|
|
|
|
sessions.Close(request.SessionId, "Closed from the console.");
|
|
|
|
Assert.Equal("Closed from the console.", await receiving.WaitAsync(TimeSpan.FromSeconds(20)));
|
|
await ScreenHostTestKit.WaitUntilAsync(() => sessions.ActiveStreams == 0);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ASilentServerEndsTheStream()
|
|
{
|
|
await using var sessions = Sessions(
|
|
ScreenHostTestKit.Host(ScreenHostTestKit.FakeHost(), new RecordingLauncher(), new FakeDesktop()),
|
|
heartbeat: TimeSpan.FromMilliseconds(100), idle: TimeSpan.FromMilliseconds(500));
|
|
var request = Request();
|
|
string? ended = null;
|
|
|
|
var reply = await sessions.OpenAsync(request, (frame, _) =>
|
|
{
|
|
if (frame[0] == ScreenFrame.End)
|
|
{
|
|
ended = ScreenFrame.Text(frame.AsMemory(ScreenFrame.HeaderBytes));
|
|
}
|
|
|
|
return ValueTask.CompletedTask;
|
|
}, CancellationToken.None);
|
|
|
|
Assert.Equal(ScreenOpenStatuses.Ok, reply.Status);
|
|
await ScreenHostTestKit.WaitUntilAsync(() => sessions.ActiveStreams == 0);
|
|
Assert.Equal("The other side stopped answering.", ended);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AConsoleSessionSwitchEndsTheStream()
|
|
{
|
|
var desktop = new FakeDesktop { Session = 1 };
|
|
await using var sessions = Sessions(ScreenHostTestKit.Host(
|
|
ScreenHostTestKit.FakeHost(), new RecordingLauncher(() => desktop.Session), desktop));
|
|
var request = Request();
|
|
var server = new ScreenHostTestKit.Server(sessions, request.StreamId);
|
|
Assert.Equal(ScreenOpenStatuses.Ok, (await sessions.OpenAsync(request, server.Publish, CancellationToken.None)).Status);
|
|
var receiving = server.ReceiveAsync(CancellationToken.None);
|
|
|
|
sessions.Sweep();
|
|
Assert.Equal(1, sessions.ActiveStreams);
|
|
|
|
desktop.Session = 2;
|
|
sessions.Sweep();
|
|
|
|
Assert.Equal("The console session changed.", await receiving.WaitAsync(TimeSpan.FromSeconds(20)));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AConsoleSwitchNotificationEndsTheStreamWithoutWaitingForTheTimer()
|
|
{
|
|
var desktop = new FakeDesktop { Session = 1 };
|
|
var watcher = new Agent.Sessions.SessionWatcher();
|
|
await using var sessions = new ScreenSessions(
|
|
ScreenHostTestKit.Host(ScreenHostTestKit.FakeHost(), new RecordingLauncher(() => desktop.Session), desktop),
|
|
() => true, () => Policy, NullLogger.Instance, watcher: watcher);
|
|
var request = Request();
|
|
var server = new ScreenHostTestKit.Server(sessions, request.StreamId);
|
|
Assert.Equal(ScreenOpenStatuses.Ok, (await sessions.OpenAsync(request, server.Publish, CancellationToken.None)).Status);
|
|
var receiving = server.ReceiveAsync(CancellationToken.None);
|
|
using var stop = new CancellationTokenSource();
|
|
var monitor = sessions.MonitorAsync(stop.Token);
|
|
await Task.Delay(100);
|
|
|
|
desktop.Session = 2;
|
|
watcher.Publish(new Agent.Sessions.SessionChange(Agent.Sessions.SessionChangeKind.ConsoleConnect, 2));
|
|
|
|
// The periodic sweep is 2 s away; the notification sweeps at once.
|
|
Assert.Equal("The console session changed.", await receiving.WaitAsync(TimeSpan.FromMilliseconds(1500)));
|
|
await stop.CancelAsync();
|
|
await monitor;
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AHostInAnotherSessionThanConsentedIsRefused()
|
|
{
|
|
var desktop = new FakeDesktop { Session = 1 };
|
|
await using var sessions = Sessions(ScreenHostTestKit.Host(
|
|
ScreenHostTestKit.FakeHost(), new RecordingLauncher(() => 5), desktop));
|
|
|
|
var reply = await sessions.OpenAsync(Request(), (_, _) => ValueTask.CompletedTask, CancellationToken.None);
|
|
|
|
Assert.Equal(ScreenOpenStatuses.Failed, reply.Status);
|
|
Assert.Contains("console session changed", reply.Message);
|
|
Assert.Equal(0, sessions.ActiveStreams);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AHostThatCannotCaptureSaysSo()
|
|
{
|
|
await using var sessions = Sessions(ScreenHostTestKit.Host(
|
|
ScreenHostTestKit.FakeHost("--exit", "2"), new RecordingLauncher(), new FakeDesktop()));
|
|
|
|
var reply = await sessions.OpenAsync(Request(), (_, _) => ValueTask.CompletedTask, CancellationToken.None);
|
|
|
|
Assert.Equal(ScreenOpenStatuses.Unavailable, reply.Status);
|
|
Assert.Equal("Screen capture is unavailable on this device.", reply.Message);
|
|
await ScreenHostTestKit.WaitUntilAsync(() => sessions.ActiveStreams == 0);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task RefusalsComeBeforeAnyLaunch()
|
|
{
|
|
var launcher = new RecordingLauncher();
|
|
var desktop = new FakeDesktop { Answer = false };
|
|
|
|
await using (var off = Sessions(ScreenHostTestKit.Host(ScreenHostTestKit.FakeHost(), launcher, desktop), enabled: false))
|
|
{
|
|
Assert.Equal(ScreenOpenStatuses.Disabled, (await off.OpenAsync(Request(), (_, _) => ValueTask.CompletedTask, CancellationToken.None)).Status);
|
|
}
|
|
|
|
await using (var missing = Sessions(ScreenHostTestKit.Host(null, launcher, desktop)))
|
|
{
|
|
var reply = await missing.OpenAsync(Request(), (_, _) => ValueTask.CompletedTask, CancellationToken.None);
|
|
Assert.Equal(ScreenOpenStatuses.Unavailable, reply.Status);
|
|
Assert.Equal("Requires the screen component.", reply.Message);
|
|
}
|
|
|
|
await using (var asking = Sessions(ScreenHostTestKit.Host(ScreenHostTestKit.FakeHost(), launcher, desktop), policy: Policy with { AskFirst = true }))
|
|
{
|
|
var reply = await asking.OpenAsync(Request(), (_, _) => ValueTask.CompletedTask, CancellationToken.None);
|
|
Assert.Equal(ScreenOpenStatuses.Declined, reply.Status);
|
|
Assert.Equal(ScreenConsentResults.Declined, reply.Consent);
|
|
}
|
|
|
|
desktop.User = null;
|
|
await using (var unattended = Sessions(ScreenHostTestKit.Host(ScreenHostTestKit.FakeHost(), launcher, desktop), policy: Policy with { AllowUnattended = false }))
|
|
{
|
|
Assert.Equal(ScreenOpenStatuses.Unattended, (await unattended.OpenAsync(Request(), (_, _) => ValueTask.CompletedTask, CancellationToken.None)).Status);
|
|
}
|
|
|
|
Assert.Empty(launcher.Started);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AReconnectReplacesTheStream_WithoutAskingAgain()
|
|
{
|
|
var desktop = new FakeDesktop();
|
|
var launcher = new RecordingLauncher();
|
|
await using var sessions = Sessions(ScreenHostTestKit.Host(ScreenHostTestKit.FakeHost(), launcher, desktop), policy: Policy with { AskFirst = true });
|
|
var session = Guid.NewGuid();
|
|
var first = Request(session);
|
|
var firstServer = new ScreenHostTestKit.Server(sessions, first.StreamId);
|
|
Assert.Equal(ScreenConsentResults.Accepted, (await sessions.OpenAsync(first, firstServer.Publish, CancellationToken.None)).Consent);
|
|
var firstReceiving = firstServer.ReceiveAsync(CancellationToken.None);
|
|
|
|
var second = Request(session, monitor: 1);
|
|
var secondServer = new ScreenHostTestKit.Server(sessions, second.StreamId);
|
|
var reply = await sessions.OpenAsync(second, secondServer.Publish, CancellationToken.None);
|
|
|
|
Assert.Equal(ScreenOpenStatuses.Ok, reply.Status);
|
|
Assert.Equal(ScreenConsentResults.Granted, reply.Consent);
|
|
Assert.Single(desktop.Asked);
|
|
Assert.Equal("Replaced by a new connection.", await firstReceiving.WaitAsync(TimeSpan.FromSeconds(20)));
|
|
await ScreenHostTestKit.WaitUntilAsync(() => sessions.ActiveStreams == 1);
|
|
|
|
sessions.Close(session, "bye");
|
|
await ScreenHostTestKit.WaitUntilAsync(() => sessions.ActiveStreams == 0);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task TheDeviceRunsAFewSessionsAtMost()
|
|
{
|
|
await using var sessions = Sessions(ScreenHostTestKit.Host(ScreenHostTestKit.FakeHost(), new RecordingLauncher(), new FakeDesktop()));
|
|
for (var i = 0; i < ScreenStreamDefaults.MaxStreamsPerDevice; i++)
|
|
{
|
|
var request = Request();
|
|
var server = new ScreenHostTestKit.Server(sessions, request.StreamId);
|
|
Assert.Equal(ScreenOpenStatuses.Ok, (await sessions.OpenAsync(request, server.Publish, CancellationToken.None)).Status);
|
|
_ = server.ReceiveAsync(CancellationToken.None);
|
|
}
|
|
|
|
var refused = await sessions.OpenAsync(Request(), (_, _) => ValueTask.CompletedTask, CancellationToken.None);
|
|
Assert.Equal(ScreenOpenStatuses.Busy, refused.Status);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task DisposingStopsEveryHost()
|
|
{
|
|
var sessions = Sessions(ScreenHostTestKit.Host(ScreenHostTestKit.FakeHost(), new RecordingLauncher(), new FakeDesktop()));
|
|
var request = Request();
|
|
var server = new ScreenHostTestKit.Server(sessions, request.StreamId);
|
|
Assert.Equal(ScreenOpenStatuses.Ok, (await sessions.OpenAsync(request, server.Publish, CancellationToken.None)).Status);
|
|
var receiving = server.ReceiveAsync(CancellationToken.None);
|
|
|
|
await sessions.DisposeAsync();
|
|
|
|
Assert.Equal(0, sessions.ActiveStreams);
|
|
Assert.Equal("The agent is stopping.", await receiving.WaitAsync(TimeSpan.FromSeconds(20)));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task TheProbeBecomesTheCapability()
|
|
{
|
|
var host = ScreenHostTestKit.Host(ScreenHostTestKit.FakeHost(), new DirectScreenProcessLauncher(), new FakeDesktop());
|
|
|
|
var capability = await host.CapabilityAsync(enabled: true, Policy, CancellationToken.None);
|
|
Assert.True(capability.Available);
|
|
Assert.Null(capability.Reason);
|
|
Assert.Equal("0.0.0-fake", capability.Version);
|
|
Assert.Equal("FAKE1", Assert.Single(capability.Monitors!).Name);
|
|
Assert.Equal(Policy, capability.Policy);
|
|
|
|
var off = await host.CapabilityAsync(enabled: false, Policy, CancellationToken.None);
|
|
Assert.False(off.Available);
|
|
Assert.Equal("Remote View is off on this device.", off.Reason);
|
|
|
|
var missing = await ScreenHostTestKit.Host(null, new DirectScreenProcessLauncher(), new FakeDesktop())
|
|
.CapabilityAsync(true, Policy, CancellationToken.None);
|
|
Assert.False(missing.Available);
|
|
Assert.Equal("Requires the screen component.", missing.Reason);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AFailedProbeIsTriedAgainAndTheInventoryFollows()
|
|
{
|
|
// The first start dies before it prints (as a host that cannot start in the console session yet does).
|
|
var launcher = new FailingFirstLauncher(failures: 1, exitCode: unchecked((int)0xC0000142));
|
|
var host = new ScreenHost(ScreenHostTestKit.FakeHost(), launcher, new FakeDesktop(), winPe: false, NullLogger.Instance)
|
|
{
|
|
RetryFirstDelay = TimeSpan.FromMilliseconds(50),
|
|
RetryMaxDelay = TimeSpan.FromMilliseconds(100),
|
|
};
|
|
|
|
var failed = await host.CapabilityAsync(enabled: true, Policy, CancellationToken.None);
|
|
Assert.False(failed.Available);
|
|
Assert.Equal("The screen host gave no answer (exit 0xC0000142).", failed.Reason);
|
|
|
|
var republished = 0;
|
|
await host.RetryFailedProbeAsync(_ => { republished++; return Task.CompletedTask; }, CancellationToken.None)
|
|
.WaitAsync(TimeSpan.FromSeconds(30));
|
|
Assert.Equal(1, republished);
|
|
Assert.True((await host.CapabilityAsync(enabled: true, Policy, CancellationToken.None)).Available);
|
|
Assert.Equal(2, launcher.Starts);
|
|
|
|
// Answered: nothing more to retry, and the inventory is not published again.
|
|
await host.RetryFailedProbeAsync(_ => { republished++; return Task.CompletedTask; }, CancellationToken.None);
|
|
Assert.Equal(1, republished);
|
|
Assert.Equal(2, launcher.Starts);
|
|
}
|
|
|
|
/// <summary>The first starts exit at once with no output; later ones start the fake host.</summary>
|
|
private sealed class FailingFirstLauncher(int failures, int exitCode) : IScreenProcessLauncher
|
|
{
|
|
private readonly DirectScreenProcessLauncher inner = new();
|
|
|
|
public int Starts { get; private set; }
|
|
|
|
public IScreenProcess Start(string fileName, IReadOnlyList<string> arguments)
|
|
=> ++Starts <= failures ? new DeadProcess(exitCode) : inner.Start(fileName, arguments);
|
|
|
|
private sealed class DeadProcess(int exitCode) : IScreenProcess
|
|
{
|
|
public Stream Input { get; } = new MemoryStream();
|
|
public Stream Output { get; } = new MemoryStream();
|
|
public Stream Error { get; } = new MemoryStream();
|
|
public int? SessionId => null;
|
|
public Task<int> Exited { get; } = Task.FromResult(exitCode);
|
|
public void Kill() { }
|
|
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public void TheRealScreenHostsProbeLineParses()
|
|
{
|
|
// Verbatim from ExecuteR-Screen 0.1.0 on a Windows desktop.
|
|
const string output = """{"version":"0.1.0","capture":true,"input":true,"monitors":[{"index":0,"name":"\\\\.\\DISPLAY257","x":0,"y":0,"width":2466,"height":1092,"primary":true}],"desktop":"default","winpe":false,"platform":"windows","reason":"capture via DXGI desktop duplication (GDI fallback available)"}""";
|
|
|
|
Assert.True(ScreenHostProtocol.TryParseProbe(output, out var probe));
|
|
Assert.True(probe!.Capture);
|
|
Assert.True(probe.Input);
|
|
var monitor = Assert.Single(probe.Monitors!);
|
|
Assert.Equal(@"\\.\DISPLAY257", monitor.Name);
|
|
Assert.Equal(2466, monitor.Width);
|
|
Assert.True(monitor.Primary);
|
|
}
|
|
|
|
/// <summary>The real Rust screen host, when it has been built here (scripts/Build-ScreenHost.ps1); otherwise nothing to check.</summary>
|
|
[Fact]
|
|
public async Task TheBuiltScreenHostAnswersTheAgentsProbe()
|
|
{
|
|
var baseDirectory = new DirectoryInfo(AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar));
|
|
var repo = baseDirectory.Parent!.Parent!.Parent!.Parent!.Parent!.FullName;
|
|
var exe = Path.Combine(repo, "src", "ScreenHost", "target", "x86_64-pc-windows-msvc", "release", "ExecuteR-Screen.exe");
|
|
if (!OperatingSystem.IsWindows() || !File.Exists(exe))
|
|
{
|
|
return;
|
|
}
|
|
|
|
var host = ScreenHostTestKit.Host(new ScreenHostCommand(exe, []), new DirectScreenProcessLauncher(), new FakeDesktop());
|
|
var capability = await host.CapabilityAsync(enabled: true, Policy, CancellationToken.None);
|
|
|
|
Assert.Equal("windows", capability.Platform);
|
|
Assert.False(string.IsNullOrEmpty(capability.Version));
|
|
Assert.True(capability.Available || capability.Reason is not null);
|
|
}
|
|
}
|