Files
Alphaeus Mote b83cdc0fe4 feat(agent): upload to S3 from the device, and the agent's path for scripts
- $ExecuteRAgentDir / $ExecuteRAgentPath in both PowerShell engines (every
  mode), and EXECUTER_AGENT_DIR / EXECUTER_AGENT_PATH for PowerShell 5 and
  Bash (PowerShell 7 shares the agent's environment, so variables only),
  resolved from the running binary (links followed) for MSI, portable,
  Windows PE and Linux/macOS layouts.
- ExecuteR-Agent upload <path|mask>... [--recurse] [--flatten|--preserve]
  [--dest] [--zip [name.zip]] [--overwrite] [--quiet]: the CLI plans paths
  and masks where it runs, the service reads the files (sharing with writers
  and deleters) and sends them over the local channel's caller checks; exit
  codes 0 all, 1 refused/none, 2 unreachable, 3 partial.
- The upload steps (begin, presign, complete, abort, finish) go on the same
  request path as `run` (AgentLink.RequestAsync, sealed both ways); bytes go
  straight to the store over HTTPS, whole or in parts, with retries, size
  checks and progress.
- The console's Upload to S3 (files/folders, and the agent's logs as a zip)
  takes the same path from the file listener.
- The upload runs as the agent, not under the pipe client's identification
  token, which leaked into pool threads and made file opens fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 19:10:00 -05:00

720 lines
32 KiB
C#

