Files
Alphaeus Mote e1fcdf4cea feat(scripts): Run As Each Signed-In User [skip ci]
The script editor's Run As is now a choice: Agent Account, Signed-In User, or
Each Signed-In User. Each runs the script once per signed-in user, in turn,
under one timeout; any failure fails the job and names who. Nobody signed in
runs nothing and succeeds. The server refuses it for agents before 1.14.0.
Migration for all three providers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 12:28:54 -05:00

201 lines
9.8 KiB
C#

using System.Net;
using System.Net.Http.Json;
using Backend.Jobs;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Shared.Contracts.Api;
using Shared.Contracts.Messages;
using Shared.Contracts.Models;
using Shared.Contracts.Serialization;
using Xunit;
namespace Backend.Tests;
/// <summary>
/// Run As Signed-In User: stored on the script, sealed into snapshots, carried to the agent, and
/// never sent to an agent too old to honor it (it would run the script as its own account).
/// </summary>
public class RunAsUserTests(BackendTestFixture fixture) : IClassFixture<BackendTestFixture>
{
private const string Current = RunAsUser.MinimumAgentVersion;
private const string Old = "1.12.0";
private static async Task<ScriptDto> SaveAsync(HttpClient client, SaveScriptRequest request, Guid? id = null)
{
var response = id is null
? await client.PostAsJsonAsync(ApiRoutes.Scripts, request, JsonDefaults.Options)
: await client.PutAsJsonAsync(ApiRoutes.For.Script(id.Value), request, JsonDefaults.Options);
response.EnsureSuccessStatusCode();
return (await response.Content.ReadFromJsonAsync<ScriptDto>(JsonDefaults.Options))!;
}
private static SaveScriptRequest Request(string name, bool? asUser = null, ScriptEngine engine = ScriptEngine.PowerShell, bool? workingDirectory = null)
=> new(name, null, "'hello'", Engine: engine, RunAsUser: asUser, SetWorkingDirectory: workingDirectory);
[Fact]
public async Task TheOptionIsSavedAndLeftOutKeepsIt()
{
using var client = await fixture.SignedInAsync("runas-admin");
Assert.False((await SaveAsync(client, Request("runas-default"))).RunAsUser);
var created = await SaveAsync(client, Request("runas-saved", asUser: true));
Assert.True(created.RunAsUser);
Assert.True((await SaveAsync(client, Request("runas-saved"), created.Id)).RunAsUser);
Assert.False((await SaveAsync(client, Request("runas-saved", asUser: false), created.Id)).RunAsUser);
}
[Fact]
public async Task PowerShell7AsTheUserStagesAFileSoItKeepsTheWorkingDirectory()
{
using var client = await fixture.SignedInAsync("runas-admin");
Assert.True((await SaveAsync(client, Request("runas-wd", asUser: true, workingDirectory: true))).SetWorkingDirectory);
Assert.False((await SaveAsync(client, Request("runas-wd-off", asUser: false, workingDirectory: true))).SetWorkingDirectory);
}
[Fact]
public async Task ACurrentAgentGetsTheOptionAndAnOlderOneGetsAFailedJob()
{
fixture.Scripts.Accept = true;
using var client = await fixture.SignedInAsync("runas-admin");
var script = await SaveAsync(client, Request("runas-dispatch", asUser: true));
var current = await fixture.SeedDeviceAsync("RUNAS-NEW", agentVersion: Current);
var old = await fixture.SeedDeviceAsync("RUNAS-OLD", agentVersion: Old);
(await client.PostAsJsonAsync(ApiRoutes.Jobs, new CreateJobRequest(null, script.Id, ClientIds: [current, old]), JsonDefaults.Options))
.EnsureSuccessStatusCode();
Assert.True(Sent(current).Single().RunAsUser);
Assert.Empty(Sent(old));
var refused = await fixture.WithDbAsync(db => db.Jobs.AsNoTracking().SingleAsync(j => j.ClientId == old && j.ScriptId == script.Id));
Assert.Equal(JobState.Failed, refused.State);
Assert.Contains(RunAsUser.MinimumAgentVersion, refused.OutputSummary);
Assert.NotNull(refused.CompletedUtc);
}
[Fact]
public async Task TheDispatcherRefusesAnOlderAgentToo()
{
fixture.Scripts.Accept = true;
using var client = await fixture.SignedInAsync("runas-admin");
var script = await SaveAsync(client, Request("runas-stagger", asUser: true));
var current = await fixture.SeedDeviceAsync("RUNAS-STAG-NEW", agentVersion: Current);
var old = await fixture.SeedDeviceAsync("RUNAS-STAG-OLD", agentVersion: Old);
var response = await client.PostAsJsonAsync(
ApiRoutes.Jobs, new CreateJobRequest(null, script.Id, ClientIds: [current, old], StaggerSeconds: 600), JsonDefaults.Options);
response.EnsureSuccessStatusCode();
var run = (await response.Content.ReadFromJsonAsync<GroupRunDto>(JsonDefaults.Options))!;
var latest = await fixture.WithDbAsync(db => db.Jobs.AsNoTracking().Where(j => j.RunId == run.RunId).MaxAsync(j => j.NotBeforeUtc));
await new JobDispatcher(fixture.Services.GetRequiredService<IServiceScopeFactory>(), NullLogger<JobDispatcher>.Instance)
.RunPassAsync(latest!.Value.AddSeconds(1), CancellationToken.None);
Assert.True(Sent(current).Single().RunAsUser);
Assert.Empty(Sent(old));
var refused = await fixture.WithDbAsync(db => db.Jobs.AsNoTracking().SingleAsync(j => j.RunId == run.RunId && j.ClientId == old));
Assert.Equal(JobState.Failed, refused.State);
}
[Fact]
public async Task EachSignedInUserTurnsRunAsOnAndTurningRunAsOffClearsIt()
{
using var client = await fixture.SignedInAsync("runas-each-admin");
var created = await SaveAsync(client, new SaveScriptRequest("runas-each", null, "'hi'", RunAsEachUser: true));
Assert.True(created.RunAsUser);
Assert.True(created.RunAsEachUser);
Assert.True((await SaveAsync(client, Request("runas-each"), created.Id)).RunAsEachUser);
var off = await SaveAsync(client, Request("runas-each", asUser: false), created.Id);
Assert.False(off.RunAsUser);
Assert.False(off.RunAsEachUser);
}
[Fact]
public async Task EachSignedInUserGoesOnlyToAgentsThatHonorIt()
{
fixture.Scripts.Accept = true;
using var client = await fixture.SignedInAsync("runas-each-run");
var script = await SaveAsync(client, new SaveScriptRequest("runas-each-dispatch", null, "'hi'", RunAsEachUser: true));
var current = await fixture.SeedDeviceAsync("RUNAS-EACH-NEW", agentVersion: RunAsUser.EachUserMinimumAgentVersion);
var older = await fixture.SeedDeviceAsync("RUNAS-EACH-OLD", agentVersion: Current);
(await client.PostAsJsonAsync(ApiRoutes.Jobs, new CreateJobRequest(null, script.Id, ClientIds: [current, older]), JsonDefaults.Options))
.EnsureSuccessStatusCode();
var sent = Sent(current).Single();
Assert.True(sent.RunAsUser && sent.RunAsEachUser);
Assert.Empty(Sent(older));
var refused = await fixture.WithDbAsync(db => db.Jobs.AsNoTracking().SingleAsync(j => j.ClientId == older && j.ScriptId == script.Id));
Assert.Equal(JobState.Failed, refused.State);
Assert.Contains(RunAsUser.EachUserMinimumAgentVersion, refused.OutputSummary);
}
[Fact]
public async Task ScriptsThatRunAsTheAgentStillGoToOlderAgents()
{
fixture.Scripts.Accept = true;
using var client = await fixture.SignedInAsync("runas-admin");
var script = await SaveAsync(client, Request("runas-not-asked"));
var old = await fixture.SeedDeviceAsync("RUNAS-OLD-PLAIN", agentVersion: Old);
(await client.PostAsJsonAsync(ApiRoutes.Jobs, new CreateJobRequest(old, script.Id), JsonDefaults.Options)).EnsureSuccessStatusCode();
Assert.False(Sent(old).Single().RunAsUser);
}
[Theory]
[InlineData("1.13.0", true)]
[InlineData("1.14.2", true)]
[InlineData("1.12.9", false)]
[InlineData(null, false)]
[InlineData("2026.10.23.1400", false)]
public void OnlyNewEnoughAgentsHonorIt(string? version, bool supported)
{
Assert.Equal(supported, RunAsUser.Supported(version));
Assert.Equal(supported, JobRunner.RunAsUserRefusal(true, version) is null);
Assert.Null(JobRunner.RunAsUserRefusal(false, version));
}
[Fact]
public void OlderSnapshotsAndCommandsDoNotRunAsTheUser()
{
var snapshot = JsonDefaults.Deserialize<RunSnapshot>(
$$"""{"scriptId":"{{Guid.NewGuid()}}","name":"n","language":"PowerShell","content":"c"}""")!;
Assert.False(snapshot.ToScript().RunAsUser);
var command = JsonDefaults.Deserialize<ShellOpenCommandPayload>($$"""{"sessionId":"{{Guid.NewGuid()}}","cols":80,"rows":24}""")!;
Assert.False(command.AsUser);
}
private List<ScriptCommandPayload> Sent(string clientId)
{
lock (fixture.Scripts.Sent)
{
return fixture.Scripts.Sent.Where(s => s.ClientId == clientId).Select(s => s.Command).ToList();
}
}
[Fact]
public async Task AShellCanNameWhichSignedInUserButOnlyAsAPlainName()
{
using var client = await fixture.SignedInAsync("runas-shell-user");
using var nkey = NATS.NKeys.KeyPair.CreatePair(NATS.NKeys.PrefixByte.User);
var credential = await (await client.PostAsJsonAsync(ApiRoutes.BrowserNatsCredential,
new BrowserCredentialRequest(nkey.GetPublicKey(), null), JsonDefaults.Options))
.Content.ReadFromJsonAsync<BrowserCredentialResponse>(JsonDefaults.Options);
var device = await fixture.SeedDeviceAsync("RUNAS-SHELL", agentVersion: Current);
Task<HttpResponseMessage> OpenAsync(bool asUser, string user)
=> client.PostAsJsonAsync(ApiRoutes.For.DeviceShell(device),
new CreateShellRequest(credential!.BrowserSessionId, 80, 24, null, asUser, user), JsonDefaults.Options);
Assert.Equal(HttpStatusCode.BadRequest, (await OpenAsync(false, "ann")).StatusCode);
Assert.Equal(HttpStatusCode.BadRequest, (await OpenAsync(true, "ann,bob")).StatusCode);
Assert.Equal(HttpStatusCode.BadRequest, (await OpenAsync(true, "../etc")).StatusCode);
// A domain account passes the check (the test server has no agent to send the open to).
Assert.NotEqual(HttpStatusCode.BadRequest, (await OpenAsync(true, @"CONTOSO\ann")).StatusCode);
}
}