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>
325 lines
16 KiB
C#
325 lines
16 KiB
C#
using Microsoft.Extensions.DependencyInjection;
|
|
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Shared.Contracts.Api;
|
|
using Shared.Contracts.Models;
|
|
using Shared.Contracts.Serialization;
|
|
using Xunit;
|
|
|
|
namespace Backend.Tests;
|
|
|
|
public class TriggerEndpointTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
|
|
{
|
|
[Fact]
|
|
public async Task OneShotInThePastIsRefused()
|
|
{
|
|
using var client = await fixture.SignedInAsync("trigger-admin");
|
|
var scriptId = await fixture.SeedScriptAsync("past-one-shot");
|
|
|
|
var response = await client.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, AllDevices: true, RunOnceUtc: DateTimeOffset.UtcNow.AddHours(-2)),
|
|
JsonDefaults.Options);
|
|
|
|
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
|
Assert.Contains("in the past", await response.Content.ReadAsStringAsync());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task UnknownTimeZoneIsReportedAsATimeZoneError()
|
|
{
|
|
using var client = await fixture.SignedInAsync("trigger-admin");
|
|
var scriptId = await fixture.SeedScriptAsync("bad-zone");
|
|
|
|
var response = await client.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, AllDevices: true, CronExpression: "0 1 * * *", TimeZoneId: "Not/AZone"),
|
|
JsonDefaults.Options);
|
|
|
|
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
|
Assert.Contains("time zone", await response.Content.ReadAsStringAsync());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task EditingChangesTheCadenceAndName()
|
|
{
|
|
using var client = await fixture.SignedInAsync("trigger-admin");
|
|
var scriptId = await fixture.SeedScriptAsync("editable");
|
|
var id = await CreateAsync(client, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, AllDevices: true, CronExpression: "0 1 * * *"));
|
|
|
|
var update = await client.PutAsJsonAsync(ApiRoutes.For.Trigger(id), new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, AllDevices: true, CronExpression: "*/10 * * * *", Name: " Every ten "),
|
|
JsonDefaults.Options);
|
|
Assert.Equal(HttpStatusCode.NoContent, update.StatusCode);
|
|
|
|
var trigger = (await ListAsync(client)).Single(t => t.Id == id);
|
|
Assert.Equal("Every ten", trigger.Name);
|
|
Assert.Equal("*/10 * * * *", trigger.CronExpression);
|
|
Assert.True(trigger.NextRunUtc <= DateTimeOffset.UtcNow.AddMinutes(10));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task RunNowQueuesOneExecutionAndKeepsTheCadence()
|
|
{
|
|
using var client = await fixture.SignedInAsync("trigger-admin");
|
|
var scriptId = await fixture.SeedScriptAsync("run-now");
|
|
var clientId = await fixture.SeedDeviceAsync("RUN-NOW-HOST");
|
|
var id = await CreateAsync(client, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, ClientIds: [clientId], CronExpression: "0 3 * * *"));
|
|
var before = (await ListAsync(client)).Single(t => t.Id == id).NextRunUtc;
|
|
|
|
var response = await client.PostAsync(ApiRoutes.For.TriggerRun(id), null);
|
|
response.EnsureSuccessStatusCode();
|
|
var result = await response.Content.ReadFromJsonAsync<TriggerRunResultDto>(JsonDefaults.Options);
|
|
|
|
Assert.Equal(1, result!.Queued);
|
|
Assert.NotNull(result.RunId);
|
|
var after = (await ListAsync(client)).Single(t => t.Id == id);
|
|
Assert.Equal(before, after.NextRunUtc);
|
|
Assert.Equal(result.RunId, after.LastRunId);
|
|
Assert.True(after.Enabled);
|
|
Assert.Equal(1, await fixture.WithDbAsync(db => db.Jobs.CountAsync(j => j.RunId == result.RunId)));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task PreviewListsUpcomingRunsOrTheError()
|
|
{
|
|
using var client = await fixture.SignedInAsync("trigger-admin");
|
|
|
|
var ok = await (await client.PostAsJsonAsync(ApiRoutes.TriggerPreview,
|
|
new SchedulePreviewRequest("*/15 * * * *", "UTC", 3), JsonDefaults.Options))
|
|
.Content.ReadFromJsonAsync<SchedulePreviewDto>(JsonDefaults.Options);
|
|
Assert.Null(ok!.Error);
|
|
Assert.Equal(3, ok.Occurrences.Count);
|
|
|
|
var bad = await (await client.PostAsJsonAsync(ApiRoutes.TriggerPreview,
|
|
new SchedulePreviewRequest("nope", "UTC"), JsonDefaults.Options))
|
|
.Content.ReadFromJsonAsync<SchedulePreviewDto>(JsonDefaults.Options);
|
|
Assert.NotNull(bad!.Error);
|
|
Assert.Empty(bad.Occurrences);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ScopedRoleCannotScheduleAgainstAllDevices()
|
|
{
|
|
using var client = await fixture.ScopedSignedInAsync("scoped-scheduler");
|
|
var scriptId = await fixture.SeedScriptAsync("scoped-script");
|
|
|
|
var response = await client.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, AllDevices: true, CronExpression: "0 1 * * *"), JsonDefaults.Options);
|
|
|
|
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ScopedRoleCannotEnableEditOrDeleteATriggerOutsideItsScope()
|
|
{
|
|
using var admin = await fixture.SignedInAsync("trigger-admin");
|
|
var scriptId = await fixture.SeedScriptAsync("fleet-wide");
|
|
var id = await CreateAsync(admin, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, AllDevices: true, CronExpression: "0 2 * * *", Enabled: false));
|
|
|
|
using var scoped = await fixture.ScopedSignedInAsync("scoped-editor");
|
|
var inScope = await fixture.SeedDeviceAsync("SCOPED-OWN");
|
|
|
|
var enable = await scoped.PatchAsJsonAsync(ApiRoutes.For.Trigger(id), new SetTriggerEnabledRequest(true), JsonDefaults.Options);
|
|
var retarget = await scoped.PutAsJsonAsync(ApiRoutes.For.Trigger(id), new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, ClientIds: [inScope], CronExpression: "0 2 * * *"), JsonDefaults.Options);
|
|
var delete = await scoped.DeleteAsync(ApiRoutes.For.Trigger(id));
|
|
|
|
Assert.Equal(HttpStatusCode.Forbidden, enable.StatusCode);
|
|
Assert.Equal(HttpStatusCode.Forbidden, retarget.StatusCode);
|
|
Assert.Equal(HttpStatusCode.Forbidden, delete.StatusCode);
|
|
Assert.False((await ListAsync(admin)).Single(t => t.Id == id).Enabled);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task APassedOneShotCannotBeReEnabled()
|
|
{
|
|
using var client = await fixture.SignedInAsync("trigger-admin");
|
|
var scriptId = await fixture.SeedScriptAsync("stale-one-shot");
|
|
var id = await CreateAsync(client, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, AllDevices: true, RunOnceUtc: DateTimeOffset.UtcNow.AddHours(1), Enabled: false));
|
|
await fixture.WithDbAsync(async db =>
|
|
{
|
|
var trigger = await db.ScheduleTriggers.SingleAsync(t => t.ScheduleId == id);
|
|
trigger.RunOnceUtc = DateTimeOffset.UtcNow.AddDays(-2);
|
|
trigger.NextRunUtc = trigger.RunOnceUtc;
|
|
await db.SaveChangesAsync();
|
|
});
|
|
|
|
var enable = await client.PatchAsJsonAsync(ApiRoutes.For.Trigger(id), new SetTriggerEnabledRequest(true), JsonDefaults.Options);
|
|
|
|
Assert.Equal(HttpStatusCode.BadRequest, enable.StatusCode);
|
|
Assert.False((await ListAsync(client)).Single(t => t.Id == id).Enabled);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ATimeZoneLeftOutIsUtc()
|
|
{
|
|
using var client = await fixture.SignedInAsync("trigger-admin");
|
|
var scriptId = await fixture.SeedScriptAsync("utc-default");
|
|
|
|
var id = await CreateAsync(client, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, AllDevices: true, CronExpression: "0 1 * * *"));
|
|
|
|
var trigger = (await ListAsync(client)).Single(t => t.Id == id);
|
|
Assert.Equal("UTC", trigger.TimeZoneId);
|
|
Assert.Equal(1, trigger.NextRunUtc!.Value.ToUniversalTime().Hour);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AScheduleNeedsAtLeastOneTargetAndAllDevicesStandsAlone()
|
|
{
|
|
using var client = await fixture.SignedInAsync("trigger-admin");
|
|
var scriptId = await fixture.SeedScriptAsync("no-target");
|
|
var device = await fixture.SeedDeviceAsync("NO-TARGET-HOST");
|
|
|
|
var none = await client.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, CronExpression: "0 1 * * *"), JsonDefaults.Options);
|
|
var emptyLists = await client.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, ClientIds: [], GroupIds: [], CronExpression: "0 1 * * *"), JsonDefaults.Options);
|
|
var mixed = await client.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, ClientIds: [device], AllDevices: true, CronExpression: "0 1 * * *"),
|
|
JsonDefaults.Options);
|
|
|
|
Assert.Equal(HttpStatusCode.BadRequest, none.StatusCode);
|
|
Assert.Contains("at least one", await none.Content.ReadAsStringAsync());
|
|
Assert.Equal(HttpStatusCode.BadRequest, emptyLists.StatusCode);
|
|
Assert.Equal(HttpStatusCode.BadRequest, mixed.StatusCode);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task TooManyTargetsAreRefusedBeforeAnyLookup()
|
|
{
|
|
using var client = await fixture.SignedInAsync("trigger-admin");
|
|
var scriptId = await fixture.SeedScriptAsync("too-many-targets");
|
|
var groups = Enumerable.Range(0, Backend.Groups.TriggerEndpoints.MaxTargets + 1).Select(_ => Guid.NewGuid()).ToList();
|
|
|
|
var response = await client.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, GroupIds: groups, CronExpression: "0 1 * * *"), JsonDefaults.Options);
|
|
|
|
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
|
Assert.Contains("at most", await response.Content.ReadAsStringAsync());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task SeveralDevicesAndGroupsAreKeptDeduplicatedAndNamed()
|
|
{
|
|
using var client = await fixture.SignedInAsync("trigger-admin");
|
|
var scriptId = await fixture.SeedScriptAsync("many-targets");
|
|
var first = await fixture.SeedDeviceAsync("MANY-ONE");
|
|
var second = await fixture.SeedDeviceAsync("MANY-TWO");
|
|
var group = await SeedGroupAsync("Many Group", first);
|
|
|
|
var id = await CreateAsync(client, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, ClientIds: [first, second, first], GroupIds: [group, group],
|
|
CronExpression: "0 1 * * *"));
|
|
|
|
var trigger = (await ListAsync(client)).Single(t => t.Id == id);
|
|
Assert.False(trigger.AllDevices);
|
|
Assert.Equal(
|
|
new (TriggerTargetKind, string, string)[]
|
|
{
|
|
(TriggerTargetKind.Group, group.ToString("D"), "Many Group"),
|
|
(TriggerTargetKind.Device, first, "MANY-ONE"),
|
|
(TriggerTargetKind.Device, second, "MANY-TWO"),
|
|
},
|
|
trigger.Targets.Select(t => (t.Kind, t.Id, t.Name)).ToArray());
|
|
Assert.All(trigger.Targets, t => Assert.False(t.Missing));
|
|
|
|
// Run Now reaches each device once.
|
|
var run = await (await client.PostAsync(ApiRoutes.For.TriggerRun(id), null))
|
|
.Content.ReadFromJsonAsync<TriggerRunResultDto>(JsonDefaults.Options);
|
|
Assert.Equal(2, run!.Queued);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AnUnknownTargetIsRefusedOnSave()
|
|
{
|
|
using var client = await fixture.SignedInAsync("trigger-admin");
|
|
var scriptId = await fixture.SeedScriptAsync("unknown-target");
|
|
var device = await fixture.SeedDeviceAsync("KNOWN-HOST");
|
|
|
|
var group = await client.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, ClientIds: [device], GroupIds: [Guid.NewGuid()], CronExpression: "0 1 * * *"),
|
|
JsonDefaults.Options);
|
|
var unknownDevice = await client.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, ClientIds: [device, "client-nobody-0001"], CronExpression: "0 1 * * *"),
|
|
JsonDefaults.Options);
|
|
|
|
Assert.Equal(HttpStatusCode.NotFound, group.StatusCode);
|
|
Assert.Equal(HttpStatusCode.NotFound, unknownDevice.StatusCode);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AScopedRoleMayAimAtSeveralTargetsOnlyWhenEveryOneIsInScope()
|
|
{
|
|
var mine = await fixture.SeedDeviceAsync("SCOPE-MINE");
|
|
var alsoMine = await fixture.SeedDeviceAsync("SCOPE-ALSO-MINE");
|
|
var theirs = await fixture.SeedDeviceAsync("SCOPE-THEIRS");
|
|
var insideGroup = await SeedGroupAsync("Scope Inside", mine);
|
|
var straddling = await SeedGroupAsync("Scope Straddling", alsoMine, theirs);
|
|
var scriptId = await fixture.SeedScriptAsync("scoped-multi");
|
|
using var scoped = await fixture.ScopedSignedInAsync("scoped-multi", mine, alsoMine);
|
|
|
|
var inside = await scoped.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, ClientIds: [mine, alsoMine], GroupIds: [insideGroup],
|
|
CronExpression: "0 1 * * *"), JsonDefaults.Options);
|
|
var oneDeviceOutside = await scoped.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, ClientIds: [mine, theirs], CronExpression: "0 1 * * *"), JsonDefaults.Options);
|
|
var oneGroupOutside = await scoped.PostAsJsonAsync(ApiRoutes.Triggers, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, ClientIds: [mine], GroupIds: [insideGroup, straddling],
|
|
CronExpression: "0 1 * * *"), JsonDefaults.Options);
|
|
|
|
Assert.Equal(HttpStatusCode.Created, inside.StatusCode);
|
|
Assert.Equal(HttpStatusCode.NotFound, oneDeviceOutside.StatusCode);
|
|
Assert.Equal(HttpStatusCode.Forbidden, oneGroupOutside.StatusCode);
|
|
Assert.Contains("Scope Straddling", await oneGroupOutside.Content.ReadAsStringAsync());
|
|
|
|
// A schedule an admin aimed partly outside the scope is not the scoped role's to run or change.
|
|
using var admin = await fixture.SignedInAsync("trigger-admin");
|
|
var adminId = await CreateAsync(admin, new SaveScriptTriggerRequest(
|
|
scriptId, ScriptTriggerType.Scheduled, ClientIds: [mine, theirs], CronExpression: "0 1 * * *"));
|
|
var run = await scoped.PostAsync(ApiRoutes.For.TriggerRun(adminId), null);
|
|
var disable = await scoped.PatchAsJsonAsync(
|
|
ApiRoutes.For.Trigger(adminId), new SetTriggerEnabledRequest(false), JsonDefaults.Options);
|
|
Assert.Equal(HttpStatusCode.NotFound, run.StatusCode);
|
|
Assert.Equal(HttpStatusCode.NotFound, disable.StatusCode);
|
|
|
|
// Its own schedule runs on its devices.
|
|
var ownId = (await inside.Content.ReadFromJsonAsync<Dictionary<string, Guid>>(JsonDefaults.Options))!["id"];
|
|
var fired = await (await scoped.PostAsync(ApiRoutes.For.TriggerRun(ownId), null))
|
|
.Content.ReadFromJsonAsync<TriggerRunResultDto>(JsonDefaults.Options);
|
|
Assert.Equal(2, fired!.Queued);
|
|
}
|
|
|
|
private Task<Guid> SeedGroupAsync(string name, params string[] members)
|
|
=> fixture.WithDbAsync(async db =>
|
|
{
|
|
var group = new Backend.Data.DeviceGroupEntity
|
|
{
|
|
Id = Guid.NewGuid(), Name = name, Kind = GroupKind.Static,
|
|
CreatedUtc = DateTimeOffset.UtcNow, UpdatedUtc = DateTimeOffset.UtcNow,
|
|
};
|
|
db.DeviceGroups.Add(group);
|
|
db.DeviceGroupMembers.AddRange(members.Select(m => new Backend.Data.DeviceGroupMemberEntity
|
|
{
|
|
GroupId = group.Id, ClientId = m, AddedUtc = DateTimeOffset.UtcNow,
|
|
}));
|
|
await db.SaveChangesAsync();
|
|
return group.Id;
|
|
});
|
|
|
|
private static async Task<Guid> CreateAsync(HttpClient client, SaveScriptTriggerRequest request)
|
|
{
|
|
var response = await client.PostAsJsonAsync(ApiRoutes.Triggers, request, JsonDefaults.Options);
|
|
response.EnsureSuccessStatusCode();
|
|
var body = await response.Content.ReadFromJsonAsync<Dictionary<string, Guid>>(JsonDefaults.Options);
|
|
return body!["id"];
|
|
}
|
|
|
|
private static async Task<List<ScriptTriggerDto>> ListAsync(HttpClient client)
|
|
=> (await client.GetFromJsonAsync<List<ScriptTriggerDto>>(ApiRoutes.Triggers, JsonDefaults.Options))!;
|
|
}
|