Files
Alphaeus Mote b5068d962f feat(scripts): per-job folders, Run From File and a configurable job root on the agent
Every script job now runs in <JobRoot>\<JobId>\, locked to SYSTEM and
Administrators (inheritance off; 0700 and root-owned on linux/macOS). The
script is staged under its own name (Install-Baseline.ps1), the 5.1
wrapper and preludes sit beside it as .executer-* helper files that are
always deleted, and the folder goes too with Clean Up After Run (default
on). Folders older than 7 days are swept at agent start.

- PowerShell 7 Run From File: the script is written to the job folder and
  invoked by path (AddCommand), so $PSScriptRoot, $PSCommandPath and
  $MyInvocation.MyCommand.Definition are the file's. The prelude runs first
  on its own; `exit N` reaches the host as with pwsh -File via the engine's
  rethrow-exit flag (with a $LASTEXITCODE fallback).
- Set Working Directory to Script Folder (staged runs only): process
  directory for 5.1/Bash, runspace location for PowerShell 7 (the shared
  process directory is never touched). Off keeps today's directory.
- $ExecuteRJobDir in both PowerShell engines (every mode) and
  EXECUTER_JOB_DIR for 5.1 and Bash.
- Bash sources the prelude through BASH_ENV, so the script file is the script.
- JobRoot policy (GPO > registry > default; ADMX/ADML, MSI JOBROOT):
  %VAR% / $VAR expansion as the agent, validation (absolute, local, not
  under user profiles, no parent others can rename), warning + default on
  a bad value, reported in the inventory.
- The script command carries RunFromFile, CleanUpAfterRun and
  SetWorkingDirectory (older backends: the defaults).

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

350 lines
14 KiB
C#

