69666d5c4e
Profiles (name, priority, enabled, the settings they set, Include/Exclude
targets as on a schedule) under /api/agent-profiles with settings.manage,
validated against the catalog (ranges, JobRoot path rules), device scope
enforced through the target checks now shared with schedules (TargetScope),
every change audited. Per setting the lowest priority number wins.
Each device's resolved set is kept with a version that only grows; a profile
edit, a group or tag change, an enrollment or an inventory report recomputes
it and pushes a changed set as a sealed durable command, a five-minute sweep
retries the rest, and the agent's pull on connect is answered (newer than the
version it holds). A device no profile reaches any more gets the empty set.
GET /api/devices/{id}/agent-settings shows the decision beside the agent's
report. Migrations AgentSettingsProfiles for SQLite, PostgreSQL and SQL Server.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
484 lines
26 KiB
C#
484 lines
26 KiB
C#
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using System.Text.Json;
|
|
using Backend.AgentSettings;
|
|
using Backend.Data;
|
|
using Backend.Jobs;
|
|
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.Messages;
|
|
using Shared.Contracts.Models;
|
|
using Shared.Contracts.Serialization;
|
|
using Xunit;
|
|
|
|
namespace Backend.Tests;
|
|
|
|
/// <summary>
|
|
/// Agent Settings profiles: CRUD and validation, the per-setting priority merge, Include and
|
|
/// Exclude, device scope, the pushes a change (or a group membership change) makes, the
|
|
/// pull's versioning, the audit trail, and the migration on a real SQLite file.
|
|
/// </summary>
|
|
public class AgentProfileTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
|
|
{
|
|
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
|
|
|
[Fact]
|
|
public async Task AProfileIsCreatedListedUpdatedAndDeleted()
|
|
{
|
|
using var client = await fixture.SignedInAsync("profile-crud");
|
|
var device = await fixture.SeedDeviceAsync("PROFILE-CRUD");
|
|
|
|
var id = await CreateAsync(client, new SaveAgentProfileRequest(
|
|
"Crud Profile", 50, Settings: new Dictionary<string, string>
|
|
{
|
|
["allowregistryaccess"] = "0",
|
|
["InventoryInterval"] = "600",
|
|
["LogLevel"] = "debug",
|
|
["JobRoot"] = @"D:\Jobs",
|
|
},
|
|
ClientIds: [device]));
|
|
|
|
var listed = (await ListAsync(client)).Single(p => p.Id == id);
|
|
Assert.Equal(("Crud Profile", 50, true, 1), (listed.Name, listed.Priority, listed.Enabled, listed.DeviceCount));
|
|
// Keys and values come back canonical.
|
|
Assert.Equal("false", listed.Settings["AllowRegistryAccess"]);
|
|
Assert.Equal("Debug", listed.Settings["LogLevel"]);
|
|
Assert.Equal("600", listed.Settings["InventoryInterval"]);
|
|
Assert.Equal(@"D:\Jobs", listed.Settings["JobRoot"]);
|
|
Assert.Equal([(TriggerTargetKind.Device, "PROFILE-CRUD")], listed.Targets.Select(t => (t.Kind, t.Name)).ToArray());
|
|
|
|
var update = await client.PutAsJsonAsync(ApiRoutes.For.AgentProfile(id), new SaveAgentProfileRequest(
|
|
"Crud Profile Renamed", 51, Enabled: false, Settings: new Dictionary<string, string> { ["AllowRegistryAccess"] = "true" },
|
|
ClientIds: [device]), Ct);
|
|
Assert.Equal(HttpStatusCode.NoContent, update.StatusCode);
|
|
listed = (await ListAsync(client)).Single(p => p.Id == id);
|
|
Assert.Equal(("Crud Profile Renamed", 51, false), (listed.Name, listed.Priority, listed.Enabled));
|
|
Assert.Equal(["AllowRegistryAccess"], listed.Settings.Keys.ToArray());
|
|
|
|
Assert.Equal(HttpStatusCode.NoContent, (await client.DeleteAsync(ApiRoutes.For.AgentProfile(id), Ct)).StatusCode);
|
|
Assert.DoesNotContain(await ListAsync(client), p => p.Id == id);
|
|
Assert.Equal(HttpStatusCode.NotFound, (await client.DeleteAsync(ApiRoutes.For.AgentProfile(id), Ct)).StatusCode);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("ServerURL", "https://elsewhere.example.com", "never set by a profile")]
|
|
[InlineData("TlsSkipVerify", "true", "never set by a profile")]
|
|
[InlineData("MessageClockSkew", "600", "never set by a profile")]
|
|
[InlineData("NoSuchSetting", "1", "not a setting profiles manage")]
|
|
[InlineData("AllowRemoteShell", "maybe", "On or Off")]
|
|
[InlineData("RemoteViewAskTimeout", "5", "10 to 120")]
|
|
[InlineData("InventoryInterval", "30", "60 to 86,400")]
|
|
[InlineData("LogLevel", "Verbose", "one of")]
|
|
[InlineData("JobRoot", @"\\server\share\jobs", "UNC")]
|
|
[InlineData("JobRoot", "relative\\jobs", "absolute")]
|
|
[InlineData("JobRoot", @"C:\", "root")]
|
|
[InlineData("JobRoot", @"C:\Users\Public\Jobs", "user profiles")]
|
|
[InlineData("JobRoot", "/home/jobs", "user profiles")]
|
|
[InlineData("JobRoot", @"C:\Jobs\..\Windows", "..")]
|
|
public async Task ASettingOutsideTheCatalogOrItsRangeIsRefused(string key, string value, string message)
|
|
{
|
|
using var client = await fixture.SignedInAsync("profile-validation");
|
|
var response = await client.PostAsJsonAsync(ApiRoutes.AgentProfiles, new SaveAgentProfileRequest(
|
|
$"Invalid {key} {Guid.NewGuid():N}", 10, Settings: new Dictionary<string, string> { [key] = value }), Ct);
|
|
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
|
Assert.Contains(message, await ErrorAsync(response), StringComparison.OrdinalIgnoreCase);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task NamePriorityAndTargetsAreValidated()
|
|
{
|
|
using var client = await fixture.SignedInAsync("profile-validation-2");
|
|
var device = await fixture.SeedDeviceAsync("PROFILE-VALID");
|
|
await CreateAsync(client, new SaveAgentProfileRequest("Taken Name", 10));
|
|
|
|
async Task<HttpStatusCode> Post(SaveAgentProfileRequest request)
|
|
=> (await client.PostAsJsonAsync(ApiRoutes.AgentProfiles, request, Ct)).StatusCode;
|
|
|
|
Assert.Equal(HttpStatusCode.Conflict, await Post(new SaveAgentProfileRequest("taken name", 11)));
|
|
Assert.Equal(HttpStatusCode.BadRequest, await Post(new SaveAgentProfileRequest(" ", 11)));
|
|
Assert.Equal(HttpStatusCode.BadRequest, await Post(new SaveAgentProfileRequest("Zero Priority", 0)));
|
|
Assert.Equal(HttpStatusCode.BadRequest, await Post(new SaveAgentProfileRequest("All And More", 12, AllDevices: true, ClientIds: [device])));
|
|
Assert.Equal(HttpStatusCode.NotFound, await Post(new SaveAgentProfileRequest("Gone Device", 12, ClientIds: ["client-nosuchdevice"])));
|
|
Assert.Equal(HttpStatusCode.NotFound, await Post(new SaveAgentProfileRequest("Gone Group", 12, GroupIds: [Guid.NewGuid()])));
|
|
Assert.Equal(HttpStatusCode.BadRequest, await Post(new SaveAgentProfileRequest(
|
|
"Duplicate Key", 12, Settings: new Dictionary<string, string> { ["AllowFileAccess"] = "true", ["allowfileaccess"] = "false" })));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ThePriorityMergeIsPerSettingAndTheLowestNumberWins()
|
|
{
|
|
using var client = await fixture.SignedInAsync("profile-merge");
|
|
var device = await fixture.SeedDeviceAsync("PROFILE-MERGE");
|
|
|
|
var low = await CreateAsync(client, new SaveAgentProfileRequest(
|
|
"Merge Baseline", 200, Settings: new Dictionary<string, string>
|
|
{
|
|
["AllowRegistryAccess"] = "true",
|
|
["AllowFileAccess"] = "false",
|
|
},
|
|
ClientIds: [device]));
|
|
var high = await CreateAsync(client, new SaveAgentProfileRequest(
|
|
"Merge Lockdown", 100, Settings: new Dictionary<string, string> { ["AllowRegistryAccess"] = "false" },
|
|
ClientIds: [device]));
|
|
// Disabled: reaches nothing, whatever its priority.
|
|
await CreateAsync(client, new SaveAgentProfileRequest(
|
|
"Merge Disabled", 1, Enabled: false, Settings: new Dictionary<string, string> { ["AllowFileAccess"] = "true" },
|
|
ClientIds: [device]));
|
|
|
|
var result = await DeviceAsync(client, device);
|
|
var registry = result.Settings.Single(s => s.Key == "AllowRegistryAccess");
|
|
var files = result.Settings.Single(s => s.Key == "AllowFileAccess");
|
|
Assert.Equal(("false", "Merge Lockdown", high), (registry.ProfileValue, registry.ProfileName, registry.ProfileId));
|
|
Assert.Equal(("false", "Merge Baseline", low), (files.ProfileValue, files.ProfileName, files.ProfileId));
|
|
Assert.Null(result.Settings.Single(s => s.Key == "AllowRemoteShell").ProfileValue);
|
|
Assert.Equal(["Merge Lockdown", "Merge Baseline"], result.Profiles.Select(p => p.Name).ToArray());
|
|
Assert.Equal(["AllowRegistryAccess"], result.Profiles[0].Wins.ToArray());
|
|
// Settings no profile manages are listed apart, without a profile value.
|
|
Assert.All(result.Settings.Where(s => !s.Managed), s => Assert.Null(s.ProfileValue));
|
|
|
|
var pushed = await LatestPushAsync(device);
|
|
Assert.Equal(
|
|
[("AllowFileAccess", "false", "Merge Baseline"), ("AllowRegistryAccess", "false", "Merge Lockdown")],
|
|
pushed.Settings.OrderBy(s => s.Key).Select(s => (s.Key, s.Value, s.Profile)).ToArray());
|
|
Assert.Equal(pushed.Version, (await DeviceAsync(client, device)).Version);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task IncludeAndExcludeDecideWhichDevicesAProfileReaches()
|
|
{
|
|
using var client = await fixture.SignedInAsync("profile-exclude");
|
|
var kept = await fixture.SeedDeviceAsync("PROFILE-IN");
|
|
var excludedDevice = await fixture.SeedDeviceAsync("PROFILE-OUT");
|
|
var inExcludedGroup = await fixture.SeedDeviceAsync("PROFILE-OUT-GROUP");
|
|
var outsider = await fixture.SeedDeviceAsync("PROFILE-NOT-TARGETED");
|
|
var group = await CreateGroupAsync(client, "Profile Include Group", kept, excludedDevice, inExcludedGroup);
|
|
var excludedGroup = await CreateGroupAsync(client, "Profile Exclude Group", inExcludedGroup);
|
|
|
|
var id = await CreateAsync(client, new SaveAgentProfileRequest(
|
|
"Include Exclude", 300, Settings: new Dictionary<string, string> { ["AllowRemoteView"] = "false" },
|
|
GroupIds: [group], ExcludeClientIds: [excludedDevice], ExcludeGroupIds: [excludedGroup]));
|
|
|
|
Assert.Equal(1, (await ListAsync(client)).Single(p => p.Id == id).DeviceCount);
|
|
Assert.Equal("false", (await DeviceAsync(client, kept)).Settings.Single(s => s.Key == "AllowRemoteView").ProfileValue);
|
|
foreach (var other in new[] { excludedDevice, inExcludedGroup, outsider })
|
|
{
|
|
Assert.Null((await DeviceAsync(client, other)).Settings.Single(s => s.Key == "AllowRemoteView").ProfileValue);
|
|
}
|
|
|
|
await SettleAsync();
|
|
Assert.Contains(Pushes(kept), p => p.Settings.Any(s => s.Key == "AllowRemoteView"));
|
|
// A device no profile ever reached is sent nothing at all.
|
|
Assert.Empty(Pushes(outsider));
|
|
Assert.Empty(Pushes(excludedDevice));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AChangePushesANewerVersionAndDeletingTheProfileClearsTheValues()
|
|
{
|
|
using var client = await fixture.SignedInAsync("profile-push");
|
|
var device = await fixture.SeedDeviceAsync("PROFILE-PUSH");
|
|
|
|
var id = await CreateAsync(client, new SaveAgentProfileRequest(
|
|
"Push Profile", 400, Settings: new Dictionary<string, string> { ["AllowRegistryAccess"] = "false" }, ClientIds: [device]));
|
|
var first = await LatestPushAsync(device);
|
|
Assert.Equal(device, first.ClientId);
|
|
Assert.Equal([("AllowRegistryAccess", "false", "Push Profile")], first.Settings.Select(s => (s.Key, s.Value, s.Profile)).ToArray());
|
|
|
|
(await client.PutAsJsonAsync(ApiRoutes.For.AgentProfile(id), new SaveAgentProfileRequest(
|
|
"Push Profile", 400, Settings: new Dictionary<string, string> { ["AllowRegistryAccess"] = "true" }, ClientIds: [device]), Ct))
|
|
.EnsureSuccessStatusCode();
|
|
var second = await LatestPushAsync(device);
|
|
Assert.True(second.Version > first.Version);
|
|
Assert.Equal("true", second.Settings.Single().Value);
|
|
|
|
// Saving it again unchanged sends nothing new.
|
|
var count = Pushes(device).Count;
|
|
(await client.PutAsJsonAsync(ApiRoutes.For.AgentProfile(id), new SaveAgentProfileRequest(
|
|
"Push Profile", 400, Settings: new Dictionary<string, string> { ["AllowRegistryAccess"] = "true" }, ClientIds: [device]), Ct))
|
|
.EnsureSuccessStatusCode();
|
|
await SettleAsync();
|
|
Assert.Equal(count, Pushes(device).Count);
|
|
|
|
(await client.DeleteAsync(ApiRoutes.For.AgentProfile(id), Ct)).EnsureSuccessStatusCode();
|
|
var cleared = await LatestPushAsync(device);
|
|
Assert.True(cleared.Version > second.Version);
|
|
Assert.Empty(cleared.Settings);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AGroupMembershipChangePushesTheDevicesItMoves()
|
|
{
|
|
using var client = await fixture.SignedInAsync("profile-membership");
|
|
var device = await fixture.SeedDeviceAsync("PROFILE-MEMBER");
|
|
var group = await CreateGroupAsync(client, "Profile Membership Group");
|
|
await CreateAsync(client, new SaveAgentProfileRequest(
|
|
"Membership Profile", 500, Settings: new Dictionary<string, string> { ["AllowRemoteShell"] = "false" }, GroupIds: [group]));
|
|
await SettleAsync();
|
|
Assert.Empty(Pushes(device));
|
|
|
|
(await client.PostAsJsonAsync(ApiRoutes.For.GroupMembers(group), new UpdateGroupMembersRequest([device], []), Ct)).EnsureSuccessStatusCode();
|
|
var joined = await LatestPushAsync(device);
|
|
Assert.Equal([("AllowRemoteShell", "false")], joined.Settings.Select(s => (s.Key, s.Value)).ToArray());
|
|
|
|
(await client.PostAsJsonAsync(ApiRoutes.For.GroupMembers(group), new UpdateGroupMembersRequest([], [device]), Ct)).EnsureSuccessStatusCode();
|
|
var left = await LatestPushAsync(device);
|
|
Assert.True(left.Version > joined.Version);
|
|
Assert.Empty(left.Settings);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ApplySettingsAddsDevicesToAnExistingProfile()
|
|
{
|
|
using var client = await fixture.SignedInAsync("profile-add");
|
|
var first = await fixture.SeedDeviceAsync("PROFILE-ADD-1");
|
|
var second = await fixture.SeedDeviceAsync("PROFILE-ADD-2");
|
|
var id = await CreateAsync(client, new SaveAgentProfileRequest(
|
|
"Add Devices", 600, Settings: new Dictionary<string, string> { ["RemoteViewAskFirst"] = "true" },
|
|
ClientIds: [first], ExcludeClientIds: [second]));
|
|
|
|
var added = await client.PostAsJsonAsync(ApiRoutes.For.AgentProfileDevices(id), new AddAgentProfileDevicesRequest([second, first]), Ct);
|
|
Assert.Equal(HttpStatusCode.NoContent, added.StatusCode);
|
|
var profile = (await ListAsync(client)).Single(p => p.Id == id);
|
|
Assert.Equal(2, profile.DeviceCount);
|
|
Assert.Empty(profile.Excludes);
|
|
Assert.Equal("true", (await LatestPushAsync(second)).Settings.Single().Value);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AScopedAdminOnlyAimsProfilesInsideItsScope()
|
|
{
|
|
var mine = await fixture.SeedDeviceAsync("PROFILE-SCOPE-MINE");
|
|
var theirs = await fixture.SeedDeviceAsync("PROFILE-SCOPE-THEIRS");
|
|
using var admin = await fixture.SignedInAsync("profile-scope-admin");
|
|
using var scoped = await fixture.ScopedSignedInAsync("profile-scope-user", mine);
|
|
|
|
Assert.Equal(HttpStatusCode.Forbidden, (await scoped.PostAsJsonAsync(ApiRoutes.AgentProfiles,
|
|
new SaveAgentProfileRequest("Scoped All", 700, AllDevices: true), Ct)).StatusCode);
|
|
Assert.Equal(HttpStatusCode.NotFound, (await scoped.PostAsJsonAsync(ApiRoutes.AgentProfiles,
|
|
new SaveAgentProfileRequest("Scoped Theirs", 700, ClientIds: [theirs]), Ct)).StatusCode);
|
|
|
|
var own = await CreateAsync(scoped, new SaveAgentProfileRequest(
|
|
"Scoped Mine", 700, Settings: new Dictionary<string, string> { ["AllowFileAccess"] = "false" }, ClientIds: [mine]));
|
|
Assert.Equal(HttpStatusCode.NotFound, (await scoped.PostAsJsonAsync(ApiRoutes.For.AgentProfileDevices(own),
|
|
new AddAgentProfileDevicesRequest([theirs]), Ct)).StatusCode);
|
|
|
|
// A profile aimed beyond the scope can be neither changed nor deleted by it.
|
|
var adminProfile = await CreateAsync(admin, new SaveAgentProfileRequest("Scope Admin Profile", 701, ClientIds: [mine, theirs]));
|
|
Assert.Equal(HttpStatusCode.NotFound, (await scoped.PutAsJsonAsync(ApiRoutes.For.AgentProfile(adminProfile),
|
|
new SaveAgentProfileRequest("Scope Admin Profile", 701, ClientIds: [mine]), Ct)).StatusCode);
|
|
Assert.Equal(HttpStatusCode.NotFound, (await scoped.DeleteAsync(ApiRoutes.For.AgentProfile(adminProfile), Ct)).StatusCode);
|
|
|
|
// Nor does it see a device outside its scope.
|
|
Assert.Equal(HttpStatusCode.NotFound, (await scoped.GetAsync(ApiRoutes.For.DeviceAgentSettings(theirs), Ct)).StatusCode);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task EditingAProfileNeedsSettingsManage()
|
|
{
|
|
using var viewer = await fixture.SignedInAsync("profile-viewer", roleName: "Viewer");
|
|
Assert.Equal(HttpStatusCode.Forbidden, (await viewer.GetAsync(ApiRoutes.AgentProfiles, Ct)).StatusCode);
|
|
Assert.Equal(HttpStatusCode.Forbidden, (await viewer.PostAsJsonAsync(ApiRoutes.AgentProfiles,
|
|
new SaveAgentProfileRequest("Viewer Profile", 1), Ct)).StatusCode);
|
|
|
|
// The catalog (device page labels) is for anyone who sees devices.
|
|
var catalog = await viewer.GetFromJsonAsync<AgentSettingCatalogDto>(ApiRoutes.AgentSettingCatalog, JsonDefaults.Options, Ct);
|
|
Assert.Contains(catalog!.Settings, s => s.Key == "AllowRegistryAccess");
|
|
Assert.Contains(catalog.NotManaged, s => s.Key == "ServerURL");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task EveryChangeIsAudited()
|
|
{
|
|
using var client = await fixture.SignedInAsync("profile-audit");
|
|
var device = await fixture.SeedDeviceAsync("PROFILE-AUDIT");
|
|
var id = await CreateAsync(client, new SaveAgentProfileRequest(
|
|
"Audited Profile", 800, Settings: new Dictionary<string, string> { ["AllowRegistryAccess"] = "false" }));
|
|
(await client.PutAsJsonAsync(ApiRoutes.For.AgentProfile(id), new SaveAgentProfileRequest(
|
|
"Audited Profile", 801, Settings: new Dictionary<string, string> { ["AllowRegistryAccess"] = "true" }), Ct)).EnsureSuccessStatusCode();
|
|
(await client.PostAsJsonAsync(ApiRoutes.For.AgentProfileDevices(id), new AddAgentProfileDevicesRequest([device]), Ct)).EnsureSuccessStatusCode();
|
|
(await client.DeleteAsync(ApiRoutes.For.AgentProfile(id), Ct)).EnsureSuccessStatusCode();
|
|
|
|
var events = await fixture.WithDbAsync(db => db.AuditEvents.AsNoTracking()
|
|
.Where(e => e.Category == "settings" && e.Detail!.Contains(id.ToString("D")))
|
|
.OrderBy(e => e.Id)
|
|
.ToListAsync(Ct));
|
|
Assert.Equal(
|
|
["agent-profile-created", "agent-profile-updated", "agent-profile-devices-added", "agent-profile-deleted"],
|
|
events.Select(e => e.Action).ToArray());
|
|
Assert.All(events, e => Assert.Equal("profile-audit", e.Actor));
|
|
Assert.Contains("settings=AllowRegistryAccess=true", events[1].Detail);
|
|
Assert.Contains("was:", events[1].Detail);
|
|
Assert.Contains("settings=AllowRegistryAccess=false", events[1].Detail![events[1].Detail!.IndexOf("was:", StringComparison.Ordinal)..]);
|
|
Assert.Equal(device, events[2].ClientId);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ThePullAnswersWithAVersionNewerThanTheAgentHolds()
|
|
{
|
|
using var client = await fixture.SignedInAsync("profile-pull");
|
|
var device = await fixture.SeedDeviceAsync("PROFILE-PULL");
|
|
var never = await fixture.SeedDeviceAsync("PROFILE-PULL-NEVER");
|
|
|
|
using (var scope = fixture.Services.CreateScope())
|
|
{
|
|
var sync = scope.ServiceProvider.GetRequiredService<AgentSettingsSync>();
|
|
|
|
// No profile, nothing held: nothing to say.
|
|
var nothing = await sync.ReconcileDeviceAsync(never, 0, push: false, Ct);
|
|
Assert.Equal((0L, 0), (nothing.Version, nothing.Settings.Count));
|
|
|
|
// The agent holds a set the server no longer knows (its record was lost): an empty
|
|
// set newer than that, so the agent clears it.
|
|
var held = DateTimeOffset.UtcNow.AddDays(1).ToUnixTimeMilliseconds();
|
|
var clear = await sync.ReconcileDeviceAsync(never, held, push: false, Ct);
|
|
Assert.True(clear.Version > held);
|
|
Assert.Empty(clear.Settings);
|
|
}
|
|
|
|
await CreateAsync(client, new SaveAgentProfileRequest(
|
|
"Pull Profile", 900, Settings: new Dictionary<string, string> { ["AllowScriptExecution"] = "false" }, ClientIds: [device]));
|
|
var pushed = await LatestPushAsync(device);
|
|
using (var scope = fixture.Services.CreateScope())
|
|
{
|
|
var sync = scope.ServiceProvider.GetRequiredService<AgentSettingsSync>();
|
|
var answer = await sync.ReconcileDeviceAsync(device, 0, push: false, Ct);
|
|
Assert.Equal(pushed.Version, answer.Version);
|
|
Assert.Equal([("AllowScriptExecution", "false", "Pull Profile")], answer.Settings.Select(s => (s.Key, s.Value, s.Profile)).ToArray());
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public void VersionsOnlyGrow()
|
|
{
|
|
var now = DateTimeOffset.UtcNow;
|
|
Assert.Equal(now.ToUnixTimeMilliseconds(), AgentSettingsSync.NextVersion(0, null, now));
|
|
var ahead = now.ToUnixTimeMilliseconds() + 5_000;
|
|
Assert.Equal(ahead + 1, AgentSettingsSync.NextVersion(ahead, null, now));
|
|
Assert.Equal(ahead + 1, AgentSettingsSync.NextVersion(3, ahead, now));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task TheMigrationAppliesOnARealSqliteFile()
|
|
{
|
|
var path = Path.Combine(Path.GetTempPath(), $"agent-profiles-migration-{Guid.NewGuid():N}.db");
|
|
try
|
|
{
|
|
await using var db = new SqliteAppDbContext(
|
|
new DbContextOptionsBuilder<SqliteAppDbContext>().UseSqlite($"Data Source={path}").Options);
|
|
var migrator = db.GetService<IMigrator>();
|
|
var migrations = db.Database.GetMigrations().ToList();
|
|
var target = migrations.Single(m => m.EndsWith("_AgentSettingsProfiles", StringComparison.Ordinal));
|
|
await migrator.MigrateAsync(migrations[migrations.IndexOf(target) - 1], Ct);
|
|
|
|
var clientId = "client-premigration2";
|
|
await db.Database.ExecuteSqlRawAsync(
|
|
"INSERT INTO Devices (ClientId, Hostname, NkeyPublic, EnrollmentId, EnrolledUtc, IsOrphaned) VALUES ({0}, 'BEFORE', 'UKEY', {1}, {2}, 0)",
|
|
[clientId, Guid.NewGuid().ToString().ToUpperInvariant(), DateTimeOffset.UtcNow.UtcTicks], Ct);
|
|
|
|
await migrator.MigrateAsync(cancellationToken: Ct);
|
|
Assert.Empty(await db.Database.GetPendingMigrationsAsync(Ct));
|
|
|
|
var profile = new AgentProfileEntity { Id = Guid.NewGuid(), Name = "Migrated", Priority = 1, CreatedUtc = DateTimeOffset.UtcNow, UpdatedUtc = DateTimeOffset.UtcNow };
|
|
profile.SetSettings(new Dictionary<string, string> { ["AllowRegistryAccess"] = "false" });
|
|
profile.SetTargets(false, [clientId], []);
|
|
db.AgentProfiles.Add(profile);
|
|
db.DeviceAgentSettings.Add(new DeviceAgentSettingsEntity
|
|
{
|
|
ClientId = clientId, Version = 1, ValuesJson = "[]", Hash = AgentSettingsResolver.Hash([]), UpdatedUtc = DateTimeOffset.UtcNow,
|
|
});
|
|
await db.SaveChangesAsync(Ct);
|
|
|
|
var stored = await db.AgentProfiles.AsNoTracking().SingleAsync(Ct);
|
|
Assert.Equal("false", stored.GetSettings()["AllowRegistryAccess"]);
|
|
Assert.Equal([clientId], stored.GetClientIds());
|
|
|
|
// The device's row goes with the device.
|
|
await db.Database.ExecuteSqlRawAsync("DELETE FROM Devices WHERE ClientId = {0}", [clientId], Ct);
|
|
Assert.False(await db.DeviceAgentSettings.AnyAsync(Ct));
|
|
}
|
|
finally
|
|
{
|
|
SqliteConnection.ClearAllPools();
|
|
File.Delete(path);
|
|
}
|
|
}
|
|
|
|
private async Task<Guid> CreateAsync(HttpClient client, SaveAgentProfileRequest request)
|
|
{
|
|
var response = await client.PostAsJsonAsync(ApiRoutes.AgentProfiles, request, Ct);
|
|
Assert.True(response.StatusCode == HttpStatusCode.Created, await response.Content.ReadAsStringAsync(Ct));
|
|
var body = await response.Content.ReadFromJsonAsync<JsonElement>(Ct);
|
|
return body.GetProperty("id").GetGuid();
|
|
}
|
|
|
|
private static async Task<List<AgentProfileDto>> ListAsync(HttpClient client)
|
|
=> (await client.GetFromJsonAsync<List<AgentProfileDto>>(ApiRoutes.AgentProfiles, JsonDefaults.Options, Ct))!;
|
|
|
|
private static async Task<DeviceAgentSettingsDto> DeviceAsync(HttpClient client, string clientId)
|
|
=> (await client.GetFromJsonAsync<DeviceAgentSettingsDto>(ApiRoutes.For.DeviceAgentSettings(clientId), JsonDefaults.Options, Ct))!;
|
|
|
|
private static async Task<Guid> CreateGroupAsync(HttpClient client, string name, params string[] members)
|
|
{
|
|
var response = await client.PostAsJsonAsync(ApiRoutes.Groups, new SaveDeviceGroupRequest(
|
|
$"{name} {Guid.NewGuid():N}"[..40], null, GroupKind.Static, null), Ct);
|
|
response.EnsureSuccessStatusCode();
|
|
var id = (await response.Content.ReadFromJsonAsync<JsonElement>(Ct)).GetProperty("id").GetGuid();
|
|
if (members.Length > 0)
|
|
{
|
|
(await client.PostAsJsonAsync(ApiRoutes.For.GroupMembers(id), new UpdateGroupMembersRequest(members, []), Ct)).EnsureSuccessStatusCode();
|
|
}
|
|
|
|
return id;
|
|
}
|
|
|
|
private static async Task<string> ErrorAsync(HttpResponseMessage response)
|
|
=> (await response.Content.ReadFromJsonAsync<JsonElement>(Ct)).GetProperty("error").GetString() ?? string.Empty;
|
|
|
|
private async Task SettleAsync()
|
|
=> Assert.True(await fixture.Services.GetRequiredService<AgentSettingsSignal>().WhenSettledAsync(TimeSpan.FromSeconds(30), Ct));
|
|
|
|
private List<AgentSettingsPayload> Pushes(string clientId) => fixture.AgentSettings.For(clientId);
|
|
|
|
private async Task<AgentSettingsPayload> LatestPushAsync(string clientId)
|
|
{
|
|
await SettleAsync();
|
|
var pushes = Pushes(clientId);
|
|
Assert.NotEmpty(pushes);
|
|
return pushes[^1];
|
|
}
|
|
}
|
|
|
|
/// <summary>Records Agent Settings pushes instead of publishing them.</summary>
|
|
public sealed class RecordingSettingsSender : IAgentSettingsSender
|
|
{
|
|
private readonly List<(string ClientId, AgentSettingsPayload Settings)> sent = [];
|
|
|
|
public bool Accept { get; set; } = true;
|
|
|
|
public Task<bool> DispatchAgentSettingsAsync(string clientId, AgentSettingsPayload settings, CancellationToken cancellationToken)
|
|
{
|
|
lock (sent)
|
|
{
|
|
if (!Accept)
|
|
{
|
|
return Task.FromResult(false);
|
|
}
|
|
|
|
sent.Add((clientId, settings));
|
|
return Task.FromResult(true);
|
|
}
|
|
}
|
|
|
|
public List<AgentSettingsPayload> For(string clientId)
|
|
{
|
|
lock (sent)
|
|
{
|
|
return sent.Where(s => s.ClientId == clientId).Select(s => s.Settings).OrderBy(s => s.Version).ToList();
|
|
}
|
|
}
|
|
}
|