Files
ExecuteR/tests/Backend.Tests/CertificateTrustScriptTests.cs
Alphaeus Mote 0b85bd5e8a feat(install): idempotent install scripts that upgrade or repair a failed agent [skip ci]
Every served install script (Windows/WinPE PowerShell 5.1, Linux and macOS
bash) now looks at the device before acting: a healthy, current agent
enrolled with this server is left alone (Already Installed), an older one is
upgraded in place with its enrollment kept, a failed one (service missing,
disabled, stopped or crash-looping, watchdog down, binary missing or broken,
Windows Installer registration or cache gone) is restarted through the
agent's own initialize and, if that does not help, reinstalled (MSI repair
REINSTALL=ALL REINSTALLMODE=vamus, cache restored from the kept package,
uninstall+install with ProgramData and the registry key set aside as a last
resort; Linux/macOS move files in one by one and re-register the unit or
daemon). The bootstrap token is used only when there is no usable credential
or the agent points at another server, never printed, and masked out of
failure messages. One setup at a time, leftovers of interrupted runs cleared.
Each run ends with one outcome line and exits 1 on failure.

The agent's status verb now prints a JSON line with version, server URL,
credential state (valid/missing/unreadable/other-device) and whether a
bootstrap token is pending, which the scripts read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 09:20:40 -05:00

166 lines
7.8 KiB
C#