using System.Security.AccessControl;
using System.Security.Principal;
using Agent.Configuration;
using Agent.PowerShell;
using Shared.Contracts.Models;
using Shared.Infrastructure.Configuration;
using Shared.Infrastructure.Constants;
using Xunit;
namespace Agent.Tests;
/// <summary>Job folders: layout, ACL, cleanup, the stale sweep and the JobRoot setting.</summary>
public sealed class JobFolderTests : IDisposable
{
private readonly string root = Path.Combine(Path.GetTempPath(), "ExecuteR-Tests-" + Guid.NewGuid().ToString("N"));
private readonly List<string> extraRoots = [];
public void Dispose()
{
foreach (var path in extraRoots.Append(root))
{
try
{
Directory.Delete(path, recursive: true);
}
catch (IOException)
{
}
}
}
[Fact]
public void TheDefaultRootIsTheAgentsTempFolder()
=> Assert.Equal(Path.Combine(Path.GetTempPath(), "ExecuteR"), JobRoot.DefaultPath());
[Fact]
public void AJobGetsRootSlashJobId()
{
var jobId = Guid.NewGuid();
var folder = JobFolder.Create(root, jobId);
Assert.Equal(Path.Combine(root, jobId.ToString("D")), folder.Path);
Assert.True(Directory.Exists(folder.Path));
}
[Theory]
[InlineData("Install-Baseline", ScriptEngine.PowerShell, "Install-Baseline.ps1")]
[InlineData("Install Baseline (v2)", ScriptEngine.WindowsPowerShell, "Install-Baseline-v2.ps1")]
[InlineData("deploy.sh", ScriptEngine.Bash, "deploy.sh")]
[InlineData("Reset.PS1", ScriptEngine.PowerShell, "Reset.ps1")]
[InlineData("..\\..\\evil/../x", ScriptEngine.PowerShell, "evil-..-x.ps1")]
[InlineData(".hidden", ScriptEngine.PowerShell, "hidden.ps1")]
[InlineData("CON", ScriptEngine.PowerShell, "script-CON.ps1")]
[InlineData("???", ScriptEngine.Bash, "script.sh")]
[InlineData("Größe prüfen", ScriptEngine.PowerShell, "Größe-prüfen.ps1")]
public void TheScriptFileIsNamedAfterTheScript(string name, ScriptEngine engine, string expected)
=> Assert.Equal(expected, JobFolder.ScriptFileName(name, engine));
[Fact]
public void ALongNameIsCut()
=> Assert.Equal(new string('a', 100) + ".ps1", JobFolder.ScriptFileName(new string('a', 300), ScriptEngine.PowerShell));
[Fact]
public void CleanUpOnRemovesTheFolder()
{
var folder = JobFolder.Create(root, Guid.NewGuid());
folder.WriteScript("Job", ScriptEngine.PowerShell, "'x'");
File.WriteAllText(Path.Combine(folder.Path, "output.log"), "made by the script");
folder.Finish(cleanUp: true);
Assert.False(Directory.Exists(folder.Path));
}
[Fact]
public void CleanUpOffKeepsTheScriptAndItsOutputButNeverTheHelpers()
{
var folder = JobFolder.Create(root, Guid.NewGuid());
var script = folder.WriteScript("Job", ScriptEngine.WindowsPowerShell, "'x'");
var wrapper = folder.WriteHelper(ExternalScriptRunner.WrapperFileName, "$Secrets = @{ ApiKey = 'k-1' }");
var prelude = folder.WriteHelper(ExternalScriptRunner.PowerShellPreludeFileName, "function F { }");
var output = Path.Combine(folder.Path, "output.log");
File.WriteAllText(output, "made by the script");
folder.Finish(cleanUp: false);
Assert.True(File.Exists(script));
Assert.True(File.Exists(output));
Assert.False(File.Exists(wrapper));
Assert.False(File.Exists(prelude));
}
[Fact]
public void TheSweepRemovesOnlyOldJobFolders()
{
Directory.CreateDirectory(root);
var now = DateTime.UtcNow;
string Make(string name, TimeSpan age)
{
var path = Path.Combine(root, name);
Directory.CreateDirectory(path);
File.WriteAllText(Path.Combine(path, "f.txt"), "x");
Directory.SetCreationTimeUtc(path, now - age);
Directory.SetLastWriteTimeUtc(path, now - age);
return path;
}
var old = Make(Guid.NewGuid().ToString("D"), TimeSpan.FromDays(8));
var recent = Make(Guid.NewGuid().ToString("D"), TimeSpan.FromDays(2));
var notAJob = Make("keep-me", TimeSpan.FromDays(30));
var removed = JobFolderSweeper.Sweep(root, JobFolderSweeper.StaleAfter, now);
Assert.Equal(1, removed);
Assert.False(Directory.Exists(old));
Assert.True(Directory.Exists(recent));
Assert.True(Directory.Exists(notAJob));
Assert.Equal(TimeSpan.FromDays(7), JobFolderSweeper.StaleAfter);
}
[Fact]
public void TheSweepOfAMissingRootDoesNothing()
=> Assert.Equal(0, JobFolderSweeper.Sweep(Path.Combine(root, "missing"), TimeSpan.Zero, DateTime.UtcNow));
[Fact]
public void FoldersAndFilesAreLockedToSystemAndAdministrators()
{
Assert.SkipUnless(OperatingSystem.IsWindows(), "Windows ACLs");
var folder = JobFolder.Create(root, Guid.NewGuid());
var script = folder.WriteScript("Job", ScriptEngine.PowerShell, "'x'");
var allowed = new HashSet<SecurityIdentifier>
{
new(WellKnownSidType.LocalSystemSid, null),
new(WellKnownSidType.BuiltinAdministratorsSid, null),
WindowsIdentity.GetCurrent().User!, // the test runner: the agent's own account outside LocalSystem
};
foreach (var security in new FileSystemSecurity[]
{
new DirectoryInfo(root).GetAccessControl(),
new DirectoryInfo(folder.Path).GetAccessControl(),
new FileInfo(script).GetAccessControl(),
})
{
Assert.True(security.AreAccessRulesProtected, "inheritance must be off");
var rules = security.GetAccessRules(includeExplicit: true, includeInherited: true, typeof(SecurityIdentifier))
.Cast<FileSystemAccessRule>().ToList();
Assert.NotEmpty(rules);
Assert.All(rules, rule =>
{
Assert.Equal(AccessControlType.Allow, rule.AccessControlType);
Assert.Contains((SecurityIdentifier)rule.IdentityReference, allowed);
});
Assert.Contains(rules, r => ((SecurityIdentifier)r.IdentityReference).IsWellKnown(WellKnownSidType.LocalSystemSid));
Assert.Contains(rules, r => ((SecurityIdentifier)r.IdentityReference).IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid));
}
}
[Fact]
public void AnExistingRootIsLockedDownAgain()
{
Assert.SkipUnless(OperatingSystem.IsWindows(), "Windows ACLs");
Directory.CreateDirectory(root);
var open = new DirectoryInfo(root).GetAccessControl();
open.AddAccessRule(new FileSystemAccessRule(
new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, AccessControlType.Allow));
new DirectoryInfo(root).SetAccessControl(open);
JobFolder.Create(root, Guid.NewGuid());
var rules = new DirectoryInfo(root).GetAccessControl()
.GetAccessRules(true, true, typeof(SecurityIdentifier)).Cast<FileSystemAccessRule>();
Assert.DoesNotContain(rules, r => ((SecurityIdentifier)r.IdentityReference).IsWellKnown(WellKnownSidType.WorldSid));
}
[Fact]
public void AJunctionAsRootIsRefused()
{
Assert.SkipUnless(OperatingSystem.IsWindows(), "junctions");
var target = Directory.CreateDirectory(Path.Combine(root, "target")).FullName;
var link = Path.Combine(root, "link");
// A junction (no privilege needed, unlike a symbolic link).
using (var mklink = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(
"cmd.exe", $"/c mklink /J \"{link}\" \"{target}\"") { UseShellExecute = false, RedirectStandardOutput = true })!)
{
mklink.WaitForExit();
Assert.Equal(0, mklink.ExitCode);
}
var ex = Assert.Throws<JobFolderException>(() => JobFolder.Create(link, Guid.NewGuid()));
Assert.Contains("link or junction", ex.Message);
}
// ── The JobRoot setting ───────────────────────────────────────────
[Fact]
public void WindowsStyleVariablesExpandFromTheAgentsEnvironment()
{
Environment.SetEnvironmentVariable("EXECUTER_TEST_JOBROOT", @"D:\Ops");
try
{
Assert.Null(JobRoot.TryExpand(@"%EXECUTER_TEST_JOBROOT%\Jobs", windowsStyle: true, out var expanded));
Assert.Equal(@"D:\Ops\Jobs", expanded);
var problem = JobRoot.TryExpand(@"%EXECUTER_TEST_UNDEFINED%\Jobs", windowsStyle: true, out _);
Assert.Contains("%EXECUTER_TEST_UNDEFINED%", problem);
}
finally
{
Environment.SetEnvironmentVariable("EXECUTER_TEST_JOBROOT", null);
}
}
[Fact]
public void UnixStyleVariablesExpandBothForms()
{
var environment = new Dictionary<string, string> { ["TMPDIR"] = "/var/tmp", ["SITE"] = "eu" };
string? Env(string name) => environment.GetValueOrDefault(name);
Assert.Null(JobRoot.TryExpand("$TMPDIR/ExecuteR-${SITE}", windowsStyle: false, out var expanded, Env));
Assert.Equal("/var/tmp/ExecuteR-eu", expanded);
var problem = JobRoot.TryExpand("$NOPE/x", windowsStyle: false, out _, Env);
Assert.Contains("$NOPE", problem);
}
[Theory]
[InlineData(@"Jobs\ExecuteR", "absolute")]
[InlineData(@"\\server\share\ExecuteR", "UNC")]
[InlineData(@"\\?\C:\ExecuteR", "UNC")]
[InlineData(@"C:\", "root")]
[InlineData(@"C:\Users\Public\ExecuteR", "user profiles")]
[InlineData(@"C:\Users\someone\AppData\Local\Temp\ExecuteR", "user profiles")]
public void BadValuesAreRefused(string value, string reason)
{
Assert.SkipUnless(OperatingSystem.IsWindows(), "Windows paths");
var problem = JobRoot.Validate(value);
Assert.NotNull(problem);
Assert.Contains(reason, problem, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void ALocalAdminOnlyFolderIsAccepted()
{
Assert.SkipUnless(OperatingSystem.IsWindows(), "Windows paths");
// C:\Windows\Temp: users may create entries but not delete or rename others'.
Assert.Null(JobRoot.Validate(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Temp", "ExecuteR")));
}
[Fact]
public void AParentOthersCanRenameIsRefused()
{
Assert.SkipUnless(OperatingSystem.IsWindows(), "Windows ACLs");
var parent = Directory.CreateDirectory(Path.Combine(root, "parent"));
var child = Path.Combine(parent.FullName, "Jobs");
Assert.Null(JobRoot.CheckParents(child));
var security = parent.GetAccessControl();
security.AddAccessRule(new FileSystemAccessRule(
new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null), FileSystemRights.Delete, AccessControlType.Allow));
parent.SetAccessControl(security);
var problem = JobRoot.CheckParents(child);
Assert.NotNull(problem);
Assert.Contains("could be replaced", problem);
}
[Fact]
public void UnsetUsesTheDefault()
{
var info = JobRoot.Resolve(new ConfigurationValue<string?>(null, ConfigurationSource.Default));
Assert.Equal(JobRoot.DefaultPath(), info.Path);
Assert.Equal(ConfigurationSource.Default, info.Source);
Assert.Null(info.Problem);
}
[Fact]
public void AGoodValueIsExpandedCreatedAndUsed()
{
Assert.SkipUnless(OperatingSystem.IsWindows(), "Windows paths");
var name = "ExecuteR-Tests-" + Guid.NewGuid().ToString("N");
var expected = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), name);
extraRoots.Add(expected);
var info = JobRoot.Resolve(new ConfigurationValue<string?>($@"%ProgramData%\{name}", ConfigurationSource.GroupPolicy));
Assert.Null(info.Problem);
Assert.Equal(expected, info.Path);
Assert.Equal(ConfigurationSource.GroupPolicy, info.Source);
Assert.True(new DirectoryInfo(expected).GetAccessControl().AreAccessRulesProtected);
Assert.Equal(new InventoryJobFolder(expected, "GroupPolicy", $@"%ProgramData%\{name}"), info.ToInventory());
}
[Theory]
[InlineData(@"%EXECUTER_TEST_UNDEFINED%\Jobs")]
[InlineData(@"\\server\share\Jobs")]
[InlineData("relative")]
public void ABadValueFallsBackToTheDefaultAndSaysWhy(string value)
{
var logger = new ListLogger();
var info = JobRoot.Resolve(new ConfigurationValue<string?>(value, ConfigurationSource.Registry), logger);
Assert.Equal(JobRoot.DefaultPath(), info.Path);
Assert.Equal(ConfigurationSource.Default, info.Source);
Assert.Equal(value, info.Configured);
Assert.NotNull(info.Problem);
Assert.Contains(logger.Messages, m => m.Level == Microsoft.Extensions.Logging.LogLevel.Warning && m.Text.Contains(value));
}
[Fact]
public void JobRootFollowsStringPrecedence()
{
var registry = new InMemoryRegistryStore();
Assert.Null(new AgentConfigurationLoader(registry, allowEnvironment: false).Load().JobRoot.Value);
registry.SetString(Branding.AgentRegistryKey, AgentConfigurationKeys.JobRoot, @"D:\Local");
var local = new AgentConfigurationLoader(registry, allowEnvironment: false).Load();
Assert.Equal(@"D:\Local", local.JobRoot.Value);
Assert.Equal(ConfigurationSource.Registry, local.JobRoot.Source);
registry.SetString(Branding.AgentPolicyRegistryKey, AgentConfigurationKeys.JobRoot, @"%SystemRoot%\Temp\ExecuteR");
var policy = new AgentConfigurationLoader(registry, allowEnvironment: false).Load();
Assert.Equal(@"%SystemRoot%\Temp\ExecuteR", policy.JobRoot.Value);
Assert.True(policy.JobRoot.IsPolicyControlled);
}
private sealed class ListLogger : Microsoft.Extensions.Logging.ILogger
{
public List<(Microsoft.Extensions.Logging.LogLevel Level, string Text)> Messages { get; } = [];
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel logLevel) => true;
public void Log<TState>(
Microsoft.Extensions.Logging.LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId, TState state,
Exception? exception, Func<TState, Exception?, string> formatter)
=> Messages.Add((logLevel, formatter(state, exception)));
}
}