Files
Alphaeus Mote 3e994102ed feat(agent): shells and scripts can run as the signed-in user [skip ci]
- Remote Shell gets Run As: Agent Account (default) or Signed-In User. Windows
  starts the shell with the user's own token, environment and profile folder on
  their desktop, headless; Linux and macOS start their login shell through su -l.
- Scripts get Run As Signed-In User. Every engine then runs out of process as the
  user (PowerShell 7 in the agent's built-in host, 5.1, Bash; su on unix), with
  no window, and the user is given that job folder only.
- The user is the console's, else the only one signed in; several and nobody at
  the console is refused rather than guessed.
- The server never sends either to agents older than 1.13.0 (they would ignore it
  and run as the agent's account): such jobs are created failed, the shell is
  refused. Migration for all three providers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 08:59:56 -05:00

104 lines
3.5 KiB
C#

using System.Security.Principal;
using System.Text;
using Agent.Platform;
using Agent.PowerShell;
using Agent.Sessions;
using Agent.Shell;
using Shared.Contracts.Messages;
using Shared.Contracts.Models;
using Xunit;
namespace Agent.Tests;
/// <summary>
/// The real thing: only as LocalSystem with someone signed in (run the suite as SYSTEM, e.g. from a
/// scheduled task, to exercise it). Elsewhere each test skips.
/// </summary>
public class RunAsUserLiveTests
{
private static SignedInUser RequireUser()
{
using var self = WindowsIdentity.GetCurrent();
Assert.SkipUnless(self.IsSystem, "Runs only as LocalSystem.");
var lookup = SignedInUsers.Default.Resolve();
Assert.SkipWhen(lookup.User is null, lookup.Reason ?? "Nobody is signed in.");
return lookup.User!;
}
[Fact]
public async Task WindowsPowerShellRunsAsTheSignedInUser()
{
var user = RequireUser();
var lines = new List<NormalizedOutputRecord>();
var result = await ExternalScriptRunner.RunAsync(
ScriptEngine.WindowsPowerShell,
"[Security.Principal.WindowsIdentity]::GetCurrent().Name; $env:USERPROFILE; (Get-Location).Path; $env:EXECUTER_JOB_DIR; Get-Content (Join-Path $env:EXECUTER_JOB_DIR 'probe.txt')",
prelude: null,
new Dictionary<string, object?>(),
secrets: null,
"Secrets",
record =>
{
lock (lines)
{
lines.Add(record);
}
},
TestContext.Current.CancellationToken,
runAs: user,
folder: WithProbe());
var output = string.Join("\n", lines.Select(l => $"{l.Stream}: {l.Text}"));
Assert.True(result.ExitCode == 0, output);
Assert.Contains(user.Name, output, StringComparison.OrdinalIgnoreCase);
Assert.Contains("probe-ok", output);
Assert.DoesNotContain(@"NT AUTHORITY\SYSTEM", output, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task ShellRunsAsTheSignedInUser()
{
var user = RequireUser();
using var token = WindowsUserToken.Open(user);
var environment = token.EnvironmentBlock(null);
var output = new StringBuilder();
var exited = new TaskCompletionSource();
using var pty = new ConPtySession(new PtyUser(token.Handle, environment, token.ProfileDirectory()));
pty.OutputReceived += data =>
{
lock (output)
{
output.Append(Encoding.UTF8.GetString(data.Span));
}
};
pty.Exited += () => exited.TrySetResult();
try
{
pty.Start(Path.Combine(Environment.SystemDirectory, "cmd.exe"), ["/c", "whoami"], 120, 30);
}
finally
{
System.Runtime.InteropServices.Marshal.FreeHGlobal(environment);
}
await exited.Task.WaitAsync(TimeSpan.FromSeconds(20), TestContext.Current.CancellationToken);
await Task.Delay(500, TestContext.Current.CancellationToken);
string text;
lock (output)
{
text = output.ToString();
}
var bare = user.Name.Split('\\').Last();
Assert.Contains(bare, text, StringComparison.OrdinalIgnoreCase);
}
private static JobFolder WithProbe()
{
var folder = JobFolder.Create(Path.Combine(Path.GetTempPath(), "executer-runas-" + Guid.NewGuid().ToString("N")), Guid.NewGuid());
folder.WriteHelper("probe.txt", "probe-ok");
return folder;
}
}