44a4c3aaec
One process-wide session watcher: the Windows service lifetime now takes SERVICE_CONTROL_SESSIONCHANGE and forwards it; a foreground run polls WTSEnumerateSessions. Remote View sweeps at once on console and logon changes. Logons (WTSINFO LogonTime and DOMAIN\user on Windows, loginctl on linux; none on macOS or in Windows PE) are caught up at start, deduped in logons.json and reported as "logon" agent events, queued while the agent is offline. Script jobs wait on the device clock until NotBeforeUtc before they run, see what started them ($Trigger, EXECUTER_TRIGGER_* for external engines) and feed a local observer keyed by the request id. `ExecuteR-Agent run <name|id> [-p Name=Value] [--wait] [--timeout s]` and `run --list` reach the running agent over a named pipe (Administrators and SYSTEM only, elevated callers, owner-checked) or a root-only Unix socket, which asks the backend with an agent.run.request. Bare `run` is still the service entry point. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
453 lines
16 KiB
C#
453 lines
16 KiB
C#
using System.Collections.Concurrent;
|
|
using System.Runtime.CompilerServices;
|
|
using System.Runtime.InteropServices;
|
|
using System.Threading.Channels;
|
|
using Agent.Messaging;
|
|
using Agent.Platform;
|
|
using Agent.Sessions;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using Shared.Contracts.Messages;
|
|
using Xunit;
|
|
|
|
namespace Agent.Tests;
|
|
|
|
internal sealed class FakeLogonSource : ILogonSource
|
|
{
|
|
public List<LogonEvent> Present { get; } = [];
|
|
public Channel<LogonEvent> Live { get; } = Channel.CreateUnbounded<LogonEvent>();
|
|
public bool Watched { get; private set; }
|
|
|
|
public IReadOnlyList<LogonEvent>? Current() => [.. Present];
|
|
|
|
public async IAsyncEnumerable<LogonEvent> WatchAsync([EnumeratorCancellation] CancellationToken cancellationToken)
|
|
{
|
|
Watched = true;
|
|
foreach (var present in Present.ToList())
|
|
{
|
|
yield return present;
|
|
}
|
|
|
|
await foreach (var logon in Live.Reader.ReadAllAsync(cancellationToken))
|
|
{
|
|
yield return logon;
|
|
}
|
|
}
|
|
}
|
|
|
|
internal sealed class FakeEventSink : IAgentEventSink
|
|
{
|
|
public TaskCompletionSource Connected { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
public ConcurrentQueue<AgentEventPayload> Published { get; } = new();
|
|
public int FailuresLeft { get; set; }
|
|
|
|
public async Task<string> WaitConnectedAsync(CancellationToken cancellationToken)
|
|
{
|
|
await Connected.Task.WaitAsync(cancellationToken);
|
|
return "client-1";
|
|
}
|
|
|
|
public Task PublishEventAsync(AgentEventPayload payload, CancellationToken cancellationToken)
|
|
{
|
|
if (FailuresLeft-- > 0)
|
|
{
|
|
throw new InvalidOperationException("disconnected");
|
|
}
|
|
|
|
Published.Enqueue(payload);
|
|
return Task.CompletedTask;
|
|
}
|
|
}
|
|
|
|
internal sealed class FakeSessionQuery : ISessionQuery
|
|
{
|
|
public int? Console { get; set; } = 1;
|
|
public Dictionary<int, SessionInfo> Sessions { get; } = [];
|
|
|
|
public int? ActiveConsoleSession() => Console;
|
|
|
|
public IReadOnlyList<SessionInfo>? Enumerate() => [.. Sessions.Values];
|
|
|
|
public SessionInfo? Query(int sessionId) => Sessions.GetValueOrDefault(sessionId);
|
|
}
|
|
|
|
public sealed class LogonTests : IDisposable
|
|
{
|
|
private static readonly DateTimeOffset Morning = DateTimeOffset.UtcNow.AddMinutes(-5);
|
|
private readonly string root = Path.Combine(Path.GetTempPath(), "executer-logon-tests", Guid.NewGuid().ToString("N"));
|
|
private readonly FakeLogonSource source = new();
|
|
private readonly FakeEventSink sink = new();
|
|
|
|
public void Dispose()
|
|
{
|
|
try
|
|
{
|
|
Directory.Delete(root, recursive: true);
|
|
}
|
|
catch (IOException)
|
|
{
|
|
}
|
|
}
|
|
|
|
private string LedgerPath => Path.Combine(root, "logons.json");
|
|
|
|
private LogonReporter Reporter(LogonLedger? ledger = null)
|
|
=> new(source, ledger ?? new LogonLedger(LedgerPath), sink, NullLogger.Instance, retryDelay: TimeSpan.FromMilliseconds(20));
|
|
|
|
private static async Task WaitUntilAsync(Func<bool> condition)
|
|
{
|
|
var deadline = DateTime.UtcNow.AddSeconds(10);
|
|
while (!condition())
|
|
{
|
|
Assert.True(DateTime.UtcNow < deadline, "Timed out waiting.");
|
|
await Task.Delay(10);
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ReportsALogonWithItsOwnTimeUserAndSession()
|
|
{
|
|
sink.Connected.SetResult();
|
|
using var stop = new CancellationTokenSource();
|
|
var running = Reporter().RunAsync(stop.Token);
|
|
|
|
source.Live.Writer.TryWrite(new LogonEvent(@"CONTOSO\ann", 2, Morning, "Console"));
|
|
await WaitUntilAsync(() => !sink.Published.IsEmpty);
|
|
await stop.CancelAsync();
|
|
await running;
|
|
|
|
var reported = Assert.Single(sink.Published);
|
|
Assert.Equal(AgentEventKinds.Logon, reported.Kind);
|
|
Assert.Equal("client-1", reported.ClientId);
|
|
Assert.Equal(Morning, reported.TimestampUtc);
|
|
Assert.Equal(@"CONTOSO\ann", reported.User);
|
|
Assert.Equal(2, reported.SessionId);
|
|
Assert.Equal("Console", reported.Detail);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task QueuesWhileDisconnectedAndSendsInOrderOnceConnected()
|
|
{
|
|
using var stop = new CancellationTokenSource();
|
|
var reporter = Reporter();
|
|
var running = reporter.RunAsync(stop.Token);
|
|
|
|
source.Live.Writer.TryWrite(new LogonEvent("ann", 2, Morning));
|
|
source.Live.Writer.TryWrite(new LogonEvent("bob", 3, Morning.AddMinutes(1)));
|
|
await WaitUntilAsync(() => reporter.Queued == 2);
|
|
Assert.Empty(sink.Published);
|
|
|
|
sink.Connected.SetResult();
|
|
await WaitUntilAsync(() => sink.Published.Count == 2);
|
|
await stop.CancelAsync();
|
|
await running;
|
|
|
|
Assert.Equal(["ann", "bob"], sink.Published.Select(p => p.User));
|
|
Assert.Equal(0, reporter.Queued);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ARepeatedNotificationIsReportedOnce()
|
|
{
|
|
sink.Connected.SetResult();
|
|
using var stop = new CancellationTokenSource();
|
|
var running = Reporter().RunAsync(stop.Token);
|
|
|
|
var logon = new LogonEvent("ann", 2, Morning);
|
|
source.Live.Writer.TryWrite(logon);
|
|
source.Live.Writer.TryWrite(logon with { });
|
|
source.Live.Writer.TryWrite(new LogonEvent("ann", 2, Morning.AddHours(-1)));
|
|
await WaitUntilAsync(() => sink.Published.Count == 2);
|
|
await Task.Delay(200);
|
|
await stop.CancelAsync();
|
|
await running;
|
|
|
|
Assert.Equal(2, sink.Published.Count);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task CatchesUpAtStartAndARestartDoesNotReportAgain()
|
|
{
|
|
sink.Connected.SetResult();
|
|
source.Present.Add(new LogonEvent("ann", 2, Morning));
|
|
|
|
using (var stop = new CancellationTokenSource())
|
|
{
|
|
var running = Reporter().RunAsync(stop.Token);
|
|
await WaitUntilAsync(() => sink.Published.Count == 1);
|
|
await stop.CancelAsync();
|
|
await running;
|
|
}
|
|
|
|
// The agent restarts: a new ledger instance reads the same file.
|
|
using (var stop = new CancellationTokenSource())
|
|
{
|
|
var running = Reporter().RunAsync(stop.Token);
|
|
source.Live.Writer.TryWrite(new LogonEvent("bob", 3, Morning.AddMinutes(2)));
|
|
await WaitUntilAsync(() => sink.Published.Count == 2);
|
|
await Task.Delay(200);
|
|
await stop.CancelAsync();
|
|
await running;
|
|
}
|
|
|
|
Assert.Equal(["ann", "bob"], sink.Published.Select(p => p.User));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ALogonQueuedButNeverSentIsCaughtUpAfterARestart()
|
|
{
|
|
source.Present.Add(new LogonEvent("ann", 2, Morning));
|
|
using (var stop = new CancellationTokenSource())
|
|
{
|
|
var reporter = Reporter();
|
|
var running = reporter.RunAsync(stop.Token);
|
|
await WaitUntilAsync(() => reporter.Queued == 1);
|
|
await stop.CancelAsync();
|
|
await running;
|
|
}
|
|
|
|
sink.Connected.SetResult();
|
|
using (var stop = new CancellationTokenSource())
|
|
{
|
|
var running = Reporter().RunAsync(stop.Token);
|
|
await WaitUntilAsync(() => sink.Published.Count == 1);
|
|
await stop.CancelAsync();
|
|
await running;
|
|
}
|
|
|
|
Assert.Equal("ann", Assert.Single(sink.Published).User);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task TheLedgerKeepsOnlySessionsStillPresent()
|
|
{
|
|
var ledger = new LogonLedger(LedgerPath);
|
|
var gone = new LogonEvent("old", 7, Morning.AddDays(-2));
|
|
var here = new LogonEvent("ann", 2, Morning);
|
|
ledger.Add(gone.Key, DateTimeOffset.UtcNow);
|
|
ledger.Add(here.Key, DateTimeOffset.UtcNow);
|
|
source.Present.Add(here);
|
|
sink.Connected.SetResult();
|
|
|
|
using var stop = new CancellationTokenSource();
|
|
var running = Reporter(new LogonLedger(LedgerPath)).RunAsync(stop.Token);
|
|
await Task.Delay(200);
|
|
await stop.CancelAsync();
|
|
await running;
|
|
|
|
var reread = new LogonLedger(LedgerPath);
|
|
Assert.False(reread.Contains(gone.Key));
|
|
Assert.True(reread.Contains(here.Key));
|
|
Assert.Empty(sink.Published);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ALogonOlderThanADayIsNotReported()
|
|
{
|
|
sink.Connected.SetResult();
|
|
var stale = new LogonEvent("ann", 2, DateTimeOffset.UtcNow - LogonReporter.MaxAge - TimeSpan.FromMinutes(1));
|
|
source.Present.Add(stale);
|
|
using var stop = new CancellationTokenSource();
|
|
var reporter = Reporter();
|
|
var running = reporter.RunAsync(stop.Token);
|
|
|
|
await WaitUntilAsync(() => new LogonLedger(LedgerPath).Contains(stale.Key));
|
|
await stop.CancelAsync();
|
|
await running;
|
|
|
|
Assert.Empty(sink.Published);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AFailedPublishIsRetried()
|
|
{
|
|
sink.Connected.SetResult();
|
|
sink.FailuresLeft = 2;
|
|
using var stop = new CancellationTokenSource();
|
|
var running = Reporter().RunAsync(stop.Token);
|
|
|
|
source.Live.Writer.TryWrite(new LogonEvent("ann", 2, Morning));
|
|
await WaitUntilAsync(() => sink.Published.Count == 1);
|
|
await stop.CancelAsync();
|
|
await running;
|
|
|
|
Assert.Equal("ann", Assert.Single(sink.Published).User);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task WindowsPeWatchesNoLogons()
|
|
{
|
|
sink.Connected.SetResult();
|
|
source.Present.Add(new LogonEvent("ann", 2, Morning));
|
|
using var service = new LogonReportService(
|
|
source, new LogonLedger(LedgerPath), sink, NullLogger<LogonReportService>.Instance, new WindowsPhase(() => true));
|
|
|
|
await service.StartAsync(CancellationToken.None);
|
|
await Task.Delay(200);
|
|
await service.StopAsync(CancellationToken.None);
|
|
|
|
Assert.False(source.Watched);
|
|
Assert.Empty(sink.Published);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task OutsideWindowsPeTheServiceReports()
|
|
{
|
|
sink.Connected.SetResult();
|
|
source.Present.Add(new LogonEvent("ann", 2, Morning));
|
|
using var service = new LogonReportService(
|
|
source, new LogonLedger(LedgerPath), sink, NullLogger<LogonReportService>.Instance, new WindowsPhase(() => false));
|
|
|
|
await service.StartAsync(CancellationToken.None);
|
|
await WaitUntilAsync(() => sink.Published.Count == 1);
|
|
await service.StopAsync(CancellationToken.None);
|
|
|
|
Assert.True(source.Watched);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task WindowsSourceCatchesUpThenFollowsLogonNotifications()
|
|
{
|
|
var query = new FakeSessionQuery();
|
|
query.Sessions[1] = new SessionInfo(1, @"CONTOSO\ann", Morning, "Console");
|
|
query.Sessions[0] = new SessionInfo(0, null, null, "Services");
|
|
var watcher = new SessionWatcher();
|
|
var windows = new WindowsLogonSource(watcher, query, TimeSpan.FromMilliseconds(10));
|
|
using var stop = new CancellationTokenSource(TimeSpan.FromSeconds(10));
|
|
var seen = new List<LogonEvent>();
|
|
|
|
await foreach (var logon in windows.WatchAsync(stop.Token))
|
|
{
|
|
seen.Add(logon);
|
|
if (seen.Count == 1)
|
|
{
|
|
query.Sessions[3] = new SessionInfo(3, @"CONTOSO\bob", null, "RDP-Tcp#0");
|
|
watcher.Publish(new SessionChange(SessionChangeKind.Lock, 1));
|
|
watcher.Publish(new SessionChange(SessionChangeKind.Logon, 3));
|
|
}
|
|
else
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
|
|
Assert.Equal(@"CONTOSO\ann", seen[0].User);
|
|
Assert.Equal(Morning, seen[0].LogonUtc);
|
|
Assert.Equal(1, seen[0].SessionId);
|
|
Assert.Equal(@"CONTOSO\bob", seen[1].User);
|
|
Assert.True(seen[1].TimeEstimated);
|
|
Assert.Equal(3, seen[1].SessionId);
|
|
}
|
|
|
|
[Fact]
|
|
public void PollingTurnsSessionListsIntoChanges()
|
|
{
|
|
var query = new FakeSessionQuery();
|
|
query.Sessions[1] = new SessionInfo(1, "ann", Morning);
|
|
var poller = new SessionPoller(query);
|
|
|
|
Assert.Empty(poller.Poll());
|
|
|
|
query.Sessions[2] = new SessionInfo(2, "bob", Morning.AddMinutes(1));
|
|
Assert.Equal([new SessionChange(SessionChangeKind.Logon, 2)], poller.Poll());
|
|
|
|
query.Sessions.Remove(1);
|
|
query.Console = 2;
|
|
Assert.Equal(
|
|
[
|
|
new SessionChange(SessionChangeKind.Logoff, 1),
|
|
new SessionChange(SessionChangeKind.ConsoleDisconnect, 1),
|
|
new SessionChange(SessionChangeKind.ConsoleConnect, 2),
|
|
],
|
|
poller.Poll());
|
|
|
|
// Same session id, a new logon (sign out and back in between polls).
|
|
query.Sessions[2] = new SessionInfo(2, "bob", Morning.AddMinutes(9));
|
|
Assert.Equal(
|
|
[new SessionChange(SessionChangeKind.Logoff, 2), new SessionChange(SessionChangeKind.Logon, 2)],
|
|
poller.Poll());
|
|
}
|
|
|
|
[Fact]
|
|
public void TheWtsInfoLayoutPutsTheLogonTimeAtOffset200()
|
|
{
|
|
Assert.Equal(216, Marshal.SizeOf<WindowsSessionInterop.WTSINFOW>());
|
|
Assert.Equal(200, Marshal.OffsetOf<WindowsSessionInterop.WTSINFOW>(nameof(WindowsSessionInterop.WTSINFOW.LogonTime)).ToInt32());
|
|
Assert.Null(WindowsSessionQuery.FromFileTime(0));
|
|
Assert.Equal(new DateTimeOffset(2026, 11, 6, 18, 0, 0, TimeSpan.Zero),
|
|
WindowsSessionQuery.FromFileTime(new DateTime(2026, 11, 6, 18, 0, 0, DateTimeKind.Utc).ToFileTimeUtc()));
|
|
}
|
|
|
|
[Fact]
|
|
public void TheRealSessionListHasThisProcessSessionWithAPastLogon()
|
|
{
|
|
var own = Screen.WindowsScreenDesktop.OwnSession();
|
|
var sessions = new WindowsSessionQuery().Enumerate();
|
|
Assert.NotNull(sessions);
|
|
if (own is null or 0)
|
|
{
|
|
return; // A service-hosted runner (session 0) has no signed-in user to look at.
|
|
}
|
|
|
|
var mine = Assert.Single(sessions, s => s.SessionId == own);
|
|
Assert.False(string.IsNullOrEmpty(mine.User));
|
|
Assert.NotNull(mine.LogonUtc);
|
|
Assert.InRange(mine.LogonUtc!.Value, new DateTimeOffset(2000, 1, 1, 0, 0, 0, TimeSpan.Zero), DateTimeOffset.UtcNow.AddMinutes(1));
|
|
Assert.Contains('\\', mine.User);
|
|
}
|
|
|
|
[Fact]
|
|
public void LoginctlOutputIsParsed()
|
|
{
|
|
Assert.Equal(["2", "c1", "15"], LinuxLogonSource.ParseSessionIds("""
|
|
2 1000 ann seat0 tty2 active no
|
|
c1 119 gdm seat0 tty1 active no
|
|
15 1001 bob pts/0 active no
|
|
|
|
"""));
|
|
|
|
var ann = LinuxLogonSource.ParseSession("2", "Name=ann\nClass=user\nTimestamp=Fri 2026-11-06 18:32:01 UTC\nRemote=no\n");
|
|
Assert.NotNull(ann);
|
|
Assert.Equal("ann", ann.User);
|
|
Assert.Equal(2, ann.SessionId);
|
|
Assert.Equal(new DateTimeOffset(2026, 11, 6, 18, 32, 1, TimeSpan.Zero), ann.LogonUtc);
|
|
Assert.Equal("local", ann.Detail);
|
|
Assert.False(ann.TimeEstimated);
|
|
|
|
Assert.Null(LinuxLogonSource.ParseSession("c1", "Name=gdm\nClass=greeter\nTimestamp=Fri 2026-11-06 18:30:00 UTC\nRemote=no"));
|
|
|
|
var remote = LinuxLogonSource.ParseSession("c7", "Name=bob\nClass=user\nTimestamp=\nRemote=yes");
|
|
Assert.NotNull(remote);
|
|
Assert.Null(remote.SessionId);
|
|
Assert.Equal("c7", remote.Session);
|
|
Assert.Equal("remote", remote.Detail);
|
|
Assert.True(remote.TimeEstimated);
|
|
}
|
|
|
|
[Fact]
|
|
public void LinuxWithoutLoginctlReportsNothing()
|
|
{
|
|
var linux = new LinuxLogonSource(NullLogger.Instance, _ => null);
|
|
Assert.Null(linux.Current());
|
|
}
|
|
|
|
[Fact]
|
|
public void LinuxSessionsAreReadWithLoginctl()
|
|
{
|
|
var calls = new List<string>();
|
|
var linux = new LinuxLogonSource(NullLogger.Instance, args =>
|
|
{
|
|
calls.Add(string.Join(' ', args));
|
|
return args[0] == "list-sessions"
|
|
? "2 1000 ann seat0 tty2\n"
|
|
: "Name=ann\nClass=user\nTimestamp=Fri 2026-11-06 18:32:01 UTC\nRemote=no";
|
|
});
|
|
|
|
var current = linux.Current();
|
|
|
|
Assert.Equal("ann", Assert.Single(current!).User);
|
|
Assert.Equal(
|
|
["list-sessions --no-legend --no-pager", "show-session 2 -p Name -p Class -p Timestamp -p Remote"],
|
|
calls);
|
|
}
|
|
}
|