Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/DebugStreamHubTests.cs
T
Joseph Doherty 513fa1aa16 docs(tests): fix CommentChecker findings across tests/ — 13,392 → 0 (repo-wide scan clean)
Comment/XML-doc changes only:
- add summaries to ~10k test methods, fixtures, fakes and helpers
  (+ <param> on theories, <returns> on async Task methods,
  <inheritdoc/> on interface implementations the checker can resolve)
- strip ~2.6k project-tracking references (WP*, P*-*, row-NN, Task N,
  #NN, Component-0NN) from comments, keeping the explanatory text;
  reword false positives in comments only
- real docs on fakes implementing BCL/library interfaces
  (IDisposable, ILogger, IOptionsMonitor, IAsyncLifetime)
- reword the last 5 src/ false positives (CWE-1236, failures-1,
  year-0001, M365)

Only non-comment edits: four one-line nested classes split across lines
so members can carry docs. Build 0 errors / 0 warnings.
2026-10-07 15:05:49 -04:00

184 lines
7.9 KiB
C#

using System.Net;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Connections.Features;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using NSubstitute;
using ZB.MOM.WW.Auth.Abstractions.Ldap;
using ZB.MOM.WW.ScadaBridge.Communication;
using ZB.MOM.WW.ScadaBridge.Communication.Grpc;
using ZB.MOM.WW.ScadaBridge.ManagementService;
using ZB.MOM.WW.ScadaBridge.Security;
using ZB.MOM.WW.ScadaBridge.Security.Auth;
namespace ZB.MOM.WW.ScadaBridge.ManagementService.Tests;
/// <summary>
/// Tests for <see cref="DebugStreamHub"/> per-instance site-scope authorization.
/// </summary>
public class DebugStreamHubTests
{
/// <summary>Verifies that a site-scoped user is allowed to access an instance within their site scope.</summary>
[Fact]
public void IsInstanceAccessAllowed_SiteScopedUser_InScopeInstance_Allowed()
{
var allowed = DebugStreamHub.IsInstanceAccessAllowed(
roles: new[] { "Deployer" },
permittedSiteIds: new[] { "1", "2" },
instanceSiteId: 2);
Assert.True(allowed);
}
/// <summary>Verifies that a site-scoped user is denied access to an instance outside their site scope.</summary>
[Fact]
public void IsInstanceAccessAllowed_SiteScopedUser_OutOfScopeInstance_Denied()
{
var allowed = DebugStreamHub.IsInstanceAccessAllowed(
roles: new[] { "Deployer" },
permittedSiteIds: new[] { "1", "2" },
instanceSiteId: 99);
Assert.False(allowed);
}
/// <summary>Verifies that a system-wide deployment user is allowed to access instances at any site.</summary>
[Fact]
public void IsInstanceAccessAllowed_SystemWideDeployment_AnySiteAllowed()
{
// Empty permitted set == system-wide Deployer.
var allowed = DebugStreamHub.IsInstanceAccessAllowed(
roles: new[] { "Deployer" },
permittedSiteIds: Array.Empty<string>(),
instanceSiteId: 99);
Assert.True(allowed);
}
/// <summary>Verifies that the Administrator role bypasses site scoping.</summary>
[Fact]
public void IsInstanceAccessAllowed_AdminRole_BypassesSiteScope()
{
var allowed = DebugStreamHub.IsInstanceAccessAllowed(
roles: new[] { "Administrator", "Deployer" },
permittedSiteIds: new[] { "1" },
instanceSiteId: 99);
Assert.True(allowed);
}
/// <summary>Verifies that the Administrator role check is case-insensitive.</summary>
[Fact]
public void IsInstanceAccessAllowed_AdminRoleCheck_IsCaseInsensitive()
{
var allowed = DebugStreamHub.IsInstanceAccessAllowed(
roles: new[] { "administrator" },
permittedSiteIds: new[] { "1" },
instanceSiteId: 99);
Assert.True(allowed);
}
// --- OnConnectedAsync delegates to ManagementAuthenticator (arch-review R2 N1) ------------
private readonly ILdapAuthService _ldap = Substitute.For<ILdapAuthService>();
private readonly ServiceProvider _provider;
private readonly LoginThrottle _throttle;
/// <summary>Initializes the test with a substituted LDAP service, a login throttle and a service provider.</summary>
public DebugStreamHubTests()
{
var services = new ServiceCollection();
services.AddSingleton<IOptions<AuthDisableLoginOptions>>(
Options.Create(new AuthDisableLoginOptions { DisableLogin = false }));
services.AddSingleton<IOptions<SecurityOptions>>(Options.Create(new SecurityOptions()));
services.AddSingleton(TimeProvider.System);
services.AddSingleton<LoginThrottle>();
services.AddSingleton(_ldap);
services.AddLogging();
_provider = services.BuildServiceProvider();
_throttle = _provider.GetRequiredService<LoginThrottle>();
}
private async Task<TestHubCallerContext> ConnectAsync(string username, string password)
{
var http = new DefaultHttpContext { RequestServices = _provider };
var creds = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}"));
http.Request.Headers.Authorization = $"Basic {creds}";
http.Connection.RemoteIpAddress = IPAddress.Parse("10.0.0.1");
var debugStreamService = new DebugStreamService(
new CommunicationService(Options.Create(new CommunicationOptions()), NullLogger<CommunicationService>.Instance),
new ServiceCollection().BuildServiceProvider(),
new SiteStreamGrpcClientFactory(NullLoggerFactory.Instance),
NullLogger<DebugStreamService>.Instance);
var hubContext = Substitute.For<IHubContext<DebugStreamHub>>();
var hub = new DebugStreamHub(debugStreamService, hubContext, NullLogger<DebugStreamHub>.Instance);
var ctx = new TestHubCallerContext(http);
hub.Context = ctx;
await hub.OnConnectedAsync();
return ctx;
}
/// <summary>Verifies that failed binds on connect feed the shared login throttle.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task OnConnectedAsync_FailedBinds_FeedTheSharedLoginThrottle()
{
// 5 failed hub connects for alice@10.0.0.1 must arm the same lockout the
// /management and /auth surfaces consult (arch-review R2 N1).
_ldap.AuthenticateAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(LdapAuthResult.Fail(LdapAuthFailure.BadCredentials));
for (var i = 0; i < 5; i++) await ConnectAsync("alice", "wrong"); // each Aborted
Assert.True(_throttle.IsLockedOut("alice", "10.0.0.1"));
}
/// <summary>Verifies that a locked-out key aborts the connection without contacting LDAP.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task OnConnectedAsync_LockedOutKey_AbortsWithoutContactingLdap()
{
for (var i = 0; i < 5; i++) _throttle.RecordFailure("alice", "10.0.0.1");
_ldap.ClearReceivedCalls();
var ctx = await ConnectAsync("alice", "whatever");
Assert.True(ctx.Aborted);
await _ldap.DidNotReceiveWithAnyArgs().AuthenticateAsync(default!, default!, default);
}
private sealed class TestHubCallerContext : HubCallerContext
{
private readonly FeatureCollection _features = new();
/// <summary>Initializes the context so that its HTTP context feature returns the given request context.</summary>
/// <param name="http">The HTTP context exposed through the context feature.</param>
public TestHubCallerContext(HttpContext http) =>
_features.Set<IHttpContextFeature>(new TestHttpContextFeature { HttpContext = http });
/// <summary>Gets a value indicating whether <see cref="Abort"/> has been called.</summary>
public bool Aborted { get; private set; }
/// <inheritdoc />
public override string ConnectionId => "test-conn";
/// <inheritdoc />
public override string? UserIdentifier => null;
/// <inheritdoc />
public override System.Security.Claims.ClaimsPrincipal? User => null;
/// <inheritdoc />
public override IDictionary<object, object?> Items { get; } = new Dictionary<object, object?>();
/// <inheritdoc />
public override IFeatureCollection Features => _features;
/// <inheritdoc />
public override CancellationToken ConnectionAborted => CancellationToken.None;
/// <inheritdoc />
public override void Abort() => Aborted = true;
private sealed class TestHttpContextFeature : IHttpContextFeature
{
/// <summary>Gets or sets the HTTP context exposed by the feature.</summary>
public HttpContext? HttpContext { get; set; }
}
}
}