21e9bad12f
- Every script gets built-ins: Set-ExecuteRGroupMembership (member when the value is true, above 0, a non-empty collection or yes-like text; pipe results in), Add-/Remove-ExecuteRGroupMembership, and executer_group in Bash. They need no credentials: the agent takes their lines out of the output and sends the answers with the job's final state. - The server adds or removes the device in that script group, creating it (top level, kind Script) the first time a device joins. Each run decides again. - Only script groups change: a curated group by that name is ignored, so a device can never add itself to one. Last answer per group wins; 25 a job. - Console: Script kind in the group editor, tree and lists (reported devices, no hand-listing), editor completions and snippets for the built-ins. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
138 lines
6.0 KiB
C#
138 lines
6.0 KiB
C#
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using Backend.Data;
|
|
using Backend.Messaging;
|
|
using Microsoft.Extensions.Hosting;
|
|
using Shared.Contracts.Messages;
|
|
using Shared.Infrastructure.Nats;
|
|
using Backend.Groups;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Shared.Contracts.Api;
|
|
using Shared.Contracts.Models;
|
|
using Shared.Contracts.Serialization;
|
|
using Xunit;
|
|
|
|
namespace Backend.Tests;
|
|
|
|
/// <summary>Script groups: a device's job reports which of them it belongs in.</summary>
|
|
public class ScriptGroupTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
|
|
{
|
|
private static GroupMembershipReport R(string group, bool member) => new(group, member);
|
|
|
|
private async Task<ScriptGroupMembership.Outcome> ReportAsync(string clientId, params GroupMembershipReport[] reports)
|
|
{
|
|
using var scope = fixture.Services.CreateScope();
|
|
return await scope.ServiceProvider.GetRequiredService<ScriptGroupMembership>()
|
|
.ApplyAsync(clientId, "Inventory Check", reports, CancellationToken.None);
|
|
}
|
|
|
|
private async Task<IReadOnlyList<string>> MembersAsync(string groupName)
|
|
{
|
|
using var scope = fixture.Services.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
|
var group = await db.DeviceGroups.AsNoTracking().SingleAsync(g => g.Name == groupName);
|
|
return await scope.ServiceProvider.GetRequiredService<DeviceGroupService>().GetMembersAsync(group, CancellationToken.None);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task TheFirstMemberCreatesTheGroupAndLaterRunsFollowTheDevice()
|
|
{
|
|
var a = await fixture.SeedDeviceAsync("SG-A");
|
|
var b = await fixture.SeedDeviceAsync("SG-B");
|
|
|
|
var first = await ReportAsync(a, R("Has Java", true));
|
|
Assert.Equal(["Has Java"], first.Created);
|
|
await ReportAsync(b, R("has java", true));
|
|
Assert.Equal(new[] { a, b }.Order(), (await MembersAsync("Has Java")).Order());
|
|
|
|
var group = await fixture.WithDbAsync(db => db.DeviceGroups.AsNoTracking().SingleAsync(g => g.Name == "Has Java"));
|
|
Assert.Equal(GroupKind.Script, group.Kind);
|
|
|
|
// The next run says otherwise: the device leaves; the group stays.
|
|
var left = await ReportAsync(a, R("Has Java", false));
|
|
Assert.Equal(["Has Java"], left.Left);
|
|
Assert.Equal([b], await MembersAsync("Has Java"));
|
|
|
|
// Saying it again changes nothing.
|
|
Assert.False((await ReportAsync(b, R("Has Java", true))).Changed);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task NotBeingAMemberOfAGroupThatDoesNotExistCreatesNothing()
|
|
{
|
|
var a = await fixture.SeedDeviceAsync("SG-NONE");
|
|
|
|
var outcome = await ReportAsync(a, R("Never Joined", false));
|
|
|
|
Assert.Empty(outcome.Created);
|
|
Assert.False(await fixture.WithDbAsync(db => db.DeviceGroups.AnyAsync(g => g.Name == "Never Joined")));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ADeviceCannotPutItselfInACuratedGroup()
|
|
{
|
|
var a = await fixture.SeedDeviceAsync("SG-CURATED");
|
|
await fixture.WithDbAsync(async db =>
|
|
{
|
|
db.DeviceGroups.Add(new DeviceGroupEntity { Id = Guid.NewGuid(), Name = "Admins Only", Kind = GroupKind.Static, CreatedUtc = DateTimeOffset.UtcNow });
|
|
await db.SaveChangesAsync();
|
|
return 0;
|
|
});
|
|
|
|
var outcome = await ReportAsync(a, R("Admins Only", true));
|
|
|
|
Assert.Equal(["Admins Only"], outcome.Ignored);
|
|
Assert.Empty(await MembersAsync("Admins Only"));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task TheLastWordPerGroupWinsAndBadNamesAreDropped()
|
|
{
|
|
var a = await fixture.SeedDeviceAsync("SG-LAST");
|
|
|
|
var outcome = await ReportAsync(a, R("Flip", true), R("flip", false), R("Flip", true), R("a/b", true), R(" ", true));
|
|
|
|
Assert.Equal(["Flip"], outcome.Joined);
|
|
Assert.Equal([a], await MembersAsync("Flip"));
|
|
Assert.False(await fixture.WithDbAsync(db => db.DeviceGroups.AnyAsync(g => g.Name == "a/b")));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task OperatorsCannotListDevicesInAScriptGroup()
|
|
{
|
|
var a = await fixture.SeedDeviceAsync("SG-MANUAL");
|
|
await ReportAsync(a, R("Reported Only", true));
|
|
var id = await fixture.WithDbAsync(db => db.DeviceGroups.Where(g => g.Name == "Reported Only").Select(g => g.Id).SingleAsync());
|
|
using var client = await fixture.SignedInAsync("script-group-admin");
|
|
|
|
var response = await client.PostAsJsonAsync(
|
|
ApiRoutes.For.GroupMembers(id), new UpdateGroupMembersRequest([a], []), JsonDefaults.Options);
|
|
|
|
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
|
Assert.Contains("set by the scripts", await response.Content.ReadAsStringAsync());
|
|
}
|
|
[Fact]
|
|
public async Task AJobsFinalStateCarriesItsReportsToTheGroups()
|
|
{
|
|
fixture.Scripts.Accept = true;
|
|
using var client = await fixture.SignedInAsync("script-group-run");
|
|
var scriptId = await fixture.SeedScriptAsync("script-group-reporter");
|
|
var device = await fixture.SeedDeviceAsync("SG-RUN");
|
|
(await client.PostAsJsonAsync(ApiRoutes.Jobs, new CreateJobRequest(device, scriptId), JsonDefaults.Options)).EnsureSuccessStatusCode();
|
|
var job = await fixture.WithDbAsync(db => db.Jobs.AsNoTracking().SingleAsync(j => j.ClientId == device));
|
|
|
|
var state = new JobStatePayload(job.JobId, device, JobState.Succeeded, 0, DateTimeOffset.UtcNow, null,
|
|
GroupMemberships: [R("From The Agent", true)]);
|
|
var workers = fixture.Services.GetServices<IHostedService>().OfType<MessagingWorkers>().Single();
|
|
await workers.StoreJobStatesAsync(
|
|
[new MessagingWorkers.JobStateMessage(
|
|
NatsSubjects.JobState(job.JobId),
|
|
MessageEnvelope.Create(MessageTypes.JobState, new EndpointRef(EndpointKinds.Agent, device), state).ToUtf8Bytes(),
|
|
DateTimeOffset.UtcNow, _ => ValueTask.CompletedTask, _ => ValueTask.CompletedTask, (_, _) => ValueTask.CompletedTask)],
|
|
CancellationToken.None);
|
|
|
|
Assert.Equal([device], await MembersAsync("From The Agent"));
|
|
}
|
|
}
|