37116f0329
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>
511 lines
24 KiB
C#
511 lines
24 KiB
C#
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using Backend.Data;
|
|
using Backend.Groups;
|
|
using Microsoft.Data.Sqlite;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
|
using Microsoft.EntityFrameworkCore.Migrations;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Shared.Contracts.Api;
|
|
using Shared.Contracts.Models;
|
|
using Shared.Contracts.Serialization;
|
|
using Xunit;
|
|
|
|
namespace Backend.Tests;
|
|
|
|
/// <summary>
|
|
/// The built-in Windows PE group and Exclude on schedules, event triggers and
|
|
/// Run Now: what runs is the targets minus the exclusions, read at run time.
|
|
/// </summary>
|
|
public class TargetExclusionTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
|
|
{
|
|
private const string Win11 = "Microsoft Windows 11 Enterprise";
|
|
|
|
[Fact]
|
|
public async Task WindowsPeHoldsOnlyDevicesInWindowsPeAndWorkstationsLeavesThemOut()
|
|
{
|
|
var pe = await SeedDeviceAsync("PE-MEMBER", DefaultSeeder.WinPeCaption);
|
|
var workstation = await SeedDeviceAsync("PE-WORKSTATION", Win11);
|
|
var server = await SeedDeviceAsync("PE-SERVER", "Microsoft Windows Server 2022 Datacenter");
|
|
var linux = await SeedDeviceAsync("PE-LINUX", "Ubuntu 24.04 LTS");
|
|
|
|
var members = await MembersByNameAsync("Windows PE", "Windows", "Windows Workstations", "Windows Servers");
|
|
|
|
Assert.Contains(pe, members["Windows PE"]);
|
|
Assert.DoesNotContain(workstation, members["Windows PE"]);
|
|
Assert.DoesNotContain(server, members["Windows PE"]);
|
|
Assert.DoesNotContain(linux, members["Windows PE"]);
|
|
|
|
// "Windows" is every Windows device, Windows PE included.
|
|
Assert.Contains(pe, members["Windows"]);
|
|
Assert.Contains(workstation, members["Windows"]);
|
|
|
|
Assert.Contains(workstation, members["Windows Workstations"]);
|
|
Assert.DoesNotContain(pe, members["Windows Workstations"]);
|
|
Assert.DoesNotContain(pe, members["Windows Servers"]);
|
|
Assert.Contains(server, members["Windows Servers"]);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AScheduleRunsOnItsTargetsMinusItsExclusions()
|
|
{
|
|
using var client = await fixture.SignedInAsync("exclude-admin");
|
|
var scriptId = await fixture.SeedScriptAsync("exclude-schedule");
|
|
var pe = await SeedDeviceAsync("SCHED-PE", DefaultSeeder.WinPeCaption);
|
|
var windows = await SeedDeviceAsync("SCHED-WIN", Win11);
|
|
var skipped = await SeedDeviceAsync("SCHED-SKIP", Win11);
|
|
|
|
var id = await CreateAsync(client, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, GroupIds: [await GroupIdAsync("Windows")], CronExpression: "0 1 * * *",
|
|
ExcludeGroupIds: [await GroupIdAsync("Windows PE")], ExcludeClientIds: [skipped]));
|
|
|
|
var trigger = (await ListAsync(client)).Single(t => t.Id == id);
|
|
Assert.Equal(
|
|
new[] { (TriggerTargetKind.Group, "Windows PE"), (TriggerTargetKind.Device, "SCHED-SKIP") },
|
|
trigger.Excludes!.Select(e => (e.Kind, e.Name)).ToArray());
|
|
|
|
var targeted = await RunNowAsync(client, id);
|
|
Assert.Contains(windows, targeted);
|
|
Assert.DoesNotContain(pe, targeted);
|
|
Assert.DoesNotContain(skipped, targeted);
|
|
|
|
// Exclusions are read at each run: a device that leaves Windows PE is reached next time.
|
|
await SetCaptionAsync(pe, Win11);
|
|
Assert.Contains(pe, await RunNowAsync(client, id));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AllDevicesCanExcludeDevicesAndGroups()
|
|
{
|
|
using var client = await fixture.SignedInAsync("exclude-admin");
|
|
var scriptId = await fixture.SeedScriptAsync("exclude-all");
|
|
var pe = await SeedDeviceAsync("ALL-PE", DefaultSeeder.WinPeCaption);
|
|
var windows = await SeedDeviceAsync("ALL-WIN", Win11);
|
|
var listed = await SeedDeviceAsync("ALL-LISTED", "Ubuntu 24.04 LTS");
|
|
|
|
var id = await CreateAsync(client, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, AllDevices: true, CronExpression: "0 1 * * *",
|
|
ExcludeGroupIds: [await GroupIdAsync("Windows PE")], ExcludeClientIds: [listed]));
|
|
|
|
var trigger = (await ListAsync(client)).Single(t => t.Id == id);
|
|
Assert.True(trigger.AllDevices);
|
|
Assert.Equal(2, trigger.Excludes!.Count);
|
|
|
|
var targeted = await RunNowAsync(client, id);
|
|
Assert.Contains(windows, targeted);
|
|
Assert.DoesNotContain(pe, targeted);
|
|
Assert.DoesNotContain(listed, targeted);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task TheScheduleSweepHonoursExclusions()
|
|
{
|
|
var scriptId = await fixture.SeedScriptAsync("exclude-sweep");
|
|
var pe = await SeedDeviceAsync("SWEEP-PE", DefaultSeeder.WinPeCaption);
|
|
var windows = await SeedDeviceAsync("SWEEP-WIN", Win11);
|
|
var peGroup = await GroupIdAsync("Windows PE");
|
|
var triggerId = await fixture.WithDbAsync(async db =>
|
|
{
|
|
var trigger = new ScriptTriggerEntity
|
|
{
|
|
Id = Guid.NewGuid(), ScriptId = scriptId, CreatedUtc = DateTimeOffset.UtcNow,
|
|
}.With(ScriptTriggerType.Scheduled, cron: "0 * * * *", nextRun: DateTimeOffset.UtcNow.AddMinutes(-1));
|
|
trigger.SetTargets(false, [pe, windows], []);
|
|
trigger.SetExcludes([], [peGroup]);
|
|
db.ScriptTriggers.Add(trigger);
|
|
await db.SaveChangesAsync();
|
|
return trigger.Id;
|
|
});
|
|
|
|
await new Backend.Jobs.ScheduleWorker(
|
|
fixture.Services.GetRequiredService<IServiceScopeFactory>(),
|
|
Microsoft.Extensions.Logging.Abstractions.NullLogger<Backend.Jobs.ScheduleWorker>.Instance)
|
|
.FireDueTriggersAsync(CancellationToken.None);
|
|
|
|
var (result, targeted) = await fixture.WithDbAsync(async db =>
|
|
{
|
|
var stored = db.ScriptTriggers.Single(t => t.Id == triggerId);
|
|
return await Task.FromResult((stored.LastResult, db.Jobs.Where(j => j.RunId == stored.LastRunId).Select(j => j.ClientId).ToList()));
|
|
});
|
|
Assert.Equal("1 job(s) queued", result);
|
|
Assert.Equal([windows], targeted);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData(ScriptTriggerType.OnRegistration)]
|
|
[InlineData(ScriptTriggerType.OnAgentReady)]
|
|
public async Task AnEventTriggerSkipsAnExcludedWindowsPeDeviceUntilItLeavesWindowsPe(ScriptTriggerType type)
|
|
{
|
|
var scriptId = await fixture.SeedScriptAsync($"exclude-event-{type}");
|
|
var pe = await SeedDeviceAsync($"EVENT-PE-{type}", DefaultSeeder.WinPeCaption);
|
|
var windows = await SeedDeviceAsync($"EVENT-WIN-{type}", Win11);
|
|
var windowsGroup = await GroupIdAsync("Windows");
|
|
var peGroup = await GroupIdAsync("Windows PE");
|
|
await fixture.WithDbAsync(async db =>
|
|
{
|
|
var trigger = new ScriptTriggerEntity
|
|
{
|
|
Id = Guid.NewGuid(), ScriptId = scriptId, CreatedUtc = DateTimeOffset.UtcNow,
|
|
}.With(type);
|
|
trigger.SetTargets(false, [], [windowsGroup]);
|
|
trigger.SetExcludes([], [peGroup]);
|
|
db.ScriptTriggers.Add(trigger);
|
|
await db.SaveChangesAsync();
|
|
});
|
|
|
|
await FireEventAsync(type, pe);
|
|
await FireEventAsync(type, windows);
|
|
Assert.Equal([windows], await JobsOfAsync(scriptId));
|
|
|
|
// Out of Windows PE (the installed OS reports in), the device gets its once-per-device run.
|
|
await SetCaptionAsync(pe, Win11);
|
|
await FireEventAsync(type, pe);
|
|
Assert.Equal(new[] { windows, pe }.Order(), (await JobsOfAsync(scriptId)).Order());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AnEventTriggerOnAllDevicesSkipsAnExcludedDevice()
|
|
{
|
|
var scriptId = await fixture.SeedScriptAsync("exclude-event-all");
|
|
var excluded = await SeedDeviceAsync("EVENT-ALL-OUT", Win11);
|
|
var included = await SeedDeviceAsync("EVENT-ALL-IN", Win11);
|
|
await fixture.WithDbAsync(async db =>
|
|
{
|
|
var trigger = new ScriptTriggerEntity
|
|
{
|
|
Id = Guid.NewGuid(), ScriptId = scriptId, CreatedUtc = DateTimeOffset.UtcNow,
|
|
}.With(ScriptTriggerType.OnAgentReady);
|
|
trigger.SetTargets(true, [], []);
|
|
trigger.SetExcludes([excluded], []);
|
|
db.ScriptTriggers.Add(trigger);
|
|
await db.SaveChangesAsync();
|
|
});
|
|
|
|
await FireEventAsync(ScriptTriggerType.OnAgentReady, excluded);
|
|
await FireEventAsync(ScriptTriggerType.OnAgentReady, included);
|
|
|
|
Assert.Equal([included], await JobsOfAsync(scriptId));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task RunNowRunsOnItsTargetsMinusItsExclusions()
|
|
{
|
|
using var client = await fixture.SignedInAsync("exclude-admin");
|
|
var scriptId = await fixture.SeedScriptAsync("exclude-run-now");
|
|
var pe = await SeedDeviceAsync("RUN-PE", DefaultSeeder.WinPeCaption);
|
|
var windows = await SeedDeviceAsync("RUN-WIN", Win11);
|
|
var listed = await SeedDeviceAsync("RUN-LISTED", Win11);
|
|
|
|
var response = await client.PostAsJsonAsync(ApiRoutes.Jobs, new CreateJobRequest(
|
|
null, scriptId, GroupIds: [await GroupIdAsync("Windows")], ClientIds: [listed],
|
|
ExcludeGroupIds: [await GroupIdAsync("Windows PE")], ExcludeClientIds: [listed]), JsonDefaults.Options);
|
|
response.EnsureSuccessStatusCode();
|
|
var run = (await response.Content.ReadFromJsonAsync<GroupRunDto>(JsonDefaults.Options))!;
|
|
|
|
var targeted = run.Jobs.Select(j => j.ClientId).ToList();
|
|
Assert.Contains(windows, targeted);
|
|
Assert.DoesNotContain(pe, targeted);
|
|
Assert.DoesNotContain(listed, targeted); // excluding wins over listing it
|
|
}
|
|
|
|
[Fact]
|
|
public async Task RunNowRefusesAnExcludedGroupThatDoesNotExist()
|
|
{
|
|
using var client = await fixture.SignedInAsync("exclude-admin");
|
|
var scriptId = await fixture.SeedScriptAsync("exclude-run-missing");
|
|
var device = await SeedDeviceAsync("RUN-MISSING", Win11);
|
|
|
|
var response = await client.PostAsJsonAsync(ApiRoutes.Jobs, new CreateJobRequest(
|
|
null, scriptId, ClientIds: [device], ExcludeGroupIds: [Guid.NewGuid()]), JsonDefaults.Options);
|
|
|
|
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task TheTargetCapCountsIncludedAndExcludedEntries()
|
|
{
|
|
using var client = await fixture.SignedInAsync("exclude-admin");
|
|
var scriptId = await fixture.SeedScriptAsync("exclude-cap");
|
|
var half = Backend.Groups.TriggerEndpoints.MaxTargets / 2;
|
|
List<Guid> Groups(int count) => Enumerable.Range(0, count).Select(_ => Guid.NewGuid()).ToList();
|
|
|
|
var over = await client.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, GroupIds: Groups(half), CronExpression: "0 1 * * *",
|
|
ExcludeGroupIds: Groups(half + 1)), JsonDefaults.Options);
|
|
var excludesAlone = await client.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, AllDevices: true, CronExpression: "0 1 * * *",
|
|
ExcludeGroupIds: Groups(Backend.Groups.TriggerEndpoints.MaxTargets + 1)), JsonDefaults.Options);
|
|
// At the cap the request passes the count and fails on the unknown groups instead.
|
|
var atCap = await client.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, GroupIds: Groups(half), CronExpression: "0 1 * * *",
|
|
ExcludeGroupIds: Groups(half)), JsonDefaults.Options);
|
|
|
|
Assert.Equal(HttpStatusCode.BadRequest, over.StatusCode);
|
|
Assert.Contains("at most", await over.Content.ReadAsStringAsync());
|
|
Assert.Equal(HttpStatusCode.BadRequest, excludesAlone.StatusCode);
|
|
Assert.Equal(HttpStatusCode.NotFound, atCap.StatusCode);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ExclusionsAloneAreNotATargetAndUnknownExclusionsAreRefused()
|
|
{
|
|
using var client = await fixture.SignedInAsync("exclude-admin");
|
|
var scriptId = await fixture.SeedScriptAsync("exclude-only");
|
|
var device = await SeedDeviceAsync("EXCLUDE-ONLY", Win11);
|
|
|
|
var excludesOnly = await client.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, CronExpression: "0 1 * * *", ExcludeClientIds: [device]), JsonDefaults.Options);
|
|
var unknownGroup = await client.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, AllDevices: true, CronExpression: "0 1 * * *",
|
|
ExcludeGroupIds: [Guid.NewGuid()]), JsonDefaults.Options);
|
|
var unknownDevice = await client.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, AllDevices: true, CronExpression: "0 1 * * *",
|
|
ExcludeClientIds: ["client-nobody-0002"]), JsonDefaults.Options);
|
|
|
|
Assert.Equal(HttpStatusCode.BadRequest, excludesOnly.StatusCode);
|
|
Assert.Equal(HttpStatusCode.NotFound, unknownGroup.StatusCode);
|
|
Assert.Equal(HttpStatusCode.NotFound, unknownDevice.StatusCode);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task DeletingAnExcludedGroupTakesItOutOfTheExclusions()
|
|
{
|
|
using var client = await fixture.SignedInAsync("exclude-admin");
|
|
var scriptId = await fixture.SeedScriptAsync("exclude-deleted-group");
|
|
var doomed = await fixture.WithDbAsync(async db =>
|
|
{
|
|
var group = new DeviceGroupEntity
|
|
{
|
|
Id = Guid.NewGuid(), Name = $"exclude-doomed-{Guid.NewGuid():N}", Kind = GroupKind.Static,
|
|
CreatedUtc = DateTimeOffset.UtcNow, UpdatedUtc = DateTimeOffset.UtcNow,
|
|
};
|
|
db.DeviceGroups.Add(group);
|
|
await db.SaveChangesAsync();
|
|
return group.Id;
|
|
});
|
|
var id = await CreateAsync(client, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, AllDevices: true, CronExpression: "0 1 * * *", ExcludeGroupIds: [doomed]));
|
|
|
|
(await client.DeleteAsync(ApiRoutes.For.Group(doomed))).EnsureSuccessStatusCode();
|
|
|
|
var trigger = (await ListAsync(client)).Single(t => t.Id == id);
|
|
Assert.Empty(trigger.Excludes!);
|
|
Assert.True(trigger.Enabled);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ATriggerWithoutExclusionsKeepsWorking()
|
|
{
|
|
using var client = await fixture.SignedInAsync("exclude-admin");
|
|
var scriptId = await fixture.SeedScriptAsync("exclude-none");
|
|
var device = await SeedDeviceAsync("NO-EXCLUDE", DefaultSeeder.WinPeCaption);
|
|
var id = await fixture.WithDbAsync(async db =>
|
|
{
|
|
// As a row saved before exclusions existed: both columns null.
|
|
var trigger = new ScriptTriggerEntity
|
|
{
|
|
Id = Guid.NewGuid(), ScriptId = scriptId, CreatedUtc = DateTimeOffset.UtcNow,
|
|
}.With(ScriptTriggerType.Scheduled, cron: "0 1 * * *", nextRun: DateTimeOffset.UtcNow.AddHours(1));
|
|
trigger.SetTargets(false, [device], []);
|
|
db.ScriptTriggers.Add(trigger);
|
|
await db.SaveChangesAsync();
|
|
return trigger.Id;
|
|
});
|
|
|
|
var listed = (await ListAsync(client)).Single(t => t.Id == id);
|
|
Assert.Empty(listed.Excludes!);
|
|
Assert.Equal([device], await RunNowAsync(client, id));
|
|
}
|
|
|
|
private async Task<List<string>> RunNowAsync(HttpClient client, Guid triggerId)
|
|
{
|
|
var response = await client.PostAsync(ApiRoutes.For.TriggerRun(triggerId), null);
|
|
response.EnsureSuccessStatusCode();
|
|
var run = (await response.Content.ReadFromJsonAsync<TriggerRunResultDto>(JsonDefaults.Options))!;
|
|
return await fixture.WithDbAsync(async db => await db.Jobs.Where(j => j.RunId == run.RunId)
|
|
.Select(j => j.ClientId).ToListAsync());
|
|
}
|
|
|
|
private async Task FireEventAsync(ScriptTriggerType type, string clientId)
|
|
{
|
|
using var scope = fixture.Services.CreateScope();
|
|
await scope.ServiceProvider.GetRequiredService<ScriptTriggerService>().FireAsync(type, clientId, CancellationToken.None);
|
|
}
|
|
|
|
private Task<List<string>> JobsOfAsync(Guid scriptId)
|
|
=> fixture.WithDbAsync(db => db.Jobs.Where(j => j.ScriptId == scriptId).Select(j => j.ClientId).ToListAsync());
|
|
|
|
private Task<Guid> GroupIdAsync(string name)
|
|
=> fixture.WithDbAsync(db => db.DeviceGroups.Where(g => g.Name == name).Select(g => g.Id).SingleAsync());
|
|
|
|
private async Task<Dictionary<string, IReadOnlyList<string>>> MembersByNameAsync(params string[] names)
|
|
{
|
|
using var scope = fixture.Services.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
|
var groups = scope.ServiceProvider.GetRequiredService<DeviceGroupService>();
|
|
var result = new Dictionary<string, IReadOnlyList<string>>();
|
|
foreach (var name in names)
|
|
{
|
|
result[name] = await groups.GetMembersAsync(await db.DeviceGroups.AsNoTracking().SingleAsync(g => g.Name == name), CancellationToken.None);
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
private Task SetCaptionAsync(string clientId, string caption)
|
|
=> fixture.WithDbAsync(async db =>
|
|
{
|
|
(await db.Devices.SingleAsync(d => d.ClientId == clientId)).OsCaption = caption;
|
|
await db.SaveChangesAsync();
|
|
});
|
|
|
|
private Task<string> SeedDeviceAsync(string hostname, string osCaption)
|
|
=> fixture.WithDbAsync(async db =>
|
|
{
|
|
var clientId = $"client-{Guid.NewGuid():N}"[..20];
|
|
db.Devices.Add(new DeviceEntity
|
|
{
|
|
ClientId = clientId,
|
|
Hostname = hostname,
|
|
OsCaption = osCaption,
|
|
NkeyPublic = $"U{Guid.NewGuid():N}",
|
|
EnrolledUtc = DateTimeOffset.UtcNow,
|
|
});
|
|
await db.SaveChangesAsync();
|
|
return clientId;
|
|
});
|
|
|
|
private static async Task<Guid> CreateAsync(HttpClient client, SaveScriptTriggerRequest request)
|
|
{
|
|
var response = await client.PostAsJsonAsync(ApiRoutes.Triggers, request, JsonDefaults.Options);
|
|
response.EnsureSuccessStatusCode();
|
|
return (await response.Content.ReadFromJsonAsync<Dictionary<string, Guid>>(JsonDefaults.Options))!["id"];
|
|
}
|
|
|
|
private static async Task<List<ScriptTriggerDto>> ListAsync(HttpClient client)
|
|
=> (await client.GetFromJsonAsync<List<ScriptTriggerDto>>(ApiRoutes.Triggers, JsonDefaults.Options))!;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The Windows PE group reaching installs that predate it, and the migration
|
|
/// leaving existing triggers with no exclusions.
|
|
/// </summary>
|
|
public class WindowsPeUpgradeTests
|
|
{
|
|
[Fact]
|
|
public async Task AnOlderInstallGetsWindowsPeOnceAndAnUntouchedWorkstationsRule()
|
|
{
|
|
await using var db = await FreshDatabaseAsync();
|
|
var now = DateTimeOffset.UtcNow;
|
|
var legacy = JsonDefaults.Serialize(DefaultSeeder.LegacyWorkstationRules());
|
|
db.DeviceGroups.Add(new DeviceGroupEntity
|
|
{
|
|
Id = Guid.NewGuid(), Name = "Windows Workstations", Kind = GroupKind.Dynamic, RulesJson = legacy,
|
|
CreatedUtc = now, UpdatedUtc = now,
|
|
});
|
|
await db.SaveChangesAsync();
|
|
|
|
// An existing install: groups already there, no Windows PE marker yet.
|
|
await DefaultSeeder.SeedAsync(db, CancellationToken.None);
|
|
|
|
var pe = await db.DeviceGroups.SingleAsync(g => g.Name == DefaultSeeder.WindowsPeGroupName);
|
|
Assert.Equal(GroupKind.Dynamic, pe.Kind);
|
|
var workstations = await db.DeviceGroups.AsNoTracking().SingleAsync(g => g.Name == "Windows Workstations");
|
|
Assert.NotEqual(legacy, workstations.RulesJson);
|
|
Assert.Contains(DefaultSeeder.WinPeCaption, workstations.RulesJson);
|
|
|
|
// Deleted on purpose, it stays deleted.
|
|
db.DeviceGroups.Remove(pe);
|
|
await db.SaveChangesAsync();
|
|
await DefaultSeeder.SeedAsync(db, CancellationToken.None);
|
|
Assert.False(await db.DeviceGroups.AnyAsync(g => g.Name == DefaultSeeder.WindowsPeGroupName));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AnEditedWorkstationsRuleAndATakenNameAreLeftAlone()
|
|
{
|
|
await using var db = await FreshDatabaseAsync();
|
|
var now = DateTimeOffset.UtcNow;
|
|
var edited = JsonDefaults.Serialize(new GroupRuleSet(RuleCombine.And,
|
|
[new RuleGroup(RuleCombine.And, [new RuleCondition("os.platform", RuleOperator.Equals, "windows")])]));
|
|
var mine = Guid.NewGuid();
|
|
db.DeviceGroups.AddRange(
|
|
new DeviceGroupEntity
|
|
{
|
|
Id = Guid.NewGuid(), Name = "Windows Workstations", Kind = GroupKind.Dynamic, RulesJson = edited,
|
|
CreatedUtc = now, UpdatedUtc = now,
|
|
},
|
|
new DeviceGroupEntity { Id = mine, Name = "windows pe", Kind = GroupKind.Static, CreatedUtc = now, UpdatedUtc = now });
|
|
await db.SaveChangesAsync();
|
|
|
|
await DefaultSeeder.SeedAsync(db, CancellationToken.None);
|
|
|
|
Assert.Equal(edited, (await db.DeviceGroups.AsNoTracking().SingleAsync(g => g.Name == "Windows Workstations")).RulesJson);
|
|
Assert.Equal(mine, (await db.DeviceGroups.AsNoTracking().SingleAsync(g => g.Name.ToLower() == "windows pe")).Id);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ANewInstallSeedsWindowsPeWithThePlatformGroups()
|
|
{
|
|
await using var db = await FreshDatabaseAsync();
|
|
|
|
await DefaultSeeder.SeedAsync(db, CancellationToken.None);
|
|
|
|
var names = await db.DeviceGroups.Select(g => g.Name).ToListAsync();
|
|
Assert.Contains(DefaultSeeder.WindowsPeGroupName, names);
|
|
Assert.Contains("Windows Workstations", names);
|
|
Assert.Equal(names.Count, names.Distinct().Count());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ATriggerSavedBeforeTheMigrationHasNoExclusionsAfterIt()
|
|
{
|
|
var path = Path.Combine(Path.GetTempPath(), $"exclude-migration-{Guid.NewGuid():N}.db");
|
|
try
|
|
{
|
|
await using var db = Open(path);
|
|
var migrator = db.GetService<IMigrator>();
|
|
var migrations = db.Database.GetMigrations().ToList();
|
|
var target = migrations.Single(m => m.EndsWith("_TargetExclusions", StringComparison.Ordinal));
|
|
await migrator.MigrateAsync(migrations[migrations.IndexOf(target) - 1]);
|
|
|
|
var id = Guid.NewGuid();
|
|
var device = "client-premigration1";
|
|
await db.Database.ExecuteSqlRawAsync(
|
|
"INSERT INTO ScriptTriggers (Id, ScriptId, ClientIdsJson, AllDevices, TriggerType, Enabled, OncePerDevice, " +
|
|
"TimeZoneId, StaggerSeconds, StaggerBatchSize, ConcurrencyStamp, CreatedUtc) " +
|
|
"VALUES ({0}, {1}, {2}, 0, 'Scheduled', 1, 1, 'UTC', 0, 1, {3}, {4})",
|
|
id.ToString().ToUpperInvariant(), Guid.NewGuid().ToString().ToUpperInvariant(),
|
|
JsonDefaults.Serialize(new[] { device }), Guid.NewGuid().ToString().ToUpperInvariant(), DateTimeOffset.UtcNow.UtcTicks);
|
|
|
|
await migrator.MigrateAsync();
|
|
|
|
var trigger = await db.ScriptTriggers.AsNoTracking().SingleAsync(t => t.Id == id);
|
|
Assert.Null(trigger.ExcludeClientIdsJson);
|
|
Assert.Null(trigger.ExcludeGroupIdsJson);
|
|
Assert.Empty(trigger.GetExcludeClientIds());
|
|
Assert.Empty(trigger.GetExcludeGroupIds());
|
|
Assert.Equal([device], trigger.GetClientIds());
|
|
}
|
|
finally
|
|
{
|
|
SqliteConnection.ClearAllPools();
|
|
File.Delete(path);
|
|
}
|
|
}
|
|
|
|
private static SqliteAppDbContext Open(string path)
|
|
=> new(new DbContextOptionsBuilder<SqliteAppDbContext>().UseSqlite($"Data Source={path}").Options);
|
|
|
|
/// <summary>An in-memory SQLite database at the current schema; disposed with the context.</summary>
|
|
private static async Task<SqliteAppDbContext> FreshDatabaseAsync()
|
|
{
|
|
var connection = new SqliteConnection("Data Source=:memory:");
|
|
await connection.OpenAsync();
|
|
var db = new SqliteAppDbContext(new DbContextOptionsBuilder<SqliteAppDbContext>().UseSqlite(connection).Options);
|
|
await db.Database.EnsureCreatedAsync();
|
|
return db;
|
|
}
|
|
}
|