feat: author and inspect grpc data connections

This commit is contained in:
Joseph Doherty
2026-11-16 20:58:43 -05:00
parent 8ad03e9c5d
commit 1df29a3124
31 changed files with 1246 additions and 141 deletions
@@ -0,0 +1,117 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections;
using ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Acls;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P09")]
public sealed class GrpcDataAuthoringTests
{
[Fact]
public async Task Editor_saves_a_disabled_draft_and_read_only_user_cannot_modify_it()
{
var factory = AclScopeTestDb.Factory(Guid.NewGuid().ToString());
var editor = new DataConnectionAdminService(factory, new Auth(true), new User());
var row = new DataConnection { ClusterId = "MAIN", DataConnectionId = "peer" };
await editor.SaveAsync("MAIN", row, TestContext.Current.CancellationToken);
var loaded = (await editor.LoadAsync(TestContext.Current.CancellationToken)).DataConnections.ShouldHaveSingleItem();
loaded.Enabled.ShouldBeFalse();
var reader = new DataConnectionAdminService(factory, new Auth(false), new User());
await Should.ThrowAsync<UnauthorizedAccessException>(() => reader.DeleteAsync("MAIN", loaded, TestContext.Current.CancellationToken));
(await editor.LoadAsync(TestContext.Current.CancellationToken)).DataConnections.Count.ShouldBe(1);
}
[Fact]
public async Task A_secret_value_is_rejected_by_the_authoritative_validator()
{
var service = new DataConnectionAdminService(AclScopeTestDb.Factory(Guid.NewGuid().ToString()), new Auth(true), new User());
await Should.ThrowAsync<InvalidOperationException>(() => service.SaveAsync("MAIN", new DataConnection { ClusterId = "MAIN", DataConnectionId = "peer", SecretReference = "raw-key" }, TestContext.Current.CancellationToken));
(await service.LoadAsync(TestContext.Current.CancellationToken)).DataConnections.ShouldBeEmpty();
}
[Fact]
public async Task Edits_advance_revision_and_stale_edits_or_deletes_are_refused()
{
var ct = TestContext.Current.CancellationToken;
var service = new DataConnectionAdminService(AclScopeTestDb.Factory(Guid.NewGuid().ToString()), new Auth(true), new User());
await service.SaveAsync("MAIN", new DataConnection { ClusterId = "MAIN", DataConnectionId = "peer" }, ct);
var original = (await service.LoadAsync(ct)).DataConnections.ShouldHaveSingleItem();
var stale = (await service.LoadAsync(ct)).DataConnections.ShouldHaveSingleItem();
original.ExpectedClusterId = "OTHER";
await service.SaveAsync("MAIN", original, ct);
(await service.LoadAsync(ct)).DataConnections.ShouldHaveSingleItem().Revision.ShouldBe(2);
await Should.ThrowAsync<DbUpdateConcurrencyException>(() => service.SaveAsync("MAIN", stale, ct));
await Should.ThrowAsync<DbUpdateConcurrencyException>(() => service.DeleteAsync("MAIN", stale, ct));
var current = (await service.LoadAsync(ct)).DataConnections.ShouldHaveSingleItem();
await service.DeleteAsync("MAIN", current, ct);
(await service.LoadAsync(ct)).DataConnections.ShouldBeEmpty();
}
[Fact]
public async Task Row_identity_cannot_be_moved_renamed_or_deleted_by_a_forged_id()
{
var ct = TestContext.Current.CancellationToken;
var service = new DataConnectionAdminService(AclScopeTestDb.Factory(Guid.NewGuid().ToString()), new Auth(true), new User());
await service.SaveAsync("MAIN", new DataConnection { ClusterId = "MAIN", DataConnectionId = "peer" }, ct);
var row = (await service.LoadAsync(ct)).DataConnections.ShouldHaveSingleItem();
row.DataConnectionId = "other";
await Should.ThrowAsync<InvalidOperationException>(() => service.SaveAsync("MAIN", row, ct));
await Should.ThrowAsync<InvalidOperationException>(() => service.DeleteAsync("MAIN", row, ct));
row.ClusterId = "OTHER";
await Should.ThrowAsync<InvalidOperationException>(() => service.SaveAsync("OTHER", row, ct));
await Should.ThrowAsync<InvalidOperationException>(() => service.DeleteAsync("OTHER", row, ct));
(await service.LoadAsync(ct)).DataConnections.ShouldHaveSingleItem().DataConnectionId.ShouldBe("peer");
}
[Fact]
public async Task Read_only_cannot_create_or_enable_write()
{
var ct = TestContext.Current.CancellationToken;
var factory = AclScopeTestDb.Factory(Guid.NewGuid().ToString());
var reader = new DataConnectionAdminService(factory, new Auth(false), new User());
var row = new DataConnection { ClusterId = "MAIN", DataConnectionId = "peer", Enabled = true,
AllowedOperations = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataOperations.Write };
await Should.ThrowAsync<UnauthorizedAccessException>(() => reader.SaveAsync("MAIN", row, ct));
(await reader.LoadAsync(ct)).DataConnections.ShouldBeEmpty();
}
[Fact]
public async Task Connection_with_enabled_mapping_cannot_be_deleted()
{
var ct = TestContext.Current.CancellationToken;
var name = Guid.NewGuid().ToString();
var factory = AclScopeTestDb.Factory(name);
await using (var db = await factory.CreateDbContextAsync(ct))
{
AclScopeTestDb.Seed(db);
db.ClusterNodes.Add(new ClusterNode { NodeId = "A", ClusterId = "MAIN", Host = "a", ApplicationUri = "urn:a", CreatedBy = "test" });
db.DataConnections.Add(new DataConnection { DataConnectionId = "peer", ClusterId = "MAIN", Enabled = true,
ConsumerNodeIds = ["A"], TargetMode = DataTargetMode.Node, ExpectedClusterId = "REMOTE", ExpectedNodeId = "B",
Endpoints = ["https://peer.example"], SecretReference = "secret:data/peer", SecretScopeClusterId = "MAIN",
AllowedOperations = DataOperations.Read });
db.RemoteNamespaceMappings.Add(new RemoteNamespaceMapping { RemoteNamespaceMappingId = "mount", ClusterId = "MAIN", Enabled = true,
DataConnectionId = "peer", ConsumerNodeIds = ["A"], Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw,
LocalParentKind = "Cluster", LocalParentId = "MAIN", BranchName = "remote", RemoteRootEntityId = "root",
RemoteNamespaceUri = V3NodeIds.RawNamespaceUri, RemoteIdentifierKind = "String", RemoteIdentifier = "root", AllowedOperations = DataOperations.Read });
await db.SaveChangesAsync(ct);
}
var service = new DataConnectionAdminService(factory, new Auth(true), new User());
var snapshot = await service.LoadAsync(ct);
DataConnectionValidator.Validate(snapshot).ShouldBeEmpty();
await Should.ThrowAsync<InvalidOperationException>(() => service.DeleteAsync("MAIN", snapshot.DataConnections.ShouldHaveSingleItem(), ct));
(await service.LoadAsync(ct)).DataConnections.Count.ShouldBe(1);
}
private sealed class User : AuthenticationStateProvider
{
public override Task<AuthenticationState> GetAuthenticationStateAsync() => Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity("test"))));
}
private sealed class Auth(bool allowed) : IAuthorizationService
{
public Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user, object? resource, IEnumerable<IAuthorizationRequirement> requirements) => Task.FromResult(allowed ? AuthorizationResult.Success() : AuthorizationResult.Failed());
public Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user, object? resource, string policyName) => Task.FromResult(allowed ? AuthorizationResult.Success() : AuthorizationResult.Failed());
}
}
@@ -0,0 +1,38 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P09")]
public sealed class GrpcDataDiagnosticsTests
{
[Fact]
public void Sample_age_uses_the_node_observation_even_when_the_node_clock_is_ahead()
{
var consumerUtc = DateTime.UtcNow.AddSeconds(30);
var row = new ZB.MOM.WW.OtOpcUa.Commons.Interfaces.DataConnectionDiagnosticsSnapshot("link", 1, "ready", null, null,
0, 0, 1, "artifact", consumerUtc, LastSampleAtUtc: consumerUtc.AddSeconds(-20), SampleAgeUpperBound: TimeSpan.FromSeconds(20));
DataConnectionDiagnostics.SampleAge(row).ShouldBe("20s at observation");
}
[Fact]
public void Deleted_draft_remains_visible_while_applied_or_observed()
{
var draft = new DataConnection { DataConnectionId = "Peer", ClusterId = "MAIN" };
var before = DataConnectionDiagnostics.Rows([draft], ["peer"], ["PEER"]);
before.ShouldHaveSingleItem().Draft.ShouldBe(draft);
var after = DataConnectionDiagnostics.Rows([], ["peer"], ["PEER"]);
var retained = after.ShouldHaveSingleItem();
retained.Id.ShouldBe("peer");
retained.Draft.ShouldBeNull();
DataConnectionDiagnostics.Rows([], [], ["peer"]).ShouldHaveSingleItem();
DataConnectionDiagnostics.Rows([], [], []).ShouldBeEmpty();
}
[Fact]
public void Unknown_runtime_status_is_not_reported_as_ready() => DataConnectionDiagnostics.State(null).ShouldBe("Unavailable");
[Fact]
public void Endpoint_display_never_includes_credentials_or_query() =>
DataConnectionDiagnostics.Endpoint("https://user:password@example.com:8443/path?token=secret").ShouldBe("https://example.com:8443");
}
@@ -0,0 +1,41 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P09")]
public sealed class GrpcDataEditorValidationTests
{
[Fact]
public void New_drafts_are_disabled_and_do_not_grant_write()
{
var connection = new DataConnectionEditorModel().Value;
var mapping = new RemoteMappingEditorModel().Value;
connection.Enabled.ShouldBeFalse(); mapping.Enabled.ShouldBeFalse();
connection.AllowedOperations.HasFlag(DataOperations.Write).ShouldBeFalse();
mapping.AllowedOperations.HasFlag(DataOperations.Write).ShouldBeFalse();
mapping.WriteThrough.ShouldBeFalse();
}
[Fact]
public void Enabled_mapping_must_use_the_connection_consumer_scope_and_require_write_through()
{
var connection = new DataConnection { DataConnectionId = "peer", ClusterId = "MAIN", Enabled = true,
ConsumerNodeIds = ["A"], TargetMode = DataTargetMode.Node, ExpectedClusterId = "REMOTE", ExpectedNodeId = "B",
Endpoints = ["https://peer.example"], SecretReference = "secret:data/peer", SecretScopeClusterId = "MAIN",
AllowedOperations = DataOperations.Read | DataOperations.Write };
var mapping = new RemoteNamespaceMapping { RemoteNamespaceMappingId = "mount", ClusterId = "MAIN", Enabled = true,
DataConnectionId = "peer", ConsumerNodeIds = ["B"], AllowedOperations = DataOperations.Write, WriteThrough = false };
var snapshot = new DraftSnapshot { GenerationId = 0, ClusterId = "MAIN", DataConnections = [connection],
RemoteNamespaceMappings = [mapping], ClusterNodes = [new ClusterNode { NodeId = "A", ClusterId = "MAIN", Host = "a", ApplicationUri = "urn:a", CreatedBy = "test" }] };
var errors = DataConnectionValidator.Validate(snapshot);
errors.ShouldContain(x => x.Code == "DataMappingConsumerScopeInvalid");
errors.ShouldContain(x => x.Code == "DataMappingOperationsInvalid");
}
[Fact]
public void List_editor_trims_lines_without_changing_order() =>
DataConnectionEditorModel.Lines(" a \r\n\n b ").ShouldBe(new[] { "a", "b" });
}
@@ -3,6 +3,7 @@ using Xunit;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.DataConnections;
[CollectionDefinition(nameof(GrpcDataDiscoveryEnvironmentCollection), DisableParallelization = true)]
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P09")]
public sealed class GrpcDataDiscoveryEnvironmentCollection
{
}
@@ -10,6 +11,7 @@ public sealed class GrpcDataDiscoveryEnvironmentCollection
[Collection(nameof(GrpcDataDiscoveryEnvironmentCollection))]
[Trait("Feature", "GrpcData")]
[Trait("Phase", "P00")]
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P09")]
public sealed class GrpcDataUnitDiscoveryIsolationTests
{
private const string Switch = "OTOPCUA_UNIT_ONLY_DISCOVERY";
@@ -19,6 +19,48 @@ public sealed class GrpcDataConnectionClientTests
private static readonly DataView View = new(new("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "x");
private static readonly DataBudget Budget = new(TimeSpan.FromSeconds(5), 16, 65536);
[Fact, Trait("Phase", "P09")]
public async Task Coalesced_notice_is_reported_separately_from_unknown_overflow()
{
var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null);
var handle = new DataItemHandle("s", 1, 1, 1);
var ack = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionAck("s", 1, 1, "open", [new("item", DataItemStatus.Good, handle, settings, null)]));
var control = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionControl("s", 1, 2, DataStreamControlKind.Coalesced, [], 1, 1, null));
ack.Serving = control.Serving = DataProtoMapper.EncodeServing(Serving);
using var manager = new DataConnectionManager("consumer", 1);
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
[new Uri("https://example.test")], new Security(new StreamWireHandler([ack, control])), manager.Acquire("link"), 65536, 1);
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), [new("item", View, settings)], false,
TimeSpan.FromMinutes(1), Budget), TestContext.Current.CancellationToken);
await using var frames = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken);
(await frames.MoveNextAsync()).ShouldBeTrue(); (await frames.MoveNextAsync()).ShouldBeTrue();
var diagnostics = connection.CaptureDiagnostics(1, 1, "artifact");
diagnostics.CoalescedCount.ShouldBe(1); diagnostics.OverflowCount.ShouldBeNull(); diagnostics.RegistrationCount.ShouldBe(1);
}
[Fact, Trait("Phase", "P09")]
public async Task Transport_diagnostics_report_verified_endpoint_and_ambiguous_write_without_secrets()
{
using var manager = new DataConnectionManager("consumer", 1);
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
[new Uri("https://user:secret@example.test:8443/private?token=secret")], new Security(new WireHandler { LoseWrite = true }), manager.Acquire("link"), 65536, 1);
connection.CaptureDiagnostics(2, 3, "artifact").State.ShouldBe("connecting");
await connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken);
var live = connection.CaptureDiagnostics(2, 3, "artifact");
live.State.ShouldBe("ready"); live.SelectedEndpoint.ShouldBe("https://example.test:8443");
live.Serving.ShouldBe(Serving); live.ActiveCalls.ShouldBe(0); live.ScopeVersion.ShouldBe(3);
live.ProtocolMinor.ShouldBe(3); live.LastSampleAtUtc.ShouldBeNull();
using var value = DataValue.FromScalar(DataValueKind.Int32, 1);
var outcome = await connection.WriteAsync(new([new("item", "one", View, value, 1, "boot", TimeSpan.FromSeconds(4), 1)], Budget), TestContext.Current.CancellationToken);
outcome.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown);
connection.CaptureDiagnostics(2, 3, "artifact").WriteUnknownCount.ShouldBe(1);
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>>());
connection.CaptureDiagnostics(2, 3, "artifact").State.ShouldBe("disabled");
}
[Fact]
public void Security_material_does_not_render_the_presented_bearer()
{
@@ -33,6 +33,24 @@ public sealed class GrpcDataDeploymentActivationTests
throw new TimeoutException("Expected deployment state did not arrive.");
}
[Fact, Trait("Phase", "P09")]
public async Task Diagnostics_never_report_a_saved_or_unaccepted_scope_as_ready()
{
var activator = new PausedActivator();
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4);
runtime.CaptureDiagnostics().ShouldBeEmpty();
runtime.Apply(Snapshot(1, Definition("link", "secret-reference")));
await activator.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
var pending = runtime.CaptureDiagnostics().ShouldHaveSingleItem();
pending.State.ShouldBe("connecting"); pending.SelectedEndpoint.ShouldBeNull();
pending.ArtifactRevision.ShouldBe("artifact-1"); pending.ScopeVersion.ShouldBe(1);
activator.Release.TrySetResult();
await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("link", out var candidate) && DisposeAndTrue(candidate!));
runtime.CaptureDiagnostics().ShouldHaveSingleItem().State.ShouldBe("connecting", "local credential activation is not a remote capability handshake");
runtime.BeginAttempt("artifact-2");
runtime.CaptureDiagnostics().ShouldHaveSingleItem().State.ShouldBe("connecting");
}
[Fact]
public async Task Transient_security_resolution_exception_retries_without_a_change_event()
{