Files
Alphaeus Mote 37116f0329 feat(schedules): a schedule owns a list of triggers, with At Logon and On Demand
A schedule (script, arguments, targets, exclusions, stagger) now owns 1..20
triggers in ScheduleTriggers: Recurring, Once, On Enrollment, On Agent
Ready, At Logon and On Demand, each with its own next/last run and, for
events, a repeat (every time, once per device, once per user per device).
The sweep fires a schedule once however many of its triggers are due.

At Logon fires on the agent's logon events with the user and session; a
Delay After Logon becomes a start time on the device's clock (logon time
plus delay) that the agent waits out. On Demand makes the script available
to the schedule's targets minus exclusions; a device asks over NATS to
start it by schedule or script id or name (ambiguity refused with the
candidates), its text parameters checked like the console's, and the run is
a normal job with source 'device', audited with the device as actor.

Migration ScheduleTriggerList (SQLite, Postgres, SQL Server) moves each
schedule's timing into one trigger under the schedule's own id, so
once-per-device records keep matching; Down throws (lossy).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 15:43:55 -05:00

230 lines
10 KiB
C#

using System.Net;
using System.Net.Http.Json;
using Backend.Api;
using Backend.Data;
using Microsoft.EntityFrameworkCore;
using NATS.NKeys;
using Shared.Contracts.Api;
using Shared.Contracts.Models;
using Shared.Contracts.Serialization;
using Shared.Infrastructure.Security;
using Xunit;
namespace Backend.Tests;
/// <summary>One device through its phases: Windows PE before imaging, then the installed OS.</summary>
public class DeviceHistoryTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
{
[Fact]
public async Task WinPeThenInstalledOsIsOneDeviceWithItsTransitionsInHistory()
{
var token = await CreateTokenAsync();
var clientId = NewClientId();
using var anonymous = fixture.CreateClient();
await EnrollAsync(anonymous, token, clientId, "MINWINPC-1A2B3C", "Windows PE", "10.0.26100");
await EnrollAsync(anonymous, token, clientId, "LAB-PC-01", "Windows 11", "10.0.26100.4351");
var devices = await fixture.WithDbAsync(db => db.Devices.Where(d => d.ClientId == clientId).ToListAsync());
var device = Assert.Single(devices);
Assert.Equal("LAB-PC-01", device.Hostname);
Assert.Equal("Windows 11", device.OsCaption);
Assert.Equal("10.0.26100.4351", device.OsVersion);
using var admin = await fixture.SignedInAsync("history-admin");
var history = await admin.GetFromJsonAsync<List<DeviceHistoryEventDto>>(
ApiRoutes.For.DeviceHistory(clientId), JsonDefaults.Options);
// Newest first: the second enrollment and the transitions it brought.
Assert.NotNull(history);
Assert.Equal(
[DeviceHistory.Enrolled, DeviceHistory.OsChanged, DeviceHistory.Renamed, DeviceHistory.Enrolled],
history.Select(e => e.Action));
Assert.Equal("LAB-PC-01 · Windows 11 10.0.26100.4351", history[0].Detail);
Assert.Equal("Windows PE 10.0.26100 → Windows 11 10.0.26100.4351", history[1].Detail);
Assert.Equal("MINWINPC-1A2B3C → LAB-PC-01", history[2].Detail);
Assert.Equal("MINWINPC-1A2B3C · Windows PE 10.0.26100", history[3].Detail);
// The enrollment audit rows carry the hostname and OS too.
var enrollments = await fixture.WithDbAsync(db => db.AuditEvents
.Where(e => e.ClientId == clientId && e.Action == "bootstrap-succeeded")
.OrderBy(e => e.Id)
.Select(e => e.Detail)
.ToListAsync());
Assert.Collection(
enrollments,
first => Assert.Contains("hostname=MINWINPC-1A2B3C os=\"Windows PE 10.0.26100\"", first),
second => Assert.Contains("hostname=LAB-PC-01 os=\"Windows 11 10.0.26100.4351\"", second));
}
[Fact]
public async Task AnUnchangedReEnrollmentRecordsNoTransition()
{
var token = await CreateTokenAsync();
var clientId = NewClientId();
using var anonymous = fixture.CreateClient();
await EnrollAsync(anonymous, token, clientId, "PC-STABLE", "Windows 11", "10.0.26100");
await EnrollAsync(anonymous, token, clientId, "pc-stable", "Windows 11", "10.0.26100");
var actions = await fixture.WithDbAsync(db => db.AuditEvents
.Where(e => e.ClientId == clientId && e.Category == "device")
.Select(e => e.Action)
.ToListAsync());
Assert.Equal([DeviceHistory.Enrolled, DeviceHistory.Enrolled], actions);
}
[Fact]
public async Task ReportsRecordOnlyRealChanges()
{
var clientId = await fixture.SeedDeviceAsync("MINWINPC-XYZ");
await fixture.WithDbAsync(async db =>
{
var device = await db.Devices.SingleAsync(d => d.ClientId == clientId);
// First OS sighting: nothing to compare with.
DeviceHistory.Apply(db, device, "MINWINPC-XYZ", reportsOs: true, "Windows PE", "10.0.26100");
// Presence: same name again.
DeviceHistory.Apply(db, device, "MINWINPC-XYZ");
// An older agent's generic enrollment string is a spelling, not an OS change.
DeviceHistory.Apply(db, device, "MINWINPC-XYZ", reportsOs: true, "Microsoft Windows NT 10.0.26100.0", "10.0.26100.0");
DeviceHistory.Apply(db, device, "MINWINPC-XYZ", reportsOs: true, "Windows PE", "10.0.26100");
// Inventory from the installed OS.
DeviceHistory.Apply(db, device, "LAB-PC-02", reportsOs: true, "Windows 11", "10.0.26100.4351");
await db.SaveChangesAsync();
});
var events = await fixture.WithDbAsync(db => db.AuditEvents
.Where(e => e.ClientId == clientId)
.OrderBy(e => e.Id)
.Select(e => new { e.Action, e.Detail })
.ToListAsync());
Assert.Collection(
events,
e => Assert.Equal((DeviceHistory.Renamed, "MINWINPC-XYZ → LAB-PC-02"), (e.Action, e.Detail)),
e => Assert.Equal(
(DeviceHistory.OsChanged, "Windows PE 10.0.26100 → Windows 11 10.0.26100.4351"), (e.Action, e.Detail)));
}
[Fact]
public async Task EnrollingTheInstalledOsDropsTheWinPeInventorySoGroupScopedTriggersSeeTheNewOs()
{
// An on-enrollment trigger aimed at "not Windows PE" must skip the
// WinPE enrollment and fire for the installed OS — even though the
// last inventory on file is still the one Windows PE sent.
var token = await CreateTokenAsync();
var clientId = NewClientId();
var scriptId = await fixture.SeedScriptAsync($"after-imaging-{Guid.NewGuid():N}");
var triggerId = await fixture.WithDbAsync(async db =>
{
var group = new DeviceGroupEntity
{
Id = Guid.NewGuid(), Name = $"installed-{Guid.NewGuid():N}", Kind = GroupKind.Dynamic,
RulesJson = JsonDefaults.Serialize(new GroupRuleSet(RuleCombine.And,
[
new RuleGroup(RuleCombine.And,
[
new RuleCondition("clientId", RuleOperator.Equals, clientId),
new RuleCondition("os.caption", RuleOperator.NotEquals, "Windows PE"),
]),
])),
CreatedUtc = DateTimeOffset.UtcNow, UpdatedUtc = DateTimeOffset.UtcNow,
};
var trigger = new ScriptTriggerEntity
{
Id = Guid.NewGuid(), ScriptId = scriptId, GroupIdsJson = JsonDefaults.Serialize(new[] { group.Id }),
CreatedUtc = DateTimeOffset.UtcNow,
}.With(ScriptTriggerType.OnRegistration);
db.DeviceGroups.Add(group);
db.ScriptTriggers.Add(trigger);
await db.SaveChangesAsync();
return trigger.Timing().Id;
});
using var anonymous = fixture.CreateClient();
await EnrollAsync(anonymous, token, clientId, "MINWINPC-TRIG", "Windows PE", "10.0.26100");
await fixture.WithDbAsync(async db =>
{
db.DeviceInventory.Add(new DeviceInventoryEntity
{
ClientId = clientId,
ReportJson = JsonDefaults.Serialize(WinPeInventory(clientId)),
UpdatedUtc = DateTimeOffset.UtcNow,
});
await db.SaveChangesAsync();
});
Assert.Equal(0, await RunsAsync());
await EnrollAsync(anonymous, token, clientId, "LAB-PC-TRIG", "Windows 11", "10.0.26100.4351");
Assert.Equal(1, await RunsAsync());
Assert.False(await fixture.WithDbAsync(db => db.DeviceInventory.AnyAsync(i => i.ClientId == clientId)));
Task<int> RunsAsync() => fixture.WithDbAsync(db =>
db.ScriptTriggerRuns.CountAsync(r => r.TriggerId == triggerId && r.ClientId == clientId));
}
[Fact]
public async Task HistoryHonorsDeviceScope()
{
var mine = await fixture.SeedDeviceAsync("SCOPED-MINE");
var theirs = await fixture.SeedDeviceAsync("SCOPED-THEIRS");
using var scoped = await fixture.ScopedSignedInAsync("history-scoped", mine);
Assert.Equal(HttpStatusCode.OK, (await scoped.GetAsync(ApiRoutes.For.DeviceHistory(mine))).StatusCode);
Assert.Equal(HttpStatusCode.NotFound, (await scoped.GetAsync(ApiRoutes.For.DeviceHistory(theirs))).StatusCode);
using var anonymous = fixture.CreateClient();
Assert.Equal(HttpStatusCode.Unauthorized, (await anonymous.GetAsync(ApiRoutes.For.DeviceHistory(mine))).StatusCode);
}
private async Task EnrollAsync(
HttpClient client, string token, string clientId, string hostname, string osCaption, string osVersion)
{
using var key = KeyPair.CreatePair(PrefixByte.User);
var response = await client.PostAsJsonAsync(
ApiRoutes.Bootstrap,
new BootstrapRequest(
BootstrapToken: token,
ClientId: clientId,
NkeyPublic: key.GetPublicKey(),
AgentVersion: "2026.10.23.0000",
Device: new EnrollDeviceInfo(hostname, "Dell Inc.", "OptiPlex", osCaption, osVersion)),
JsonDefaults.Options);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
private async Task<string> CreateTokenAsync()
{
var token = TokenGenerator.CreateUrlSafeToken(32);
await fixture.WithDbAsync(async db =>
{
db.BootstrapTokens.Add(new BootstrapTokenEntity
{
Id = Guid.NewGuid(),
TokenHash = TokenHashing.Sha256Hex(token),
CreatedUtc = DateTimeOffset.UtcNow,
ExpiresUtc = DateTimeOffset.UtcNow.AddHours(1),
MaxUses = 1,
});
await db.SaveChangesAsync();
});
return token;
}
private static InventoryReport WinPeInventory(string clientId) => new(
new InventoryIdentity(clientId, "MINWINPC-TRIG", "Dell Inc.", "OptiPlex", "SN1", null, null, "WORKGROUP", false,
"x64-based PC", null, null, null),
new InventoryOs("Windows PE", "10.0.26100", "26100", "64-bit", null, null, null),
new InventoryCpu("CPU", 4, 2),
[],
8L << 30,
[],
[],
[],
DateTimeOffset.UtcNow);
private static string NewClientId() => $"{Guid.NewGuid():N}{Guid.NewGuid():N}";
}