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; using ZB.MOM.WW.OtOpcUa.Configuration.Entities; using ZB.MOM.WW.OtOpcUa.Configuration.Enums; using ZB.MOM.WW.OtOpcUa.Configuration.Validation; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.DataConnections; /// /// lmxopcua#996 (review C-11 / A-5): the data-connections page and its save/delete no longer read the whole ConfigDb. /// The narrow loader must (a) skip the tables the validator never reads, (b) keep exactly the tag data the rules do read /// (the alarm bit), and (c) leave the authoring rules unchanged. /// [Trait("Category", "Unit"), Trait("Feature", "GrpcData")] public sealed class DataConnectionsNarrowLoadTests { private const string AlarmConfig = "{\"alarm\":{\"alarmType\":\"AlarmCondition\",\"severity\":700}}"; private static async Task> SeedAsync() { var name = $"dc-narrow-{Guid.NewGuid():N}"; await using (var db = AclScopeTestDb.CreateNamed(name)) { AclScopeTestDb.Seed(db); // MAIN cluster, DEV-1, TAG-speed ("{}") and four ApiKeys db.Tags.Add(new Tag { TagId = "TAG-alarm", DeviceId = AclScopeTestDb.DeviceId, TagGroupId = null, Name = "overtemp", DataType = "Boolean", AccessLevel = TagAccessLevel.Read, TagConfig = AlarmConfig, }); db.Tags.Add(new Tag { TagId = "TAG-bulky", DeviceId = AclScopeTestDb.DeviceId, TagGroupId = null, Name = "bulky", DataType = "Float", AccessLevel = TagAccessLevel.Read, TagConfig = "{\"address\":\"" + new string('x', 4000) + "\"}", }); db.Scripts.Add(new Script { ScriptId = "S1", Name = "s", SourceCode = "return 1;", SourceHash = "h" }); await db.SaveChangesAsync(TestContext.Current.CancellationToken); } return AclScopeTestDb.Factory(name); } [Fact] public async Task Narrow_snapshot_skips_tables_the_validator_never_reads_and_strips_tag_config() { var ct = TestContext.Current.CancellationToken; var factory = await SeedAsync(); await using var db = await factory.CreateDbContextAsync(ct); var narrow = await DraftSnapshotFactory.FromConfigDbForDataConnectionsAsync(db, ct); var full = await DraftSnapshotFactory.FromConfigDbAsync(db, ct); // Positive control: the full snapshot DOES carry them, so the absence below is a real difference. full.ApiKeys.Count.ShouldBeGreaterThan(0); full.Scripts.Count.ShouldBe(1); full.Tags.Single(t => t.TagId == "TAG-bulky").TagConfig.Length.ShouldBeGreaterThan(4000); narrow.ApiKeys.ShouldBeEmpty(); narrow.Scripts.ShouldBeEmpty(); narrow.NodeAcls.ShouldBeEmpty(); narrow.PollGroups.ShouldBeEmpty(); narrow.Tags.Select(t => t.TagId).ShouldBe(full.Tags.Select(t => t.TagId)); narrow.Tags.Single(t => t.TagId == "TAG-bulky").TagConfig.ShouldBe("{}"); narrow.Tags.Single(t => t.TagId == AclScopeTestDb.TagId).TagConfig.ShouldBe("{}"); narrow.Tags.Single(t => t.TagId == "TAG-alarm").TagConfig.ShouldBe(AlarmConfig); // Same rows for everything the validator reads. narrow.DataConnections.Count.ShouldBe(full.DataConnections.Count); narrow.ClusterNodes.Count.ShouldBe(full.ClusterNodes.Count); narrow.Devices.Count.ShouldBe(full.Devices.Count); DataConnectionValidator.Validate(narrow).ShouldBe(DataConnectionValidator.Validate(full)); } [Fact] public void Narrow_tag_query_selects_tag_config_only_behind_an_alarm_guard() { using var db = new OtOpcUaConfigDbContext(new DbContextOptionsBuilder() .UseSqlServer("Server=127.0.0.1,1;Database=never;Connect Timeout=1").Options); var sql = DraftSnapshotFactory.NarrowTags(db).ToQueryString(); sql.ShouldContain("CASE"); sql.ShouldContain("alarm"); sql.ShouldNotContain("[t].[DataType]"); sql.ShouldNotContain("[t].[AccessLevel]"); sql.ShouldNotContain("[t].[PollGroupId]"); // Positive control: the whole-entity read selects them. var whole = db.Tags.AsNoTracking().ToQueryString(); whole.ShouldContain("[t].[DataType]"); } [Fact] public async Task An_export_rooted_at_an_alarm_bearing_tag_is_still_refused_through_the_narrow_load() { var ct = TestContext.Current.CancellationToken; var factory = await SeedAsync(); var service = new DataConnectionAdminService(factory, new Auth(), new User()); DataExport Export(string id, string tag) => new() { ClusterId = "MAIN", DataExportId = id, Enabled = true, Realm = DataRealm.Raw, RootKind = "RawTag", RootEntityId = tag, PrincipalId = "peer", AllowedOperations = DataOperations.Browse | DataOperations.Read, }; await service.SaveAsync("MAIN", Export("exp-value", AclScopeTestDb.TagId), ct); await Should.ThrowAsync(() => service.SaveAsync("MAIN", Export("exp-alarm", "TAG-alarm"), ct)); (await service.LoadAsync(ct)).DataExports.Select(e => e.DataExportId).ShouldBe(["exp-value"]); } private sealed class User : AuthenticationStateProvider { public override Task GetAuthenticationStateAsync() => Task.FromResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity("test")))); } private sealed class Auth : IAuthorizationService { public Task AuthorizeAsync(ClaimsPrincipal user, object? resource, IEnumerable requirements) => Task.FromResult(AuthorizationResult.Success()); public Task AuthorizeAsync(ClaimsPrincipal user, object? resource, string policyName) => Task.FromResult(AuthorizationResult.Success()); } }