b3675112be
An MSI install hands the MSI over with the kept MSI of its version (or the server's, downloaded, checked and kept; or none, said so), keeps what it brought, refuses the zip, and is refused by a portable install; a kept MSI whose bytes are not its folder's hash is not used; an MSI of another version or not the agent's fails as package; msi.json makes it busy; kept packages stay at the newest three plus those still needed. The outcome reporter passes an MSI run's own detail on. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
270 lines
10 KiB
C#
270 lines
10 KiB
C#
using System.Net;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using Agent.Upgrade;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using Shared.Contracts.Messages;
|
|
using Shared.Contracts.Models;
|
|
using Shared.Contracts.Serialization;
|
|
using Shared.Infrastructure.Routing;
|
|
using Xunit;
|
|
|
|
namespace Agent.Tests;
|
|
|
|
/// <summary>An MSI is a file whose text is "msi <version>"; anything else is not the agent's MSI.</summary>
|
|
internal sealed class FakeMsiInspector : IMsiInspector
|
|
{
|
|
public string Install { get; set; } = AgentInstallKinds.Msi;
|
|
|
|
public string DetectInstall(string installDirectory) => Install;
|
|
|
|
public string? ReadAgentVersion(string msiPath)
|
|
{
|
|
var text = File.Exists(msiPath) ? File.ReadAllText(msiPath) : "";
|
|
return text.StartsWith("msi ", StringComparison.Ordinal) ? text["msi ".Length..] : null;
|
|
}
|
|
}
|
|
|
|
public sealed class AgentMsiUpgradeTests : IDisposable
|
|
{
|
|
private const string Current = "1.3.0";
|
|
private const string Target = "1.4.0";
|
|
private const string MsiUrl = "/api/agent/packages/by-sha/target";
|
|
private const string RollbackUrl = "/api/agent/packages/by-sha/rollback";
|
|
|
|
private readonly string root = Path.Combine(Path.GetTempPath(), "executer-msi-upgrade-tests", Guid.NewGuid().ToString("N"));
|
|
private readonly UpgradeFolders folders;
|
|
private readonly RecordingEvents events = new();
|
|
private readonly FakeWatchdog watchdog = new();
|
|
private readonly FakeMsiInspector inspector = new();
|
|
private readonly List<string> requests = [];
|
|
private byte[] target = Encoding.UTF8.GetBytes($"msi {Target}");
|
|
private readonly byte[] previous = Encoding.UTF8.GetBytes($"msi {Current}");
|
|
private WatchdogHandover? handedOver;
|
|
|
|
public AgentMsiUpgradeTests()
|
|
{
|
|
folders = new UpgradeFolders(Path.Combine(root, "data"), Path.Combine(root, "install"));
|
|
Directory.CreateDirectory(folders.InstallDirectory);
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
try
|
|
{
|
|
Directory.Delete(root, recursive: true);
|
|
}
|
|
catch (IOException)
|
|
{
|
|
}
|
|
}
|
|
|
|
private static string Sha(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes));
|
|
|
|
private AgentUpgradeHandler CreateHandler(string install = AgentInstallKinds.Msi)
|
|
{
|
|
inspector.Install = install;
|
|
return new AgentUpgradeHandler(new AgentUpgradeContext
|
|
{
|
|
Folders = folders,
|
|
ClientId = "client-1",
|
|
CurrentVersion = Current,
|
|
RuntimeIdentifier = "win-x64",
|
|
CanSelfUpgrade = true,
|
|
InstallKind = install,
|
|
MsiInspector = inspector,
|
|
ServerUrl = ServerUrl.Parse("https://control.example.com"),
|
|
CreateHttpHandler = () => new Stub(request =>
|
|
{
|
|
var path = request.RequestUri!.AbsolutePath;
|
|
requests.Add(path);
|
|
return new HttpResponseMessage(HttpStatusCode.OK)
|
|
{
|
|
Content = new ByteArrayContent(path.EndsWith("rollback", StringComparison.Ordinal) ? previous : target),
|
|
};
|
|
}),
|
|
Delay = (_, _) =>
|
|
{
|
|
// The watchdog takes the hand-over at its first look.
|
|
handedOver ??= WatchdogFileStore.Read(folders.Handover, WatchdogJsonContext.Default.WatchdogHandover);
|
|
File.Delete(folders.Handover);
|
|
return Task.CompletedTask;
|
|
},
|
|
RandomMilliseconds = max => max,
|
|
Gate = new UpgradeGate(),
|
|
}, events, watchdog, NullLogger.Instance);
|
|
}
|
|
|
|
private AgentUpgradeCommandPayload Command(bool rollbackFields = false, string packageType = AgentPackageTypes.Msi)
|
|
=> new(Guid.NewGuid(), Target, packageType, MsiUrl, Sha(target), target.Length, Revert: false, HealthDeadlineSeconds: 600,
|
|
RollbackVersion: rollbackFields ? Current : null,
|
|
RollbackDownloadUrl: rollbackFields ? RollbackUrl : null,
|
|
RollbackSha256: rollbackFields ? Sha(previous) : null,
|
|
RollbackSizeBytes: rollbackFields ? previous.Length : null);
|
|
|
|
/// <summary>The MSI the device was installed from, as the installer's KeepInstallerPackage leaves it (no description file).</summary>
|
|
private string KeepInstalled(byte[] bytes, string? folderName = null)
|
|
{
|
|
var folder = Path.Combine(folders.KeptPackages, folderName ?? Sha(bytes));
|
|
Directory.CreateDirectory(folder);
|
|
var path = Path.Combine(folder, "ExecuteR-Agent.msi");
|
|
File.WriteAllBytes(path, bytes);
|
|
return path;
|
|
}
|
|
|
|
private AgentUpgradeEventPayload Last => events.Published[^1];
|
|
|
|
[Fact]
|
|
public async Task AnMsiInstallHandsTheMsiOverWithTheKeptMsiOfItsVersionToRollBackTo()
|
|
{
|
|
KeepInstalled(previous);
|
|
var command = Command();
|
|
|
|
await CreateHandler().RunAsync(command, CancellationToken.None);
|
|
|
|
Assert.Equal([MsiUrl], requests);
|
|
Assert.Equal(AgentUpgradeStates.Installing, Last.State);
|
|
Assert.NotNull(handedOver);
|
|
Assert.Equal(WatchdogHandoverKinds.Msi, handedOver.Kind);
|
|
Assert.Empty(handedOver.Files);
|
|
Assert.Equal(Current, handedOver.FromVersion);
|
|
|
|
var msi = handedOver.Msi!;
|
|
Assert.Equal(Path.Combine(folders.Msi, "ExecuteR-Agent-1.4.0.msi"), msi.Path);
|
|
Assert.True(Path.IsPathFullyQualified(msi.Path));
|
|
Assert.Equal(Sha(target), msi.Sha256);
|
|
Assert.Equal(target.Length, msi.Size);
|
|
|
|
var rollback = handedOver.RollbackMsi!;
|
|
Assert.Equal(Path.Combine(folders.MsiRollback, "ExecuteR-Agent-1.3.0.msi"), rollback.Path);
|
|
Assert.Equal(Sha(previous), rollback.Sha256);
|
|
Assert.Equal(previous, File.ReadAllBytes(rollback.Path));
|
|
Assert.Equal(Current, handedOver.RollbackVersion);
|
|
|
|
// The MSI the upgrade brought is kept for the next one's rollback.
|
|
Assert.Equal(target, File.ReadAllBytes(Path.Combine(folders.KeptPackages, Sha(target), "ExecuteR-Agent-1.4.0.msi")));
|
|
Assert.Equal(folders.Msi, watchdog.EnsuredFor);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task WithoutAKeptMsiTheServersMsiOfTheRunningVersionIsDownloadedCheckedAndKept()
|
|
{
|
|
await CreateHandler().RunAsync(Command(rollbackFields: true), CancellationToken.None);
|
|
|
|
Assert.Equal([MsiUrl, RollbackUrl], requests);
|
|
Assert.Equal(Sha(previous), handedOver!.RollbackMsi!.Sha256);
|
|
Assert.Equal(Current, handedOver.RollbackVersion);
|
|
Assert.True(File.Exists(Path.Combine(folders.KeptPackages, Sha(previous), "ExecuteR-Agent-1.3.0.msi")));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task WithNoMsiToGoBackToTheUpgradeGoesOnAndSaysItCannotRollBack()
|
|
{
|
|
await CreateHandler().RunAsync(Command(), CancellationToken.None);
|
|
|
|
Assert.NotNull(handedOver);
|
|
Assert.Null(handedOver.RollbackMsi);
|
|
Assert.Null(handedOver.RollbackVersion);
|
|
Assert.Equal(AgentUpgradeStates.Installing, Last.State);
|
|
Assert.Contains("cannot be rolled back automatically", Last.Detail, StringComparison.Ordinal);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AKeptMsiWhoseBytesDoNotMatchItsFolderIsNotUsed()
|
|
{
|
|
KeepInstalled(previous, folderName: new string('a', 64));
|
|
|
|
await CreateHandler().RunAsync(Command(rollbackFields: true), CancellationToken.None);
|
|
|
|
Assert.Equal([MsiUrl, RollbackUrl], requests);
|
|
Assert.NotNull(handedOver!.RollbackMsi);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task APortableInstallRefusesTheMsi()
|
|
{
|
|
await CreateHandler(AgentInstallKinds.Portable).RunAsync(Command(), CancellationToken.None);
|
|
|
|
Assert.Equal(AgentUpgradeStates.Failed, Last.State);
|
|
Assert.Equal(AgentUpgradeReasons.Unsupported, Last.Reason);
|
|
Assert.Empty(requests);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AnMsiInstallRefusesThePortableZip()
|
|
{
|
|
await CreateHandler().RunAsync(Command(packageType: AgentPackageTypes.WindowsZip), CancellationToken.None);
|
|
|
|
Assert.Equal(AgentUpgradeReasons.Unsupported, Last.Reason);
|
|
Assert.Contains("through the MSI", Last.Detail, StringComparison.Ordinal);
|
|
Assert.Empty(requests);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AnMsiOfAnotherVersionFailsAsPackage()
|
|
{
|
|
target = Encoding.UTF8.GetBytes("msi 1.5.0");
|
|
|
|
await CreateHandler().RunAsync(Command(), CancellationToken.None);
|
|
|
|
Assert.Equal(AgentUpgradeReasons.Package, Last.Reason);
|
|
Assert.Null(handedOver);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task APackageThatIsNotTheAgentsMsiFailsAsPackage()
|
|
{
|
|
target = Encoding.UTF8.GetBytes("PK zip bytes");
|
|
|
|
await CreateHandler().RunAsync(Command(), CancellationToken.None);
|
|
|
|
Assert.Equal(AgentUpgradeReasons.Package, Last.Reason);
|
|
Assert.False(File.Exists(folders.Handover));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task AnMsiRunUnderWayMakesTheAgentBusy()
|
|
{
|
|
Directory.CreateDirectory(folders.Root);
|
|
File.WriteAllText(folders.MsiJournal, "{}");
|
|
|
|
await CreateHandler().RunAsync(Command(), CancellationToken.None);
|
|
|
|
Assert.Equal(AgentUpgradeReasons.Busy, Last.Reason);
|
|
Assert.Empty(requests);
|
|
}
|
|
|
|
[Fact]
|
|
public void KeptPackagesStayAtTheNewestThreePlusTheOnesStillNeeded()
|
|
{
|
|
var kept = new KeptMsiPackages(folders.KeptPackages, inspector, NullLogger.Instance);
|
|
var source = Path.Combine(root, "source.msi");
|
|
var start = DateTime.UtcNow.AddHours(-10);
|
|
string[] versions = ["1.0.0", "1.1.0", "1.2.0", Current, Target];
|
|
for (var i = 0; i < versions.Length; i++)
|
|
{
|
|
var bytes = Encoding.UTF8.GetBytes($"msi {versions[i]}");
|
|
File.WriteAllBytes(source, bytes);
|
|
kept.Keep(source, Sha(bytes), versions[i], "1.0.0");
|
|
var folder = Path.Combine(folders.KeptPackages, Sha(bytes));
|
|
foreach (var file in Directory.GetFiles(folder))
|
|
{
|
|
File.SetLastWriteTimeUtc(file, start.AddHours(i));
|
|
}
|
|
|
|
Directory.SetLastWriteTimeUtc(folder, start.AddHours(i));
|
|
}
|
|
|
|
var left = Directory.GetDirectories(folders.KeptPackages).Select(d => File.ReadAllText(Directory.GetFiles(d, "*.msi").Single())).Order().ToList();
|
|
Assert.Equal(["msi 1.0.0", "msi 1.2.0", $"msi {Current}", $"msi {Target}"], left);
|
|
Assert.Equal(Target, kept.Find(Target)!.Version);
|
|
Assert.Null(kept.Find("1.1.0"));
|
|
}
|
|
|
|
private sealed class Stub(Func<HttpRequestMessage, HttpResponseMessage> respond) : HttpMessageHandler
|
|
{
|
|
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
|
=> Task.FromResult(respond(request));
|
|
}
|
|
}
|