c5cd280739
UI-6: Save overrides diffs the working values against the stored rows (OverrideSaveDiff) and applies only the changed ones inside ONE ExecuteInstanceAsync transaction; any row failure throws inside it so nothing commits (no partial apply). InstanceService.SetAttributeOverrideAsync skips the write and the UpdateOverride audit row when the value is unchanged. ~260 overrides, one edited: 260 transactions / ~1,300 round trips / 260 audit rows -> 1 transaction / 1 SetAttributeOverride / 1 audit row. UI-12: ParkedMessages bulk retry/discard authorise once per action (role + site scope + site list) instead of per message (bunit: 5 messages -> 1 site read, was 5; each also saved two forced session revalidations). Deployments.LoadDataAsync resolves the scope once (new SiteScopeService.ResolveScopeAsync) instead of IsSystemWide + PermittedSiteIds (2 -> 1 revalidation per 500 ms reload). SecuredWrites loads connections with one GetAllDataConnectionsAsync instead of one query per site. Not changed: ConnectionHealthQueryService's per-tick site/connection reads. UI-13 (decided: split deadline): the script deadline is armed when the worker sends a new 'running' frame (RunInWorkerAsync's userCodeStarting hook, after compile + trust check + gate); admission, process start-up and compile are bounded by a separate StartupCeiling (30 s + the script budget) with its own message. Test QueuedAndColdStartTime_IsNotChargedToTheScriptBudget (TimeoutSeconds=1, queued ~2 s behind four busy workers + a cold worker start): before: 'Script execution exceeded the 1-second sandbox timeout' after: succeeds, returns 7.
148 lines
7.7 KiB
C#
148 lines
7.7 KiB
C#
using System.Collections.Concurrent;
|
|
using System.Security.Claims;
|
|
using Akka.Actor;
|
|
using Bunit;
|
|
using Microsoft.AspNetCore.Components.Authorization;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using Microsoft.Extensions.Options;
|
|
using NSubstitute;
|
|
using ZB.MOM.WW.ScadaBridge.CentralUI.Auth;
|
|
using ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Monitoring;
|
|
using ZB.MOM.WW.ScadaBridge.CentralUI.Components.Shared;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Messages.RemoteQuery;
|
|
using ZB.MOM.WW.ScadaBridge.Communication;
|
|
using ZB.MOM.WW.ScadaBridge.Security;
|
|
|
|
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Auth;
|
|
|
|
public class ParkedMessagesMutationRegressionTests : BunitContext
|
|
{
|
|
/// <summary>Verifies that a retry for a site with a non-numeric identifier is relayed only while the user's current site grant allows it.</summary>
|
|
/// <param name="revoke"><c>true</c> to revoke the user's site grant before retrying, <c>false</c> to keep it.</param>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Theory]
|
|
[InlineData(false)]
|
|
[InlineData(true)]
|
|
public async Task NonnumericSiteIdentifier_RelaysOnlyWhileCurrentSiteGrantAllows(bool revoke)
|
|
{
|
|
using var system = ActorSystem.Create("parked-mutation-" + Guid.NewGuid().ToString("N"));
|
|
var dispatched = new ConcurrentQueue<SiteEnvelope>();
|
|
var comms = new CommunicationService(Options.Create(new CommunicationOptions()), NullLogger<CommunicationService>.Instance);
|
|
comms.SetCommunicationActor(system.ActorOf(Props.Create(() => new ReplyActor(dispatched))));
|
|
Services.AddSingleton(comms);
|
|
var sites = Substitute.For<ISiteRepository>();
|
|
sites.GetAllSitesAsync(Arg.Any<CancellationToken>()).Returns(new List<Site> { new("Plant A", "plant-a") { Id = 42 } });
|
|
Services.AddSingleton(sites);
|
|
var auth = new MutableAuth("42");
|
|
Services.AddSingleton<AuthenticationStateProvider>(auth);
|
|
Services.AddScoped<SiteScopeService>();
|
|
Services.AddAuthorizationCore();
|
|
Services.AddLogging();
|
|
Services.AddSingleton(Substitute.For<IDialogService>());
|
|
JSInterop.Mode = JSRuntimeMode.Loose;
|
|
|
|
var page = Render<ParkedMessages>();
|
|
await page.Find("select").ChangeAsync(new() { Value = "plant-a" });
|
|
page.WaitForAssertion(() => Assert.Contains("ERP", page.Markup));
|
|
await page.FindAll("tr").Single(row => row.TextContent.Contains("ERP")).ClickAsync(new());
|
|
page.WaitForAssertion(() => Assert.Contains("Retry", page.Markup));
|
|
if (revoke) auth.SiteId = "99";
|
|
// The same rendered page still contains the old site and row. The click must
|
|
// resolve SiteIdentifier through Site.Id and consult the live grant.
|
|
await page.FindAll("button").Single(button => button.TextContent.Trim() == "Retry").ClickAsync(new());
|
|
|
|
if (revoke)
|
|
{
|
|
Assert.Empty(dispatched);
|
|
Assert.Contains("Site access was revoked", page.Markup);
|
|
}
|
|
else
|
|
{
|
|
var envelope = Assert.Single(dispatched);
|
|
Assert.Equal("plant-a", envelope.SiteId);
|
|
var retry = Assert.IsType<ParkedMessageRetryRequest>(envelope.Message);
|
|
Assert.Equal("parked-message-1", retry.MessageId);
|
|
Assert.Equal("plant-a", retry.SiteId);
|
|
}
|
|
await system.Terminate();
|
|
}
|
|
|
|
/// <summary>
|
|
/// UI-12 (WP6 6.8): a bulk retry authorises once — one site-list read for the whole batch,
|
|
/// not one per message — and still relays every selected message.
|
|
/// </summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task BulkRetry_AuthorisesOncePerAction_NotPerMessage()
|
|
{
|
|
using var system = ActorSystem.Create("parked-bulk-" + Guid.NewGuid().ToString("N"));
|
|
var dispatched = new ConcurrentQueue<SiteEnvelope>();
|
|
var comms = new CommunicationService(Options.Create(new CommunicationOptions()), NullLogger<CommunicationService>.Instance);
|
|
comms.SetCommunicationActor(system.ActorOf(Props.Create(() => new ReplyActor(dispatched, 5))));
|
|
Services.AddSingleton(comms);
|
|
var sites = Substitute.For<ISiteRepository>();
|
|
sites.GetAllSitesAsync(Arg.Any<CancellationToken>()).Returns(new List<Site> { new("Plant A", "plant-a") { Id = 42 } });
|
|
Services.AddSingleton(sites);
|
|
Services.AddSingleton<AuthenticationStateProvider>(new MutableAuth("42"));
|
|
Services.AddScoped<SiteScopeService>();
|
|
Services.AddAuthorizationCore();
|
|
Services.AddLogging();
|
|
var dialog = Substitute.For<IDialogService>();
|
|
dialog.ConfirmAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<string?>()).Returns(true);
|
|
Services.AddSingleton(dialog);
|
|
JSInterop.Mode = JSRuntimeMode.Loose;
|
|
|
|
var page = Render<ParkedMessages>();
|
|
await page.Find("select").ChangeAsync(new() { Value = "plant-a" });
|
|
page.WaitForAssertion(() => Assert.Equal(5, page.FindAll("tr.parked-row").Count));
|
|
await page.Find("input[aria-label='Select all']").ChangeAsync(new() { Value = true });
|
|
page.WaitForAssertion(() => Assert.Contains("Retry selected", page.Markup));
|
|
sites.ClearReceivedCalls();
|
|
|
|
await page.FindAll("button").Single(b => b.TextContent.Trim() == "Retry selected").ClickAsync(new());
|
|
|
|
page.WaitForAssertion(() => Assert.Equal(5, dispatched.Count(e => e.Message is ParkedMessageRetryRequest)));
|
|
// One read for the bulk authorisation (the page refresh afterwards adds none of its own here).
|
|
await sites.Received(1).GetAllSitesAsync(Arg.Any<CancellationToken>());
|
|
await system.Terminate();
|
|
}
|
|
|
|
private sealed class MutableAuth(string siteId) : AuthenticationStateProvider
|
|
{
|
|
/// <summary>Gets or sets the site identifier carried in the user's site-scope claim.</summary>
|
|
public string SiteId { get; set; } = siteId;
|
|
/// <inheritdoc />
|
|
public override Task<AuthenticationState> GetAuthenticationStateAsync() => Task.FromResult(new AuthenticationState(
|
|
new ClaimsPrincipal(new ClaimsIdentity(new[] {
|
|
new Claim(JwtTokenService.UsernameClaimType, "operator"),
|
|
new Claim(JwtTokenService.RoleClaimType, Roles.Deployer),
|
|
new Claim(JwtTokenService.SiteIdClaimType, SiteId)
|
|
}, "test"))));
|
|
}
|
|
|
|
private sealed class ReplyActor : ReceiveActor
|
|
{
|
|
/// <summary>Initializes the actor with the queue that records relayed retry requests.</summary>
|
|
/// <param name="dispatched">The queue that receives each relayed retry envelope.</param>
|
|
/// <param name="rows">How many parked rows the query reply carries.</param>
|
|
public ReplyActor(ConcurrentQueue<SiteEnvelope> dispatched, int rows = 1)
|
|
{
|
|
Receive<SiteEnvelope>(envelope =>
|
|
{
|
|
if (envelope.Message is ParkedMessageQueryRequest query)
|
|
Sender.Tell(new ParkedMessageQueryResponse(query.CorrelationId, envelope.SiteId,
|
|
Enumerable.Range(1, rows).Select(i => new ParkedMessageEntry($"parked-message-{i}", "ERP", "Send", "Offline", 2, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow)).ToArray(),
|
|
rows, 1, 25, true, null, DateTimeOffset.UtcNow));
|
|
else if (envelope.Message is ParkedMessageRetryRequest retry)
|
|
{
|
|
dispatched.Enqueue(envelope);
|
|
Sender.Tell(new ParkedMessageRetryResponse(retry.CorrelationId, true));
|
|
}
|
|
});
|
|
}
|
|
}
|
|
}
|