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>
170 lines
7.9 KiB
C#
170 lines
7.9 KiB
C#
using Backend.Data;
|
|
using Backend.Jobs;
|
|
using Backend.Upgrades;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using Shared.Contracts.Api;
|
|
using Shared.Contracts.Messages;
|
|
using Shared.Contracts.Models;
|
|
using Shared.Contracts.Serialization;
|
|
|
|
namespace Backend.Tests;
|
|
|
|
/// <summary>Records upgrade commands instead of publishing them (or refuses them, as NATS being down would).</summary>
|
|
internal sealed class RecordingUpgradeSender : IAgentUpgradeSender
|
|
{
|
|
public List<(string ClientId, AgentUpgradeCommandPayload Command)> Sent { get; } = [];
|
|
|
|
public bool Fail { get; set; }
|
|
|
|
public Task<bool> DispatchAgentUpgradeAsync(string clientId, AgentUpgradeCommandPayload command, CancellationToken cancellationToken)
|
|
{
|
|
if (Fail)
|
|
{
|
|
return Task.FromResult(false);
|
|
}
|
|
|
|
lock (Sent)
|
|
{
|
|
Sent.Add((clientId, command));
|
|
}
|
|
|
|
return Task.FromResult(true);
|
|
}
|
|
}
|
|
|
|
/// <summary>Seeding and driving helpers for the agent upgrade tests.</summary>
|
|
internal static class AgentUpgradeTestKit
|
|
{
|
|
public const string V1 = "2026.10.20.1200";
|
|
public const string V2 = "2026.10.23.1400";
|
|
public const string V3 = "2026.10.30.0900";
|
|
|
|
/// <summary>Removes every upgrade, package and device, so each test starts from an empty fleet.</summary>
|
|
public static Task ResetAsync(this BackendTestFixture fixture)
|
|
=> fixture.WithDbAsync(async db =>
|
|
{
|
|
await db.AgentUpgrades.ExecuteDeleteAsync();
|
|
await db.AgentPackages.ExecuteDeleteAsync();
|
|
await db.DeviceGroupMembers.ExecuteDeleteAsync();
|
|
await db.DeviceInventory.ExecuteDeleteAsync();
|
|
await db.Devices.ExecuteDeleteAsync();
|
|
await db.AppSettings.Where(s => s.Key == AgentUpgradeSettingsStore.Key || s.Key == Backend.Enrollment.AgentDownloadAccess.PublicKey).ExecuteDeleteAsync();
|
|
fixture.Services.GetRequiredService<AgentUpgradeSettingsStore>().Invalidate();
|
|
});
|
|
|
|
/// <summary>Public agent downloads on or off (off is the default).</summary>
|
|
public static async Task SetPublicDownloadsAsync(this BackendTestFixture fixture, bool on)
|
|
{
|
|
using var scope = fixture.Services.CreateScope();
|
|
await scope.ServiceProvider.GetRequiredService<Backend.Enrollment.AgentDownloadAccess>().SetPublicAsync(on, "test", CancellationToken.None);
|
|
}
|
|
|
|
/// <summary>Imports a package built from <paramref name="content"/> through the catalog, as the sync does.</summary>
|
|
public static async Task<AgentPackageEntity> SeedPackageAsync(
|
|
this BackendTestFixture fixture, string version, string packageType = AgentPackageTypes.WindowsZip, string? content = null)
|
|
{
|
|
var source = Path.Combine(fixture.DataPath, "incoming", Guid.NewGuid().ToString("N"), "Agent.zip");
|
|
Directory.CreateDirectory(Path.GetDirectoryName(source)!);
|
|
await File.WriteAllTextAsync(source, content ?? $"agent {version} {packageType}");
|
|
using var scope = fixture.Services.CreateScope();
|
|
var package = await scope.ServiceProvider.GetRequiredService<AgentCatalogService>()
|
|
.ImportAsync(packageType, source, version, CancellationToken.None);
|
|
return package ?? throw new InvalidOperationException($"{version} {packageType} was not imported");
|
|
}
|
|
|
|
public static async Task<string> SeedAgentAsync(
|
|
this BackendTestFixture fixture, string hostname, string? version, string? runtime = "win-x64",
|
|
bool online = true, string? osCaption = null, string? install = null)
|
|
{
|
|
var clientId = await fixture.SeedDeviceAsync(hostname, online);
|
|
await fixture.WithDbAsync(async db =>
|
|
{
|
|
var device = await db.Devices.SingleAsync(d => d.ClientId == clientId);
|
|
device.AgentVersion = version;
|
|
device.AgentRuntime = runtime;
|
|
device.OsCaption = osCaption;
|
|
device.AgentInstall = install;
|
|
await db.SaveChangesAsync();
|
|
});
|
|
return clientId;
|
|
}
|
|
|
|
public static Task<AgentUpgradeEntity> SeedUpgradeAsync(
|
|
this BackendTestFixture fixture, string clientId, string from, string target, string state,
|
|
string? reason = null, string source = AgentUpgradeSources.Manual, Guid? packageId = null,
|
|
Action<AgentUpgradeEntity>? configure = null)
|
|
=> fixture.WithDbAsync(async db =>
|
|
{
|
|
var row = new AgentUpgradeEntity
|
|
{
|
|
Id = Guid.NewGuid(),
|
|
ClientId = clientId,
|
|
FromVersion = from,
|
|
TargetVersion = target,
|
|
PackageType = AgentPackageTypes.WindowsZip,
|
|
PackageId = packageId,
|
|
Source = source,
|
|
State = state,
|
|
Reason = reason,
|
|
CreatedUtc = DateTimeOffset.UtcNow,
|
|
FinishedUtc = AgentUpgradeStates.Finished.Contains(state) ? DateTimeOffset.UtcNow : null,
|
|
};
|
|
configure?.Invoke(row);
|
|
db.AgentUpgrades.Add(row);
|
|
await db.SaveChangesAsync();
|
|
return row;
|
|
});
|
|
|
|
public static Task<AgentUpgradeEntity> UpgradeAsync(this BackendTestFixture fixture, Guid id)
|
|
=> fixture.WithDbAsync(db => db.AgentUpgrades.AsNoTracking().SingleAsync(u => u.Id == id));
|
|
|
|
public static Task<List<AgentUpgradeEntity>> UpgradesOfAsync(this BackendTestFixture fixture, string clientId)
|
|
=> fixture.WithDbAsync(db => db.AgentUpgrades.AsNoTracking().Where(u => u.ClientId == clientId).ToListAsync());
|
|
|
|
public static Task<List<AuditEventEntity>> HistoryAsync(this BackendTestFixture fixture, string clientId)
|
|
=> fixture.WithDbAsync(db => db.AuditEvents.AsNoTracking()
|
|
.Where(e => e.ClientId == clientId && e.Category == "device")
|
|
.OrderBy(e => e.Id)
|
|
.ToListAsync());
|
|
|
|
public static Task SaveSettingsAsync(this BackendTestFixture fixture, AgentUpgradeSettingsDto settings)
|
|
=> fixture.WithDbAsync(async db =>
|
|
{
|
|
var row = await Backend.Auth.SettingsDocuments.LoadAsync(db, AgentUpgradeSettingsStore.Key, CancellationToken.None);
|
|
Backend.Auth.SettingsDocuments.Stage(db, row, AgentUpgradeSettingsStore.Key, null, settings, "test", always: true);
|
|
await db.SaveChangesAsync();
|
|
fixture.Services.GetRequiredService<AgentUpgradeSettingsStore>().Invalidate();
|
|
});
|
|
|
|
public static AgentUpgradeScheduler Scheduler(this BackendTestFixture fixture, IAgentUpgradeSender sender)
|
|
=> new(fixture.Services.GetRequiredService<IServiceScopeFactory>(), sender, NullLogger<AgentUpgradeScheduler>.Instance);
|
|
|
|
/// <summary>Keeps every device online as of <paramref name="now"/> (a simulated clock).</summary>
|
|
public static Task TouchAllAsync(this BackendTestFixture fixture, DateTimeOffset now, params string[] except)
|
|
=> fixture.WithDbAsync(async db =>
|
|
{
|
|
var excluded = except.ToList();
|
|
await db.Devices.Where(d => !excluded.Contains(d.ClientId))
|
|
.ExecuteUpdateAsync(s => s.SetProperty(d => d.LastSeenUtc, now));
|
|
});
|
|
|
|
public static async Task<bool> ApplyEventAsync(
|
|
this BackendTestFixture fixture, Guid upgradeId, string clientId, string state, string? reason = null,
|
|
string? subjectClientId = null, IReadOnlyList<string>? log = null)
|
|
{
|
|
using var scope = fixture.Services.CreateScope();
|
|
return await scope.ServiceProvider.GetRequiredService<AgentUpgradeService>().ApplyEventAsync(
|
|
subjectClientId ?? clientId,
|
|
new AgentUpgradeEventPayload(upgradeId, clientId, state, reason, null, null, null, log, DateTimeOffset.UtcNow),
|
|
CancellationToken.None);
|
|
}
|
|
|
|
public static async Task<T> ReadAsync<T>(this HttpResponseMessage response)
|
|
{
|
|
var body = await response.Content.ReadAsStringAsync();
|
|
return JsonDefaults.Deserialize<T>(body) ?? throw new InvalidOperationException(body);
|
|
}
|
|
}
|