b4202e9794
- Stable links per package (/api/downloads/agent/Agent.msi, Agent.zip, Agent-<os>-<arch>.zip) always serve the newest build (GET and HEAD, X-Agent-Version); /api/downloads/agent lists version, SHA-256, size and link as JSON. With offload on they redirect to a fresh presigned link (S3 presigned links cannot be permanent). - Public Downloads setting (off by default): on, anyone; off, install scripts (their package URLs carry the bootstrap token) and signed-in users with devices.view. - No MSI/ZIP choice: the Windows script installs the MSI, or the ZIP in Windows PE. Add Device is redesigned: platform cards, token step with summary chips, install step, and per-platform downloads. - Settings > Enrollment Tokens gains an Agent Downloads card. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
723 lines
39 KiB
C#
723 lines
39 KiB
C#
using System.Net;
|
||
using System.Net.Http.Headers;
|
||
using System.Net.Http.Json;
|
||
using Backend.Api;
|
||
using Backend.Data;
|
||
using Backend.Upgrades;
|
||
using Microsoft.EntityFrameworkCore;
|
||
using Microsoft.Extensions.DependencyInjection;
|
||
using Shared.Contracts.Api;
|
||
using Shared.Contracts.Models;
|
||
using Shared.Contracts.Serialization;
|
||
using Xunit;
|
||
using static Backend.Tests.AgentUpgradeTestKit;
|
||
|
||
namespace Backend.Tests;
|
||
|
||
/// <summary>The version catalog: import, prune rules, removal and the package download.</summary>
|
||
public class AgentCatalogTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
|
||
{
|
||
private string CatalogFile(string version, string fileName)
|
||
=> Path.Combine(fixture.DataPath, "agent-packages", version, fileName);
|
||
|
||
[Fact]
|
||
public async Task ImportCopiesThePackageOnceAndSkipsUnknownVersions()
|
||
{
|
||
await fixture.ResetAsync();
|
||
var package = await fixture.SeedPackageAsync(V1, content: "zip v1");
|
||
|
||
Assert.Equal("Agent.zip", package.FileName);
|
||
Assert.Equal($"{V1}/Agent.zip", package.StoragePath);
|
||
Assert.Equal("zip v1", await File.ReadAllTextAsync(CatalogFile(V1, "Agent.zip")));
|
||
Assert.Equal(6, package.SizeBytes);
|
||
|
||
// Same version and type again: the existing row, no second copy.
|
||
var again = await fixture.SeedPackageAsync(V1, content: "zip v1");
|
||
Assert.Equal(package.Id, again.Id);
|
||
|
||
var source = Path.Combine(fixture.DataPath, "incoming-unknown.zip");
|
||
await File.WriteAllTextAsync(source, "dev build");
|
||
using var scope = fixture.Services.CreateScope();
|
||
var catalog = scope.ServiceProvider.GetRequiredService<AgentCatalogService>();
|
||
Assert.Null(await catalog.ImportAsync(AgentPackageTypes.WindowsZip, source, "0.0.0.0", CancellationToken.None));
|
||
Assert.Null(await catalog.ImportAsync(AgentPackageTypes.WindowsZip, source, null, CancellationToken.None));
|
||
Assert.Equal(1, await fixture.WithDbAsync(db => db.AgentPackages.CountAsync()));
|
||
|
||
// The MSI is catalogued too: MSI installs upgrade through it.
|
||
var msi = await catalog.ImportAsync(AgentPackageTypes.Msi, source, V1, CancellationToken.None);
|
||
Assert.NotNull(msi);
|
||
Assert.Equal("Agent.msi", msi.FileName);
|
||
Assert.Equal($"{V1}/Agent.msi", msi.StoragePath);
|
||
Assert.True(File.Exists(CatalogFile(V1, "Agent.msi")));
|
||
Assert.Equal(2, await fixture.WithDbAsync(db => db.AgentPackages.CountAsync()));
|
||
}
|
||
|
||
[Fact]
|
||
public async Task PruneKeepsTheNewestVersionsAndEveryVersionStillNeeded()
|
||
{
|
||
await fixture.ResetAsync();
|
||
string[] versions = ["2026.1.1.1", "2026.2.1.1", "2026.3.1.1", "2026.4.1.1", "2026.5.1.1"];
|
||
foreach (var version in versions)
|
||
{
|
||
await fixture.SeedPackageAsync(version);
|
||
}
|
||
|
||
// 2026.2 is a device's rollback target; an open upgrade goes to 2026.1.
|
||
var device = await fixture.SeedAgentAsync("PRUNE-1", "2026.5.1.1");
|
||
await fixture.SeedUpgradeAsync(device, "2026.2.1.1", "2026.5.1.1", AgentUpgradeStates.Succeeded);
|
||
var other = await fixture.SeedAgentAsync("PRUNE-2", "2026.5.1.1");
|
||
await fixture.SeedUpgradeAsync(other, "2026.5.1.1", "2026.1.1.1", AgentUpgradeStates.Queued);
|
||
|
||
await fixture.SaveSettingsAsync(AgentUpgradeSettingsStore.Defaults with { KeepVersions = 2 });
|
||
using (var scope = fixture.Services.CreateScope())
|
||
{
|
||
await scope.ServiceProvider.GetRequiredService<AgentCatalogService>().PruneAsync(CancellationToken.None);
|
||
}
|
||
|
||
var left = await fixture.WithDbAsync(db => db.AgentPackages.Select(p => p.Version).ToListAsync());
|
||
Assert.Equal(["2026.1.1.1", "2026.2.1.1", "2026.4.1.1", "2026.5.1.1"], left.Order());
|
||
Assert.False(Directory.Exists(Path.GetDirectoryName(CatalogFile("2026.3.1.1", "Agent.zip"))));
|
||
|
||
// An older build arriving now would be pruned straight away: not imported.
|
||
using (var scope = fixture.Services.CreateScope())
|
||
{
|
||
var source = Path.Combine(fixture.DataPath, "old.zip");
|
||
await File.WriteAllTextAsync(source, "old");
|
||
Assert.Null(await scope.ServiceProvider.GetRequiredService<AgentCatalogService>()
|
||
.ImportAsync(AgentPackageTypes.WindowsZip, source, "2026.3.1.1", CancellationToken.None));
|
||
}
|
||
}
|
||
|
||
[Fact]
|
||
public async Task VersionsListNewestFirstAndRemovalIsRefusedWhileNeeded()
|
||
{
|
||
await fixture.ResetAsync();
|
||
await fixture.SeedPackageAsync(V1);
|
||
await fixture.SeedPackageAsync(V2);
|
||
await fixture.SeedPackageAsync(V2, AgentPackageTypes.LinuxX64);
|
||
await fixture.SeedPackageAsync(V3);
|
||
var device = await fixture.SeedAgentAsync("VERSIONS-1", V3);
|
||
await fixture.SeedAgentAsync("VERSIONS-2", V3);
|
||
await fixture.SeedUpgradeAsync(device, V2, V3, AgentUpgradeStates.Succeeded);
|
||
|
||
using var admin = await fixture.SignedInAsync("catalog-admin");
|
||
var listed = await (await admin.GetAsync(ApiRoutes.AgentVersions)).ReadAsync<List<AgentVersionDto>>();
|
||
Assert.Equal([V3, V2, V1], listed.Select(v => v.Version));
|
||
Assert.True(listed[0].Newest);
|
||
Assert.Equal(2, listed[0].DeviceCount);
|
||
Assert.NotNull(listed[0].RemoveBlockedReason);
|
||
Assert.Equal(2, listed[1].Packages.Count);
|
||
Assert.Contains("roll back", listed[1].RemoveBlockedReason);
|
||
Assert.Null(listed[2].RemoveBlockedReason);
|
||
|
||
var newest = await admin.DeleteAsync(ApiRoutes.For.AgentVersion(V3));
|
||
Assert.Equal(HttpStatusCode.Conflict, newest.StatusCode);
|
||
Assert.Contains("newest", await newest.Content.ReadAsStringAsync());
|
||
Assert.Equal(HttpStatusCode.Conflict, (await admin.DeleteAsync(ApiRoutes.For.AgentVersion(V2))).StatusCode);
|
||
Assert.Equal(HttpStatusCode.NoContent, (await admin.DeleteAsync(ApiRoutes.For.AgentVersion(V1))).StatusCode);
|
||
Assert.Equal(HttpStatusCode.NotFound, (await admin.DeleteAsync(ApiRoutes.For.AgentVersion(V1))).StatusCode);
|
||
Assert.False(Directory.Exists(Path.GetDirectoryName(CatalogFile(V1, "Agent.zip"))));
|
||
|
||
using var viewer = await fixture.SignedInAsync("catalog-viewer", "Viewer");
|
||
Assert.Equal(HttpStatusCode.OK, (await viewer.GetAsync(ApiRoutes.AgentVersions)).StatusCode);
|
||
Assert.Equal(HttpStatusCode.Forbidden, (await viewer.DeleteAsync(ApiRoutes.For.AgentVersion(V2))).StatusCode);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task PackagesDownloadAnonymouslyByHashWithRanges()
|
||
{
|
||
await fixture.ResetAsync();
|
||
var package = await fixture.SeedPackageAsync(V2, content: "0123456789");
|
||
using var anonymous = fixture.CreateClient();
|
||
|
||
var whole = await anonymous.GetAsync(ApiRoutes.For.AgentPackageBySha(package.Sha256));
|
||
Assert.Equal(HttpStatusCode.OK, whole.StatusCode);
|
||
Assert.Equal("0123456789", await whole.Content.ReadAsStringAsync());
|
||
|
||
using var ranged = new HttpRequestMessage(HttpMethod.Get, ApiRoutes.For.AgentPackageBySha(package.Sha256));
|
||
ranged.Headers.Range = new RangeHeaderValue(4, null);
|
||
var rest = await anonymous.SendAsync(ranged);
|
||
Assert.Equal(HttpStatusCode.PartialContent, rest.StatusCode);
|
||
Assert.Equal("456789", await rest.Content.ReadAsStringAsync());
|
||
|
||
Assert.Equal(HttpStatusCode.NotFound, (await anonymous.GetAsync(ApiRoutes.For.AgentPackageBySha(new string('a', 64)))).StatusCode);
|
||
Assert.Equal(HttpStatusCode.NotFound, (await anonymous.GetAsync(ApiRoutes.For.AgentPackageBySha("not-a-hash"))).StatusCode);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task InstallsGetTheNewestCataloguedBuild()
|
||
{
|
||
await fixture.ResetAsync();
|
||
await fixture.SeedPackageAsync(V3, content: "zip v3");
|
||
await fixture.SeedPackageAsync(V1, content: "zip v1");
|
||
await fixture.SeedPackageAsync(V2, AgentPackageTypes.Msi, content: "msi v2");
|
||
await fixture.SetPublicDownloadsAsync(true);
|
||
using var anonymous = fixture.CreateClient();
|
||
|
||
var zip = await anonymous.GetAsync($"{ApiRoutes.AgentPackage}?type=zip");
|
||
Assert.Equal(HttpStatusCode.OK, zip.StatusCode);
|
||
Assert.Equal("zip v3", await zip.Content.ReadAsStringAsync());
|
||
Assert.Equal("Agent.zip", zip.Content.Headers.ContentDisposition?.FileName?.Trim('"'));
|
||
|
||
var msi = await anonymous.GetAsync($"{ApiRoutes.AgentPackage}?type=msi");
|
||
Assert.Equal("msi v2", await msi.Content.ReadAsStringAsync());
|
||
Assert.Equal("application/x-msi", msi.Content.Headers.ContentType?.MediaType);
|
||
|
||
// No build of this platform anywhere.
|
||
Assert.Equal(HttpStatusCode.NotFound, (await anonymous.GetAsync($"{ApiRoutes.AgentPackage}?type=linux-x64")).StatusCode);
|
||
}
|
||
}
|
||
|
||
/// <summary>Starting upgrades and roll backs, cancelling, listing.</summary>
|
||
public class AgentUpgradeStartTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
|
||
{
|
||
[Fact]
|
||
public async Task StartQueuesDevicesAndGroupMembersAndSaysWhyOthersAreLeftOut()
|
||
{
|
||
await fixture.ResetAsync();
|
||
await fixture.SeedPackageAsync(V1);
|
||
await fixture.SeedPackageAsync(V2);
|
||
await fixture.SeedPackageAsync(V2, AgentPackageTypes.LinuxX64);
|
||
|
||
var direct = await fixture.SeedAgentAsync("UP-DIRECT", V1);
|
||
var nested = await fixture.SeedAgentAsync("UP-NESTED", V1, "linux-x64");
|
||
var already = await fixture.SeedAgentAsync("UP-ALREADY", V2);
|
||
var arm = await fixture.SeedAgentAsync("UP-ARM", V1, "win-arm64");
|
||
var busy = await fixture.SeedAgentAsync("UP-BUSY", V1);
|
||
var offline = await fixture.SeedAgentAsync("UP-OFFLINE", V1, online: false);
|
||
var mac = await fixture.SeedAgentAsync("UP-MAC", V1, "osx-arm64");
|
||
var older = await fixture.SeedAgentAsync("UP-OLDER", V1, runtime: null, osCaption: "Microsoft Windows 11 Pro");
|
||
await fixture.SeedUpgradeAsync(busy, V1, V2, AgentUpgradeStates.Sent);
|
||
|
||
// A folder holding a static group holding the Linux device: nested membership counts.
|
||
var folderId = await fixture.WithDbAsync(async db =>
|
||
{
|
||
var folder = new DeviceGroupEntity { Id = Guid.NewGuid(), Name = $"folder-{Guid.NewGuid():N}", Kind = GroupKind.Folder, CreatedUtc = DateTimeOffset.UtcNow, UpdatedUtc = DateTimeOffset.UtcNow };
|
||
var child = new DeviceGroupEntity { Id = Guid.NewGuid(), ParentId = folder.Id, Name = $"child-{Guid.NewGuid():N}", Kind = GroupKind.Static, CreatedUtc = DateTimeOffset.UtcNow, UpdatedUtc = DateTimeOffset.UtcNow };
|
||
db.DeviceGroups.AddRange(folder, child);
|
||
db.DeviceGroupMembers.Add(new DeviceGroupMemberEntity { GroupId = child.Id, ClientId = nested, AddedUtc = DateTimeOffset.UtcNow });
|
||
await db.SaveChangesAsync();
|
||
return folder.Id;
|
||
});
|
||
|
||
using var admin = await fixture.SignedInAsync("upgrade-admin");
|
||
var response = await admin.PostAsJsonAsync(ApiRoutes.AgentUpgrades, new StartAgentUpgradeRequest(
|
||
[direct, already, arm, busy, offline, mac, older], [folderId]), JsonDefaults.Options);
|
||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||
var batch = await response.ReadAsync<AgentUpgradeBatchDto>();
|
||
|
||
Assert.Equal(
|
||
new[] { direct, nested, offline, older }.Order(),
|
||
batch.Upgrades.Select(u => u.ClientId).Order());
|
||
Assert.All(batch.Upgrades, u =>
|
||
{
|
||
Assert.Equal(V2, u.TargetVersion);
|
||
Assert.Equal(AgentUpgradeStates.Queued, u.State);
|
||
Assert.Equal(AgentUpgradeSources.Manual, u.Source);
|
||
Assert.Equal(V1, u.FromVersion);
|
||
Assert.Equal("upgrade-admin", u.RequestedBy);
|
||
});
|
||
Assert.Equal("UP-DIRECT", batch.Upgrades.Single(u => u.ClientId == direct).Hostname);
|
||
|
||
var skipped = batch.Skipped.ToDictionary(s => s.ClientId, s => s.Reason);
|
||
Assert.Equal(AgentUpgradeReasons.Already, skipped[already]);
|
||
Assert.Equal(AgentUpgradeReasons.Unsupported, skipped[arm]);
|
||
Assert.Equal(AgentUpgradeReasons.Busy, skipped[busy]);
|
||
Assert.Equal(AgentUpgradeReasons.NoPackage, skipped[mac]);
|
||
|
||
var linux = Assert.Single(await fixture.UpgradesOfAsync(nested));
|
||
Assert.Equal(AgentPackageTypes.LinuxX64, linux.PackageType);
|
||
|
||
// An explicit older version is the operator's choice (a downgrade).
|
||
var down = await (await admin.PostAsJsonAsync(ApiRoutes.AgentUpgrades,
|
||
new StartAgentUpgradeRequest([already], Version: V1), JsonDefaults.Options)).ReadAsync<AgentUpgradeBatchDto>();
|
||
Assert.Equal(V1, Assert.Single(down.Upgrades).TargetVersion);
|
||
|
||
Assert.Equal(HttpStatusCode.NotFound, (await admin.PostAsJsonAsync(ApiRoutes.AgentUpgrades,
|
||
new StartAgentUpgradeRequest([direct], Version: "2027.1.1.1"), JsonDefaults.Options)).StatusCode);
|
||
Assert.Equal(HttpStatusCode.BadRequest, (await admin.PostAsJsonAsync(ApiRoutes.AgentUpgrades,
|
||
new StartAgentUpgradeRequest(), JsonDefaults.Options)).StatusCode);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task OlderAgentsWithoutARuntimeUseTheInventoryPlatform()
|
||
{
|
||
Assert.Equal(AgentPackageTypes.WindowsZip, AgentUpgradeService.ResolvePackageType(null, "Microsoft Windows 11 Pro", "64-bit"));
|
||
Assert.Equal(AgentPackageTypes.WindowsZip, AgentUpgradeService.ResolvePackageType(null, "Windows PE", null));
|
||
Assert.Null(AgentUpgradeService.ResolvePackageType(null, "Microsoft Windows 11 Pro", "ARM 64-bit Processor"));
|
||
Assert.Equal(AgentPackageTypes.LinuxArm64, AgentUpgradeService.ResolvePackageType(null, "Ubuntu 24.04 LTS", "Arm64"));
|
||
Assert.Equal(AgentPackageTypes.LinuxX64, AgentUpgradeService.ResolvePackageType(null, "Debian GNU/Linux 12", "X64"));
|
||
Assert.Equal(AgentPackageTypes.MacArm64, AgentUpgradeService.ResolvePackageType(null, "macOS 15.1", "Arm64"));
|
||
Assert.Null(AgentUpgradeService.ResolvePackageType(null, "Ubuntu 24.04 LTS", null));
|
||
Assert.Null(AgentUpgradeService.ResolvePackageType(null, null, null));
|
||
Assert.Equal(AgentPackageTypes.LinuxX64, AgentUpgradeService.ResolvePackageType("linux-x64", "Microsoft Windows", "Arm64"));
|
||
|
||
// From a stored inventory snapshot.
|
||
await fixture.ResetAsync();
|
||
var clientId = await fixture.SeedAgentAsync("UP-INVENTORY", V1, runtime: null);
|
||
await fixture.WithDbAsync(async db =>
|
||
{
|
||
var report = new InventoryReport(
|
||
new InventoryIdentity(clientId, "UP-INVENTORY", null, null, null, null, null, null, false, "X64"),
|
||
new InventoryOs("Ubuntu 24.04 LTS", "24.04", null, "Arm64", null, null, null),
|
||
new InventoryCpu(null, 4, 4), [], 0, [], [], [], DateTimeOffset.UtcNow);
|
||
db.DeviceInventory.Add(new DeviceInventoryEntity { ClientId = clientId, ReportJson = JsonDefaults.Serialize(report), UpdatedUtc = DateTimeOffset.UtcNow });
|
||
await db.SaveChangesAsync();
|
||
});
|
||
|
||
using var scope = fixture.Services.CreateScope();
|
||
var device = await scope.ServiceProvider.GetRequiredService<AppDbContext>().Devices.SingleAsync(d => d.ClientId == clientId);
|
||
var types = await scope.ServiceProvider.GetRequiredService<AgentUpgradeService>().ResolvePackageTypesAsync([device], CancellationToken.None);
|
||
Assert.Equal(AgentPackageTypes.LinuxArm64, types[clientId]);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task AScopedCallerOnlyReachesItsOwnDevices()
|
||
{
|
||
await fixture.ResetAsync();
|
||
await fixture.SeedPackageAsync(V2);
|
||
var inside = await fixture.SeedAgentAsync("SCOPE-IN", V1);
|
||
var outside = await fixture.SeedAgentAsync("SCOPE-OUT", V1);
|
||
var outsideUpgrade = await fixture.SeedUpgradeAsync(outside, V1, V2, AgentUpgradeStates.Queued);
|
||
|
||
using var scoped = await fixture.ScopedSignedInAsync($"scoped-{Guid.NewGuid():N}"[..20], inside);
|
||
var batch = await (await scoped.PostAsJsonAsync(ApiRoutes.AgentUpgrades,
|
||
new StartAgentUpgradeRequest([inside, outside]), JsonDefaults.Options)).ReadAsync<AgentUpgradeBatchDto>();
|
||
Assert.Equal(inside, Assert.Single(batch.Upgrades).ClientId);
|
||
Assert.Empty(batch.Skipped);
|
||
|
||
var listed = await (await scoped.GetAsync(ApiRoutes.AgentUpgrades)).ReadAsync<List<AgentUpgradeDto>>();
|
||
Assert.Equal(inside, Assert.Single(listed).ClientId);
|
||
Assert.Equal(HttpStatusCode.NotFound, (await scoped.PostAsync(ApiRoutes.For.AgentUpgradeCancel(outsideUpgrade.Id), null)).StatusCode);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task RollBackGoesToTheVersionTheLastUpgradeCameFrom()
|
||
{
|
||
await fixture.ResetAsync();
|
||
await fixture.SeedPackageAsync(V1);
|
||
await fixture.SeedPackageAsync(V2);
|
||
await fixture.SeedPackageAsync(V3);
|
||
|
||
var upgraded = await fixture.SeedAgentAsync("RB-UPGRADED", V3);
|
||
await fixture.SeedUpgradeAsync(upgraded, V1, V2, AgentUpgradeStates.Succeeded,
|
||
configure: u => u.FinishedUtc = DateTimeOffset.UtcNow.AddDays(-2));
|
||
await fixture.SeedUpgradeAsync(upgraded, V2, V3, AgentUpgradeStates.Succeeded);
|
||
var never = await fixture.SeedAgentAsync("RB-NEVER", V3);
|
||
var gone = await fixture.SeedAgentAsync("RB-GONE", V3);
|
||
await fixture.SeedUpgradeAsync(gone, "2026.1.1.1", V3, AgentUpgradeStates.Succeeded);
|
||
|
||
using var admin = await fixture.SignedInAsync("rollback-admin");
|
||
var batch = await (await admin.PostAsJsonAsync(ApiRoutes.AgentUpgradesRollback,
|
||
new RollBackAgentRequest([upgraded, never, gone]), JsonDefaults.Options)).ReadAsync<AgentUpgradeBatchDto>();
|
||
|
||
var rollback = Assert.Single(batch.Upgrades);
|
||
Assert.Equal(upgraded, rollback.ClientId);
|
||
Assert.Equal(V2, rollback.TargetVersion);
|
||
Assert.Equal(AgentUpgradeSources.Rollback, rollback.Source);
|
||
Assert.Equal(AgentUpgradeService.SkipNoPrevious, batch.Skipped.Single(s => s.ClientId == never).Reason);
|
||
Assert.Equal(AgentUpgradeService.SkipNoPrevious, batch.Skipped.Single(s => s.ClientId == gone).Reason);
|
||
|
||
// The command reverts.
|
||
var sender = new RecordingUpgradeSender();
|
||
await fixture.Scheduler(sender).RunPassAsync(DateTimeOffset.UtcNow, CancellationToken.None);
|
||
Assert.True(Assert.Single(sender.Sent, s => s.ClientId == upgraded).Command.Revert);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task OnlyAQueuedUpgradeCanBeCancelledAndTheListFilters()
|
||
{
|
||
await fixture.ResetAsync();
|
||
var device = await fixture.SeedAgentAsync("CANCEL-1", V1);
|
||
var other = await fixture.SeedAgentAsync("CANCEL-2", V1);
|
||
var queued = await fixture.SeedUpgradeAsync(device, V1, V2, AgentUpgradeStates.Queued);
|
||
var sent = await fixture.SeedUpgradeAsync(other, V1, V2, AgentUpgradeStates.Sent);
|
||
await fixture.SeedUpgradeAsync(other, V1, V2, AgentUpgradeStates.Failed, AgentUpgradeReasons.Download,
|
||
configure: u => u.CreatedUtc = DateTimeOffset.UtcNow.AddHours(-1));
|
||
|
||
using var admin = await fixture.SignedInAsync("cancel-admin");
|
||
var cancelled = await (await admin.PostAsync(ApiRoutes.For.AgentUpgradeCancel(queued.Id), null)).ReadAsync<AgentUpgradeDto>();
|
||
Assert.Equal(AgentUpgradeStates.Cancelled, cancelled.State);
|
||
Assert.Equal(AgentUpgradeReasons.Cancelled, cancelled.Reason);
|
||
Assert.Equal(HttpStatusCode.Conflict, (await admin.PostAsync(ApiRoutes.For.AgentUpgradeCancel(queued.Id), null)).StatusCode);
|
||
Assert.Equal(HttpStatusCode.Conflict, (await admin.PostAsync(ApiRoutes.For.AgentUpgradeCancel(sent.Id), null)).StatusCode);
|
||
Assert.Equal(HttpStatusCode.NotFound, (await admin.PostAsync(ApiRoutes.For.AgentUpgradeCancel(Guid.NewGuid()), null)).StatusCode);
|
||
|
||
var ofOther = await (await admin.GetAsync($"{ApiRoutes.AgentUpgrades}?clientId={other}")).ReadAsync<List<AgentUpgradeDto>>();
|
||
Assert.Equal([AgentUpgradeStates.Sent, AgentUpgradeStates.Failed], ofOther.Select(u => u.State));
|
||
Assert.Equal("CANCEL-2", ofOther[0].Hostname);
|
||
var open = await (await admin.GetAsync($"{ApiRoutes.AgentUpgrades}?open=true")).ReadAsync<List<AgentUpgradeDto>>();
|
||
Assert.Equal(sent.Id, Assert.Single(open).Id);
|
||
var limited = await (await admin.GetAsync($"{ApiRoutes.AgentUpgrades}?limit=1")).ReadAsync<List<AgentUpgradeDto>>();
|
||
Assert.Single(limited);
|
||
}
|
||
}
|
||
|
||
/// <summary>The scheduler: paced sends, deadlines, presence, and the agent's events.</summary>
|
||
public class AgentUpgradeSchedulerTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
|
||
{
|
||
private async Task<(AgentPackageEntity Package, List<string> Devices)> QueueAsync(int count, bool online = true, string prefix = "SEND")
|
||
{
|
||
var package = await fixture.SeedPackageAsync(V2);
|
||
var devices = new List<string>();
|
||
await fixture.WithDbAsync(async db =>
|
||
{
|
||
for (var i = 0; i < count; i++)
|
||
{
|
||
var clientId = $"{prefix.ToLowerInvariant()}-{Guid.NewGuid():N}"[..20];
|
||
db.Devices.Add(new DeviceEntity
|
||
{
|
||
ClientId = clientId, Hostname = $"{prefix}-{i}", NkeyPublic = $"U{Guid.NewGuid():N}",
|
||
EnrolledUtc = DateTimeOffset.UtcNow, AgentVersion = V1, AgentRuntime = "win-x64",
|
||
LastSeenUtc = online ? DateTimeOffset.UtcNow : DateTimeOffset.UtcNow.AddDays(-1),
|
||
});
|
||
db.AgentUpgrades.Add(new AgentUpgradeEntity
|
||
{
|
||
Id = Guid.NewGuid(), ClientId = clientId, FromVersion = V1, TargetVersion = V2,
|
||
PackageType = AgentPackageTypes.WindowsZip, PackageId = package.Id, Sha256 = package.Sha256,
|
||
Source = AgentUpgradeSources.Manual, State = AgentUpgradeStates.Queued, CreatedUtc = DateTimeOffset.UtcNow,
|
||
});
|
||
devices.Add(clientId);
|
||
}
|
||
|
||
await db.SaveChangesAsync();
|
||
});
|
||
return (package, devices);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task OnlineDevicesGetTheCommandAndOfflineOnesWait()
|
||
{
|
||
await fixture.ResetAsync();
|
||
var (package, online) = await QueueAsync(3);
|
||
var (_, offline) = await QueueAsync(2, online: false, prefix: "AWAY");
|
||
var sender = new RecordingUpgradeSender();
|
||
|
||
var pass = await fixture.Scheduler(sender).RunPassAsync(DateTimeOffset.UtcNow, CancellationToken.None);
|
||
|
||
Assert.Equal(3, pass.Sent);
|
||
Assert.Equal(online.Order(), sender.Sent.Select(s => s.ClientId).Order());
|
||
var command = sender.Sent[0].Command;
|
||
Assert.Equal(ApiRoutes.For.AgentPackageBySha(package.Sha256), command.DownloadUrl);
|
||
Assert.StartsWith("/", command.DownloadUrl);
|
||
Assert.Equal(package.Sha256, command.Sha256);
|
||
Assert.Equal(package.SizeBytes, command.SizeBytes);
|
||
Assert.Equal(V2, command.Version);
|
||
Assert.Equal(AgentPackageTypes.WindowsZip, command.PackageType);
|
||
Assert.Equal(600, command.HealthDeadlineSeconds);
|
||
Assert.Equal(AgentUpgradeScheduler.StartJitterSeconds, command.StartJitterSeconds);
|
||
Assert.False(command.Revert);
|
||
|
||
var sentRow = Assert.Single(await fixture.UpgradesOfAsync(online[0]));
|
||
Assert.Equal(AgentUpgradeStates.Sent, sentRow.State);
|
||
Assert.Equal(1, sentRow.Attempts);
|
||
Assert.NotNull(sentRow.SentUtc);
|
||
foreach (var id in offline)
|
||
{
|
||
Assert.Equal(AgentUpgradeStates.Queued, (await fixture.UpgradesOfAsync(id)).Single().State);
|
||
}
|
||
|
||
// Nothing is sent twice.
|
||
await fixture.Scheduler(sender).RunPassAsync(DateTimeOffset.UtcNow, CancellationToken.None);
|
||
Assert.Equal(3, sender.Sent.Count);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task ALargeQueueStartsInPacedBatchesWithinTheWindow()
|
||
{
|
||
await fixture.ResetAsync();
|
||
var (_, devices) = await QueueAsync(1000);
|
||
var sender = new RecordingUpgradeSender();
|
||
var scheduler = fixture.Scheduler(sender);
|
||
var windowTicks = AgentUpgradeSettingsStore.Defaults.StartWithinMinutes * 60 / 15;
|
||
|
||
var now = DateTimeOffset.UtcNow;
|
||
var batches = new List<int>();
|
||
while (sender.Sent.Count < devices.Count && batches.Count < 2 * windowTicks)
|
||
{
|
||
await fixture.TouchAllAsync(now);
|
||
batches.Add((await scheduler.RunPassAsync(now, CancellationToken.None)).Sent);
|
||
now += AgentUpgradeScheduler.Tick;
|
||
}
|
||
|
||
Assert.Equal(devices.Count, sender.Sent.Select(s => s.ClientId).Distinct().Count());
|
||
Assert.True(batches.Count <= windowTicks, $"took {batches.Count} ticks: {string.Join(',', batches)}");
|
||
Assert.All(batches, b => Assert.InRange(b, AgentUpgradeScheduler.MinimumBatch, 100));
|
||
}
|
||
|
||
[Fact]
|
||
public async Task ASmallQueueStillGoesAtLeastTenATick()
|
||
{
|
||
await fixture.ResetAsync();
|
||
var (_, devices) = await QueueAsync(25);
|
||
var sender = new RecordingUpgradeSender();
|
||
var scheduler = fixture.Scheduler(sender);
|
||
|
||
var now = DateTimeOffset.UtcNow;
|
||
var batches = new List<int>();
|
||
for (var tick = 0; tick < 3; tick++)
|
||
{
|
||
await fixture.TouchAllAsync(now);
|
||
batches.Add((await scheduler.RunPassAsync(now, CancellationToken.None)).Sent);
|
||
now += AgentUpgradeScheduler.Tick;
|
||
}
|
||
|
||
Assert.Equal([10, 10, 5], batches);
|
||
Assert.Equal(devices.Count, sender.Sent.Count);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task WhenMessagingIsDownTheRowGoesBackToTheQueue()
|
||
{
|
||
await fixture.ResetAsync();
|
||
var (_, devices) = await QueueAsync(1);
|
||
var sender = new RecordingUpgradeSender { Fail = true };
|
||
await fixture.Scheduler(sender).RunPassAsync(DateTimeOffset.UtcNow, CancellationToken.None);
|
||
|
||
var row = Assert.Single(await fixture.UpgradesOfAsync(devices[0]));
|
||
Assert.Equal(AgentUpgradeStates.Queued, row.State);
|
||
Assert.Equal(0, row.Attempts);
|
||
|
||
sender.Fail = false;
|
||
await fixture.Scheduler(sender).RunPassAsync(DateTimeOffset.UtcNow, CancellationToken.None);
|
||
Assert.Equal(AgentUpgradeStates.Sent, (await fixture.UpgradeAsync(row.Id)).State);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task EventsCarryTheUpgradeToItsOutcomeAndIntoDeviceHistory()
|
||
{
|
||
await fixture.ResetAsync();
|
||
var device = await fixture.SeedAgentAsync("EVENT-1", V1);
|
||
var stranger = await fixture.SeedAgentAsync("EVENT-2", V1);
|
||
var row = await fixture.SeedUpgradeAsync(device, V1, V2, AgentUpgradeStates.Sent);
|
||
|
||
Assert.False(await fixture.ApplyEventAsync(Guid.NewGuid(), device, AgentUpgradeStates.Downloading));
|
||
Assert.False(await fixture.ApplyEventAsync(row.Id, stranger, AgentUpgradeStates.Downloading));
|
||
Assert.False(await fixture.ApplyEventAsync(row.Id, device, AgentUpgradeStates.Downloading, subjectClientId: stranger));
|
||
Assert.False(await fixture.ApplyEventAsync(row.Id, device, AgentUpgradeStates.Cancelled));
|
||
|
||
Assert.True(await fixture.ApplyEventAsync(row.Id, device, AgentUpgradeStates.Downloading));
|
||
Assert.True(await fixture.ApplyEventAsync(row.Id, device, AgentUpgradeStates.Installing));
|
||
Assert.False(await fixture.ApplyEventAsync(row.Id, device, AgentUpgradeStates.Downloading)); // never backwards
|
||
Assert.True(await fixture.ApplyEventAsync(row.Id, device, AgentUpgradeStates.Succeeded, log: ["swapped", "healthy"]));
|
||
Assert.False(await fixture.ApplyEventAsync(row.Id, device, AgentUpgradeStates.Failed)); // finished stays
|
||
|
||
var done = await fixture.UpgradeAsync(row.Id);
|
||
Assert.Equal(AgentUpgradeStates.Succeeded, done.State);
|
||
Assert.NotNull(done.FinishedUtc);
|
||
Assert.Equal(["swapped", "healthy"], JsonDefaults.Deserialize<List<string>>(done.LastLogJson!));
|
||
var history = Assert.Single(await fixture.HistoryAsync(device));
|
||
Assert.Equal(DeviceHistory.AgentUpgraded, history.Action);
|
||
Assert.Equal($"{V1} → {V2}", history.Detail);
|
||
|
||
// The watchdog undoing an upgrade.
|
||
var again = await fixture.SeedUpgradeAsync(device, V2, V3, AgentUpgradeStates.Installing);
|
||
Assert.True(await fixture.ApplyEventAsync(again.Id, device, AgentUpgradeStates.RolledBack, AgentUpgradeReasons.HealthDeadline));
|
||
var rolledBack = await fixture.UpgradeAsync(again.Id);
|
||
Assert.Equal(AgentUpgradeStates.RolledBack, rolledBack.State);
|
||
Assert.Equal(AgentUpgradeReasons.HealthDeadline, rolledBack.Reason);
|
||
var last = (await fixture.HistoryAsync(device)).Last();
|
||
Assert.Equal(DeviceHistory.AgentRolledBack, last.Action);
|
||
Assert.Equal($"{V3} → {V2} · health-deadline", last.Detail);
|
||
|
||
// An operator's roll back that succeeds.
|
||
var operatorRollback = await fixture.SeedUpgradeAsync(device, V2, V1, AgentUpgradeStates.Sent, source: AgentUpgradeSources.Rollback);
|
||
Assert.True(await fixture.ApplyEventAsync(operatorRollback.Id, device, AgentUpgradeStates.Succeeded));
|
||
Assert.Equal(DeviceHistory.AgentRolledBack, (await fixture.HistoryAsync(device)).Last().Action);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task SilentDevicesFailWithNoReportAndALateOutcomeStillCounts()
|
||
{
|
||
await fixture.ResetAsync();
|
||
var now = DateTimeOffset.UtcNow;
|
||
var silent = await fixture.SeedAgentAsync("SILENT-1", V1);
|
||
var installing = await fixture.SeedAgentAsync("SILENT-2", V1);
|
||
var fresh = await fixture.SeedAgentAsync("SILENT-3", V1);
|
||
var stale = await fixture.SeedUpgradeAsync(silent, V1, V2, AgentUpgradeStates.Downloading,
|
||
configure: u => { u.SentUtc = now.AddMinutes(-40); u.LastEventUtc = now.AddMinutes(-31); });
|
||
var stuck = await fixture.SeedUpgradeAsync(installing, V1, V2, AgentUpgradeStates.Installing,
|
||
configure: u => { u.SentUtc = now.AddMinutes(-40); u.LastEventUtc = now.AddMinutes(-26); });
|
||
var recent = await fixture.SeedUpgradeAsync(fresh, V1, V2, AgentUpgradeStates.Installing,
|
||
configure: u => { u.SentUtc = now.AddMinutes(-30); u.LastEventUtc = now.AddMinutes(-20); });
|
||
|
||
await fixture.Scheduler(new RecordingUpgradeSender()).RunPassAsync(now, CancellationToken.None);
|
||
|
||
foreach (var id in new[] { stale.Id, stuck.Id })
|
||
{
|
||
var row = await fixture.UpgradeAsync(id);
|
||
Assert.Equal(AgentUpgradeStates.Failed, row.State);
|
||
Assert.Equal(AgentUpgradeReasons.NoReport, row.Reason);
|
||
}
|
||
|
||
Assert.Equal(AgentUpgradeStates.Installing, (await fixture.UpgradeAsync(recent.Id)).State);
|
||
Assert.Equal(DeviceHistory.AgentUpgradeFailed, Assert.Single(await fixture.HistoryAsync(silent)).Action);
|
||
|
||
// The device comes back and reports what happened after all.
|
||
Assert.True(await fixture.ApplyEventAsync(stuck.Id, installing, AgentUpgradeStates.Succeeded));
|
||
Assert.Equal(AgentUpgradeStates.Succeeded, (await fixture.UpgradeAsync(stuck.Id)).State);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task PresenceOnTheTargetVersionClosesTheUpgrade()
|
||
{
|
||
await fixture.ResetAsync();
|
||
var device = await fixture.SeedAgentAsync("PRESENCE-1", V1);
|
||
var row = await fixture.SeedUpgradeAsync(device, V1, V2, AgentUpgradeStates.Installing,
|
||
configure: u => u.SentUtc = DateTimeOffset.UtcNow);
|
||
var expired = await fixture.SeedUpgradeAsync(await fixture.SeedAgentAsync("EXPIRED-1", V1, online: false), V1, V2,
|
||
AgentUpgradeStates.Queued, configure: u => u.CreatedUtc = DateTimeOffset.UtcNow.AddDays(-8));
|
||
|
||
await fixture.WithDbAsync(db => db.Devices.Where(d => d.ClientId == device)
|
||
.ExecuteUpdateAsync(s => s.SetProperty(d => d.AgentVersion, V2)));
|
||
await fixture.Scheduler(new RecordingUpgradeSender()).RunPassAsync(DateTimeOffset.UtcNow, CancellationToken.None);
|
||
|
||
var done = await fixture.UpgradeAsync(row.Id);
|
||
Assert.Equal(AgentUpgradeStates.Succeeded, done.State);
|
||
Assert.Equal(AgentUpgradeService.PresenceConfirmed, done.Detail);
|
||
Assert.Equal(DeviceHistory.AgentUpgraded, Assert.Single(await fixture.HistoryAsync(device)).Action);
|
||
|
||
var stale = await fixture.UpgradeAsync(expired.Id);
|
||
Assert.Equal(AgentUpgradeStates.Cancelled, stale.State);
|
||
Assert.Equal(AgentUpgradeReasons.Expired, stale.Reason);
|
||
|
||
// The watchdog's later verdict wins over what presence suggested.
|
||
Assert.True(await fixture.ApplyEventAsync(row.Id, device, AgentUpgradeStates.RolledBack, AgentUpgradeReasons.Crashed));
|
||
Assert.Equal(AgentUpgradeStates.RolledBack, (await fixture.UpgradeAsync(row.Id)).State);
|
||
}
|
||
}
|
||
|
||
/// <summary>Automatic Upgrades.</summary>
|
||
public class AutomaticAgentUpgradeTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
|
||
{
|
||
[Fact]
|
||
public async Task OnlineOutdatedDevicesOutsideExcludedGroupsAreKeptOnTheNewest()
|
||
{
|
||
await fixture.ResetAsync();
|
||
await fixture.SeedPackageAsync(V1);
|
||
await fixture.SeedPackageAsync(V2);
|
||
|
||
var outdated = await fixture.SeedAgentAsync("AUTO-OUTDATED", V1);
|
||
var ahead = await fixture.SeedAgentAsync("AUTO-AHEAD", V3);
|
||
var current = await fixture.SeedAgentAsync("AUTO-CURRENT", V2);
|
||
var offline = await fixture.SeedAgentAsync("AUTO-OFFLINE", V1, online: false);
|
||
var excluded = await fixture.SeedAgentAsync("AUTO-EXCLUDED", V1);
|
||
var failedBefore = await fixture.SeedAgentAsync("AUTO-FAILED", V1);
|
||
var rolledBefore = await fixture.SeedAgentAsync("AUTO-ROLLED", V1);
|
||
var failedOlder = await fixture.SeedAgentAsync("AUTO-FAILED-OLD", V1);
|
||
await fixture.SeedUpgradeAsync(failedBefore, V1, V2, AgentUpgradeStates.Failed, AgentUpgradeReasons.Download);
|
||
await fixture.SeedUpgradeAsync(rolledBefore, V1, V2, AgentUpgradeStates.RolledBack, AgentUpgradeReasons.HealthDeadline);
|
||
await fixture.SeedUpgradeAsync(failedOlder, "2026.1.1.1", V1, AgentUpgradeStates.Failed, AgentUpgradeReasons.Download);
|
||
|
||
// Excluded through a folder: nested membership counts.
|
||
var folderId = await fixture.WithDbAsync(async db =>
|
||
{
|
||
var folder = new DeviceGroupEntity { Id = Guid.NewGuid(), Name = $"ring0-{Guid.NewGuid():N}", Kind = GroupKind.Folder, CreatedUtc = DateTimeOffset.UtcNow, UpdatedUtc = DateTimeOffset.UtcNow };
|
||
var child = new DeviceGroupEntity { Id = Guid.NewGuid(), ParentId = folder.Id, Name = $"pilot-{Guid.NewGuid():N}", Kind = GroupKind.Static, CreatedUtc = DateTimeOffset.UtcNow, UpdatedUtc = DateTimeOffset.UtcNow };
|
||
db.DeviceGroups.AddRange(folder, child);
|
||
db.DeviceGroupMembers.Add(new DeviceGroupMemberEntity { GroupId = child.Id, ClientId = excluded, AddedUtc = DateTimeOffset.UtcNow });
|
||
await db.SaveChangesAsync();
|
||
return folder.Id;
|
||
});
|
||
|
||
var sender = new RecordingUpgradeSender();
|
||
var scheduler = fixture.Scheduler(sender);
|
||
|
||
// Off by default: nothing happens.
|
||
await scheduler.RunPassAsync(DateTimeOffset.UtcNow, CancellationToken.None);
|
||
Assert.Empty(sender.Sent);
|
||
|
||
await fixture.SaveSettingsAsync(AgentUpgradeSettingsStore.Defaults with { AutomaticUpgrades = true, ExcludedGroupIds = [folderId] });
|
||
var pass = await scheduler.RunPassAsync(DateTimeOffset.UtcNow, CancellationToken.None);
|
||
|
||
Assert.Equal(2, pass.Queued);
|
||
Assert.Equal(new[] { outdated, failedOlder }.Order(), sender.Sent.Select(s => s.ClientId).Order());
|
||
var row = (await fixture.UpgradesOfAsync(outdated)).Single();
|
||
Assert.Equal(AgentUpgradeSources.Automatic, row.Source);
|
||
Assert.Equal(AgentUpgradeScheduler.AutomaticRequester, row.RequestedBy);
|
||
Assert.Equal(V2, row.TargetVersion);
|
||
foreach (var untouched in new[] { ahead, current, offline, excluded })
|
||
{
|
||
Assert.Empty(await fixture.UpgradesOfAsync(untouched));
|
||
}
|
||
|
||
Assert.Single(await fixture.UpgradesOfAsync(failedBefore));
|
||
Assert.Single(await fixture.UpgradesOfAsync(rolledBefore));
|
||
|
||
// While it runs, the device is not queued again.
|
||
await scheduler.RunPassAsync(DateTimeOffset.UtcNow, CancellationToken.None);
|
||
Assert.Single(await fixture.UpgradesOfAsync(outdated));
|
||
}
|
||
}
|
||
|
||
/// <summary>Settings › Agent Upgrades.</summary>
|
||
public class AgentUpgradeSettingsTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
|
||
{
|
||
[Fact]
|
||
public async Task SettingsAreValidatedSavedAndAudited()
|
||
{
|
||
await fixture.ResetAsync();
|
||
using var admin = await fixture.SignedInAsync("upgrade-settings-admin");
|
||
|
||
var defaults = await (await admin.GetAsync(ApiRoutes.AgentUpgradeSettings)).ReadAsync<AgentUpgradeSettingsDto>();
|
||
Assert.False(defaults.AutomaticUpgrades);
|
||
Assert.Equal(3, defaults.StartWithinMinutes);
|
||
Assert.Equal(10, defaults.HealthDeadlineMinutes);
|
||
Assert.Equal(5, defaults.KeepVersions);
|
||
Assert.Empty(defaults.ExcludedGroupIds);
|
||
|
||
AgentUpgradeSettingsDto[] invalid =
|
||
[
|
||
defaults with { StartWithinMinutes = 0 },
|
||
defaults with { StartWithinMinutes = 31 },
|
||
defaults with { HealthDeadlineMinutes = 1 },
|
||
defaults with { HealthDeadlineMinutes = 61 },
|
||
defaults with { KeepVersions = 1 },
|
||
defaults with { KeepVersions = 51 },
|
||
defaults with { ExcludedGroupIds = [Guid.NewGuid()] },
|
||
];
|
||
foreach (var settings in invalid)
|
||
{
|
||
var refused = await admin.PutAsJsonAsync(ApiRoutes.AgentUpgradeSettings, settings, JsonDefaults.Options);
|
||
Assert.Equal(HttpStatusCode.BadRequest, refused.StatusCode);
|
||
}
|
||
|
||
var groupId = await fixture.WithDbAsync(async db =>
|
||
{
|
||
var group = new DeviceGroupEntity { Id = Guid.NewGuid(), Name = $"no-auto-{Guid.NewGuid():N}", Kind = GroupKind.Static, CreatedUtc = DateTimeOffset.UtcNow, UpdatedUtc = DateTimeOffset.UtcNow };
|
||
db.DeviceGroups.Add(group);
|
||
await db.SaveChangesAsync();
|
||
return group.Id;
|
||
});
|
||
|
||
var wanted = new AgentUpgradeSettingsDto(true, 30, 60, [groupId], 2);
|
||
var saved = await admin.PutAsJsonAsync(ApiRoutes.AgentUpgradeSettings, wanted, JsonDefaults.Options);
|
||
Assert.Equal(HttpStatusCode.OK, saved.StatusCode);
|
||
var stored = await saved.ReadAsync<AgentUpgradeSettingsDto>();
|
||
Assert.True(stored.AutomaticUpgrades);
|
||
Assert.Equal(30, stored.StartWithinMinutes);
|
||
Assert.Equal([groupId], stored.ExcludedGroupIds);
|
||
|
||
// A stale If-Match is refused.
|
||
using var stalePut = new HttpRequestMessage(HttpMethod.Put, ApiRoutes.AgentUpgradeSettings)
|
||
{
|
||
Content = JsonContent.Create(defaults, options: JsonDefaults.Options),
|
||
};
|
||
stalePut.Headers.TryAddWithoutValidation("If-Match", "\"stale\"");
|
||
Assert.Equal(HttpStatusCode.PreconditionFailed, (await admin.SendAsync(stalePut)).StatusCode);
|
||
|
||
var audit = await fixture.WithDbAsync(db => db.AuditEvents
|
||
.Where(e => e.Action == "agent-upgrade-settings-updated")
|
||
.OrderByDescending(e => e.Id)
|
||
.FirstAsync());
|
||
Assert.Contains("startWithinMinutes: 3 → 30", audit.Detail);
|
||
|
||
using var viewer = await fixture.SignedInAsync("upgrade-settings-viewer", "Viewer");
|
||
Assert.Equal(HttpStatusCode.OK, (await viewer.GetAsync(ApiRoutes.AgentUpgradeSettings)).StatusCode);
|
||
Assert.Equal(HttpStatusCode.Forbidden,
|
||
(await viewer.PutAsJsonAsync(ApiRoutes.AgentUpgradeSettings, defaults, JsonDefaults.Options)).StatusCode);
|
||
Assert.Equal(HttpStatusCode.Forbidden, (await viewer.PostAsJsonAsync(ApiRoutes.AgentUpgrades,
|
||
new StartAgentUpgradeRequest(["x"]), JsonDefaults.Options)).StatusCode);
|
||
}
|
||
}
|