Files
Heimdall/tests/Heimdall.Web.Tests/Hubs/IsolationHubTests.cs
T

157 lines
8.8 KiB
C#
Raw Normal View History

using Heimdall.Api.Hubs;
using Heimdall.Api.Security;
using Heimdall.Application.Settings.Queries.GetEffectiveAgentConfig;
using Heimdall.Application.Settings.Commands.SetAgentSetting;
using Heimdall.Application.Common;
using Heimdall.Domain.Entities;
using Heimdall.Infrastructure.Security;
using Heimdall.Web.Tests.Security;
using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using Shouldly;
namespace Heimdall.Web.Tests.Hubs;
public sealed class IsolationHubTests
{
[Theory]
[InlineData(AppRoles.Admin, "none", true, true)]
[InlineData(AppRoles.Supervisor, "site", true, false)]
[InlineData(AppRoles.Viewer, "site", true, false)]
[InlineData(AppRoles.Supervisor, "group", false, false)]
[InlineData(AppRoles.Viewer, "direct", false, false)]
[InlineData(AppRoles.Viewer, "none", false, false)]
public async Task Monitoring_requires_full_site_and_admin_broadcast_requires_admin(string role, string grant, bool siteAllowed, bool adminAllowed)
{
using var f = new AccessFixture();
var user = f.User(role, grant);
var context = Substitute.For<HubCallerContext>();
context.ConnectionId.Returns("c"); context.User.Returns(AccessFixture.Principal(user.Id));
using var hub = new MonitoringHub(NullLogger<MonitoringHub>.Instance, f.Access, new LiveSubscriptions())
{ Context = context, Groups = Substitute.For<IGroupManager>() };
if (siteAllowed) await hub.JoinSiteMonitoring(f.A.Id.ToString());
else await Should.ThrowAsync<HubException>(() => hub.JoinSiteMonitoring(f.A.Id.ToString()));
if (role != AppRoles.Admin) await Should.ThrowAsync<HubException>(() => hub.JoinSiteMonitoring(f.B.Id.ToString()));
if (adminAllowed) await hub.JoinAdminBroadcast();
else await Should.ThrowAsync<HubException>(() => hub.JoinAdminBroadcast());
}
[Fact]
public async Task Config_channel_cannot_be_impersonated_even_inside_same_site()
{
using var f = new AccessFixture();
var context = Substitute.For<HubCallerContext>();
context.ConnectionId.Returns("c"); context.User.Returns(AccessFixture.Principal(f.KeyA.Id, true));
using var hub = new ConfigHub(NullLogger<ConfigHub>.Instance, f.Access, new LiveSubscriptions())
{ Context = context, Groups = Substitute.For<IGroupManager>() };
await hub.JoinAgentGroup(f.AgentA.Id.ToString("B"));
await hub.Groups.Received().AddToGroupAsync("c", $"agent_{f.AgentA.Id}");
await Should.ThrowAsync<HubException>(() => hub.JoinAgentGroup(f.PeerA.Id.ToString()));
await Should.ThrowAsync<HubException>(() => hub.JoinAgentGroup(f.AgentB.Id.ToString()));
}
[Fact]
public async Task Subscriptions_reauthorize_after_group_removal_and_key_revocation()
{
using var f = new AccessFixture();
var user = f.User(AppRoles.Viewer, "group");
var subscriptions = new LiveSubscriptions();
subscriptions.Join("events", "human", "camera", AccessFixture.Principal(user.Id));
(await subscriptions.AuthorizedAsync("events", "camera", f.Access, r => f.Access.CameraAsync(r, f.A1.Id))).ShouldBe(["human"]);
f.Db.UserGroups.RemoveRange(f.Db.UserGroups); await f.Db.SaveChangesAsync();
(await subscriptions.AuthorizedAsync("events", "camera", f.Access, r => f.Access.CameraAsync(r, f.A1.Id))).ShouldBeEmpty();
subscriptions.Join("config", "agent", "all", AccessFixture.Principal(f.KeyA.Id, true));
f.KeyA.Disable(); await f.Db.SaveChangesAsync();
(await subscriptions.AuthorizedAsync("config", "all", f.Access, _ => Task.FromResult(true))).ShouldBeEmpty();
}
[Theory]
[InlineData("stamp")]
[InlineData("lock")]
public async Task Existing_hub_subscriptions_are_revoked_after_session_invalidation(string change)
{
using var f = new AccessFixture();
var user = f.User(AppRoles.Admin, "none");
var subscriptions = new LiveSubscriptions();
var principal = AccessFixture.Principal(user.Id);
foreach (var hub in new[] { "events", "monitoring", "admin", "notifications" })
subscriptions.Join(hub, $"{hub}-connection", "channel", principal);
foreach (var hub in new[] { "events", "monitoring", "admin", "notifications" })
(await subscriptions.AuthorizedAsync(hub, "channel", f.Access, r => Task.FromResult(r.Kind == RequesterKind.Human)))
.ShouldBe([$"{hub}-connection"]);
// Keep this context's user tracked with its original values while a separate
// context commits the revocation, reproducing a long-lived hub scope.
f.Db.Users.Single(u => u.Id == user.Id).SecurityStamp.ShouldBe("fixture-stamp");
await using (var revocationDb = f.CreateDbContext())
{
var persistedUser = await revocationDb.Users.SingleAsync(u => u.Id == user.Id);
if (change == "stamp") persistedUser.SecurityStamp = "rotated-stamp";
else
{
persistedUser.LockoutEnabled = true;
persistedUser.LockoutEnd = DateTimeOffset.UtcNow.AddMinutes(5);
}
await revocationDb.SaveChangesAsync();
}
f.Db.Entry(user).State.ShouldBe(EntityState.Unchanged);
foreach (var hub in new[] { "events", "monitoring", "admin", "notifications" })
(await subscriptions.AuthorizedAsync(hub, "channel", f.Access, r => Task.FromResult(r.Kind == RequesterKind.Human)))
.ShouldBeEmpty();
await using (var restoreDb = f.CreateDbContext())
{
var persistedUser = await restoreDb.Users.SingleAsync(u => u.Id == user.Id);
if (change == "stamp") persistedUser.SecurityStamp = "fixture-stamp";
else persistedUser.LockoutEnd = DateTimeOffset.UtcNow.AddMinutes(-1);
await restoreDb.SaveChangesAsync();
}
foreach (var hub in new[] { "events", "monitoring", "admin", "notifications" })
(await subscriptions.AuthorizedAsync(hub, "channel", f.Access, r => Task.FromResult(r.Kind == RequesterKind.Human)))
.ShouldBeEmpty();
}
[Fact]
public async Task Server_settings_are_excluded_from_push_overrides_and_full_reload()
{
using var f = new AccessFixture();
f.Db.AppSettings.AddRange(new AppSetting("smtp.password", "SMTP_SECRET", "email", agentScoped: false),
new AppSetting("s3.secret", "S3_SECRET", "storage", agentScoped: false),
new AppSetting("agent.heartbeat", "30", "agent", agentScoped: true));
// An old persisted override must not bypass the current scope.
f.Db.AgentSettings.Add(new(f.AgentA.Id, "smtp.password", "OLD_SECRET"));
await f.Db.SaveChangesAsync();
var subscriptions = new LiveSubscriptions();
subscriptions.Join("config", "c", "all", AccessFixture.Principal(f.KeyA.Id, true));
var hubContext = Substitute.For<IHubContext<ConfigHub>>();
var clients = Substitute.For<IHubClients>(); hubContext.Clients.Returns(clients);
clients.Clients(Arg.Any<IReadOnlyList<string>>()).Returns(Substitute.For<IClientProxy>());
var logger = new CaptureLogger<ConfigBroadcastService>();
using var scopedServices = new ServiceCollection()
.AddSingleton<Heimdall.Application.Common.IApplicationDbContext>(f.Db)
.AddSingleton(f.Access)
.AddSingleton(subscriptions)
.AddSingleton<IHubContext<ConfigHub>>(hubContext)
.AddSingleton<ILogger<ConfigBroadcastService>>(logger)
.BuildServiceProvider();
var broadcast = new ConfigBroadcastService(hubContext, logger, scopedServices.GetRequiredService<IServiceScopeFactory>());
await broadcast.NotifyGlobalSettingChanged("smtp.password", "SMTP_SECRET");
await broadcast.NotifyAgentSettingChanged(f.AgentA.Id, "s3.secret", "S3_SECRET");
clients.DidNotReceiveWithAnyArgs().Clients(default!);
var result = await new GetEffectiveAgentConfigQueryHandler(f.Db, Substitute.For<ICredentialProtector>())
.Handle(new(f.AgentA.Id), default);
result.Data!.ShouldNotContainKey("smtp.password"); result.Data!.ShouldNotContainKey("s3.secret");
result.Data!["agent.heartbeat"].ShouldBe("30");
(await new SetAgentSettingCommandHandler(f.Db).Handle(new(f.AgentA.Id, "smtp.password", "secret"), default)).IsSuccess.ShouldBeFalse();
await broadcast.NotifyGlobalSettingChanged("agent.heartbeat", "45");
clients.Received().Clients(Arg.Is<IReadOnlyList<string>>(ids => ids != null && ids.Count == 1 && ids[0] == "c"));
var logs = string.Join("\n", logger.Messages);
logs.ShouldNotContain("SMTP_SECRET"); logs.ShouldNotContain("S3_SECRET"); logs.ShouldNotContain("45");
}
}