using Akka.Actor;
using Akka.TestKit.Xunit2;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Security;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
using ZB.MOM.WW.ScadaBridge.Security;
namespace ZB.MOM.WW.ScadaBridge.ManagementService.Tests;
///
/// Security-023 (membership-validation half): the LDAP-group-mapping Role arrives
/// as a free string over the CLI/Management API. The single server-side write path
/// (ManagementActor.HandleCreateRoleMapping / HandleUpdateRoleMapping) now
/// rejects any role that is not in the canonical set, returning a
/// COMMAND_FAILED error before any DB write. A non-canonical role never functioned
/// (no authorization policy or ManagementActor check matched it), so rejecting it removes
/// a silent-misconfiguration footgun rather than changing behaviour.
///
///
/// Per Security-023's scope: only the membership check is added. The pre-existing
/// case-sensitivity asymmetry (case-sensitive UI RequireClaim vs case-insensitive
/// ManagementActor authz) is a separately-deferred change and is NOT touched — the
/// membership check accepts a correctly-cased canonical role and stores it verbatim.
///
public class RoleMappingValidationTests : TestKit, IDisposable
{
private readonly ISecurityRepository _securityRepo;
private readonly IAuditService _auditService;
private readonly ServiceCollection _services;
public RoleMappingValidationTests()
{
_securityRepo = Substitute.For();
_auditService = Substitute.For();
_services = new ServiceCollection();
_services.AddScoped(_ => _securityRepo);
_services.AddScoped(_ => _auditService);
}
private IActorRef CreateActor()
{
var sp = _services.BuildServiceProvider();
return Sys.ActorOf(Props.Create(() => new ManagementActor(
sp, NullLogger.Instance)));
}
// CreateRoleMappingCommand / UpdateRoleMappingCommand both require Administrator
// (see ManagementActor.GetRequiredRole), so the test principal carries that role.
private static ManagementEnvelope Envelope(object command) =>
new(new AuthenticatedUser("admin", "admin", new[] { Roles.Administrator }, Array.Empty()),
command, Guid.NewGuid().ToString("N"));
void IDisposable.Dispose() => Shutdown();
[Fact]
public void CreateRoleMapping_UnknownRole_ReturnsError_NoRowInserted()
{
var actor = CreateActor();
actor.Tell(Envelope(new CreateRoleMappingCommand("SCADA-Admins", "Wizard")));
var response = ExpectMsg(TimeSpan.FromSeconds(5));
Assert.Equal("COMMAND_FAILED", response.ErrorCode);
Assert.Contains("Wizard", response.Error);
_securityRepo.DidNotReceiveWithAnyArgs().AddMappingAsync(default!, default);
}
[Fact]
public void CreateRoleMapping_MisspelledCanonicalRole_ReturnsError_NoRowInserted()
{
// A pure typo of a real role ("Deploer" for "Deployer") is exactly the silent
// footgun Security-023 describes: it would stamp a role claim no policy matches.
var actor = CreateActor();
actor.Tell(Envelope(new CreateRoleMappingCommand("SCADA-Deploy", "Deploer")));
var response = ExpectMsg(TimeSpan.FromSeconds(5));
Assert.Equal("COMMAND_FAILED", response.ErrorCode);
_securityRepo.DidNotReceiveWithAnyArgs().AddMappingAsync(default!, default);
}
[Fact]
public void UpdateRoleMapping_UnknownRole_ReturnsError_NoRowUpdated()
{
var actor = CreateActor();
actor.Tell(Envelope(new UpdateRoleMappingCommand(7, "SCADA-Admins", "Wizard")));
var response = ExpectMsg(TimeSpan.FromSeconds(5));
Assert.Equal("COMMAND_FAILED", response.ErrorCode);
Assert.Contains("Wizard", response.Error);
// Rejected before the mapping is even looked up.
_securityRepo.DidNotReceiveWithAnyArgs().GetMappingByIdAsync(default, default);
_securityRepo.DidNotReceiveWithAnyArgs().UpdateMappingAsync(default!, default);
}
[Fact]
public void CreateRoleMapping_CanonicalRole_Succeeds_RowInserted()
{
LdapGroupMapping? inserted = null;
_securityRepo
.When(r => r.AddMappingAsync(Arg.Any(), Arg.Any()))
.Do(ci => inserted = ci.Arg());
var actor = CreateActor();
actor.Tell(Envelope(new CreateRoleMappingCommand("SCADA-Deploy", Roles.Deployer)));
ExpectMsg(TimeSpan.FromSeconds(5));
Assert.NotNull(inserted);
// Membership check does not alter the stored value's casing (case-sensitivity
// asymmetry is a separately-deferred change).
Assert.Equal(Roles.Deployer, inserted!.Role);
Assert.Equal("SCADA-Deploy", inserted.LdapGroupName);
}
}