using System.IO.Compression;
using System.IO.Pipes;
using System.Security.AccessControl;
using System.Security.Principal;
using Agent.Commands;
using Agent.LocalRun;
using Agent.PowerShell;
using Agent.Uploads;
using Microsoft.Extensions.Logging.Abstractions;
using Shared.Contracts.Messages;
using Shared.Contracts.Models;
using Xunit;
namespace Agent.Tests;
/// <summary>
/// Stands in for the server and the store at once: begins (keys below a fixed folder), presigns fake URLs, takes the
/// PUTs, assembles parts on complete and checks sizes, the way the real ones do.
/// </summary>
internal sealed class FakeUploadBackend : IDeviceUploadServer, IUploadTransport
{
public const string Folder = "uploads/devices/test-host/20261106-120000/";
public long MultipartThreshold { get; set; } = long.MaxValue;
public long PartSize { get; set; } = 4;
public HashSet<string> Existing { get; } = new(StringComparer.Ordinal);
public HashSet<string> FailPutFor { get; } = new(StringComparer.Ordinal);
public DeviceUploadReplyPayload? BeginAnswer { get; set; }
public bool Unreachable { get; set; }
public int FailFirstPuts { get; set; }
public List<DeviceUploadRequestPayload> Requests { get; } = [];
public Dictionary<string, byte[]> Objects { get; } = new(StringComparer.Ordinal);
public Dictionary<string, byte[]> Puts { get; } = new(StringComparer.Ordinal);
public List<string> Aborted { get; } = [];
public int PutCount { get; private set; }
public Task<DeviceUploadReplyPayload> RequestAsync(DeviceUploadRequestPayload request, CancellationToken cancellationToken)
{
if (Unreachable)
{
throw new DeviceRunUnavailableException("Not connected to the server.");
}
lock (Requests)
{
Requests.Add(request);
}
return Task.FromResult(request.Action switch
{
DeviceUploadActions.Begin => BeginAnswer ?? Begin(request),
DeviceUploadActions.Presign => Presign(request),
DeviceUploadActions.Complete => Complete(request),
DeviceUploadActions.Abort => Abort(request),
_ => new DeviceUploadReplyPayload(DeviceUploadStatuses.Ok),
});
}
private DeviceUploadReplyPayload Begin(DeviceUploadRequestPayload request)
=> new(
DeviceUploadStatuses.Ok,
Folder: Folder,
Grant: "grant",
Targets: [.. request.Files!.Select(f => Existing.Contains(f.Name)
? new DeviceUploadTarget(DeviceUploadStatuses.Exists, f.Name, Message: "Already there.")
: f.Size > MultipartThreshold
? new DeviceUploadTarget(DeviceUploadStatuses.Ok, f.Name, PartSize, (int)((f.Size + PartSize - 1) / PartSize))
: new DeviceUploadTarget(DeviceUploadStatuses.Ok, f.Name))]);
private static DeviceUploadReplyPayload Presign(DeviceUploadRequestPayload request)
{
Check(request.Grant == "grant", "grant");
Check(request.Key?.StartsWith(Folder, StringComparison.Ordinal) == true, "key outside the folder");
if (request.FirstPart == 0)
{
return new DeviceUploadReplyPayload(DeviceUploadStatuses.Ok, Url: "put:" + request.Key);
}
var multipart = request.MultipartId ?? "mp-" + request.Key;
return new DeviceUploadReplyPayload(
DeviceUploadStatuses.Ok,
MultipartId: multipart,
PartUrls: [.. Enumerable.Range(request.FirstPart, request.PartCount).Select(n => new DeviceUploadPartUrl(n, $"part:{request.Key}:{n}"))]);
}
private DeviceUploadReplyPayload Complete(DeviceUploadRequestPayload request)
{
byte[] whole;
lock (Puts)
{
whole = request.Parts is { Count: > 0 } parts
? [.. parts.OrderBy(p => p.Number).SelectMany(p => Puts[$"part:{request.Key}:{p.Number}"])]
: Puts["put:" + request.Key];
}
if (whole.Length != request.Size)
{
return new DeviceUploadReplyPayload(DeviceUploadStatuses.Failed, "Arrived with the wrong size; removed.");
}
Objects[request.Key!] = whole;
return new DeviceUploadReplyPayload(DeviceUploadStatuses.Ok);
}
private DeviceUploadReplyPayload Abort(DeviceUploadRequestPayload request)
{
Aborted.Add(request.Key!);
return new DeviceUploadReplyPayload(DeviceUploadStatuses.Ok);
}
/// <summary>Not an xunit assertion: these run on the agent's side of the pipe, outside any test's context.</summary>
private static void Check(bool condition, string what)
{
if (!condition)
{
throw new InvalidOperationException($"The fake backend got a bad request: {what}.");
}
}
public async Task<string?> PutAsync(string url, Stream content, long length, CancellationToken cancellationToken)
{
using var buffer = new MemoryStream();
await content.CopyToAsync(buffer, cancellationToken);
Check(length == buffer.Length, "length");
lock (Puts)
{
PutCount++;
if (FailFirstPuts > 0)
{
FailFirstPuts--;
throw new UploadTransportException("The store answered 503.");
}
if (FailPutFor.Any(url.Contains))
{
throw new UploadTransportException("The store answered 403 AccessDenied.");
}
Puts[url] = buffer.ToArray();
}
return $"\"etag-{url.GetHashCode():x}\"";
}
}
public sealed class UploadPlannerTests : IDisposable
{
private readonly string root = Directory.CreateTempSubdirectory("executer-plan-").FullName;
public UploadPlannerTests()
{
Write("Logs/app.log", "a");
Write("Logs/app.1.log", "bb");
Write("Logs/readme.txt", "ccc");
Write("Logs/old/app.log", "dddd");
Write("Logs/old/deeper/x.log", "eeeee");
Write("Other/app.log", "ffffff");
}
public void Dispose() => Directory.Delete(root, recursive: true);
private void Write(string relative, string content)
{
var path = Path.Combine(root, relative);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, content);
}
private UploadPlan Plan(bool recurse, UploadLayout layout, params string[] inputs) => UploadPlanner.Plan(inputs, recurse, layout, root);
[Fact]
public void AMaskTakesMatchingFilesInItsFolderOnly()
{
var plan = Plan(false, UploadLayout.Preserve, Path.Combine(root, "Logs", "*.log"));
Assert.Equal(["app.1.log", "app.log"], plan.Files.Select(f => f.Name));
Assert.Empty(plan.Problems);
Assert.Equal(1, plan.Files.Single(f => f.Name == "app.log").Size);
}
[Fact]
public void RecurseKeepsPathsBelowTheMasksFolder()
{
var plan = Plan(true, UploadLayout.Preserve, Path.Combine(root, "Logs", "*.log"));
Assert.Equal(["app.1.log", "app.log", "old/app.log", "old/deeper/x.log"], plan.Files.Select(f => f.Name));
}
[Fact]
public void AFolderKeepsItsOwnNameAndRecursesOnlyWhenAsked()
{
Assert.Equal(["Logs/app.1.log", "Logs/app.log", "Logs/readme.txt"], Plan(false, UploadLayout.Preserve, "Logs").Files.Select(f => f.Name));
Assert.Equal(5, Plan(true, UploadLayout.Preserve, "Logs").Files.Count);
Assert.Contains("Logs/old/deeper/x.log", Plan(true, UploadLayout.Preserve, "Logs").Files.Select(f => f.Name));
}
[Fact]
public void FlattenDropsFoldersAndNumbersClashesAndSaysSo()
{
var plan = Plan(true, UploadLayout.Flatten, "Logs", Path.Combine("Other", "app.log"));
Assert.Equal(["app.1.log", "app.log", "app-2.log", "x.log", "readme.txt", "app-3.log"], plan.Files.Select(f => f.Name));
Assert.Equal(2, plan.Renamed.Count);
Assert.Contains(plan.Renamed, r => r.EndsWith("as app-3.log", StringComparison.Ordinal) && r.Contains("Other"));
}
[Fact]
public void PreserveNumbersAClashBetweenTwoInputsToo()
{
var plan = Plan(false, UploadLayout.Preserve, Path.Combine("Logs", "app.log"), Path.Combine("Other", "app.log"));
Assert.Equal(["app.log", "app-2.log"], plan.Files.Select(f => f.Name));
Assert.Single(plan.Renamed);
}
[Fact]
public void AFileNamedTwiceGoesOnce()
{
var plan = Plan(false, UploadLayout.Preserve, Path.Combine("Logs", "app.log"), Path.Combine(root, "Logs", "*.log"));
Assert.Equal(["app.log", "app.1.log"], plan.Files.Select(f => f.Name));
Assert.Empty(plan.Renamed);
}
[Fact]
public void WhatIsNotThereIsReportedAndTheRestGoes()
{
var plan = Plan(false, UploadLayout.Preserve, "missing.log", Path.Combine("Logs", "*.zip"), Path.Combine("*", "app.log"), Path.Combine("Logs", "readme.txt"));
Assert.Equal(["readme.txt"], plan.Files.Select(f => f.Name));
Assert.Equal(3, plan.Problems.Count);
Assert.Contains(plan.Problems, p => p.Contains("no such file or folder"));
Assert.Contains(plan.Problems, p => p.Contains("nothing matches"));
Assert.Contains(plan.Problems, p => p.Contains("last part"));
}
[Fact]
public void EnvironmentVariablesExpand()
{
Environment.SetEnvironmentVariable("EXECUTER_TEST_UPLOAD_ROOT", root);
try
{
var input = OperatingSystem.IsWindows() ? @"%EXECUTER_TEST_UPLOAD_ROOT%\Logs\*.txt" : "$EXECUTER_TEST_UPLOAD_ROOT/Logs/*.txt";
Assert.Equal(["readme.txt"], UploadPlanner.Plan([input], false, UploadLayout.Preserve, Path.GetTempPath()).Files.Select(f => f.Name));
Assert.Equal(Path.Combine(root, "x"), UploadPlanner.Expand("%EXECUTER_TEST_UPLOAD_ROOT%" + Path.DirectorySeparatorChar + "x"));
}
finally
{
Environment.SetEnvironmentVariable("EXECUTER_TEST_UPLOAD_ROOT", null);
}
}
[Fact]
public void UniqueNumbersBeforeTheExtensionAndKeepsTheFolder()
{
var taken = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "a/b.tar.gz", "a/b.tar-2.gz", "noext" };
Assert.Equal("a/B.tar-3.gz", UploadPlanner.Unique("a/B.tar.gz", taken));
Assert.Equal("noext-2", UploadPlanner.Unique("noext", taken));
Assert.Equal("new.log", UploadPlanner.Unique("new.log", taken));
}
}
public sealed class UploadZipTests : IDisposable
{
private readonly string root = Directory.CreateTempSubdirectory("executer-zip-").FullName;
public void Dispose() => Directory.Delete(root, recursive: true);
[Fact]
public void ZipsUnderThePlannedNamesReadsFilesBeingWrittenAndSkipsLockedOnes()
{
var open = Path.Combine(root, "open.log");
var locked = Path.Combine(root, "locked.log");
var plain = Path.Combine(root, "plain.txt");
File.WriteAllText(plain, "plain");
File.WriteAllText(locked, "locked");
using var writer = new FileStream(open, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
writer.Write("being written"u8);
writer.Flush();
UploadZipResult result;
using (new FileStream(locked, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
result = UploadZip.Create(
[new UploadSource(open, "logs/open.log", 0), new UploadSource(locked, "logs/locked.log", 0), new UploadSource(plain, "plain.txt", 0)],
Path.Combine(root, "out.zip"), null, CancellationToken.None);
}
Assert.Equal(2, result.Added);
Assert.Contains(result.Problems, p => p.StartsWith(locked, StringComparison.Ordinal));
using var zip = ZipFile.OpenRead(result.Path);
Assert.Equal(["logs/open.log", "plain.txt"], zip.Entries.Select(e => e.FullName));
using var reader = new StreamReader(zip.GetEntry("logs/open.log")!.Open());
Assert.Equal("being written", reader.ReadToEnd());
}
[Theory]
[InlineData(null, "host-20261106-120000.zip")]
[InlineData("archive", "archive.zip")]
[InlineData("Archive.ZIP", "Archive.ZIP")]
[InlineData("../evil/name.zip", "name.zip")]
[InlineData("..", "host-20261106-120000.zip")]
public void ZipNames(string? asked, string expected)
=> Assert.Equal(expected, UploadZip.NameFor(asked, "host", new DateTimeOffset(2026, 11, 6, 12, 0, 0, TimeSpan.Zero)));
}
public sealed class DeviceUploaderTests : IDisposable
{
private readonly string root = Directory.CreateTempSubdirectory("executer-uploader-").FullName;
public void Dispose() => Directory.Delete(root, recursive: true);
private UploadSource File(string name, string content)
{
var path = Path.Combine(root, name.Replace('/', Path.DirectorySeparatorChar));
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
System.IO.File.WriteAllText(path, content);
return new UploadSource(path, name, content.Length);
}
private static DeviceUploader Uploader(FakeUploadBackend backend) => new(backend, backend, NullLogger<DeviceUploader>.Instance);
[Fact]
public async Task EveryFileArrivesWholeAndTheServerHearsHowItWent()
{
var backend = new FakeUploadBackend();
var events = new List<UploadEvent>();
var outcome = await Uploader(backend).RunAsync(
new UploadJob([File("a.log", "alpha"), File("sub/b.log", "bravo!")], Folder: "logs", LocalUser: "admin", JobId: Guid.Empty),
events.Add, CancellationToken.None);
Assert.Equal(UploadOutcome.AllUploaded, outcome.ExitCode);
Assert.Equal(FakeUploadBackend.Folder, outcome.Folder);
Assert.Equal("alpha"u8.ToArray(), backend.Objects[FakeUploadBackend.Folder + "a.log"]);
Assert.Equal("bravo!"u8.ToArray(), backend.Objects[FakeUploadBackend.Folder + "sub/b.log"]);
var begin = backend.Requests.First();
Assert.Equal(DeviceUploadActions.Begin, begin.Action);
Assert.Equal("logs", begin.Folder);
Assert.Equal("admin", begin.LocalUser);
Assert.Equal([new DeviceUploadFile("a.log", 5), new DeviceUploadFile("sub/b.log", 6)], begin.Files);
var finish = backend.Requests.Last();
Assert.Equal(DeviceUploadActions.Finish, finish.Action);
Assert.Equal((2, 0, 0, 11L), (finish.Summary!.Uploaded, finish.Summary.Failed, finish.Summary.Skipped, finish.Summary.Bytes));
Assert.All(backend.Requests, r => Assert.Equal(begin.UploadId, r.UploadId));
Assert.IsType<UploadStarted>(events.First());
Assert.Equal(2, events.OfType<UploadFileDone>().Count());
Assert.Contains(events.OfType<UploadProgress>(), p => p.TotalBytes == 11 && p.TotalSize == 11);
}
[Fact]
public async Task ALargeFileGoesInPartsAndIsCompletedThroughTheServer()
{
var backend = new FakeUploadBackend { MultipartThreshold = 10, PartSize = 4 };
var content = string.Concat(Enumerable.Range(0, 50).Select(i => (char)('a' + (i % 26))));
var outcome = await Uploader(backend).RunAsync(new UploadJob([File("big.bin", content)]), null, CancellationToken.None);
Assert.Equal(UploadOutcome.AllUploaded, outcome.ExitCode);
Assert.Equal(System.Text.Encoding.ASCII.GetBytes(content), backend.Objects[FakeUploadBackend.Folder + "big.bin"]);
// 13 parts, asked for 8 at a time, one multipart upload throughout.
var presigns = backend.Requests.Where(r => r.Action == DeviceUploadActions.Presign).ToList();
Assert.Equal([1, 9], presigns.Select(p => p.FirstPart));
Assert.Null(presigns[0].MultipartId);
Assert.Equal("mp-" + FakeUploadBackend.Folder + "big.bin", presigns[1].MultipartId);
var complete = backend.Requests.Single(r => r.Action == DeviceUploadActions.Complete);
Assert.Equal(Enumerable.Range(1, 13), complete.Parts!.Select(p => p.Number));
Assert.Equal(50, complete.Size);
}
[Fact]
public async Task AFailedFileIsReportedTheRestCarryOnAndTheExitCodeSaysPartial()
{
var backend = new FakeUploadBackend { MultipartThreshold = 10, PartSize = 4 };
backend.FailPutFor.Add("bad.bin");
backend.Existing.Add("there.log");
var outcome = await Uploader(backend).RunAsync(
new UploadJob([File("good.log", "ok"), File("bad.bin", new string('x', 20)), File("there.log", "x")], Problems: ["missing.log: no such file or folder"]),
null, CancellationToken.None);
Assert.Equal(UploadOutcome.Partial, outcome.ExitCode);
Assert.Equal((1, 1, 1), (outcome.Uploaded, outcome.Failed, outcome.Skipped));
Assert.Contains("403", outcome.Files.Single(f => f.Name == "bad.bin").Message);
Assert.Equal([FakeUploadBackend.Folder + "bad.bin"], backend.Aborted);
var finish = backend.Requests.Last().Summary!;
Assert.Equal((1, 1, 1), (finish.Uploaded, finish.Failed, finish.Skipped));
Assert.Contains(finish.Problems!, p => p.Contains("missing.log"));
}
[Fact]
public async Task ATransientFailureIsTriedAgain()
{
var backend = new FakeUploadBackend { FailFirstPuts = 1 };
var outcome = await Uploader(backend).RunAsync(new UploadJob([File("a.log", "alpha")]), null, CancellationToken.None);
Assert.Equal(UploadOutcome.AllUploaded, outcome.ExitCode);
Assert.Equal(2, backend.PutCount);
}
[Fact]
public async Task ARefusalSendsNothingAndExits1()
{
var backend = new FakeUploadBackend { BeginAnswer = new DeviceUploadReplyPayload(DeviceUploadStatuses.Disabled, "Device uploads are turned off on the server.") };
var outcome = await Uploader(backend).RunAsync(new UploadJob([File("a.log", "alpha")]), null, CancellationToken.None);
Assert.Equal(UploadOutcome.NoneUploaded, outcome.ExitCode);
Assert.Equal("Device uploads are turned off on the server.", outcome.Refusal);
Assert.Empty(backend.Puts);
}
[Fact]
public async Task NoServerExits2()
{
var backend = new FakeUploadBackend { Unreachable = true };
var outcome = await Uploader(backend).RunAsync(new UploadJob([File("a.log", "alpha")]), null, CancellationToken.None);
Assert.Equal(UploadOutcome.Unreachable, outcome.ExitCode);
}
[Fact]
public async Task EverythingSkippedIsNothingUploaded()
{
var backend = new FakeUploadBackend();
backend.Existing.Add("a.log");
var outcome = await Uploader(backend).RunAsync(new UploadJob([File("a.log", "alpha")]), null, CancellationToken.None);
Assert.Equal(UploadOutcome.NoneUploaded, outcome.ExitCode);
}
[Fact]
public async Task ZipModeSendsOneArchiveAndCleansUp()
{
var backend = new FakeUploadBackend();
var outcome = await Uploader(backend).RunAsync(
new UploadJob([File("a.log", "alpha"), File("sub/b.log", "bravo")], Zip: true, ZipName: "bundle"), null, CancellationToken.None);
Assert.Equal(UploadOutcome.AllUploaded, outcome.ExitCode);
var key = Assert.Single(backend.Objects.Keys);
Assert.Equal(FakeUploadBackend.Folder + "bundle.zip", key);
using var zip = new ZipArchive(new MemoryStream(backend.Objects[key]));
Assert.Equal(["a.log", "sub/b.log"], zip.Entries.Select(e => e.FullName));
Assert.Equal(new DeviceUploadFile("bundle.zip", backend.Objects[key].Length), Assert.Single(backend.Requests.First().Files!));
}
[Fact]
public async Task AFileThatShrankWhileSentFails()
{
var backend = new FakeUploadBackend();
var source = File("a.log", "alpha");
var shrinking = new ShrinkingTransport(backend, source.Path);
var outcome = await new DeviceUploader(backend, shrinking, NullLogger<DeviceUploader>.Instance)
.RunAsync(new UploadJob([source]), null, CancellationToken.None);
Assert.Equal(UploadOutcome.NoneUploaded, outcome.ExitCode);
Assert.Contains("shorter", outcome.Files.Single().Message);
}
/// <summary>Truncates the file once the size has been declared, before reading it.</summary>
private sealed class ShrinkingTransport(IUploadTransport inner, string path) : IUploadTransport
{
public Task<string?> PutAsync(string url, Stream content, long length, CancellationToken cancellationToken)
{
using (var file = new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete))
{
file.SetLength(2);
}
return inner.PutAsync(url, content, length, cancellationToken);
}
}
}
public sealed class UploadCommandTests : IDisposable
{
private readonly string root = Directory.CreateTempSubdirectory("executer-upload-cli-").FullName;
public void Dispose() => Directory.Delete(root, recursive: true);
[Fact]
public void ParsesEveryOption()
{
Assert.True(UploadCommand.TryParse(
[@"C:\Logs\*.log", "/var/log/app*.log", "-r", "--flatten", "--dest", "case-42", "--zip", "bundle.zip", "--overwrite", "-q"],
out var options, out var error), error);
Assert.Equal([@"C:\Logs\*.log", "/var/log/app*.log"], options.Paths);
Assert.True(options.Recurse);
Assert.Equal(UploadLayout.Flatten, options.Layout);
Assert.Equal("case-42", options.Dest);
Assert.True(options.Zip);
Assert.Equal("bundle.zip", options.ZipName);
Assert.True(options.Overwrite);
Assert.True(options.Quiet);
}
[Fact]
public void ZipTakesANameOnlyWhenItIsOne()
{
Assert.True(UploadCommand.TryParse(["--zip", @"C:\out\a.zip"], out var a, out _));
Assert.Null(a.ZipName);
Assert.Equal([@"C:\out\a.zip"], a.Paths);
Assert.True(UploadCommand.TryParse(["x", "--zip=named"], out var b, out _));
Assert.Equal("named", b.ZipName);
Assert.True(UploadCommand.TryParse(["x", "-z"], out var c, out _));
Assert.True(c.Zip);
Assert.Null(c.ZipName);
Assert.Equal(UploadLayout.Preserve, c.Layout);
}
[Theory]
[InlineData(new string[0], "A file, folder or mask is required.")]
[InlineData(new[] { "x", "--flatten", "--preserve" }, "--flatten or --preserve, not both.")]
[InlineData(new[] { "x", "--dest" }, "--dest needs a folder name.")]
[InlineData(new[] { "x", "--bogus" }, "Unknown option '--bogus'.")]
public void BadCommandLines(string[] args, string message)
{
Assert.False(UploadCommand.TryParse(args, out _, out var error));
Assert.Equal(message, error);
}
[Fact]
public void TheJobComesFromTheJobFolder()
{
var id = Guid.NewGuid();
Assert.Equal(id, UploadCommand.JobIdFrom(Path.Combine(root, id.ToString("D")) + Path.DirectorySeparatorChar));
Assert.Null(UploadCommand.JobIdFrom(root));
Assert.Null(UploadCommand.JobIdFrom(null));
}
[Fact]
public async Task NothingFoundExits1WithoutAskingTheAgent()
{
var error = new StringWriter();
var code = await UploadCommand.ExecuteAsync(
new UploadOptions(["missing-*.log"]),
_ => throw new InvalidOperationException("must not connect"),
new StringWriter(), error, "me", root, interactive: false, CancellationToken.None);
Assert.Equal(UploadCommand.NoneUploaded, code);
Assert.Contains("Nothing to upload.", error.ToString());
}
// ── Over a real named pipe, through the agent's local channel ───────
private async Task<(int Code, string Out, string Error, FakeUploadBackend Backend)> RunOverPipeAsync(
Action<FakeUploadBackend>? arrange, bool allowed, params string[] args)
{
Assert.SkipUnless(OperatingSystem.IsWindows(), "The pipe rig is Windows'");
var backend = new FakeUploadBackend();
arrange?.Invoke(backend);
var name = $"executer-test-{Guid.NewGuid():N}";
var server = new LocalRunServer(
new FakeDeviceRunClient(_ => throw new InvalidOperationException()),
new JobObservers(),
NullLogger<LocalRunServer>.Instance,
new DeviceUploader(backend, backend, NullLogger<DeviceUploader>.Instance));
var me = WindowsIdentity.GetCurrent().User!;
using var stop = new CancellationTokenSource();
var listening = new WindowsPipeListener(
name, server, NullLogger.Instance,
security: () =>
{
var security = new PipeSecurity();
security.SetAccessRuleProtection(true, false);
security.AddAccessRule(new PipeAccessRule(me, PipeAccessRights.FullControl, AccessControlType.Allow));
return security;
},
authorize: _ => allowed).RunAsync(stop.Token);
Assert.True(UploadCommand.TryParse(args, out var options, out var parseError), parseError);
var stdout = new StringWriter();
var stderr = new StringWriter();
var jobId = Guid.NewGuid();
var code = await UploadCommand.ExecuteAsync(
options,
ct => WindowsPipeClient.ConnectAsync(name, ct, owner => owner == me || WindowsPipeClient.IsTrustedOwner(owner)),
stdout, stderr, "claimed-user", root, interactive: true, CancellationToken.None, jobId).WaitAsync(TimeSpan.FromSeconds(60));
await stop.CancelAsync();
await listening;
if (backend.Requests.FirstOrDefault() is { } begin)
{
Assert.True(begin.JobId == jobId, $"job {begin.JobId}");
Assert.Equal(DeviceUploadSources.Cli, begin.Source);
// The agent names the caller from the pipe, not from the client's claim.
Assert.Equal(WindowsIdentity.GetCurrent().Name, begin.LocalUser);
}
return (code, stdout.ToString(), stderr.ToString(), backend);
}
[Fact]
public async Task UploadsThroughTheAgentAndExits0()
{
Directory.CreateDirectory(Path.Combine(root, "Logs", "old"));
File.WriteAllText(Path.Combine(root, "Logs", "a.log"), "alpha");
File.WriteAllText(Path.Combine(root, "Logs", "old", "b.log"), "bravo");
var (code, stdout, stderr, backend) = await RunOverPipeAsync(null, true, @"Logs\*.log", "--recurse", "--dest", "case-1");
Assert.True(code == UploadCommand.AllUploaded, stdout + stderr);
Assert.Equal(["a.log", "old/b.log"], backend.Objects.Keys.Select(k => k[FakeUploadBackend.Folder.Length..]).Order());
Assert.Equal("case-1", backend.Requests.First().Folder);
Assert.Contains($"Uploading 2 files (10 B) to {FakeUploadBackend.Folder}", stdout);
Assert.Contains($"-> {FakeUploadBackend.Folder}old/b.log", stdout);
Assert.Contains("2 uploaded (10 B), 0 failed, 0 skipped", stdout);
Assert.DoesNotContain("put:", stdout + stderr);
}
[Fact]
public async Task SomeUploadedExits3AndSaysWhatWasNot()
{
File.WriteAllText(Path.Combine(root, "a.log"), "alpha");
File.WriteAllText(Path.Combine(root, "b.log"), "bravo");
var (code, stdout, stderr, _) = await RunOverPipeAsync(b => b.Existing.Add("b.log"), true, "*.log", "missing.txt", "-q");
Assert.Equal(UploadCommand.Partial, code);
Assert.Empty(stdout);
Assert.Contains("Skipped: b.log: Already there.", stderr);
Assert.Contains("missing.txt: no such file or folder", stderr);
}
[Fact]
public async Task ARefusalExits1()
{
File.WriteAllText(Path.Combine(root, "a.log"), "alpha");
var (code, _, stderr, _) = await RunOverPipeAsync(
b => b.BeginAnswer = new DeviceUploadReplyPayload(DeviceUploadStatuses.TooMany, "At most 1 files at once; this is 2."), true, "a.log");
Assert.Equal(UploadCommand.NoneUploaded, code);
Assert.Contains("At most 1 files at once", stderr);
}
[Fact]
public async Task ACallerWhoIsNotAnElevatedAdministratorIsRefused()
{
File.WriteAllText(Path.Combine(root, "a.log"), "alpha");
var (code, _, stderr, backend) = await RunOverPipeAsync(null, false, "a.log");
Assert.Equal(UploadCommand.NoneUploaded, code);
Assert.Contains("elevated administrator", stderr);
Assert.Empty(backend.Requests);
}
[Fact]
public async Task NoAgentExits2()
{
Assert.SkipUnless(OperatingSystem.IsWindows(), "named pipes");
File.WriteAllText(Path.Combine(root, "a.log"), "alpha");
var code = await UploadCommand.ExecuteAsync(
new UploadOptions(["a.log"]),
ct => WindowsPipeClient.ConnectAsync($"executer-none-{Guid.NewGuid():N}", ct),
new StringWriter(), new StringWriter(), "me", root, interactive: false, CancellationToken.None);
Assert.Equal(UploadCommand.Unreachable, code);
}
}
/// <summary>Every engine and mode knows where the agent is, to call it from a script.</summary>
public sealed class AgentLocationTests : IDisposable
{
private readonly string root = Directory.CreateTempSubdirectory("executer-agentloc-").FullName;
public void Dispose()
{
try
{
Directory.Delete(root, recursive: true);
}
catch (IOException)
{
}
}
[Fact]
public void TheAgentBinaryIsItselfAnyOtherHostNamesTheBinaryBesideIt()
{
var binary = Shared.Infrastructure.Constants.Branding.AgentBinaryName;
var installed = Path.Combine(root, "Agent", binary);
Assert.Equal((Path.Combine(root, "Agent"), installed), AgentLocation.Resolve(installed, Path.Combine(root, "elsewhere")));
Assert.Equal((Path.Combine(root, "bin"), Path.Combine(root, "bin", binary)), AgentLocation.Resolve(Path.Combine(root, "testhost.exe"), Path.Combine(root, "bin") + Path.DirectorySeparatorChar));
Assert.Equal(Path.Combine(AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar), binary), AgentLocation.ExecutablePath);
}
[Fact]
public async Task PowerShell7HasTheVariablesOnly()
{
var lines = new List<string>();
var result = await new PowerShellExecutionService().ExecuteAsync(
"\"dir=$ExecuteRAgentDir\"; \"path=$ExecuteRAgentPath\"",
null,
r => lines.Add(r.Text),
_ => { },
CancellationToken.None);
Assert.Null(result.FailureMessage);
Assert.Contains($"dir={AgentLocation.Directory}", lines);
Assert.Contains($"path={AgentLocation.ExecutablePath}", lines);
}
private async Task<List<string>> RunExternalAsync(ScriptEngine engine, string script)
{
var lines = new List<string>();
var folder = JobFolder.Create(root, Guid.NewGuid());
await ExternalScriptRunner.RunAsync(
engine, script, null, new Dictionary<string, object?>(), null, "Secrets", r => { lock (lines) lines.Add(r.Text); }, CancellationToken.None, folder: folder);
folder.Finish(cleanUp: true);
return lines;
}
[Fact]
public async Task WindowsPowerShellHasTheVariablesAndTheEnvironment()
{
Assert.SkipUnless(OperatingSystem.IsWindows(), "powershell.exe is Windows-only");
var lines = await RunExternalAsync(
ScriptEngine.WindowsPowerShell,
"\"dir=$ExecuteRAgentDir\"; \"path=$ExecuteRAgentPath\"; \"envdir=$env:EXECUTER_AGENT_DIR\"; \"envpath=$env:EXECUTER_AGENT_PATH\"");
Assert.Contains($"dir={AgentLocation.Directory}", lines);
Assert.Contains($"path={AgentLocation.ExecutablePath}", lines);
Assert.Contains($"envdir={AgentLocation.Directory}", lines);
Assert.Contains($"envpath={AgentLocation.ExecutablePath}", lines);
}
[Fact]
public async Task BashHasTheEnvironment()
{
Assert.SkipUnless(ExternalScriptRunner.IsAvailable(ScriptEngine.Bash), "bash is not available on this machine");
var lines = await RunExternalAsync(ScriptEngine.Bash, "echo \"envdir=$EXECUTER_AGENT_DIR\"\necho \"envpath=$EXECUTER_AGENT_PATH\"\n");
Assert.Contains($"envdir={AgentLocation.Directory}", lines);
Assert.Contains($"envpath={AgentLocation.ExecutablePath}", lines);
}
}