using System.Diagnostics;
using System.Net;
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text.Json;
using Backend.Enrollment;
using Xunit;
namespace Backend.Tests;
/// <summary>The install scripts trust the server as the agent does: normal validation, then the CA pinned to the token.</summary>
public class CertificateTrustScriptTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
{
private const string Fingerprint = "0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a69788796a5b4c3d2e1f0";
[Theory]
[InlineData(null)]
[InlineData("zip")]
public async Task APinnedTokenMakesTheWindowsDownloadValidateFirstAndPinOnlyOnFailure(string? type)
{
using var client = fixture.CreateClient();
var url = $"/api/enrollment/install?token=secret.{Fingerprint}" + (type is null ? "" : $"&type={type}");
var script = await (await client.GetAsync(url)).Content.ReadAsStringAsync();
// The one-liner's accept-any is undone before anything is downloaded.
var reset = script.IndexOf("ServerCertificateValidationCallback = $null", StringComparison.Ordinal);
var firstDownload = script.IndexOf("Save-ExecuteRFile $", StringComparison.Ordinal);
Assert.True(reset >= 0 && reset < firstDownload, "validation is restored before the first download");
Assert.Contains($"$global:ExecuteRCaPin = '{Fingerprint}'", script);
Assert.Contains("TrustFailure", script);
Assert.Contains("/api/enrollment/ca", script);
Assert.Contains("-eq $global:ExecuteRCa.Anchor", script);
}
[Fact]
public async Task APinnedTokenMakesTheUnixDownloadValidateFirstAndPinOnlyOnFailure()
{
using var client = fixture.CreateClient();
var script = await (await client.GetAsync($"/api/enrollment/install?token=secret.{Fingerprint}&type=linux")).Content.ReadAsStringAsync();
Assert.Contains($"pin='{Fingerprint}'", script);
Assert.Contains("download \"$pkg\" \"$tmp/agent.zip\"", script);
Assert.Contains("curl -fsSL \"$1\" -o \"$2\" || rc=$?", script);
Assert.Contains("--cacert \"$cafile\"", script);
Assert.Contains("openssl verify -CAfile \"$anchor\"", script);
Assert.DoesNotContain("curl -fsSLk \"$pkg\"", script);
Assert.DoesNotContain("\r", script);
}
[Fact]
public void TheTokenFingerprintIsReadAsTheAgentReadsIt()
{
Assert.Equal(Fingerprint, InstallEndpoints.TokenFingerprint($"abc.{Fingerprint.ToUpperInvariant()}"));
Assert.Null(InstallEndpoints.TokenFingerprint("abc"));
Assert.Null(InstallEndpoints.TokenFingerprint("abc.not-hex"));
Assert.Null(InstallEndpoints.TokenFingerprint($"abc.{Fingerprint}00"));
}
[Fact]
public async Task WindowsPowerShellHashesTheSubjectPublicKeyInfoAsDotNetDoes()
{
var powershell = Path.Combine(Environment.SystemDirectory, @"WindowsPowerShell\v1.0\powershell.exe");
Assert.SkipUnless(OperatingSystem.IsWindows() && File.Exists(powershell), "Needs Windows PowerShell 5.1.");
using var pki = new TestPki();
using var rsaLeaf = pki.IssueLeaf();
using var ecKey = ECDsa.Create(ECCurve.NamedCurves.nistP384);
using var ecRoot = new CertificateRequest("CN=EC Root", ecKey, HashAlgorithmName.SHA384).CreateSelfSigned(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddYears(1));
var folder = Path.Combine(Path.GetTempPath(), "executer-spki-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(folder);
try
{
var certificates = new[] { pki.Root, pki.Intermediate, rsaLeaf, ecRoot };
for (var i = 0; i < certificates.Length; i++)
{
File.WriteAllBytes(Path.Combine(folder, $"{i}.cer"), certificates[i].RawData);
}
var script = Path.Combine(folder, "spki.ps1");
File.WriteAllText(script, "$server = 'https://unused'\n" + InstallEndpoints.PsDownload(Fingerprint) + "\n"
+ $"0..{certificates.Length - 1} | ForEach-Object {{ Get-ExecuteRSpkiHash ([IO.File]::ReadAllBytes((Join-Path '{folder}' \"$_.cer\"))) }}\n");
using var process = Process.Start(new ProcessStartInfo(powershell, $"-NoProfile -NonInteractive -ExecutionPolicy Bypass -File \"{script}\"")
{
RedirectStandardOutput = true,
RedirectStandardError = true,
})!;
var output = await process.StandardOutput.ReadToEndAsync();
var errors = await process.StandardError.ReadToEndAsync();
await process.WaitForExitAsync();
Assert.True(process.ExitCode == 0, errors);
Assert.Equal(
certificates.Select(c => Convert.ToHexStringLower(SHA256.HashData(c.PublicKey.ExportSubjectPublicKeyInfo()))),
output.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries));
}
finally
{
Directory.Delete(folder, recursive: true);
}
}
}
/// <summary>
/// A provided certificate from a private CA: the server hands agents that CA (never the leaf) and tokens pin its root,
/// exactly as with the managed chain.
/// </summary>
public sealed class ProvidedCertificateEnrollmentTests : IClassFixture<BackendTestFixture>, IDisposable
{
private const string Password = "enrollment-pfx";
private readonly BackendTestFixture fixture;
private readonly TestPki pki = new("Enrollment Test");
private readonly string pfx = Path.Combine(Path.GetTempPath(), $"executer-provided-{Guid.NewGuid():N}.pfx");
public ProvidedCertificateEnrollmentTests(BackendTestFixture fixture)
{
this.fixture = fixture;
if (!fixture.Settings.ContainsKey("TLS_CERT_FILE"))
{
using var leaf = pki.IssueLeaf();
pki.WritePfx(pfx, leaf, Password);
fixture.Settings["TLS_CERT_SOURCE"] = "file";
fixture.Settings["TLS_CERT_FILE"] = pfx;
fixture.Settings["TLS_CERT_PASSWORD"] = Password;
// File mode: never the machine stores from a test run.
fixture.Settings["TLS_CERT_DIR"] = Path.Combine(fixture.DataPath, "tls");
}
}
private X509Certificate2 ServedRoot()
{
var collection = X509CertificateLoader.LoadPkcs12CollectionFromFile(fixture.Settings["TLS_CERT_FILE"]!, Password);
return collection.Cast<X509Certificate2>().Single(c => c.Subject == c.Issuer);
}
[Fact]
public async Task TheCaEndpointServesTheEnterpriseChainWithoutTheLeaf()
{
using var client = fixture.CreateClient();
var response = await client.GetAsync("/api/enrollment/ca");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
X509Certificate2Collection chain = [];
chain.ImportFromPem(await response.Content.ReadAsStringAsync());
Assert.Equal(2, chain.Count);
Assert.Equal(ServedRoot().Thumbprint, chain[1].Thumbprint);
Assert.All(chain.Cast<X509Certificate2>(), c => Assert.Contains(c.Extensions.OfType<X509BasicConstraintsExtension>(), b => b.CertificateAuthority));
}
[Fact]
public async Task TokensCarryTheEnterpriseRootsFingerprint()
{
using var admin = await fixture.SignedInAsync("provided-tls-admin");
var response = await admin.PostAsJsonAsync("/api/admin/bootstrap-tokens", new { maxUses = 1, validMinutes = 60 });
response.EnsureSuccessStatusCode();
using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
var token = body.RootElement.GetProperty("token").GetString()!;
Assert.EndsWith("." + Convert.ToHexStringLower(SHA256.HashData(ServedRoot().PublicKey.ExportSubjectPublicKeyInfo())), token);
}
public void Dispose()
{
pki.Dispose();
}
}