1d2170a152
ManagementAuthenticator — the only identity source for POST /management, the audit REST endpoints and the debug-stream hub — now enforces "no role, no login" the way #144 does for /auth/login and /auth/token: - HTTP Basic: a bind whose groups map to zero roles, or whose role mapping throws, answers the bad-password 401 AUTH_FAILED body and counts as a LoginThrottle failure. RecordSuccess moved after the mapping, so a refusal no longer clears earlier failures. Request cancellation still propagates. - Bearer: a token with no role claim (minted before #144 shipped) gets the invalid-token 401; no throttle, as for every bearer failure. - Each refusal is logged at Warning (category ManagementAuthenticator) with the request path, the username and the reason. Before this, a zero-role Basic caller reached every command that ManagementActor.GetRequiredRoles opens to any authenticated user. DisableLogin is unchanged. Tests: ManagementZeroRoleRefusalTests — zero roles / mapper throws / one role over Basic and Bearer for /management (ListSites), /api/audit/query and the debug-stream hub; every null-role command is unreachable by a zero-role principal; throttle accounting. 47 of the 58 fail against the old authenticator (the 11 that pass are the one-role/bypass regression guards). Claude-Session: https://claude.ai/code/session_01GT67AFKC45MBz1wPZnVbX8
532 lines
23 KiB
C#
532 lines
23 KiB
C#
using System.Net;
|
|
using System.Runtime.CompilerServices;
|
|
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;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using Microsoft.Extensions.Options;
|
|
using NSubstitute;
|
|
using NSubstitute.ExceptionExtensions;
|
|
using ZB.MOM.WW.Audit;
|
|
using ZB.MOM.WW.Auth.Abstractions.Ldap;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
|
|
using ZB.MOM.WW.ScadaBridge.Communication;
|
|
using ZB.MOM.WW.ScadaBridge.Communication.Grpc;
|
|
using ZB.MOM.WW.ScadaBridge.Security;
|
|
using ZB.MOM.WW.ScadaBridge.Security.Auth;
|
|
|
|
namespace ZB.MOM.WW.ScadaBridge.ManagementService.Tests;
|
|
|
|
/// <summary>
|
|
/// ScadaBridge#145 — the management/CLI surfaces (<c>POST /management</c>, the audit REST endpoints and
|
|
/// the debug-stream hub) refuse a principal with no ScadaBridge role, mirroring #144's rule for
|
|
/// <c>/auth/login</c> and <c>/auth/token</c>. Over HTTP Basic, a bind whose groups map to zero roles, or
|
|
/// whose role mapping throws, is refused exactly like a bad password (same 401 body, a login-throttle
|
|
/// failure); over Bearer, a token with no role claim is refused like an invalid token. Each refusal is
|
|
/// logged at Warning with the endpoint, the username and the reason.
|
|
/// </summary>
|
|
public class ManagementZeroRoleRefusalTests
|
|
{
|
|
private const string Category = ManagementAuthenticator.LoggerCategory;
|
|
private const string Key = "this-is-a-test-signing-key-for-hmac-sha256-must-be-long-enough";
|
|
private const string Ip = "10.0.0.7";
|
|
|
|
/// <summary>The role outcome the substituted <see cref="RoleMapper"/> produces.</summary>
|
|
public enum Mapping
|
|
{
|
|
/// <summary>The groups map to no role.</summary>
|
|
ZeroRoles,
|
|
|
|
/// <summary>The mapper throws (e.g. the configuration database is unreachable).</summary>
|
|
Throws,
|
|
|
|
/// <summary>The groups map to exactly one role (the one the surface needs).</summary>
|
|
OneRole,
|
|
}
|
|
|
|
private sealed class Rig : IDisposable
|
|
{
|
|
public required ServiceProvider Provider { get; init; }
|
|
public required LoginThrottle Throttle { get; init; }
|
|
public required CapturingLoggerProvider Logs { get; init; }
|
|
public required RoleMapper RoleMapper { get; init; }
|
|
|
|
public void Dispose() => Provider.Dispose();
|
|
}
|
|
|
|
/// <summary>
|
|
/// LDAP accepts alice/password (groups ["Domain Users"]) and rejects alice/wrong; the role mapper
|
|
/// answers per <paramref name="mapping"/>, with <paramref name="oneRole"/> as the single role.
|
|
/// </summary>
|
|
private static Rig BuildRig(Mapping mapping, string oneRole, int maxFailures = 5)
|
|
{
|
|
var logs = new CapturingLoggerProvider();
|
|
var services = new ServiceCollection();
|
|
services.AddLogging(b => b.AddProvider(logs));
|
|
services.AddSingleton<IOptions<AuthDisableLoginOptions>>(
|
|
Options.Create(new AuthDisableLoginOptions { DisableLogin = false }));
|
|
services.AddSingleton<IOptions<SecurityOptions>>(Options.Create(new SecurityOptions
|
|
{
|
|
JwtSigningKey = Key,
|
|
JwtExpiryMinutes = 15,
|
|
MaxLoginFailuresPerWindow = maxFailures,
|
|
PerIpMaxFailures = 25,
|
|
}));
|
|
services.AddSingleton(TimeProvider.System);
|
|
services.AddSingleton<LoginThrottle>();
|
|
services.AddScoped<JwtTokenService>();
|
|
|
|
var ldap = Substitute.For<ILdapAuthService>();
|
|
ldap.AuthenticateAsync("alice", "password", Arg.Any<CancellationToken>())
|
|
.Returns(LdapAuthResult.Success("alice", "Alice", ["Domain Users"]));
|
|
ldap.AuthenticateAsync("alice", "wrong", Arg.Any<CancellationToken>())
|
|
.Returns(LdapAuthResult.Fail(LdapAuthFailure.BadCredentials));
|
|
services.AddSingleton(ldap);
|
|
|
|
var roleMapper = Substitute.For<RoleMapper>(Substitute.For<ISecurityRepository>());
|
|
var call = roleMapper.MapGroupsToRolesAsync(Arg.Any<IReadOnlyList<string>>(), Arg.Any<CancellationToken>());
|
|
switch (mapping)
|
|
{
|
|
case Mapping.Throws:
|
|
call.ThrowsAsync(new InvalidOperationException("configuration database unreachable"));
|
|
break;
|
|
case Mapping.ZeroRoles:
|
|
call.Returns(new RoleMappingResult([], [], IsSystemWideDeployment: false));
|
|
break;
|
|
default:
|
|
call.Returns(new RoleMappingResult([oneRole], [], IsSystemWideDeployment: true));
|
|
break;
|
|
}
|
|
services.AddSingleton(roleMapper);
|
|
|
|
// /management: no actor → a request that passes authentication and parsing answers 503.
|
|
services.AddSingleton(new ManagementActorHolder());
|
|
|
|
var repo = Substitute.For<IAuditLogRepository>();
|
|
repo.QueryAsync(Arg.Any<AuditLogQueryFilter>(), Arg.Any<AuditLogPaging>(), Arg.Any<CancellationToken>())
|
|
.Returns(Task.FromResult<IReadOnlyList<AuditEvent>>(Array.Empty<AuditEvent>()));
|
|
services.AddSingleton(repo);
|
|
|
|
var provider = services.BuildServiceProvider();
|
|
return new Rig
|
|
{
|
|
Provider = provider,
|
|
Throttle = provider.GetRequiredService<LoginThrottle>(),
|
|
Logs = logs,
|
|
RoleMapper = roleMapper,
|
|
};
|
|
}
|
|
|
|
private static string Basic(string password) =>
|
|
"Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes($"alice:{password}"));
|
|
|
|
private static string Bearer(params string[] roles)
|
|
{
|
|
var jwt = new JwtTokenService(
|
|
Options.Create(new SecurityOptions { JwtSigningKey = Key, JwtExpiryMinutes = 15 }),
|
|
NullLogger<JwtTokenService>.Instance);
|
|
return "Bearer " + jwt.GenerateToken("Alice", "alice", roles, null);
|
|
}
|
|
|
|
private static DefaultHttpContext Request(Rig rig, string path, string authorization)
|
|
{
|
|
var context = new DefaultHttpContext { RequestServices = rig.Provider };
|
|
context.Request.Path = path;
|
|
context.Request.Headers.Authorization = authorization;
|
|
context.Connection.RemoteIpAddress = IPAddress.Parse(Ip);
|
|
context.Response.Body = new MemoryStream();
|
|
return context;
|
|
}
|
|
|
|
private static async Task<(int Status, string Body)> Execute(HttpContext context, IResult result)
|
|
{
|
|
await result.ExecuteAsync(context);
|
|
context.Response.Body.Position = 0;
|
|
using var reader = new StreamReader(context.Response.Body);
|
|
return (context.Response.StatusCode, await reader.ReadToEndAsync());
|
|
}
|
|
|
|
private static async Task<(int Status, string Body)> PostManagement(Rig rig, string authorization, string command = "ListSites")
|
|
{
|
|
var context = Request(rig, "/management", authorization);
|
|
context.Request.Method = "POST";
|
|
var body = Encoding.UTF8.GetBytes("{\"command\":\"" + command + "\",\"payload\":{}}");
|
|
context.Request.Body = new MemoryStream(body);
|
|
context.Request.ContentLength = body.Length;
|
|
return await Execute(context, await ManagementEndpoints.HandleRequest(context));
|
|
}
|
|
|
|
private static async Task<(int Status, string Body)> GetAuditQuery(Rig rig, string authorization)
|
|
{
|
|
var context = Request(rig, "/api/audit/query", authorization);
|
|
context.Request.Method = "GET";
|
|
return await Execute(context, await AuditEndpoints.HandleQuery(context));
|
|
}
|
|
|
|
/// <summary>The 401 body a bad password gets on the same surface — every Basic refusal must match it.</summary>
|
|
private static async Task<(int Status, string Body)> BadPassword(Func<Rig, string, Task<(int, string)>> send, string oneRole)
|
|
{
|
|
using var rig = BuildRig(Mapping.OneRole, oneRole);
|
|
return await send(rig, Basic("wrong"));
|
|
}
|
|
|
|
private static CapturingLoggerProvider.Entry SingleRefusal(Rig rig) =>
|
|
Assert.Single(rig.Logs.Entries, e => e.Category == Category && e.Level == LogLevel.Warning);
|
|
|
|
private static void AssertBasicRefusalLogged(Rig rig, Mapping mapping, string endpoint)
|
|
{
|
|
var entry = SingleRefusal(rig);
|
|
Assert.Contains("alice", entry.Message);
|
|
Assert.Contains(endpoint, entry.Message);
|
|
if (mapping == Mapping.Throws)
|
|
{
|
|
Assert.Contains("role mapping failed", entry.Message);
|
|
Assert.IsType<InvalidOperationException>(entry.Exception);
|
|
}
|
|
else
|
|
{
|
|
Assert.Contains("maps to a ScadaBridge role", entry.Message);
|
|
}
|
|
}
|
|
|
|
private static void AssertNoRefusalLogged(Rig rig) =>
|
|
Assert.DoesNotContain(rig.Logs.Entries, e => e.Category == Category && e.Level >= LogLevel.Warning);
|
|
|
|
// ── POST /management (CLI) ──────────────────────────────────────────────────────────────
|
|
|
|
/// <summary>The command these tests send is one <c>GetRequiredRoles</c> opens to any authenticated user.</summary>
|
|
[Fact]
|
|
public void ListSites_IsOpenToAnyAuthenticatedUser()
|
|
{
|
|
Assert.Null(ManagementActor.GetRequiredRoles(new ListSitesCommand()));
|
|
}
|
|
|
|
/// <summary>A zero-role or mapper-fault Basic bind gets the bad-password 401 on a null-role command, and it is logged.</summary>
|
|
/// <param name="mapping">The refused mapping outcome.</param>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Theory]
|
|
[InlineData(Mapping.ZeroRoles)]
|
|
[InlineData(Mapping.Throws)]
|
|
public async Task Management_Basic_RefusedLikeABadPassword(Mapping mapping)
|
|
{
|
|
using var rig = BuildRig(mapping, Roles.Viewer);
|
|
|
|
var (status, body) = await PostManagement(rig, Basic("password"));
|
|
var badPassword = await BadPassword((r, a) => PostManagement(r, a), Roles.Viewer);
|
|
|
|
Assert.Equal(401, status);
|
|
Assert.Equal(badPassword, (status, body));
|
|
Assert.Contains("AUTH_FAILED", body);
|
|
Assert.Contains(LdapAuthFailureMessages.InvalidCredentials, body);
|
|
AssertBasicRefusalLogged(rig, mapping, "/management");
|
|
}
|
|
|
|
/// <summary>A one-role Basic bind passes authentication and reaches dispatch (503: no actor in the rig).</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Management_Basic_OneRole_ReachesDispatch()
|
|
{
|
|
using var rig = BuildRig(Mapping.OneRole, Roles.Viewer);
|
|
|
|
var (status, _) = await PostManagement(rig, Basic("password"));
|
|
|
|
Assert.Equal(503, status);
|
|
AssertNoRefusalLogged(rig);
|
|
}
|
|
|
|
/// <summary>A bearer token with no role claim is refused with the invalid-token 401, and it is logged.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Management_Bearer_ZeroRoles_Refused()
|
|
{
|
|
using var rig = BuildRig(Mapping.OneRole, Roles.Viewer);
|
|
|
|
var (status, body) = await PostManagement(rig, Bearer());
|
|
var (_, invalidTokenBody) = await PostManagement(rig, "Bearer not-a-token");
|
|
|
|
Assert.Equal(401, status);
|
|
Assert.Equal(invalidTokenBody, body);
|
|
var entry = SingleRefusal(rig);
|
|
Assert.Contains("alice", entry.Message);
|
|
Assert.Contains("/management", entry.Message);
|
|
Assert.Contains("no ScadaBridge role", entry.Message);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Bearer performs no role mapping: a one-role token is accepted even while the mapper throws, and
|
|
/// the mapper is never called. (The mapper-fault refusal is a Basic-path rule.)
|
|
/// </summary>
|
|
/// <param name="mapping">The mapper state, which a bearer request must not consult.</param>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Theory]
|
|
[InlineData(Mapping.OneRole)]
|
|
[InlineData(Mapping.Throws)]
|
|
public async Task Management_Bearer_OneRole_ReachesDispatch_WithoutMapping(Mapping mapping)
|
|
{
|
|
using var rig = BuildRig(mapping, Roles.Viewer);
|
|
|
|
var (status, _) = await PostManagement(rig, Bearer(Roles.Viewer));
|
|
|
|
Assert.Equal(503, status);
|
|
AssertNoRefusalLogged(rig);
|
|
await rig.RoleMapper.DidNotReceiveWithAnyArgs().MapGroupsToRolesAsync(default!, default);
|
|
}
|
|
|
|
/// <summary>Every management command <c>GetRequiredRoles</c> opens to any authenticated user.</summary>
|
|
/// <returns>The theory data rows of command names.</returns>
|
|
public static IEnumerable<object[]> NullRoleCommands()
|
|
=> typeof(ManagementEnvelope).Assembly.GetTypes()
|
|
.Where(t => t.Namespace == typeof(ManagementEnvelope).Namespace
|
|
&& t.Name.EndsWith("Command", StringComparison.Ordinal) && !t.IsAbstract
|
|
&& ManagementActor.GetRequiredRoles(RuntimeHelpers.GetUninitializedObject(t)) is null)
|
|
.Select(t => new object[] { t.Name[..^"Command".Length] });
|
|
|
|
/// <summary>
|
|
/// No command open to any authenticated user is reachable by a zero-role principal, over Basic or
|
|
/// Bearer: authentication answers 401 before the command is parsed or dispatched.
|
|
/// </summary>
|
|
/// <param name="command">A null-role command name.</param>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Theory, MemberData(nameof(NullRoleCommands))]
|
|
public async Task NullRoleCommand_IsNotReachableByAZeroRolePrincipal(string command)
|
|
{
|
|
using var rig = BuildRig(Mapping.ZeroRoles, Roles.Viewer);
|
|
|
|
var (basicStatus, _) = await PostManagement(rig, Basic("password"), command);
|
|
var (bearerStatus, _) = await PostManagement(rig, Bearer(), command);
|
|
|
|
Assert.Equal(401, basicStatus);
|
|
Assert.Equal(401, bearerStatus);
|
|
}
|
|
|
|
/// <summary>A zero-role Basic refusal counts against the login throttle like a bad password.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Management_Basic_ZeroRoles_CountsAsAThrottleFailure()
|
|
{
|
|
using var rig = BuildRig(Mapping.ZeroRoles, Roles.Viewer, maxFailures: 2);
|
|
|
|
await PostManagement(rig, Basic("password"));
|
|
await PostManagement(rig, Basic("password"));
|
|
|
|
Assert.True(rig.Throttle.IsLockedOut("alice", Ip));
|
|
var (status, body) = await PostManagement(rig, Basic("password"));
|
|
Assert.Equal(429, status);
|
|
Assert.Contains("AUTH_THROTTLED", body);
|
|
}
|
|
|
|
/// <summary>
|
|
/// A refusal does not clear earlier failures the way a successful sign-in does: a bad password
|
|
/// followed by a zero-role bind leaves both failures on the throttle.
|
|
/// </summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Management_Basic_ZeroRoles_DoesNotResetTheThrottle()
|
|
{
|
|
using var rig = BuildRig(Mapping.ZeroRoles, Roles.Viewer, maxFailures: 2);
|
|
|
|
await PostManagement(rig, Basic("wrong"));
|
|
await PostManagement(rig, Basic("password"));
|
|
|
|
Assert.True(rig.Throttle.IsLockedOut("alice", Ip));
|
|
}
|
|
|
|
// ── GET /api/audit/query ────────────────────────────────────────────────────────────────
|
|
|
|
/// <summary>A zero-role or mapper-fault Basic bind gets the bad-password 401 on an audit query (not a 403), and it is logged.</summary>
|
|
/// <param name="mapping">The refused mapping outcome.</param>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Theory]
|
|
[InlineData(Mapping.ZeroRoles)]
|
|
[InlineData(Mapping.Throws)]
|
|
public async Task Audit_Basic_RefusedLikeABadPassword(Mapping mapping)
|
|
{
|
|
using var rig = BuildRig(mapping, Roles.Administrator);
|
|
|
|
var (status, body) = await GetAuditQuery(rig, Basic("password"));
|
|
var badPassword = await BadPassword((r, a) => GetAuditQuery(r, a), Roles.Administrator);
|
|
|
|
Assert.Equal(401, status);
|
|
Assert.Equal(badPassword, (status, body));
|
|
AssertBasicRefusalLogged(rig, mapping, "/api/audit/query");
|
|
}
|
|
|
|
/// <summary>A one-role Basic bind with an audit role gets the query page.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Audit_Basic_OneRole_Answers()
|
|
{
|
|
using var rig = BuildRig(Mapping.OneRole, Roles.Administrator);
|
|
|
|
var (status, _) = await GetAuditQuery(rig, Basic("password"));
|
|
|
|
Assert.Equal(200, status);
|
|
AssertNoRefusalLogged(rig);
|
|
}
|
|
|
|
/// <summary>A bearer token with no role claim gets 401 on an audit query (not a 403), and it is logged.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Audit_Bearer_ZeroRoles_Refused()
|
|
{
|
|
using var rig = BuildRig(Mapping.OneRole, Roles.Administrator);
|
|
|
|
var (status, body) = await GetAuditQuery(rig, Bearer());
|
|
|
|
Assert.Equal(401, status);
|
|
Assert.Contains("AUTH_FAILED", body);
|
|
Assert.Contains("/api/audit/query", SingleRefusal(rig).Message);
|
|
}
|
|
|
|
/// <summary>A one-role bearer token gets the query page without any role mapping, even while the mapper throws.</summary>
|
|
/// <param name="mapping">The mapper state, which a bearer request must not consult.</param>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Theory]
|
|
[InlineData(Mapping.OneRole)]
|
|
[InlineData(Mapping.Throws)]
|
|
public async Task Audit_Bearer_OneRole_Answers(Mapping mapping)
|
|
{
|
|
using var rig = BuildRig(mapping, Roles.Administrator);
|
|
|
|
var (status, _) = await GetAuditQuery(rig, Bearer(Roles.Administrator));
|
|
|
|
Assert.Equal(200, status);
|
|
AssertNoRefusalLogged(rig);
|
|
}
|
|
|
|
// ── /hubs/debug-stream ──────────────────────────────────────────────────────────────────
|
|
|
|
private static async Task<TestHubCallerContext> ConnectHub(Rig rig, string authorization)
|
|
{
|
|
var http = Request(rig, "/hubs/debug-stream", authorization);
|
|
var debugStreamService = new DebugStreamService(
|
|
new CommunicationService(Options.Create(new CommunicationOptions()), NullLogger<CommunicationService>.Instance),
|
|
new ServiceCollection().BuildServiceProvider(),
|
|
new SiteStreamGrpcClientFactory(NullLoggerFactory.Instance),
|
|
NullLogger<DebugStreamService>.Instance);
|
|
var hub = new DebugStreamHub(debugStreamService, Substitute.For<IHubContext<DebugStreamHub>>(),
|
|
NullLogger<DebugStreamHub>.Instance);
|
|
var ctx = new TestHubCallerContext(http);
|
|
hub.Context = ctx;
|
|
await hub.OnConnectedAsync();
|
|
return ctx;
|
|
}
|
|
|
|
/// <summary>
|
|
/// A zero-role or mapper-fault Basic connect is aborted by the shared authenticator — logged as a
|
|
/// sign-in refusal and counted as a throttle failure — not merely by the hub's Deployer check.
|
|
/// </summary>
|
|
/// <param name="mapping">The refused mapping outcome.</param>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Theory]
|
|
[InlineData(Mapping.ZeroRoles)]
|
|
[InlineData(Mapping.Throws)]
|
|
public async Task Hub_Basic_Refused(Mapping mapping)
|
|
{
|
|
using var rig = BuildRig(mapping, Roles.Deployer, maxFailures: 1);
|
|
|
|
var ctx = await ConnectHub(rig, Basic("password"));
|
|
|
|
Assert.True(ctx.Aborted);
|
|
AssertBasicRefusalLogged(rig, mapping, "/hubs/debug-stream");
|
|
Assert.True(rig.Throttle.IsLockedOut("alice", Ip));
|
|
}
|
|
|
|
/// <summary>A one-role (Deployer) Basic connect is established.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Hub_Basic_OneRole_Connects()
|
|
{
|
|
using var rig = BuildRig(Mapping.OneRole, Roles.Deployer);
|
|
|
|
var ctx = await ConnectHub(rig, Basic("password"));
|
|
|
|
Assert.False(ctx.Aborted);
|
|
AssertNoRefusalLogged(rig);
|
|
}
|
|
|
|
/// <summary>A bearer token with no role claim is refused by the shared authenticator, and it is logged.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Hub_Bearer_ZeroRoles_Refused()
|
|
{
|
|
using var rig = BuildRig(Mapping.OneRole, Roles.Deployer);
|
|
|
|
var ctx = await ConnectHub(rig, Bearer());
|
|
|
|
Assert.True(ctx.Aborted);
|
|
var entry = SingleRefusal(rig);
|
|
Assert.Contains("/hubs/debug-stream", entry.Message);
|
|
Assert.Contains("no ScadaBridge role", entry.Message);
|
|
}
|
|
|
|
/// <summary>A one-role (Deployer) bearer connect is established without role mapping, even while the mapper throws.</summary>
|
|
/// <param name="mapping">The mapper state, which a bearer request must not consult.</param>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Theory]
|
|
[InlineData(Mapping.OneRole)]
|
|
[InlineData(Mapping.Throws)]
|
|
public async Task Hub_Bearer_OneRole_Connects(Mapping mapping)
|
|
{
|
|
using var rig = BuildRig(mapping, Roles.Deployer);
|
|
|
|
var ctx = await ConnectHub(rig, Bearer(Roles.Deployer));
|
|
|
|
Assert.False(ctx.Aborted);
|
|
AssertNoRefusalLogged(rig);
|
|
}
|
|
|
|
// ── DisableLogin stays unchanged ────────────────────────────────────────────────────────
|
|
|
|
/// <summary>The dev/test bypass still admits every surface with all roles, without LDAP or role mapping.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task DisableLogin_StillBypasses_WithAllRoles()
|
|
{
|
|
var services = new ServiceCollection();
|
|
services.AddSingleton<IOptions<AuthDisableLoginOptions>>(
|
|
Options.Create(new AuthDisableLoginOptions { DisableLogin = true }));
|
|
using var provider = services.BuildServiceProvider();
|
|
|
|
var outcome = await ManagementAuthenticator.AuthenticateAsync(new DefaultHttpContext { RequestServices = provider });
|
|
|
|
Assert.Null(outcome.Failure);
|
|
Assert.Equal(Roles.All, outcome.User!.Roles);
|
|
}
|
|
|
|
private sealed class TestHubCallerContext : HubCallerContext
|
|
{
|
|
private readonly FeatureCollection _features = new();
|
|
|
|
public TestHubCallerContext(HttpContext http) =>
|
|
_features.Set<IHttpContextFeature>(new TestHttpContextFeature { HttpContext = http });
|
|
|
|
public bool Aborted { get; private set; }
|
|
|
|
public override string ConnectionId => "test-conn";
|
|
|
|
public override string? UserIdentifier => null;
|
|
|
|
public override System.Security.Claims.ClaimsPrincipal? User => null;
|
|
|
|
public override IDictionary<object, object?> Items { get; } = new Dictionary<object, object?>();
|
|
|
|
public override IFeatureCollection Features => _features;
|
|
|
|
public override CancellationToken ConnectionAborted => CancellationToken.None;
|
|
|
|
public override void Abort() => Aborted = true;
|
|
|
|
private sealed class TestHttpContextFeature : IHttpContextFeature
|
|
{
|
|
public HttpContext? HttpContext { get; set; }
|
|
}
|
|
}
|
|
}
|