b5068d962f
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>
188 lines
7.1 KiB
C#
188 lines
7.1 KiB
C#
using Agent.PowerShell;
|
|
using Shared.Contracts.Messages;
|
|
using Shared.Contracts.Models;
|
|
using Xunit;
|
|
|
|
namespace Agent.Tests;
|
|
|
|
/// <summary>
|
|
/// Windows PowerShell 5.1 and Bash in the job folder: the staged script's
|
|
/// name and what it reports about itself, the job folder variable, the
|
|
/// working directory option and the helper files (secrets) never surviving.
|
|
/// </summary>
|
|
public sealed class ExternalJobFolderTests : IDisposable
|
|
{
|
|
private readonly string root = Path.Combine(Path.GetTempPath(), "ExecuteR-Tests-" + Guid.NewGuid().ToString("N"));
|
|
private readonly JobFolder folder;
|
|
|
|
public ExternalJobFolderTests() => folder = JobFolder.Create(root, Guid.NewGuid());
|
|
|
|
public void Dispose()
|
|
{
|
|
try
|
|
{
|
|
Directory.Delete(root, recursive: true);
|
|
}
|
|
catch (IOException)
|
|
{
|
|
}
|
|
}
|
|
|
|
private async Task<(List<string> Lines, ExternalScriptRunner.ExternalResult Result)> RunAsync(
|
|
ScriptEngine engine, string script, string? prelude = null, bool setWorkingDirectory = false)
|
|
{
|
|
var records = new List<NormalizedOutputRecord>();
|
|
var result = await ExternalScriptRunner.RunAsync(
|
|
engine,
|
|
script,
|
|
prelude,
|
|
parameters: new Dictionary<string, object?> { ["Label"] = "widget" },
|
|
secrets: [new ScriptSecret("ApiKey", "k-789")],
|
|
secretsVariableName: "Secrets",
|
|
onRecord: r => { lock (records) records.Add(r); },
|
|
CancellationToken.None,
|
|
folder: folder,
|
|
scriptName: "Install Baseline",
|
|
setWorkingDirectory: setWorkingDirectory);
|
|
return (records.Select(r => r.Text).ToList(), result);
|
|
}
|
|
|
|
private static void RequireWindowsPowerShell()
|
|
=> Assert.SkipUnless(OperatingSystem.IsWindows(), "powershell.exe is Windows-only");
|
|
|
|
private static void RequireBash()
|
|
=> Assert.SkipUnless(ExternalScriptRunner.IsAvailable(ScriptEngine.Bash), "bash is not available on this machine");
|
|
|
|
[Fact]
|
|
public async Task WindowsPowerShellSeesItsOwnFile()
|
|
{
|
|
RequireWindowsPowerShell();
|
|
|
|
var (lines, result) = await RunAsync(
|
|
ScriptEngine.WindowsPowerShell,
|
|
"""
|
|
param([string]$Label)
|
|
"root=$PSScriptRoot"
|
|
"path=$PSCommandPath"
|
|
"def=$($MyInvocation.MyCommand.Definition)"
|
|
"name=$($MyInvocation.MyCommand.Name)"
|
|
"var=$ExecuteRJobDir"
|
|
"env=$env:EXECUTER_JOB_DIR"
|
|
"$(Get-Greeting) $Label $($Secrets.apikey)"
|
|
"helpers=$((Get-ChildItem -Force -LiteralPath $PSScriptRoot -Filter '.executer-*' | Sort-Object Name | ForEach-Object Name) -join ',')"
|
|
exit 4
|
|
""",
|
|
prelude: "function Get-Greeting { 'hello' }");
|
|
|
|
var path = Path.Combine(folder.Path, "Install-Baseline.ps1");
|
|
Assert.Equal(4, result.ExitCode);
|
|
Assert.Contains($"root={folder.Path}", lines);
|
|
Assert.Contains($"path={path}", lines);
|
|
Assert.Contains($"def={path}", lines);
|
|
Assert.Contains("name=Install-Baseline.ps1", lines);
|
|
Assert.Contains($"var={folder.Path}", lines);
|
|
Assert.Contains($"env={folder.Path}", lines);
|
|
Assert.Contains("hello widget k-789", lines);
|
|
// The wrapper (holding the secrets) and the prelude sat beside the script while it ran.
|
|
Assert.Contains("helpers=.executer-prelude.ps1,.executer-wrapper.ps1", lines);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData(true)]
|
|
[InlineData(false)]
|
|
public async Task WindowsPowerShellWorkingDirectoryOption(bool setWorkingDirectory)
|
|
{
|
|
RequireWindowsPowerShell();
|
|
|
|
var (lines, _) = await RunAsync(ScriptEngine.WindowsPowerShell, "\"loc=$((Get-Location).Path)\"", setWorkingDirectory: setWorkingDirectory);
|
|
|
|
var expected = setWorkingDirectory ? folder.Path : Path.TrimEndingDirectorySeparator(Environment.CurrentDirectory);
|
|
Assert.Contains($"loc={expected}", lines.Select(l => l.TrimEnd('\\')));
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData(true)]
|
|
[InlineData(false)]
|
|
public async Task HelperFilesHoldingSecretsNeverSurviveTheRun(bool cleanUp)
|
|
{
|
|
RequireWindowsPowerShell();
|
|
|
|
await RunAsync(ScriptEngine.WindowsPowerShell, "'ran'", prelude: "function F { }");
|
|
folder.Finish(cleanUp);
|
|
|
|
if (cleanUp)
|
|
{
|
|
Assert.False(Directory.Exists(folder.Path));
|
|
}
|
|
else
|
|
{
|
|
Assert.Equal(["Install-Baseline.ps1"], Directory.GetFiles(folder.Path).Select(Path.GetFileName));
|
|
Assert.DoesNotContain(
|
|
Directory.GetFiles(folder.Path).Select(File.ReadAllText), text => text.Contains("k-789"));
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public async Task BashSeesItsOwnFileAndThePrelude()
|
|
{
|
|
RequireBash();
|
|
|
|
var (lines, result) = await RunAsync(
|
|
ScriptEngine.Bash,
|
|
"""
|
|
echo "zero=$(basename "$0")"
|
|
echo "source=$(basename "${BASH_SOURCE[0]}")"
|
|
echo "dir=$(cd "$(dirname "$0")" && pwd)"
|
|
echo "jobdir=$(cd "$EXECUTER_JOB_DIR" && pwd)"
|
|
echo "$(greet) $Label $ApiKey"
|
|
echo "bash_env=${BASH_ENV:-unset}"
|
|
exit 6
|
|
""",
|
|
prelude: "greet() { echo hello; }");
|
|
|
|
Assert.Equal(6, result.ExitCode);
|
|
Assert.Contains("zero=Install-Baseline.sh", lines);
|
|
Assert.Contains("source=Install-Baseline.sh", lines);
|
|
var dir = Assert.Single(lines, l => l.StartsWith("dir=", StringComparison.Ordinal))[4..];
|
|
Assert.Contains($"jobdir={dir}", lines);
|
|
Assert.Contains("hello widget k-789", lines);
|
|
// The prelude unsets BASH_ENV, so bash scripts the job starts do not re-run it.
|
|
Assert.Contains("bash_env=unset", lines);
|
|
Assert.False(File.Exists(Path.Combine(folder.Path, "Install-Baseline.sh")) && File.ReadAllText(Path.Combine(folder.Path, "Install-Baseline.sh")).Contains("greet()"));
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData(true)]
|
|
[InlineData(false)]
|
|
public async Task BashWorkingDirectoryOption(bool setWorkingDirectory)
|
|
{
|
|
RequireBash();
|
|
|
|
var (lines, _) = await RunAsync(
|
|
ScriptEngine.Bash,
|
|
"""
|
|
here=$(pwd)
|
|
script=$(cd "$(dirname "$0")" && pwd)
|
|
if [ "$here" = "$script" ]; then echo "in-folder"; else echo "elsewhere"; fi
|
|
""",
|
|
setWorkingDirectory: setWorkingDirectory);
|
|
|
|
Assert.Contains(setWorkingDirectory ? "in-folder" : "elsewhere", lines);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task WithoutAFolderAThrowawayOneIsUsedAndRemoved()
|
|
{
|
|
RequireWindowsPowerShell();
|
|
|
|
var records = new List<NormalizedOutputRecord>();
|
|
await ExternalScriptRunner.RunAsync(
|
|
ScriptEngine.WindowsPowerShell, "\"root=$PSScriptRoot\"", null, new Dictionary<string, object?>(), null, "Secrets",
|
|
r => { lock (records) records.Add(r); }, CancellationToken.None);
|
|
|
|
var reported = Assert.Single(records, r => r.Text.StartsWith("root=")).Text[5..];
|
|
Assert.Equal(JobRoot.DefaultPath(), Path.GetDirectoryName(reported));
|
|
Assert.False(Directory.Exists(reported));
|
|
}
|
|
}
|