using System.Security.Claims;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.CentralUI.Services;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.HealthMonitoring;
using ZB.MOM.WW.ScadaBridge.Security;
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Services;
public class AuditTreeScopeTests
{
/// Verifies that the production tree read resolves a fresh caller scope on every call.
/// A task that represents the asynchronous operation.
[Fact]
public async Task ProductionTreeRead_UsesFreshCallerScope_EveryTime()
{
var repo = Substitute.For();
using var provider = new ServiceCollection().AddSingleton(repo).BuildServiceProvider();
var auth = new ChangingAuth();
var service = new AuditLogQueryService(provider.GetRequiredService(),
Substitute.For(), auth);
var execution = Guid.NewGuid();
auth.Site = "42";
await service.GetExecutionTreeAsync(execution);
auth.Site = "43";
await service.GetExecutionTreeAsync(execution);
await repo.Received(1).GetExecutionTreeAsync(execution, Arg.Any(),
Arg.Is?>(x => x != null && x.SequenceEqual(new[] { "42" })));
await repo.Received(1).GetExecutionTreeAsync(execution, Arg.Any(),
Arg.Is?>(x => x != null && x.SequenceEqual(new[] { "43" })));
}
private sealed class ChangingAuth : AuthenticationStateProvider
{
/// Gets or sets the site id claim that the next authentication state carries.
public string Site { get; set; } = "42";
///
public override Task GetAuthenticationStateAsync() => Task.FromResult(new AuthenticationState(
new ClaimsPrincipal(new ClaimsIdentity(new[] {
new Claim(JwtTokenService.RoleClaimType, Roles.Viewer),
new Claim(JwtTokenService.SiteIdClaimType, Site)
}, "test"))));
}
}