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

163 lines
7.0 KiB
C#

using System.Net.Http.Json;
using Backend.Auth;
using Backend.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Shared.Contracts.Models;
namespace Backend.Tests;
/// <summary>Signed-in HTTP clients and seed helpers shared by the endpoint tests.</summary>
internal static class TestClients
{
public const string Password = "test-account-password";
/// <summary>
/// A client signed in as a built-in account whose group is bound to the
/// named system role (or <paramref name="roleId"/>), with the CSRF header
/// that cookie-authenticated writes require.
/// </summary>
public static async Task<HttpClient> SignedInAsync(
this BackendTestFixture fixture, string username, string roleName = "Admin", Guid? roleId = null)
{
await fixture.WithDbAsync(async db =>
{
var role = roleId is { } id
? await db.Roles.SingleAsync(r => r.Id == id)
: await db.Roles.SingleAsync(r => r.IsSystem && r.Name == roleName);
var user = await db.Users.SingleOrDefaultAsync(u => u.Kind == SignInProviders.Local && u.UserName == username);
if (user is null)
{
user = new UserEntity
{
Id = Guid.NewGuid(),
Kind = SignInProviders.Local,
UserName = username,
DisplayName = username,
PasswordHash = PasswordHashing.Hash(Password),
CreatedUtc = DateTimeOffset.UtcNow,
UpdatedUtc = DateTimeOffset.UtcNow,
};
db.Users.Add(user);
}
var group = await db.LocalGroups.SingleOrDefaultAsync(g => g.Name == $"role:{role.Name}");
if (group is null)
{
group = new LocalGroupEntity { Id = Guid.NewGuid(), Name = $"role:{role.Name}", CreatedUtc = DateTimeOffset.UtcNow, UpdatedUtc = DateTimeOffset.UtcNow };
db.LocalGroups.Add(group);
db.RoleBindings.Add(new RoleBindingEntity
{
Id = Guid.NewGuid(), RoleId = role.Id, PrincipalKind = PrincipalKinds.LocalGroup, PrincipalId = group.Id.ToString("D"),
PrincipalName = group.Name, CreatedUtc = DateTimeOffset.UtcNow,
});
}
if (!await db.LocalGroupMembers.AnyAsync(m => m.GroupId == group.Id && m.UserId == user.Id))
{
db.LocalGroupMembers.Add(new LocalGroupMemberEntity { GroupId = group.Id, UserId = user.Id });
}
await db.SaveChangesAsync();
});
// Bindings and roles are cached; rows seeded behind the API's back need a reload.
fixture.Services.GetRequiredService<AccessResolver>().Invalidate();
fixture.Services.GetRequiredService<RoleCache>().Invalidate();
var client = fixture.CreateClient();
(await client.SignInAsync(username, Password)).EnsureSuccessStatusCode();
return client;
}
/// <summary>Signs a client in through the form and carries the CSRF cookie into the header, as the console does.</summary>
public static async Task<HttpResponseMessage> SignInAsync(this HttpClient client, string userName, string password, string? provider = SignInProviders.Local)
{
var response = await client.PostAsJsonAsync(Shared.Contracts.Api.ApiRoutes.AuthSignIn, new { provider, userName, password });
if (response.Headers.TryGetValues("Set-Cookie", out var cookies)
&& cookies.Select(c => c.Split(';')[0]).FirstOrDefault(c => c.StartsWith("csrf=", StringComparison.Ordinal)) is { } csrf)
{
client.DefaultRequestHeaders.Remove(SessionCookies.CsrfHeader);
client.DefaultRequestHeaders.Add(SessionCookies.CsrfHeader, csrf["csrf=".Length..]);
}
return response;
}
/// <summary>
/// A client whose role (all permissions) only reaches the listed devices:
/// its device scope is one static group holding exactly those.
/// </summary>
public static async Task<HttpClient> ScopedSignedInAsync(
this BackendTestFixture fixture, string username, params string[] scopeDeviceIds)
{
var roleId = await fixture.WithDbAsync(async db =>
{
var group = new DeviceGroupEntity
{
Id = Guid.NewGuid(), Name = $"scope-{username}-{Guid.NewGuid():N}", Kind = GroupKind.Static,
CreatedUtc = DateTimeOffset.UtcNow, UpdatedUtc = DateTimeOffset.UtcNow,
};
db.DeviceGroups.Add(group);
foreach (var clientId in scopeDeviceIds)
{
db.DeviceGroupMembers.Add(new DeviceGroupMemberEntity
{
GroupId = group.Id, ClientId = clientId, AddedUtc = DateTimeOffset.UtcNow,
});
}
var role = new RoleEntity
{
Id = Guid.NewGuid(), Name = $"scoped-{Guid.NewGuid():N}",
PermissionsJson = Shared.Contracts.Serialization.JsonDefaults.Serialize(new[] { "*" }),
DeviceScopeGroupIdsJson = Shared.Contracts.Serialization.JsonDefaults.Serialize(new[] { group.Id }),
CreatedUtc = DateTimeOffset.UtcNow, UpdatedUtc = DateTimeOffset.UtcNow,
};
db.Roles.Add(role);
await db.SaveChangesAsync();
return role.Id;
});
return await fixture.SignedInAsync(username, roleId: roleId);
}
public static Task<Guid> SeedScriptAsync(this BackendTestFixture fixture, string name)
=> fixture.WithDbAsync(async db =>
{
var script = new ScriptEntity
{
Id = Guid.NewGuid(),
Name = name,
Language = "PowerShell",
Content = "Write-Output 'hello'",
CreatedUtc = DateTimeOffset.UtcNow,
UpdatedUtc = DateTimeOffset.UtcNow,
};
db.Scripts.Add(script);
await db.SaveChangesAsync();
return script.Id;
});
public static Task<string> SeedDeviceAsync(
this BackendTestFixture fixture, string hostname, bool online = false, bool orphaned = false,
IReadOnlyList<string>? tags = null, string? agentVersion = null)
=> fixture.WithDbAsync(async db =>
{
var clientId = $"client-{Guid.NewGuid():N}"[..20];
db.Devices.Add(new DeviceEntity
{
ClientId = clientId,
Hostname = hostname,
NkeyPublic = $"U{Guid.NewGuid():N}",
EnrolledUtc = DateTimeOffset.UtcNow,
LastSeenUtc = online ? DateTimeOffset.UtcNow : DateTimeOffset.UtcNow.AddDays(-2),
IsOrphaned = orphaned,
TagsJson = tags is { Count: > 0 } ? Shared.Contracts.Serialization.JsonDefaults.Serialize(tags) : null,
AgentVersion = agentVersion,
});
await db.SaveChangesAsync();
return clientId;
});
}