Files
ExecuteR/tests/Agent.Tests/ScriptFileFetcherTests.cs
Alphaeus Mote cf2c83fb56 feat(agent): file downloads follow server paths, with the server's trust
A delivery's URL can now be a path, resolved against the server URL the agent
already reaches, as upgrades do. Both downloaders also use enrollment's trust,
so a self-signed server's links work.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 08:50:36 -05:00

191 lines
7.1 KiB
C#

using System.Net;
using System.Text;
using Agent.PowerShell;
using Shared.Contracts.Messages;
using Shared.Contracts.Models;
using Xunit;
namespace Agent.Tests;
public class ScriptFileFetcherTests
{
[Theory]
[InlineData("sub/file.txt", true)]
[InlineData("deep/er/tree.bin", true)]
[InlineData("../evil.txt", false)]
[InlineData("a/../../evil.txt", false)]
[InlineData("/rooted.txt", false)]
[InlineData("C:\\rooted.txt", false)]
public void SafeCombineRefusesEscapes(string relative, bool allowed)
{
var root = Path.Combine(Path.GetTempPath(), "fetcher-root");
if (allowed)
{
var combined = ScriptFileFetcher.SafeCombine(root, relative);
Assert.StartsWith(Path.GetFullPath(root), combined);
}
else
{
Assert.Throws<InvalidOperationException>(() => ScriptFileFetcher.SafeCombine(root, relative));
}
}
[Fact]
public async Task DownloadsFilesAndDirectoriesAndHonorsContinueOnFailure()
{
using var server = new StaticServer(new Dictionary<string, string>
{
["/single.txt"] = "single-content",
["/dir/a.txt"] = "alpha",
["/dir/sub/b.txt"] = "beta",
});
var workDir = Path.Combine(Path.GetTempPath(), $"fetcher-test-{Guid.NewGuid():N}");
try
{
var deliveries = new List<ScriptFileDelivery>
{
new("Config", Path.Combine(workDir, "config.txt"), false, false,
[new ScriptFileItem("", server.Url("/single.txt"))]),
new("Tools", Path.Combine(workDir, "tools"), true, false,
[
new ScriptFileItem("a.txt", server.Url("/dir/a.txt")),
new ScriptFileItem("sub/b.txt", server.Url("/dir/sub/b.txt")),
]),
// 404s, but continue-on-failure keeps the job alive.
new("Optional", Path.Combine(workDir, "optional.txt"), false, true,
[new ScriptFileItem("", server.Url("/missing.txt"))]),
};
var records = new List<NormalizedOutputRecord>();
var result = await ScriptFileFetcher.FetchAsync(
deliveries, new Agent.Files.ServerDownloads(null, false), path => path, records.Add, CancellationToken.None);
Assert.Null(result.FailureMessage);
Assert.Equal("single-content", await File.ReadAllTextAsync(Path.Combine(workDir, "config.txt")));
Assert.Equal("beta", await File.ReadAllTextAsync(Path.Combine(workDir, "tools", "sub", "b.txt")));
// Case-insensitive dictionary of FileInfo / DirectoryInfo.
var config = Assert.IsType<FileInfo>(result.Files["CONFIG"]);
Assert.True(config.Exists);
var tools = Assert.IsType<DirectoryInfo>(result.Files["tools"]);
Assert.True(tools.Exists);
// The failed optional entry still resolves (Exists = false) and warned.
var optional = Assert.IsType<FileInfo>(result.Files["Optional"]);
Assert.False(optional.Exists);
Assert.Contains(records, r => r.Stream == OutputStreamKind.Warning && r.Text.Contains("Optional"));
}
finally
{
if (Directory.Exists(workDir))
{
Directory.Delete(workDir, recursive: true);
}
}
}
[Fact]
public async Task AFailedRequiredDeliveryFailsBeforeTheScriptRuns()
{
using var server = new StaticServer([]);
var workDir = Path.Combine(Path.GetTempPath(), $"fetcher-test-{Guid.NewGuid():N}");
var deliveries = new List<ScriptFileDelivery>
{
new("Required", Path.Combine(workDir, "required.txt"), false, false,
[new ScriptFileItem("", server.Url("/missing.txt"))]),
};
var result = await ScriptFileFetcher.FetchAsync(
deliveries, new Agent.Files.ServerDownloads(null, false), path => path, _ => { }, CancellationToken.None);
Assert.NotNull(result.FailureMessage);
Assert.Contains("Required", result.FailureMessage);
}
[Fact]
public async Task ServerSideResolutionErrorsRespectContinueOnFailure()
{
var deliveries = new List<ScriptFileDelivery>
{
new("Broken", Path.Combine(Path.GetTempPath(), "x.txt"), false, true, [],
Error: "no objects under prefix"),
};
var records = new List<NormalizedOutputRecord>();
var result = await ScriptFileFetcher.FetchAsync(
deliveries, new Agent.Files.ServerDownloads(null, false), path => path, records.Add, CancellationToken.None);
Assert.Null(result.FailureMessage);
Assert.IsType<FileInfo>(result.Files["Broken"]);
Assert.Contains(records, r => r.Stream == OutputStreamKind.Warning);
}
/// <summary>Tiny loopback HTTP server for real download round-trips.</summary>
private sealed class StaticServer : IDisposable
{
private readonly HttpListener listener = new();
private readonly string baseUrl;
public StaticServer(Dictionary<string, string> content)
{
// A random port occasionally collided with one in use and Start()
// threw; ask the OS for a free one (retrying the rare race in which
// it is taken again before HttpListener binds).
for (var attempt = 0; ; attempt++)
{
var probe = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0);
probe.Start();
var port = ((IPEndPoint)probe.LocalEndpoint).Port;
probe.Stop();
baseUrl = $"http://127.0.0.1:{port}";
listener.Prefixes.Clear();
listener.Prefixes.Add(baseUrl + "/");
try
{
listener.Start();
break;
}
catch (HttpListenerException) when (attempt < 5)
{
}
}
_ = Task.Run(async () =>
{
while (listener.IsListening)
{
HttpListenerContext context;
try
{
context = await listener.GetContextAsync();
}
catch (Exception)
{
return;
}
if (content.TryGetValue(context.Request.Url!.AbsolutePath, out var body))
{
var bytes = Encoding.UTF8.GetBytes(body);
context.Response.StatusCode = 200;
await context.Response.OutputStream.WriteAsync(bytes);
}
else
{
context.Response.StatusCode = 404;
}
context.Response.Close();
}
});
}
public string Url(string path) => baseUrl + path;
public void Dispose() => listener.Stop();
}
}