diff --git a/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementAuthenticator.cs b/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementAuthenticator.cs
index 56375a67..504f2a98 100644
--- a/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementAuthenticator.cs
+++ b/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementAuthenticator.cs
@@ -1,6 +1,8 @@
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.Auth.Abstractions.Ldap;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
@@ -42,9 +44,24 @@ namespace ZB.MOM.WW.ScadaBridge.ManagementService;
/// ). The startup AUTH DISABLED warning
/// (emitted by AddSecurity) already announces this posture. Dev/test ONLY.
///
+///
+/// No role, no login (ScadaBridge#145, the management-surface half of #144; scadaproj NAM
+/// cutover plan §3.2): a Basic bind whose groups map to zero roles, or whose role mapping throws,
+/// is refused exactly like a bad password — the same 401 AUTH_FAILED body and a
+/// failure — and a bearer token that carries no role claim is refused
+/// like any other invalid token. Every refusal is logged at Warning under
+/// with the endpoint, the username and the reason. Because the three
+/// callers (, , the debug-stream hub)
+/// take their only from here, none of them can admit a role-less
+/// principal — including the commands ManagementActor.GetRequiredRoles opens to any
+/// authenticated user.
+///
///
public static class ManagementAuthenticator
{
+ /// The logger category for the sign-in refusals logged by this authenticator.
+ public const string LoggerCategory = "ZB.MOM.WW.ScadaBridge.ManagementService.ManagementAuthenticator";
+
/// Outcome of : exactly one of the two fields is set.
/// The authenticated principal on success; otherwise .
/// The 401 to return on failure; otherwise .
@@ -143,11 +160,19 @@ public static class ManagementAuthenticator
new { error = LdapAuthFailureMessages.ToMessage(authResult.Failure), code = "AUTH_FAILED" }, statusCode: 401));
}
- throttle.RecordSuccess(username, remoteIp!);
+ // 3. Role resolution. No role, no login (ScadaBridge#145, mirrors #144's /auth/login and
+ // /auth/token): a successful bind whose groups map to zero roles — or whose mapping
+ // throws — is refused exactly like a bad password: same 401 body, a throttle failure.
+ // The reason is logged server-side only.
+ var mappingResult = await ResolveBasicRolesAsync(context, authResult, username);
+ if (mappingResult is null)
+ {
+ throttle.RecordFailure(username, remoteIp!);
+ return new AuthOutcome(null, Results.Json(
+ new { error = LdapAuthFailureMessages.InvalidCredentials, code = "AUTH_FAILED" }, statusCode: 401));
+ }
- // 3. Role resolution
- var roleMapper = context.RequestServices.GetRequiredService();
- var mappingResult = await roleMapper.MapGroupsToRolesAsync(authResult.Groups, context.RequestAborted);
+ throttle.RecordSuccess(username, remoteIp!);
var permittedSiteIds = mappingResult.IsSystemWideDeployment
? Array.Empty()
@@ -162,10 +187,67 @@ public static class ManagementAuthenticator
return new AuthOutcome(resolvedUser, null);
}
+ ///
+ /// Maps a successful Basic bind's groups to roles, enforcing no role, no login
+ /// (ScadaBridge#145). Returns — the caller then answers exactly as for a
+ /// bad password — when the groups map to zero roles or the mapper throws; the refusal is logged
+ /// at Warning with the endpoint, the username and the reason. Cancellation of the request is not
+ /// a refusal and propagates.
+ ///
+ /// The current HTTP context (services, request path, request-aborted token).
+ /// The successful LDAP bind result.
+ /// The username as sent, used when the bind returned no canonical name.
+ /// The role mapping, or when the request must be refused.
+ private static async Task ResolveBasicRolesAsync(
+ HttpContext context, LdapAuthResult authResult, string username)
+ {
+ var logger = Logger(context);
+ var endpoint = EndpointName(context);
+ var who = string.IsNullOrEmpty(authResult.Username) ? username : authResult.Username;
+
+ RoleMappingResult mappingResult;
+ try
+ {
+ var roleMapper = context.RequestServices.GetRequiredService();
+ mappingResult = await roleMapper.MapGroupsToRolesAsync(authResult.Groups, context.RequestAborted);
+ }
+ catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested)
+ {
+ throw;
+ }
+ catch (Exception ex)
+ {
+ logger.LogWarning(ex,
+ "Sign-in refused at {Endpoint} for {Username}: the LDAP bind succeeded but role mapping failed. " +
+ "The client sees the bad-credentials response.",
+ endpoint, who);
+ return null;
+ }
+
+ if (mappingResult.Roles is not { Count: > 0 })
+ {
+ logger.LogWarning(
+ "Sign-in refused at {Endpoint} for {Username}: the LDAP bind succeeded but none of the user's {GroupCount} " +
+ "group(s) maps to a ScadaBridge role. The client sees the bad-credentials response.",
+ endpoint, who, authResult.Groups.Count);
+ return null;
+ }
+
+ return mappingResult;
+ }
+
+ private static ILogger Logger(HttpContext context) =>
+ context.RequestServices.GetService()?.CreateLogger(LoggerCategory) ?? NullLogger.Instance;
+
+ private static string EndpointName(HttpContext context) =>
+ context.Request.Path.HasValue ? context.Request.Path.Value! : "management";
+
///
/// Validates a bearer JWT and projects its claims onto an .
/// The token's roles and site scope are taken as-is (authoritative until expiry); an
- /// empty site-id set is the same system-wide signal the Basic path produces.
+ /// empty site-id set is the same system-wide signal the Basic path produces. A token with
+ /// no role claim is refused like an invalid token (ScadaBridge#145): /auth/token no
+ /// longer mints one, but a token minted before that rule shipped stays valid until it expires.
///
private static AuthOutcome AuthenticateBearer(HttpContext context, string token)
{
@@ -181,8 +263,21 @@ public static class ManagementAuthenticator
var displayName = principal.FindFirst(JwtTokenService.DisplayNameClaimType)?.Value;
var roles = principal.FindAll(JwtTokenService.RoleClaimType)
.Select(c => c.Value)
+ .Where(r => !string.IsNullOrWhiteSpace(r))
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToArray();
+
+ // No role, no login (ScadaBridge#145): the same 401 as an invalid token. Like any other
+ // bearer failure it performs no LDAP bind, so it does not feed the login throttle.
+ if (roles.Length == 0)
+ {
+ Logger(context).LogWarning(
+ "Sign-in refused at {Endpoint} for {Username}: the bearer token carries no ScadaBridge role. " +
+ "The client sees the invalid-token response.",
+ EndpointName(context), username);
+ return new AuthOutcome(null, Results.Json(
+ new { error = "Invalid or expired bearer token.", code = "AUTH_FAILED" }, statusCode: 401));
+ }
var permittedSiteIds = principal.FindAll(JwtTokenService.SiteIdClaimType)
.Select(c => c.Value)
.Distinct(StringComparer.Ordinal)
diff --git a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/CapturingLoggerProvider.cs b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/CapturingLoggerProvider.cs
new file mode 100644
index 00000000..0ae9183c
--- /dev/null
+++ b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/CapturingLoggerProvider.cs
@@ -0,0 +1,37 @@
+using System.Collections.Concurrent;
+using Microsoft.Extensions.Logging;
+
+namespace ZB.MOM.WW.ScadaBridge.ManagementService.Tests;
+
+/// An in-memory logger provider that records every formatted log line with its category and level.
+internal sealed class CapturingLoggerProvider : ILoggerProvider
+{
+ /// One captured log entry.
+ /// The logger category.
+ /// The log level.
+ /// The formatted message.
+ /// The logged exception, if any.
+ public sealed record Entry(string Category, LogLevel Level, string Message, Exception? Exception);
+
+ /// Every entry logged through this provider, in order.
+ public ConcurrentQueue Entries { get; } = new();
+
+ ///
+ public ILogger CreateLogger(string categoryName) => new Logger(categoryName, Entries);
+
+ ///
+ public void Dispose()
+ {
+ }
+
+ private sealed class Logger(string category, ConcurrentQueue sink) : ILogger
+ {
+ public IDisposable? BeginScope(TState state) where TState : notnull => null;
+
+ public bool IsEnabled(LogLevel logLevel) => true;
+
+ public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
+ Func formatter) =>
+ sink.Enqueue(new Entry(category, logLevel, formatter(state, exception), exception));
+ }
+}
diff --git a/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ManagementZeroRoleRefusalTests.cs b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ManagementZeroRoleRefusalTests.cs
new file mode 100644
index 00000000..531036f4
--- /dev/null
+++ b/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ManagementZeroRoleRefusalTests.cs
@@ -0,0 +1,531 @@
+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;
+
+///
+/// ScadaBridge#145 — the management/CLI surfaces (POST /management, the audit REST endpoints and
+/// the debug-stream hub) refuse a principal with no ScadaBridge role, mirroring #144's rule for
+/// /auth/login and /auth/token. 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.
+///
+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";
+
+ /// The role outcome the substituted produces.
+ public enum Mapping
+ {
+ /// The groups map to no role.
+ ZeroRoles,
+
+ /// The mapper throws (e.g. the configuration database is unreachable).
+ Throws,
+
+ /// The groups map to exactly one role (the one the surface needs).
+ 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();
+ }
+
+ ///
+ /// LDAP accepts alice/password (groups ["Domain Users"]) and rejects alice/wrong; the role mapper
+ /// answers per , with as the single role.
+ ///
+ 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>(
+ Options.Create(new AuthDisableLoginOptions { DisableLogin = false }));
+ services.AddSingleton>(Options.Create(new SecurityOptions
+ {
+ JwtSigningKey = Key,
+ JwtExpiryMinutes = 15,
+ MaxLoginFailuresPerWindow = maxFailures,
+ PerIpMaxFailures = 25,
+ }));
+ services.AddSingleton(TimeProvider.System);
+ services.AddSingleton();
+ services.AddScoped();
+
+ var ldap = Substitute.For();
+ ldap.AuthenticateAsync("alice", "password", Arg.Any())
+ .Returns(LdapAuthResult.Success("alice", "Alice", ["Domain Users"]));
+ ldap.AuthenticateAsync("alice", "wrong", Arg.Any())
+ .Returns(LdapAuthResult.Fail(LdapAuthFailure.BadCredentials));
+ services.AddSingleton(ldap);
+
+ var roleMapper = Substitute.For(Substitute.For());
+ var call = roleMapper.MapGroupsToRolesAsync(Arg.Any>(), Arg.Any());
+ 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();
+ repo.QueryAsync(Arg.Any(), Arg.Any(), Arg.Any())
+ .Returns(Task.FromResult>(Array.Empty()));
+ services.AddSingleton(repo);
+
+ var provider = services.BuildServiceProvider();
+ return new Rig
+ {
+ Provider = provider,
+ Throttle = provider.GetRequiredService(),
+ 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.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));
+ }
+
+ /// The 401 body a bad password gets on the same surface — every Basic refusal must match it.
+ private static async Task<(int Status, string Body)> BadPassword(Func> 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(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) ──────────────────────────────────────────────────────────────
+
+ /// The command these tests send is one GetRequiredRoles opens to any authenticated user.
+ [Fact]
+ public void ListSites_IsOpenToAnyAuthenticatedUser()
+ {
+ Assert.Null(ManagementActor.GetRequiredRoles(new ListSitesCommand()));
+ }
+
+ /// A zero-role or mapper-fault Basic bind gets the bad-password 401 on a null-role command, and it is logged.
+ /// The refused mapping outcome.
+ /// A task that represents the asynchronous operation.
+ [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");
+ }
+
+ /// A one-role Basic bind passes authentication and reaches dispatch (503: no actor in the rig).
+ /// A task that represents the asynchronous operation.
+ [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);
+ }
+
+ /// A bearer token with no role claim is refused with the invalid-token 401, and it is logged.
+ /// A task that represents the asynchronous operation.
+ [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);
+ }
+
+ ///
+ /// 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.)
+ ///
+ /// The mapper state, which a bearer request must not consult.
+ /// A task that represents the asynchronous operation.
+ [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);
+ }
+
+ /// Every management command GetRequiredRoles opens to any authenticated user.
+ /// The theory data rows of command names.
+ public static IEnumerable