0b85bd5e8a
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>
219 lines
10 KiB
C#
219 lines
10 KiB
C#
using System.Net.Http.Json;
|
|
using System.Text.Json;
|
|
using Backend.Data;
|
|
using Microsoft.AspNetCore.Hosting;
|
|
using Microsoft.AspNetCore.Mvc.Testing;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Shared.Contracts.Models;
|
|
using Xunit;
|
|
|
|
namespace Backend.Tests;
|
|
|
|
public class InstallScriptTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
|
|
{
|
|
[Theory]
|
|
[InlineData(0, 0)] // unlimited sentinel round-trips
|
|
[InlineData(1, 1)]
|
|
[InlineData(9999, 9999)]
|
|
public async Task TokenUseLimitsAcceptZeroThroughMax(int requested, int expected)
|
|
{
|
|
using var client = await AdminClientAsync();
|
|
var response = await client.PostAsJsonAsync(
|
|
"/api/admin/bootstrap-tokens", new { maxUses = requested, validMinutes = 60 });
|
|
|
|
response.EnsureSuccessStatusCode();
|
|
using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
|
Assert.Equal(expected, body.RootElement.GetProperty("maxUses").GetInt32());
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData(10000)]
|
|
[InlineData(-1)]
|
|
public async Task TokenUseLimitsRejectOutOfRange(int requested)
|
|
{
|
|
using var client = await AdminClientAsync();
|
|
var response = await client.PostAsJsonAsync(
|
|
"/api/admin/bootstrap-tokens", new { maxUses = requested, validMinutes = 60 });
|
|
|
|
Assert.Equal(System.Net.HttpStatusCode.BadRequest, response.StatusCode);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ValidMinutesZeroMeansNoExpiry()
|
|
{
|
|
using var client = await AdminClientAsync();
|
|
var response = await client.PostAsJsonAsync(
|
|
"/api/admin/bootstrap-tokens", new { maxUses = 1, validMinutes = 0 });
|
|
|
|
response.EnsureSuccessStatusCode();
|
|
using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
|
var expires = body.RootElement.GetProperty("expiresUtc").GetDateTimeOffset();
|
|
Assert.True(expires.Year > 9000, $"expected a never-expires sentinel, got {expires:u}");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task NegativeValidMinutesIsRejected()
|
|
{
|
|
using var client = await AdminClientAsync();
|
|
var response = await client.PostAsJsonAsync(
|
|
"/api/admin/bootstrap-tokens", new { maxUses = 1, validMinutes = -5 });
|
|
|
|
Assert.Equal(System.Net.HttpStatusCode.BadRequest, response.StatusCode);
|
|
}
|
|
|
|
private Task<HttpClient> AdminClientAsync() => fixture.SignedInAsync("token-admin");
|
|
|
|
[Theory]
|
|
[InlineData(null, "msiexec")]
|
|
[InlineData("msi", "msiexec")]
|
|
[InlineData("zip", "[System.IO.Compression.ZipFile]::ExtractToDirectory")]
|
|
public async Task WindowsVariantsReturnPowerShell(string? type, string marker)
|
|
{
|
|
using var client = fixture.CreateClient();
|
|
var url = "/api/enrollment/install?token=test-token" + (type is null ? "" : $"&type={type}");
|
|
var response = await client.GetAsync(url);
|
|
|
|
response.EnsureSuccessStatusCode();
|
|
var script = await response.Content.ReadAsStringAsync();
|
|
Assert.Contains(marker, script);
|
|
Assert.Contains("test-token", script);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData(null)]
|
|
[InlineData("msi")]
|
|
public async Task MsiScriptTakesThePortablePathInWindowsPe(string? type)
|
|
{
|
|
// Windows Installer does not run in Windows PE: the default script
|
|
// detects WinPE (the MiniNT key) and installs the portable package as
|
|
// a service instead, so the one-liner the console shows works there.
|
|
using var client = fixture.CreateClient();
|
|
var url = "/api/enrollment/install?token=test-token" + (type is null ? "" : $"&type={type}");
|
|
var script = await (await client.GetAsync(url)).Content.ReadAsStringAsync();
|
|
|
|
Assert.Matches(@"\$zipUrl = '[^']*/api/enrollment/agent-package\?type=zip&token=test-token'", script);
|
|
Assert.Contains(@"$portable = [bool]($portableOnly -or -not $msiUrl -or (Test-Path 'HKLM:\SYSTEM\CurrentControlSet\Control\MiniNT'))", script);
|
|
Assert.Contains("if ($Portable) { Install-ExecuteRPortable $Enroll } else { Install-ExecuteRMsi $Enroll $Downgrade }", script);
|
|
Assert.Contains("& $exe initialize", script);
|
|
|
|
// No Being Viewed banner in Windows PE: the portable install drops it there, before starting the agent.
|
|
var portable = script.IndexOf("function Install-ExecuteRPortable", StringComparison.Ordinal);
|
|
var dropBanner = script.IndexOf("Remove-Item (Join-Path $dest 'ExecuteR-Banner.exe')", StringComparison.Ordinal);
|
|
Assert.True(dropBanner > portable && dropBanner < script.IndexOf("& $exe initialize", portable, StringComparison.Ordinal), "WinPE must drop the banner before starting the agent");
|
|
Assert.True(script.LastIndexOf(@"Test-Path 'HKLM:\SYSTEM\CurrentControlSet\Control\MiniNT'", dropBanner, StringComparison.Ordinal) > portable,
|
|
"Only Windows PE drops the banner");
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData(null)]
|
|
[InlineData("zip")]
|
|
public async Task WindowsScriptsAvoidWhatWindowsPeLacks(string? type)
|
|
{
|
|
// Minimal PowerShell (WinPE-PowerShell) may lack the Archive module and
|
|
// has no CIM without WinPE-WMI; .NET's ZipFile is always present. The
|
|
// service is registered by the agent itself (SCM APIs), never sc.exe.
|
|
using var client = fixture.CreateClient();
|
|
var url = "/api/enrollment/install?token=test-token" + (type is null ? "" : $"&type={type}");
|
|
var script = await (await client.GetAsync(url)).Content.ReadAsStringAsync();
|
|
|
|
Assert.DoesNotContain("Expand-Archive", script);
|
|
Assert.DoesNotContain("Get-CimInstance", script);
|
|
Assert.DoesNotContain("Get-WmiObject", script);
|
|
Assert.DoesNotContain("sc.exe", script);
|
|
Assert.DoesNotContain("New-Service", script);
|
|
Assert.Contains("Add-Type -AssemblyName System.IO.Compression.FileSystem", script);
|
|
Assert.Contains("$LASTEXITCODE", script);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData(null)]
|
|
[InlineData("msi")]
|
|
[InlineData("zip")]
|
|
public async Task WindowsScriptsRunInPlaceWithoutAutoElevation(string? type)
|
|
{
|
|
// Auto-elevation was removed: the self-relaunch tripped AV/EDR ClickFix
|
|
// heuristics (Win32/ClickFix). The operator runs the command from an
|
|
// elevated PowerShell (the Add device modal states this). So: no UAC
|
|
// re-launch, no temp .ps1 scriptblock, no -EncodedCommand, and no
|
|
// #Requires -RunAsAdministrator.
|
|
using var client = fixture.CreateClient();
|
|
var url = "/api/enrollment/install?token=test-token" + (type is null ? "" : $"&type={type}");
|
|
var script = await (await client.GetAsync(url)).Content.ReadAsStringAsync();
|
|
|
|
Assert.DoesNotContain("WindowsBuiltInRole]::Administrator", script);
|
|
Assert.DoesNotContain("-Verb RunAs", script);
|
|
Assert.DoesNotContain("$install", script);
|
|
Assert.DoesNotContain("-EncodedCommand", script);
|
|
Assert.DoesNotContain("#Requires -RunAsAdministrator", script);
|
|
|
|
// The package download uses WebClient (fast) over TLS 1.2, never the
|
|
// slow Invoke-WebRequest.
|
|
Assert.Contains("System.Net.WebClient", script);
|
|
Assert.Contains("Tls12", script);
|
|
Assert.DoesNotContain("Invoke-WebRequest", script);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("linux", "type=linux-${arch}")]
|
|
[InlineData("osx", "type=osx-${arch}")]
|
|
[InlineData("macos", "type=osx-${arch}")]
|
|
public async Task UnixVariantsReturnBashWithArchDetection(string type, string packageMarker)
|
|
{
|
|
using var client = fixture.CreateClient();
|
|
var response = await client.GetAsync($"/api/enrollment/install?token=test-token&type={type}");
|
|
|
|
response.EnsureSuccessStatusCode();
|
|
var script = await response.Content.ReadAsStringAsync();
|
|
Assert.StartsWith("#!/usr/bin/env bash", script);
|
|
Assert.Contains("uname -m", script);
|
|
Assert.Contains(packageMarker, script);
|
|
Assert.Contains("configure --url", script);
|
|
Assert.Contains("initialize", script);
|
|
Assert.Contains("test-token", script);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task MissingTokenIsRefused()
|
|
{
|
|
using var client = fixture.CreateClient();
|
|
var response = await client.GetAsync("/api/enrollment/install");
|
|
Assert.Equal(System.Net.HttpStatusCode.BadRequest, response.StatusCode);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task TrustIsDecidedByServerNotAQueryParameter()
|
|
{
|
|
// The server decides trust: with self-signed TLS OFF (the test host
|
|
// runs plain HTTP) the scripts neither skip verification nor
|
|
// auto-install a CA, and the legacy skipVerify=1 parameter is ignored.
|
|
using var client = fixture.CreateClient();
|
|
|
|
var msi = await (await client.GetAsync("/api/enrollment/install?token=t")).Content.ReadAsStringAsync();
|
|
Assert.DoesNotContain("ServerCertificateValidationCallback", msi);
|
|
Assert.DoesNotContain("SkipCertificateCheck", msi);
|
|
Assert.DoesNotContain("CAINSTALL", msi);
|
|
|
|
var zip = await (await client.GetAsync("/api/enrollment/install?token=t&type=zip")).Content.ReadAsStringAsync();
|
|
Assert.DoesNotContain("ServerCaAutoInstall", zip);
|
|
|
|
var bash = await (await client.GetAsync("/api/enrollment/install?token=t&type=linux")).Content.ReadAsStringAsync();
|
|
Assert.DoesNotContain("fsSLk", bash); // no -k: verification stays on
|
|
Assert.DoesNotContain("--install-server-ca", bash);
|
|
|
|
// A stray skipVerify=1 no longer changes anything — trust is not a knob.
|
|
var ignored = await (await client.GetAsync("/api/enrollment/install?token=t&skipVerify=1")).Content.ReadAsStringAsync();
|
|
Assert.DoesNotContain("SkipCertificateCheck", ignored);
|
|
Assert.DoesNotContain("CAINSTALL", ignored);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task CaChainIs404WhenNotSelfSigned()
|
|
{
|
|
// The test fixture runs plain HTTP (TLS_SELF_SIGNED off), so there is
|
|
// no managed chain to distribute.
|
|
using var client = fixture.CreateClient();
|
|
var response = await client.GetAsync("/api/enrollment/ca");
|
|
Assert.Equal(System.Net.HttpStatusCode.NotFound, response.StatusCode);
|
|
}
|
|
}
|