Merge branch 'master' into fix/832-docker-dev-batch

This commit is contained in:
Joseph Doherty
2026-11-11 02:32:42 -05:00
140 changed files with 6336 additions and 568 deletions
@@ -0,0 +1,78 @@
using Microsoft.Extensions.Logging.Abstractions;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Browsing;
using ZB.MOM.WW.OtOpcUa.Commons.Browsing;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Browsing;
/// <summary>
/// lmxopcua#815: the AdminUI live browse (Galaxy / OpcUaClient bespoke browsers, and the Discover-backed universal
/// browser) resolves the config's credential references and sends them to the author-chosen endpoint — an
/// out-of-namespace reference is refused before any browser is opened.
/// </summary>
[Trait("Category", "Unit")]
public sealed class BrowserSessionCredentialScopeTests
{
[Theory]
[InlineData(DriverTypeNames.Galaxy, """{"Gateway":{"Endpoint":"http://evil:5001","ApiKeySecretRef":"env:ConnectionStrings__ConfigDb"}}""")]
[InlineData(DriverTypeNames.OpcUaClient, """{"EndpointUrl":"opc.tcp://evil:4840","Password":"secret:otopcua/historian/api-key"}""")]
[InlineData(DriverTypeNames.Heidenhain, """{"Access":{"InspectPassword":"secret:galaxy/main/apikey"}}""")]
public async Task Out_of_namespace_reference_never_opens_a_browser(string driverType, string config)
{
var bespoke = new RecordingBrowser(DriverTypeNames.Galaxy);
var bespoke2 = new RecordingBrowser(DriverTypeNames.OpcUaClient);
var universal = new RecordingUniversal();
var svc = new BrowserSessionService(
[bespoke, bespoke2], new BrowseSessionRegistry(), NullLogger<BrowserSessionService>.Instance, universal, null!, null!);
var result = await svc.OpenAsync(driverType, config, TestContext.Current.CancellationToken);
result.Ok.ShouldBeFalse();
result.Message.ShouldNotBeNull().ShouldContain("lmxopcua#815");
bespoke.Opens.ShouldBe(0);
bespoke2.Opens.ShouldBe(0);
universal.Opens.ShouldBe(0);
}
/// <summary>Positive control: a namespaced reference reaches the browser.</summary>
[Fact]
public async Task A_namespaced_reference_reaches_the_browser()
{
var bespoke = new RecordingBrowser(DriverTypeNames.Galaxy);
var svc = new BrowserSessionService(
[bespoke], new BrowseSessionRegistry(), NullLogger<BrowserSessionService>.Instance, new RecordingUniversal(), null!, null!);
await svc.OpenAsync(DriverTypeNames.Galaxy, """{"Gateway":{"ApiKeySecretRef":"secret:galaxy/main/apikey"}}""",
TestContext.Current.CancellationToken);
bespoke.Opens.ShouldBe(1);
}
private sealed class RecordingBrowser(string driverType) : IDriverBrowser
{
public int Opens { get; private set; }
public string DriverType => driverType;
public Task<IBrowseSession> OpenAsync(string configJson, CancellationToken cancellationToken)
{
Opens++;
throw new InvalidOperationException("opened");
}
}
private sealed class RecordingUniversal : IUniversalDriverBrowser
{
public int Opens { get; private set; }
public bool CanBrowse(string driverType, string configJson) => true;
public Task<IBrowseSession> OpenAsync(string driverType, string configJson, CancellationToken ct)
{
Opens++;
throw new InvalidOperationException("opened");
}
}
}
@@ -0,0 +1,177 @@
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Deployments;
using ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Uns;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Drivers;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Deployments;
/// <summary>
/// lmxopcua#815 upgrade preflight: stored (draft) and deployed configs with out-of-namespace credential references
/// are listed and logged — driver, device, field, allowed form — and never the value; nothing is resolved.
/// </summary>
[Trait("Category", "Unit")]
public sealed class CredentialReferencePreflightTests
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private const string LegacyGalaxy = """{"Gateway":{"Endpoint":"http://gw:5001","ApiKeySecretRef":"env:MX_API_KEY"}}""";
private static string SeedLegacy()
{
var name = RawTreeTestDb.SeedFresh();
using var db = RawTreeTestDb.CreateNamed(name);
// Written straight to the DB, as a pre-#815 build would have — the save gate now refuses it.
db.DriverInstances.Add(new DriverInstance
{
DriverInstanceId = "gx-old", ClusterId = RawTreeTestDb.ClusterId, Name = "Galaxy main",
DriverType = DriverTypeNames.Galaxy, DriverConfig = LegacyGalaxy,
});
db.Devices.Add(new Device
{
DeviceId = "ouc-dev", DriverInstanceId = "gx-old", Name = "gw1",
DeviceConfig = """{"AlarmAck":{"FallbackPasswordSecretRef":"file:C:\\keys\\ack.txt"}}""",
});
db.DriverInstances.Add(new DriverInstance
{
DriverInstanceId = "mb", ClusterId = RawTreeTestDb.ClusterId, Name = "modbus",
DriverType = DriverTypeNames.Modbus, DriverConfig = """{"Password":"env:ConnectionStrings__ConfigDb"}""",
});
var artifact = """
{"DriverInstances":[{"DriverInstanceId":"ouc","Name":"Upstream","DriverType":"OpcUaClient",
"DriverConfig":"{\"Password\":\"secret:plant/opcua-pw\"}"}]}
""";
db.Deployments.Add(new Deployment { RevisionHash = "abc", CreatedBy = "t", ArtifactBlob = Encoding.UTF8.GetBytes(artifact) });
db.SaveChanges();
return name;
}
[Fact]
public async Task Scan_lists_draft_rows_devices_and_the_deployed_artifact_without_values()
{
var findings = await new CredentialReferencePreflight(RawTreeTestDb.Factory(SeedLegacy())).ScanAsync(Ct);
findings.ShouldContain(f => f.Source == CredentialFindingSource.Draft && f.DriverName == "Galaxy main"
&& f.DeviceName == null && f.Problem.Contains("Gateway.ApiKeySecretRef")
&& f.Problem.Contains("env:OTOPCUA_GALAXY_<NAME>"));
findings.ShouldContain(f => f.Source == CredentialFindingSource.Draft && f.DeviceName == "gw1"
&& f.Problem.Contains("AlarmAck.FallbackPasswordSecretRef"));
findings.ShouldContain(f => f.Source == CredentialFindingSource.Deployed && f.DriverName == "Upstream"
&& f.Problem.Contains("secret:opcuaclient/<name>"));
findings.ShouldNotContain(f => f.DriverInstanceId == "mb"); // not a credential-resolving driver
findings.ShouldAllBe(f => !f.Problem.Contains("MX_API_KEY") && !f.Problem.Contains("plant/opcua-pw")
&& !f.Problem.Contains("ack.txt"));
}
[Fact]
public async Task A_clean_database_has_no_findings()
=> (await new CredentialReferencePreflight(RawTreeTestDb.Factory(RawTreeTestDb.SeedFresh())).ScanAsync(Ct)).ShouldBeEmpty();
[Fact]
public async Task The_boot_pass_logs_one_warning_per_finding_and_publishes_the_state()
{
var services = new ServiceCollection()
.AddSingleton(RawTreeTestDb.Factory(SeedLegacy()))
.BuildServiceProvider();
var state = new CredentialReferencePreflightState();
var logger = new CaptureLogger();
var svc = new CredentialReferencePreflightService(services, new FakeLifetime(), state, logger) { StartDelay = TimeSpan.Zero };
var findings = await svc.RunOnceAsync(Ct);
findings.Count.ShouldBe(3);
state.Current.Findings.Count.ShouldBe(3);
state.Current.ScannedAtUtc.ShouldNotBeNull();
var warnings = logger.Entries.Where(e => e.Level == LogLevel.Warning).ToList();
warnings.Count.ShouldBe(3);
warnings.ShouldAllBe(w => w.Message.Contains("lmxopcua#815") && !w.Message.Contains("MX_API_KEY"));
warnings.ShouldContain(w => w.Message.Contains("Galaxy main") && w.Message.Contains("Gateway.ApiKeySecretRef"));
}
[Fact]
public async Task A_node_without_a_config_db_skips_quietly()
{
var svc = new CredentialReferencePreflightService(
new ServiceCollection().BuildServiceProvider(), new FakeLifetime(), new CredentialReferencePreflightState(), new CaptureLogger());
(await svc.RunOnceAsync(Ct)).ShouldBeEmpty();
}
[Fact]
public async Task The_hosted_service_waits_for_ApplicationStarted_before_scanning()
{
var services = new ServiceCollection().AddSingleton(RawTreeTestDb.Factory(SeedLegacy())).BuildServiceProvider();
var lifetime = new FakeLifetime();
var state = new CredentialReferencePreflightState();
var svc = new CredentialReferencePreflightService(services, lifetime, state, new CaptureLogger()) { StartDelay = TimeSpan.Zero };
await svc.StartAsync(Ct);
await Task.Delay(100, Ct);
state.Current.ScannedAtUtc.ShouldBeNull(); // nothing before the host has started
lifetime.Start();
var deadline = DateTime.UtcNow.AddSeconds(10);
while (state.Current.ScannedAtUtc is null && DateTime.UtcNow < deadline) await Task.Delay(20, Ct);
state.Current.Findings.Count.ShouldBe(3);
await svc.StopAsync(Ct);
}
[Fact]
public void Running_drivers_reporting_warn_only_resolution_are_surfaced_from_driver_health()
{
var snapshots = new[]
{
new DriverHealthChanged("c", "gx-old", "Healthy", null, null, 0, DateTime.UtcNow,
Diagnostics: new Dictionary<string, string>
{
[LegacyCredentialReferenceTracker.DiagnosticsKeyPrefix + "Gateway.ApiKeySecretRef"] = "deprecated …",
["s7.pdu"] = "480",
}),
new DriverHealthChanged("c", "mb", "Healthy", null, null, 0, DateTime.UtcNow),
};
var running = CredentialReferencePreflight.RunningFindings(snapshots);
running.ShouldHaveSingleItem().ShouldSatisfyAllConditions(
f => f.Source.ShouldBe(CredentialFindingSource.Running),
f => f.DriverInstanceId.ShouldBe("gx-old"),
f => f.Problem.ShouldStartWith("Gateway.ApiKeySecretRef"));
}
private sealed class FakeLifetime : IHostApplicationLifetime
{
private readonly CancellationTokenSource _started = new();
public CancellationToken ApplicationStarted => _started.Token;
public CancellationToken ApplicationStopping => CancellationToken.None;
public CancellationToken ApplicationStopped => CancellationToken.None;
public void Start() => _started.Cancel();
public void StopApplication()
{
}
}
private sealed class CaptureLogger : ILogger<CredentialReferencePreflightService>
{
public List<(LogLevel Level, string Message)> Entries { get; } = new();
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
lock (Entries) Entries.Add((logLevel, formatter(state, exception)));
}
}
}
@@ -180,6 +180,31 @@ public sealed class OpcUaClientDriverPageFormSerializationTests
def.DiscoveryUrl.ShouldBeNull();
}
/// <summary>
/// #816: the server host-name check is tri-state. Unset must stay unset through the form (so a later change of
/// the driver default reaches configs nobody chose for), and an explicit opt-in / NAT opt-out must survive.
/// </summary>
[Theory]
[InlineData(null)]
[InlineData(true)]
[InlineData(false)]
public void FormModel_RoundTrip_PreservesHostNameValidationTriState(bool? value)
{
var formOpts = new JsonSerializerOptions(_opts) { Converters = { new JsonStringEnumConverter() } };
var original = new OpcUaClientDriverOptions
{
CertificateValidation = new OpcUaCertificateValidationOptions { ValidateServerHostName = value },
};
var back = OpcUaClientDriverForm.OpcUaClientFormModel.FromRecord(original).ToRecord([]);
back.CertificateValidation.ValidateServerHostName.ShouldBe(value);
var reparsed = JsonSerializer.Deserialize<OpcUaClientDriverOptions>(
JsonSerializer.Serialize(back, formOpts), formOpts)!;
reparsed.CertificateValidation.ValidateServerHostName.ShouldBe(value);
reparsed.CertificateValidation.EffectiveValidateServerHostName.ShouldBe(value ?? false);
}
/// <summary>
/// #648: stored DriverConfig JSON from before <c>targetNamespaceKind</c>/<c>unsMappingTable</c> were removed
/// must still load into the form (the form's options use <c>UnmappedMemberHandling.Skip</c>) and the legacy
@@ -0,0 +1,77 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Uns;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Uns;
/// <summary>
/// lmxopcua#815 at the SAVE path (RawTreeService): a Galaxy / OpcUaClient credential reference outside the
/// driver's namespace never reaches the config DB, through driver and device create + update.
/// </summary>
[Trait("Category", "Unit")]
public sealed class CredentialReferenceSavePathTests
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
[Theory]
[InlineData(DriverTypeNames.Galaxy, """{"Gateway":{"Endpoint":"http://evil:5001","ApiKeySecretRef":"env:ConnectionStrings__ConfigDb"}}""")]
[InlineData(DriverTypeNames.Galaxy, """{"Gateway":{"ApiKeySecretRef":"file:appsettings.json"}}""")]
[InlineData(DriverTypeNames.Galaxy, """{"AlarmAck":{"FallbackPasswordSecretRef":"secret:otopcua/apikeys/ab/galaxy-ack-password"}}""")]
[InlineData(DriverTypeNames.OpcUaClient, """{"EndpointUrl":"opc.tcp://evil:4840","Password":"secret:otopcua/historian/api-key"}""")]
[InlineData(DriverTypeNames.OpcUaClient, """{"UserCertificatePassword":"env:ServerHistorian__ApiKey"}""")]
public async Task CreateDriver_refuses_an_out_of_namespace_reference_and_persists_nothing(string type, string config)
{
var name = RawTreeTestDb.SeedFresh();
var svc = new RawTreeService(RawTreeTestDb.Factory(name));
var result = await svc.CreateDriverAsync(RawTreeTestDb.ClusterId, null, "d815", type, config, Ct);
result.Ok.ShouldBeFalse();
result.Error!.ShouldContain("lmxopcua#815");
using var db = RawTreeTestDb.CreateNamed(name);
db.DriverInstances.ShouldNotContain(d => d.Name == "d815");
}
[Fact]
public async Task Update_paths_refuse_and_keep_the_stored_config()
{
var name = RawTreeTestDb.SeedFresh();
var svc = new RawTreeService(RawTreeTestDb.Factory(name));
var created = await svc.CreateDriverAsync(RawTreeTestDb.ClusterId, null, "gx", DriverTypeNames.Galaxy,
"""{"Gateway":{"Endpoint":"http://gw:5001","ApiKeySecretRef":"secret:galaxy/gx/apikey"}}""", Ct);
created.Ok.ShouldBeTrue(created.Error);
byte[] rv;
string deviceId;
byte[] deviceRv;
using (var db = RawTreeTestDb.CreateNamed(name))
{
rv = db.DriverInstances.Single(d => d.DriverInstanceId == created.CreatedId).RowVersion;
var device = db.Devices.Single(d => d.DriverInstanceId == created.CreatedId);
deviceId = device.DeviceId;
deviceRv = device.RowVersion;
}
(await svc.UpdateDriverAsync(created.CreatedId!, "gx",
"""{"Gateway":{"ApiKeySecretRef":"env:ConnectionStrings__ConfigDb"}}""", null, rv, Ct)).Ok.ShouldBeFalse();
(await svc.UpdateDeviceAsync(deviceId, "dev",
"""{"Gateway":{"ApiKeySecretRef":"env:ConnectionStrings__ConfigDb"}}""", true, deviceRv, Ct)).Ok.ShouldBeFalse();
(await svc.CreateDeviceAsync(created.CreatedId!, "dev2",
"""{"Gateway":{"ApiKeySecretRef":"secret:otopcua/historian/api-key"}}""", Ct)).Ok.ShouldBeFalse();
using var check = RawTreeTestDb.CreateNamed(name);
check.DriverInstances.Single(d => d.DriverInstanceId == created.CreatedId).DriverConfig.ShouldContain("secret:galaxy/gx/apikey");
check.Devices.Where(d => d.DriverInstanceId == created.CreatedId)
.ShouldAllBe(d => !d.DeviceConfig.Contains("ConnectionStrings") && !d.DeviceConfig.Contains("historian"));
}
[Theory]
[InlineData(DriverTypeNames.Galaxy, """{"Gateway":{"ApiKeySecretRef":"env:GALAXY_MXGW_API_KEY"},"AlarmAck":{"FallbackPasswordSecretRef":"secret:otopcua/galaxy/ack-fallback"}}""")]
[InlineData(DriverTypeNames.OpcUaClient, """{"Password":"literal-password","UserCertificatePassword":"secret:opcuaclient/plant/cert"}""")]
public async Task Namespaced_references_save(string type, string config)
{
var name = RawTreeTestDb.SeedFresh();
var svc = new RawTreeService(RawTreeTestDb.Factory(name));
var result = await svc.CreateDriverAsync(RawTreeTestDb.ClusterId, null, "ok815", type, config, Ct);
result.Ok.ShouldBeTrue(result.Error);
}
}
@@ -53,7 +53,10 @@ public sealed class HeidenhainAuthoringTests
{
var m = HeidenhainDriverFormModel.FromJson("{}");
m.DncPassword = "hunter2";
m.Validate()!.ShouldNotContain("hunter2");
// #830: the credential refusal is the hosting modal's (the save gate), reported once — not the form's too.
var refusal = DriverConfigSaveGate.Validate(DriverTypeNames.Heidenhain, m.ToJson());
refusal.ShouldNotBeNull();
refusal.ShouldNotContain("hunter2");
m.DncPassword = null;
m.StatusMs = 10;
m.Validate().ShouldNotBeNull();
@@ -66,7 +69,7 @@ public sealed class HeidenhainAuthoringTests
d.Port.ShouldBe(19000);
d.Validate().ShouldBeNull();
d.DataPassword = "plain";
d.Validate().ShouldNotBeNull();
DriverConfigSaveGate.Validate(DriverTypeNames.Heidenhain, d.ToJson()).ShouldNotBeNull(); // #830: the modal's gate
d.DataPassword = "env:OTOPCUA_HEIDENHAIN_DATA";
var json = d.ToJson();
JsonNode.Parse(json)!["Note"]!.GetValue<string>().ShouldBe("keep");
@@ -0,0 +1,176 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Drivers.DeviceForms;
using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Drivers.Forms;
using ZB.MOM.WW.OtOpcUa.AdminUI.Uns;
using ZB.MOM.WW.OtOpcUa.AdminUI.Uns.TagEditors;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Heidenhain;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Uns;
/// <summary>
/// lmxopcua#830 authoring UX: (a) the CSV review grid previews the SAME row rule the commit applies, (b) the
/// driver-dictated data type is a lock, never a silent rewrite, (c) a credential refusal is reported once.
/// Plus the #831 ALARM: authoring seams (editor seeding, native-alarm editor visibility).
/// </summary>
[Trait("Category", "Unit")]
public sealed class HeidenhainAuthoringUxTests
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private const string Header = "Name,DataType,AccessLevel,TagConfigJson";
private static string Csv(params string[] rows) => Header + "\n" + string.Join("\n", rows);
private static string Json(string json) => "\"" + json.Replace("\"", "\"\"") + "\"";
// ---- (a) CSV preview == commit ----
[Fact]
public void Csv_preview_flags_ReadWrite_and_data_type_mismatch_rows_like_the_commit()
{
var exec = Json("""{"address":"Status/ExecutionState"}""");
var result = RawTagCsvMapper.Parse(DriverTypeNames.Heidenhain, Csv(
$"ok,Int32,Read,{exec}",
$"rw,Int32,ReadWrite,{exec}",
$"dt,Double,Read,{exec}",
$"feed,Int32,Read,{Json("""{"address":"Overrides/Feed"}""")}"));
result.FatalError.ShouldBeNull();
var rows = result.Rows;
rows[0].Ok.ShouldBeTrue(rows[0].Error);
rows[1].Error!.ShouldContain("read-only");
rows[2].Error!.ShouldContain("Int32");
rows[3].Error!.ShouldContain("Double"); // a Float64 leaf publishes Double — picked as Int32 it used to preview OK
result.CanCommit.ShouldBeFalse();
}
[Fact]
public async Task Csv_preview_and_ImportTags_agree_row_for_row()
{
var exec = Json("""{"address":"Status/ExecutionState"}""");
var csv = Csv($"ok,Int32,Read,{exec}", $"rw,Int32,ReadWrite,{exec}", $"dt,String,Read,{exec}",
$"plc,Int64,Read,{Json("""{"address":"PLC:DWORD:0","dataType":"Int64"}""")}");
var preview = RawTagCsvMapper.Parse(DriverTypeNames.Heidenhain, csv);
var name = RawTreeTestDb.SeedFresh();
var svc = new RawTreeService(RawTreeTestDb.Factory(name));
var created = await svc.CreateDriverAsync(RawTreeTestDb.ClusterId, null, "hh1", DriverTypeNames.Heidenhain, "{}", Ct);
string deviceId;
using (var db = RawTreeTestDb.CreateNamed(name)) deviceId = db.Devices.Single(d => d.DriverInstanceId == created.CreatedId).DeviceId;
// Feed EVERY parsed row (the invalid ones too, rebuilt from their cells) to the commit and compare verdicts.
foreach (var row in preview.Rows)
{
var dataType = row.Cells[1];
var access = Enum.Parse<TagAccessLevel>(row.Cells[2]);
var input = new RawTagInput(row.Cells[0], dataType, access, false, null, row.Cells[3]);
var outcome = await svc.ImportTagsAsync(deviceId, [new RawTagImportRow(null, input)], Ct);
(outcome.Errors.Count == 0).ShouldBe(row.Ok, $"{row.Name}: preview {row.Error ?? "OK"} vs commit {string.Join("; ", outcome.Errors)}");
}
}
[Fact]
public void Row_rules_are_driver_dispatched_not_named_at_call_sites()
{
RawTagRowRules.DriverTypesWithRules.ShouldContain(DriverTypeNames.Heidenhain);
RawTagRowRules.Problem(DriverTypeNames.Modbus, TagAccessLevel.ReadWrite, "Float", "{}").ShouldBeNull();
RawTagRowRules.Problem(DriverTypeNames.Heidenhain, TagAccessLevel.ReadWrite, "Int32", """{"address":"Status/ExecutionState"}""")
.ShouldBe(HeidenhainTagRules.DescribeRowProblem(true, "Int32", """{"address":"Status/ExecutionState"}"""));
RawTagRowRules.IsReadOnlyDriver(DriverTypeNames.Heidenhain).ShouldBeTrue();
RawTagRowRules.IsReadOnlyDriver(DriverTypeNames.S7).ShouldBeFalse();
}
// ---- (b) dictated data type is a lock ----
[Theory]
[InlineData("""{"address":"Axes/Positions","isArray":true}""", "Double")]
[InlineData("""{"address":"PLC:WORD:3","dataType":"Int16"}""", "Int16")]
[InlineData("""{"address":"ALARM:*","alarm":{}}""", "Boolean")]
public void The_dictated_data_type_is_what_the_grid_and_modal_lock_to(string config, string expected)
{
RawTagRowDefaults.DictatedDataType(DriverTypeNames.Heidenhain, config).ShouldBe(expected);
// ...and the locked value is exactly what the save path accepts — nothing to rewrite on commit.
RawTagRowRules.Problem(DriverTypeNames.Heidenhain, TagAccessLevel.Read, expected, config).ShouldBeNull();
}
[Fact]
public void An_unresolved_config_or_another_driver_leaves_the_data_type_to_the_operator()
{
RawTagRowDefaults.DictatedDataType(DriverTypeNames.Heidenhain, "{}").ShouldBeNull();
RawTagRowDefaults.DictatedDataType(DriverTypeNames.Modbus, """{"address":"Axes/Positions","isArray":true}""").ShouldBeNull();
}
// ---- (c) credential error shown once ----
[Fact]
public void A_literal_password_is_reported_by_the_modal_save_gate_only_not_also_by_the_form()
{
var driver = HeidenhainDriverFormModel.FromJson("{}");
driver.InspectPassword = "hunter2";
var json = driver.ToJson();
DriverConfigSaveGate.Validate(DriverTypeNames.Heidenhain, json).ShouldNotBeNull(); // the modal's one notice + Save disabled
driver.Validate().ShouldBeNull(); // the form no longer repeats it
driver.StatusMs = 10;
driver.Validate()!.ShouldContain("StatusMs"); // non-credential problems still show in the form
var device = HeidenhainDeviceModel.FromJson("""{"Host":"cnc-7"}""");
device.DncPassword = "hunter2";
DriverConfigSaveGate.Validate(DriverTypeNames.Heidenhain, device.ToJson()).ShouldNotBeNull();
device.Validate().ShouldBeNull();
HeidenhainDeviceModel.FromJson("{}").Validate().ShouldNotBeNull(); // host still required in the form
}
// ---- #831 authoring seams ----
[Fact]
public void Picking_an_alarm_selector_seeds_the_alarm_object_and_leaving_it_drops_it()
{
var m = HeidenhainTagConfigModel.FromJson("{}");
m.Address = "ALARM:CLASS=7";
var json = m.ToJson();
m.Validate().ShouldBeNull();
TagConfigValidator.Validate(DriverTypeNames.Heidenhain, json).ShouldBeNull();
NativeAlarmModel.FromJson(json).IsAlarm.ShouldBeTrue();
HeidenhainTagDefinitionFactory.TryFromTagConfig("p", "d", json, out var def, out _).ShouldBeTrue();
def!.Alarm!.Severity.ShouldBe(HeidenhainTagConfigModel.DefaultAlarmSeverity);
// An authored severity is never overwritten by a later edit.
var edited = NativeAlarmModel.Edit(json, a => a.Severity = 950);
var again = HeidenhainTagConfigModel.FromJson(edited);
again.Address = "ALARM:*";
HeidenhainTagDefinitionFactory.TryFromTagConfig("p", "d", again.ToJson(), out def, out _).ShouldBeTrue();
def!.Alarm!.Severity.ShouldBe(950);
again.Address = "Status/ExecutionState";
var plain = again.ToJson();
NativeAlarmModel.FromJson(plain).IsAlarm.ShouldBeFalse();
TagConfigValidator.Validate(DriverTypeNames.Heidenhain, plain).ShouldBeNull();
}
[Fact]
public void Heidenhain_offers_the_native_alarm_editor_and_a_csv_alarm_row_imports()
{
NativeAlarmModel.SupportsNativeAlarms(DriverTypeNames.Heidenhain).ShouldBeTrue();
var result = RawTagCsvMapper.Parse(DriverTypeNames.Heidenhain,
"Name,DataType,AccessLevel,TagConfigJson,Alarm.AlarmType,Alarm.Severity\n" +
$"Any,Boolean,Read,{Json("""{"address":"ALARM:*"}""")},AlarmCondition,800\n" +
$"NoAlarm,Boolean,Read,{Json("""{"address":"ALARM:*"}""")},,\n");
result.Rows[0].Ok.ShouldBeTrue(result.Rows[0].Error);
result.Rows[1].Ok.ShouldBeFalse(); // a selector without the alarm object is refused in the preview
}
[Fact]
public void The_driver_form_round_trips_the_alarm_cadence()
{
var m = HeidenhainDriverFormModel.FromJson("{}");
m.AlarmMs.ShouldBe(2000);
m.AlarmMs = 500;
var o = HeidenhainOptionsParser.Parse(m.ToJson());
o.Polling.AlarmMs.ShouldBe(500);
m.AlarmMs = 50;
m.Validate()!.ShouldContain("AlarmMs");
}
}
@@ -98,7 +98,7 @@ public sealed class NativeAlarmEditorModelTests
public void SupportsNativeAlarms_covers_exactly_the_IAlarmSource_drivers()
{
foreach (var t in new[] { DriverTypeNames.MTConnect, DriverTypeNames.AbCip, DriverTypeNames.FOCAS,
DriverTypeNames.OpcUaClient, DriverTypeNames.Galaxy })
DriverTypeNames.OpcUaClient, DriverTypeNames.Galaxy, DriverTypeNames.Heidenhain })
NativeAlarmModel.SupportsNativeAlarms(t).ShouldBeTrue(t);
foreach (var t in new[] { DriverTypeNames.Modbus, DriverTypeNames.S7, DriverTypeNames.Mqtt, null })
NativeAlarmModel.SupportsNativeAlarms(t).ShouldBeFalse(t);
@@ -47,6 +47,9 @@
<ProjectReference Include="..\..\..\src\Drivers\ZB.MOM.WW.OtOpcUa.Driver.FOCAS\ZB.MOM.WW.OtOpcUa.Driver.FOCAS.csproj"/>
<ProjectReference Include="..\..\..\src\Drivers\ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient\ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.csproj"/>
<ProjectReference Include="..\..\..\src\Drivers\ZB.MOM.WW.OtOpcUa.Driver.Galaxy\ZB.MOM.WW.OtOpcUa.Driver.Galaxy.csproj"/>
<!-- #831: NativeAlarmDriverSetGuardTests discovers IAlarmSource implementers by scanning the driver DLLs
deployed here, so a driver that raises native alarms must be referenced or the guard misses it. -->
<ProjectReference Include="..\..\..\src\Drivers\ZB.MOM.WW.OtOpcUa.Driver.Heidenhain\ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.csproj"/>
</ItemGroup>
</Project>
@@ -0,0 +1,67 @@
using Akka.Actor;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
using ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests;
/// <summary>
/// lmxopcua#815: Test Connect with a credential reference outside the driver's namespace is refused BEFORE any
/// probe runs — the probe is the seam that would resolve the reference (store / environment) and send the value
/// to the author-chosen endpoint, so "the probe was never invoked" is "nothing was read".
/// </summary>
public sealed class AdminOperationsActorCredentialScopeTests : ControlPlaneActorTestBase
{
[Theory]
[InlineData(DriverTypeNames.Galaxy, """{"Gateway":{"Endpoint":"http://attacker:5001","ApiKeySecretRef":"env:ConnectionStrings__ConfigDb"}}""")]
[InlineData(DriverTypeNames.Galaxy, """{"Gateway":{"Endpoint":"http://attacker:5001","ApiKeySecretRef":"env:MX_API_KEY"}}""")]
[InlineData(DriverTypeNames.Galaxy, """{"Gateway":{"Endpoint":"http://attacker:5001","ApiKeySecretRef":"env:ServerHistorian__ApiKey"}}""")]
[InlineData(DriverTypeNames.Galaxy, """{"Gateway":{"Endpoint":"http://attacker:5001","ApiKeySecretRef":"file:appsettings.json"}}""")]
[InlineData(DriverTypeNames.OpcUaClient, """{"EndpointUrl":"opc.tcp://attacker:4840","Password":"secret:otopcua/historian/api-key"}""")]
[InlineData(DriverTypeNames.Heidenhain, """{"Access":{"InspectPassword":"secret:galaxy/main/apikey"},"Devices":[{"Host":"attacker"}]}""")]
public void Out_of_namespace_reference_never_reaches_the_probe(string driverType, string config)
{
var probe = new RecordingProbe(driverType);
var actor = Sys.ActorOf(AdminOperationsActor.Props(NewInMemoryDbFactory(), CreateTestProbe("coord").Ref, new IDriverProbe[] { probe }));
actor.Tell(new TestDriverConnect(driverType, config, 5, Guid.NewGuid()));
var reply = ExpectMsg<TestDriverConnectResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
reply.Ok.ShouldBeFalse();
reply.Message.ShouldNotBeNull().ShouldContain("Test Connect refused");
reply.Message.ShouldContain("lmxopcua#815");
probe.Calls.ShouldBe(0);
}
/// <summary>Positive control: a namespaced reference does reach the probe (the refusal is not blanket).</summary>
[Fact]
public void A_namespaced_reference_reaches_the_probe()
{
var probe = new RecordingProbe(DriverTypeNames.Galaxy);
var actor = Sys.ActorOf(AdminOperationsActor.Props(NewInMemoryDbFactory(), CreateTestProbe("coord").Ref, new IDriverProbe[] { probe }));
actor.Tell(new TestDriverConnect(
DriverTypeNames.Galaxy, """{"Gateway":{"Endpoint":"http://gw:5001","ApiKeySecretRef":"secret:galaxy/main/apikey"}}""", 5, Guid.NewGuid()));
ExpectMsg<TestDriverConnectResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken).Ok.ShouldBeTrue();
probe.Calls.ShouldBe(1);
}
private sealed class RecordingProbe(string driverType) : IDriverProbe
{
private int _calls;
public int Calls => Volatile.Read(ref _calls);
public string DriverType => driverType;
public Task<DriverProbeResult> ProbeAsync(string configJson, TimeSpan timeout, CancellationToken ct)
{
Interlocked.Increment(ref _calls);
return Task.FromResult(new DriverProbeResult(true, null, TimeSpan.Zero));
}
}
}
@@ -130,7 +130,7 @@ public sealed class HistorianBackendRegistryTests
o.TablePrefix.ShouldBe("rig_");
}
/// <summary>The seventeen aggregates the SQL backends serve, spelled out (not derived) so a drift in either the
/// <summary>The nineteen aggregates the SQL backends serve, spelled out (not derived) so a drift in either the
/// family table or a backend's declaration fails here (#682).</summary>
private static readonly HistoryAggregateType[] SqlServed =
[
@@ -139,6 +139,7 @@ public sealed class HistorianBackendRegistryTests
HistoryAggregateType.MinimumActualTime, HistoryAggregateType.MaximumActualTime, HistoryAggregateType.TimeAverage,
HistoryAggregateType.TimeAverage2, HistoryAggregateType.Total, HistoryAggregateType.Total2,
HistoryAggregateType.Interpolative, HistoryAggregateType.PercentGood, HistoryAggregateType.PercentBad,
HistoryAggregateType.DurationGood, HistoryAggregateType.DurationBad,
];
[Fact]
@@ -88,7 +88,7 @@ public sealed class AclEventSubscriptionEnforcementTests
// The next deployment carries only EqB's grant.
state.Apply(Cluster, "rev-2", [], [EquipmentGrant(EqB)], ScopePaths(),
ServerEventRig.EquipmentOwnerPaths(), ServerEventRig.ScriptedAlarmOwners(), ServerEventRig.FolderScopes());
ServerEventRig.EquipmentOwnerPaths(), ServerEventRig.ScriptedAlarmOwners(), ServerEventRig.FolderScopes(), ServerEventRig.TagReferences());
rig.AttachedEventItems.ShouldBe(1);
rig.Transition("t2", active: false);
@@ -100,7 +100,7 @@ public sealed class AclEventSubscriptionEnforcementTests
// A deployment that restores the grant brings the feed back on its own.
state.Apply(Cluster, "rev-3", [], [EquipmentGrant(EqA), EquipmentGrant(EqB)], ScopePaths(),
ServerEventRig.EquipmentOwnerPaths(), ServerEventRig.ScriptedAlarmOwners(), ServerEventRig.FolderScopes());
ServerEventRig.EquipmentOwnerPaths(), ServerEventRig.ScriptedAlarmOwners(), ServerEventRig.FolderScopes(), ServerEventRig.TagReferences());
rig.AttachedEventItems.ShouldBe(2);
rig.Transition("t3", active: true);
@@ -143,7 +143,7 @@ public sealed class AclEventSubscriptionEnforcementTests
rig.AttachedEventItems.ShouldBe(2);
state.Apply(Cluster, "rev-2", [], [EquipmentGrant(EqB)], ScopePaths(),
ServerEventRig.EquipmentOwnerPaths(), ServerEventRig.ScriptedAlarmOwners(), ServerEventRig.FolderScopes());
ServerEventRig.EquipmentOwnerPaths(), ServerEventRig.ScriptedAlarmOwners(), ServerEventRig.FolderScopes(), ServerEventRig.TagReferences());
rig.AttachedEventItems.ShouldBe(1);
subscription.RemoveItem(onA);
@@ -153,7 +153,7 @@ public sealed class AclEventSubscriptionEnforcementTests
// A restoring deployment must not re-attach the deleted item. The client could never see that
// happen — it has deleted the item — so the server-side fan-out is what is asserted.
state.Apply(Cluster, "rev-3", [], [EquipmentGrant(EqA), EquipmentGrant(EqB)], ScopePaths(),
ServerEventRig.EquipmentOwnerPaths(), ServerEventRig.ScriptedAlarmOwners(), ServerEventRig.FolderScopes());
ServerEventRig.EquipmentOwnerPaths(), ServerEventRig.ScriptedAlarmOwners(), ServerEventRig.FolderScopes(), ServerEventRig.TagReferences());
rig.AttachedEventItems.ShouldBe(1, "the deleted item must not be resurrected onto EqA's fan-out");
rig.Transition("t2", active: false);
@@ -410,7 +410,7 @@ public sealed class AclEventSubscriptionEnforcementTests
await WaitUntilAsync(() => events.Has(item, "t1") && controlEvents.Has(controlItem, "t1"));
state.Apply(Cluster, "rev-2", [key], [ClusterGrant(KeyPrincipal, "acl-key")], ScopePaths(),
ServerEventRig.EquipmentOwnerPaths(), ServerEventRig.ScriptedAlarmOwners(), ServerEventRig.FolderScopes());
ServerEventRig.EquipmentOwnerPaths(), ServerEventRig.ScriptedAlarmOwners(), ServerEventRig.FolderScopes(), ServerEventRig.TagReferences());
rig.Transition("t2", active: false);
await WaitUntilAsync(() => controlEvents.Has(controlItem, "t2"));
@@ -418,7 +418,7 @@ public sealed class AclEventSubscriptionEnforcementTests
events.Has(item, "t2").ShouldBeFalse("the revoked session must not receive alarms after the deployment");
state.Apply(Cluster, "rev-3", [key], [EquipmentGrant(EqA), ClusterGrant(KeyPrincipal, "acl-key")], ScopePaths(),
ServerEventRig.EquipmentOwnerPaths(), ServerEventRig.ScriptedAlarmOwners(), ServerEventRig.FolderScopes());
ServerEventRig.EquipmentOwnerPaths(), ServerEventRig.ScriptedAlarmOwners(), ServerEventRig.FolderScopes(), ServerEventRig.TagReferences());
rig.Transition("t3", active: true);
await WaitUntilAsync(() => events.Has(item, "t3") && controlEvents.Has(controlItem, "t3"));
@@ -1049,7 +1049,7 @@ public sealed class AclEventSubscriptionEnforcementTests
{
var state = new DataPlaneAuthorityState();
state.Apply(Cluster, "rev-1", keys, grants, ScopePaths(),
ServerEventRig.EquipmentOwnerPaths(), ServerEventRig.ScriptedAlarmOwners(), ServerEventRig.FolderScopes());
ServerEventRig.EquipmentOwnerPaths(), ServerEventRig.ScriptedAlarmOwners(), ServerEventRig.FolderScopes(), ServerEventRig.TagReferences());
Nm.DataPlaneAuthority = state;
Nm.Authorizer = new DataPlaneAuthorizer(
@@ -27,9 +27,11 @@ public sealed class AdvertisedAggregateFunctionsWireTests
"Average", "Count", "Delta", "End", "Maximum", "MaximumActualTime", "Minimum", "MinimumActualTime", "Range", "Start",
];
// #820 added DurationBad / DurationGood (the PercentBad / PercentGood region times, in ms).
private static readonly string[] SqlNames =
[
"Average", "Count", "Delta", "End", "Interpolative", "Maximum", "MaximumActualTime", "Minimum", "MinimumActualTime",
"Average", "Count", "Delta", "DurationBad", "DurationGood", "End", "Interpolative", "Maximum", "MaximumActualTime",
"Minimum", "MinimumActualTime",
"PercentBad", "PercentGood", "Range", "Start", "TimeAverage", "TimeAverage2", "Total", "Total2",
];
@@ -0,0 +1,188 @@
using Opc.Ua;
using Opc.Ua.Client;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests;
/// <summary>
/// Review of Gitea #826: the SDK memoizes each folder event item's per-event verdict per
/// <c>(item, event type, SourceNode)</c>, so the per-event decision is only as fresh as its invalidation. These pin
/// the three ways it went stale or cost too much: an ORPHANED subscription (no session to invalidate by), a stale
/// DENY left by a replaced instance's late event, and invalidation running with enforcement off.
/// </summary>
public sealed class FolderEventVerdictInvalidationTests
{
private const string EqA = ServerEventRig.EqA;
private const string EqB = ServerEventRig.EqB;
/// <summary>
/// A subscription orphaned by its session (closed without deleting its subscriptions) keeps its items on the
/// folder fan-out with NO session. A deployment that drops EqA's reference must still reach those items: the
/// native alarm's events raised while orphaned are not queued to the EqA item, so a TransferSubscriptions to a
/// new session delivers them only through EqB (positive control on the same subscription and event).
/// </summary>
[Fact]
public async Task An_orphaned_folder_item_does_not_keep_a_stale_allow_across_a_deploy_and_a_transfer()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("Folder826Orphan", encrypted: false, ct);
rig.KeyRoles = [];
rig.MaterialiseNative();
NodeAcl[] grants = [KeyEquipmentGrant(EqA), KeyEquipmentGrant(EqB)];
var state = rig.Enforce(true, [ServerEventRig.Key()], grants);
using var first = await rig.ConnectAsync(anonymous: false, ct);
var events = new RecordedEvents();
var subscription = await RecordedEvents.SubscribeAsync(first, events, ct);
var onA = RecordedEvents.AddEventItem(subscription, ServerEventRig.UnsNodeId(first, EqA));
var onB = RecordedEvents.AddEventItem(subscription, ServerEventRig.UnsNodeId(first, EqB));
await subscription.ApplyChangesAsync(ct);
onA.Status.Error.ShouldBeNull();
// Seed the SDK's cache with an ALLOW for the EqA item.
rig.Project(native: true, State("t1"));
await RecordedEvents.WaitUntilAsync(() => events.Has(onA, "t1") && events.Has(onB, "t1"));
// Orphan the subscription: a raw CloseSession with deleteSubscriptions=false, so the subscription and its items
// stay on the server with no session. The raw service leaves the client session OBJECT alive (Session.CloseAsync
// would dispose it), as a reconnecting client's is, so the high-level transfer can take the subscription over.
var orphaned = new SubscriptionCollection(first.Subscriptions);
await ((ISessionClient)first).CloseSessionAsync(null, deleteSubscriptions: false, ct);
// The deployment drops EqA's reference; the alarm reports while the subscription has no session.
Deploy(state, "rev-2", grants, EqB);
rig.Project(native: true, State("t2"));
using var second = await rig.ConnectAsync(anonymous: false, ct);
(await second.TransferSubscriptionsAsync(orphaned, sendInitialValues: false, ct)).ShouldBeTrue();
rig.Project(native: true, State("t3"));
await RecordedEvents.WaitUntilAsync(() => events.Has(onB, "t2") && events.Has(onB, "t3"));
await Task.Delay(TimeSpan.FromMilliseconds(700), ct);
events.Has(onA, "t2").ShouldBeFalse("an event raised while orphaned must not be queued on a stale allow");
events.Has(onA, "t3").ShouldBeFalse();
await second.CloseAsync(ct);
}
/// <summary>
/// A surgical replace of a scripted condition under the SAME NodeId (remove + re-materialise, the folder item
/// survives), with the old instance's last event still waiting in the SDK's per-folder queue when the apply's
/// invalidation runs. That late event must not leave a cached DENY the new instance inherits: the new
/// instance's events keep reaching the folder subscriber.
/// </summary>
[Fact]
public async Task A_replaced_instances_late_event_does_not_leave_a_cached_deny_for_the_new_instance()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("Folder826Replace", encrypted: false, ct);
rig.KeyRoles = [];
rig.MaterialiseScripted();
rig.MaterialiseNative(); // also wired into EqA: its event is the deterministic blocker below
rig.Enforce(true, [], ServerEventRig.EquipmentGrant(EqA, NodePermissions.ReadOnly));
using var session = await rig.ConnectAsync(anonymous: true, ct);
var events = new RecordedEvents();
var subscription = await RecordedEvents.SubscribeAsync(session, events, ct);
var onA = RecordedEvents.AddEventItem(subscription, ServerEventRig.UnsNodeId(session, EqA));
await subscription.ApplyChangesAsync(ct);
onA.Status.Error.ShouldBeNull();
rig.Project(native: false, State("s1"));
await RecordedEvents.WaitUntilAsync(() => events.Has(onA, "s1"));
// Holding the node-manager lock parks EqA's SDK delivery task: the native event "n1" is queued first and its
// verdict (a cache miss after the first invalidation) needs the lock in the inherited role check — its node is
// never removed, so that check always takes it. The OLD scripted instance's "s2", queued behind it on the same
// single-reader queue, is therefore decided only after the replace and the apply's invalidation.
lock (rig.Nm.Lock)
{
rig.Nm.CompleteAddressSpaceApply(); // forget the cached allows, so both verdicts must be computed
rig.Project(native: true, State("n1"));
rig.Project(native: false, State("s2"));
((ISurgicalAddressSpaceSink)rig.Sink)
.RemoveAlarmConditionNode(ServerEventRig.ScriptedAlarmId, AddressSpaceRealm.Uns).ShouldBeTrue();
rig.MaterialiseScripted();
rig.Nm.CompleteAddressSpaceApply();
}
rig.Project(native: false, State("s3"));
// The new instance's event arrives (a cached deny would withhold it until the next invalidation), and so does
// the old instance's late one — decided on the live instance, exactly as the live one's would be.
await RecordedEvents.WaitUntilAsync(() => events.Has(onA, "s3") && events.Has(onA, "s2"));
await session.CloseAsync(ct);
}
/// <summary>
/// Review of #826 (perf): with enforcement OFF the folder verdicts are the SDK's own role check, so nothing
/// invalidates them — not the revalidation tick, not a deploy, not the end of an apply. Positive control: the
/// same calls invalidate once enforcement is on.
/// </summary>
[Fact]
public async Task Folder_verdicts_are_not_invalidated_while_enforcement_is_off()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("Folder826AclOff", encrypted: false, ct);
rig.MaterialiseNative();
var state = rig.Enforce(false, [], ServerEventRig.EquipmentGrant(EqA, NodePermissions.ReadOnly));
using var session = await rig.ConnectAsync(anonymous: true, ct);
var events = new RecordedEvents();
var subscription = await RecordedEvents.SubscribeAsync(session, events, ct);
RecordedEvents.AddEventItem(subscription, ServerEventRig.UnsNodeId(session, EqA));
await subscription.ApplyChangesAsync(ct);
var before = rig.Nm.FolderEventVerdictInvalidations;
rig.Nm.RevalidateMonitoredItems();
rig.Nm.CompleteAddressSpaceApply();
state.Apply(ServerEventRig.Cluster, "rev-off-2", [], [ServerEventRig.EquipmentGrant(EqA, NodePermissions.ReadOnly)],
ServerEventRig.ScopePaths());
rig.Nm.FolderEventVerdictInvalidations.ShouldBe(before, "enforcement off: nothing to invalidate");
rig.Enforce(true, [], ServerEventRig.EquipmentGrant(EqA, NodePermissions.ReadOnly));
var enforced = rig.Nm.FolderEventVerdictInvalidations;
enforced.ShouldBeGreaterThan(before, "switching enforcement on invalidates the verdicts decided while off");
rig.Nm.CompleteAddressSpaceApply();
rig.Nm.FolderEventVerdictInvalidations.ShouldBeGreaterThan(enforced);
await session.CloseAsync(ct);
}
/// <summary>
/// The node-wide invalidation rests on a PRIVATE method of the pinned SDK (<c>MonitoredNode2.InvalidatePermissionCaches</c>).
/// If an SDK upgrade drops it the node manager silently falls back to the weaker supported route — this fails
/// first, so the upgrade is looked at.
/// </summary>
[Fact]
public void The_sdks_node_wide_permission_cache_invalidation_is_still_resolvable()
{
OtOpcUaNodeManager.InvalidateNodePermissionCaches.ShouldNotBeNull(
"MonitoredNode2.InvalidatePermissionCaches() is gone — re-check InvalidateFolderEventVerdicts against the new SDK");
}
private static AlarmConditionSnapshot State(string message) =>
new(true, false, false, true, AlarmShelvingKind.Unshelved, 700, message);
private static void Deploy(DataPlaneAuthorityState state, string revision, NodeAcl[] grants, params string[] referencing) =>
state.Apply(
ServerEventRig.Cluster, revision, [ServerEventRig.Key()], grants, ServerEventRig.ScopePaths(),
ServerEventRig.EquipmentOwnerPaths(), ServerEventRig.ScriptedAlarmOwners(), ServerEventRig.FolderScopes(),
new Dictionary<string, IReadOnlySet<string>> { [ServerEventRig.RawAlarmPath] = referencing.ToHashSet() });
private static NodeAcl KeyEquipmentGrant(string equipment) => new()
{
NodeAclId = $"acl-key-{equipment}",
ClusterId = ServerEventRig.Cluster,
Principal = ServerEventRig.KeyPrincipal,
ScopeKind = NodeAclScopeKind.Equipment,
ScopeId = $"eq-{equipment}",
PermissionFlags = NodePermissions.ReadOnly,
};
}
@@ -0,0 +1,55 @@
using Opc.Ua;
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests;
/// <summary>
/// #821 / #809 facts, through the BOOTED server's runtime <c>AggregateManager</c> — the calculators a live
/// AggregateFilter monitored item gets, under the server's own default configuration. This pins current behaviour for
/// the owner decision; it does not choose. The HistoryRead (Part 13) answers and SDK 2.0.1's stock answers for the
/// same input are pinned beside it in <c>SdkAggregateParityTests</c>.
/// </summary>
public sealed class LiveAggregateLateStartFactsTests
{
private static readonly DateTime T0 = new(2026, 11, 11, 8, 0, 0, DateTimeKind.Utc);
/// <summary>The #810 QualityMix tag QP: Uncertain 10 at +5, Good 11 at +12, Uncertain 12 at +25, nothing after.</summary>
private static readonly (double Seconds, double Value, uint Status)[] Qp =
[
(5, 10, 0x40000000u), (12, 11, 0x00000000u), (25, 12, 0x40000000u), // Uncertain, Good, Uncertain
];
[Fact]
public async Task Live_AggregateFilter_calculators_on_an_Uncertain_first_late_start_interval()
{
await using var rig = await ServerEventRig.StartAsync("AggregateLateStart", encrypted: false,
TestContext.Current.CancellationToken);
var manager = rig.Server.CurrentInstance.AggregateManager;
var config = manager.GetDefaultConfiguration(NodeId.Null);
config.TreatUncertainAsBad.ShouldBeFalse("the server pins TreatUncertainAsBad = false (#782)");
double One(NodeId aggregate)
{
var calc = manager.CreateCalculator(aggregate, T0, T0.AddSeconds(20), 20_000, false, config);
calc.ShouldNotBeNull();
foreach (var (s, v, st) in Qp)
calc.QueueRawValue(new DataValue(Variant.From(v), st, T0.AddSeconds(s), T0.AddSeconds(s)));
calc.TryGetProcessedValue(true, out var dv).ShouldBeTrue();
dv.WrappedValue.TryGetValue(out double d).ShouldBeTrue();
return d;
}
// Part 13 (HistoryRead on SqlServer/QuestDB): Total = 73.5 + 88 + 32/13 = 163.96…, TimeAverage = Total ÷ 15 s.
// The live calculators integrate the uncovered [0,5) as a ramp from 0 (+25) and divide by the whole 20 s.
const double part13Total = 73.5 + 88 + 32d / 13;
One(ObjectIds.AggregateFunction_Total).ShouldBe(part13Total + 25, 1e-9); // 188.96…
One(ObjectIds.AggregateFunction_TimeAverage).ShouldBe((part13Total + 25) / 20, 1e-9); // 9.448… (Part 13: 10.93…)
// #809: the Uncertain [5,12) counts as Good live (HistoryRead: 8 000 ms / 40 %).
One(ObjectIds.AggregateFunction_DurationGood).ShouldBe(15_000d, 1e-9);
One(ObjectIds.AggregateFunction_PercentGood).ShouldBe(75d, 1e-9);
// DurationBad / PercentBad agree with HistoryRead: the 5 s before the data is Bad.
One(ObjectIds.AggregateFunction_DurationBad).ShouldBe(5_000d, 1e-9);
One(ObjectIds.AggregateFunction_PercentBad).ShouldBe(25d, 1e-9);
}
}
@@ -0,0 +1,117 @@
using Opc.Ua;
using Opc.Ua.Client;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests;
/// <summary>
/// Gitea #826, native variant, over the wire: a native alarm materialises once at its raw tag and is wired as an
/// extra event notifier into every referencing equipment folder. A deployment that drops one equipment's reference
/// installs its generation BEFORE the rebuild that unwires the folder (and an apply that fails keeps the old
/// wiring), so the folder's subscribers used to keep receiving the alarm — EventId included — through the SDK's
/// per-folder fan-out, which no ACL decision reached, and through the Server object, whose scopes admitted every
/// wired folder. Both now ask the CURRENT generation whether it still projects the raw tag into that equipment.
/// </summary>
public sealed class NativeAlarmFolderEventAclWireTests
{
private const string EqA = ServerEventRig.EqA;
private const string EqB = ServerEventRig.EqB;
/// <summary>
/// Anonymous holds EqA, the key holds EqB, the alarm is wired into both. The generation drops EqA's reference
/// with the wiring still in place: EqA's folder item and the anonymous Server-object item stop receiving the
/// alarm (live AND ConditionRefresh), while the key's EqB folder and Server-object items receive the same events
/// (positive control). Restoring the reference restores EqA's feed with no client action — the SDK's memoized
/// per-event verdict is invalidated by the generation change.
/// </summary>
[Fact]
public async Task A_native_alarm_stops_reaching_a_folder_whose_reference_the_generation_dropped()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("Folder826Native", encrypted: false, ct);
rig.KeyRoles = [];
rig.MaterialiseNative();
NodeAcl[] grants = [ServerEventRig.EquipmentGrant(EqA, NodePermissions.ReadOnly), KeyEquipmentGrant(EqB)];
var state = rig.Enforce(true, [ServerEventRig.Key()], grants);
using var anonymous = await rig.ConnectAsync(anonymous: true, ct);
using var keyed = await rig.ConnectAsync(anonymous: false, ct);
var anonEvents = new RecordedEvents();
var anonSub = await RecordedEvents.SubscribeAsync(anonymous, anonEvents, ct);
var onA = RecordedEvents.AddEventItem(anonSub, ServerEventRig.UnsNodeId(anonymous, EqA));
var anonServer = RecordedEvents.AddEventItem(anonSub, ObjectIds.Server);
await anonSub.ApplyChangesAsync(ct);
onA.Status.Error.ShouldBeNull();
var keyEvents = new RecordedEvents();
var keySub = await RecordedEvents.SubscribeAsync(keyed, keyEvents, ct);
var onB = RecordedEvents.AddEventItem(keySub, ServerEventRig.UnsNodeId(keyed, EqB));
var keyServer = RecordedEvents.AddEventItem(keySub, ObjectIds.Server);
await keySub.ApplyChangesAsync(ct);
onB.Status.Error.ShouldBeNull();
// Baseline: every item receives the alarm while both references are deployed.
rig.Project(native: true, State("t1"));
await RecordedEvents.WaitUntilAsync(() =>
anonEvents.Has(onA, "t1") && anonEvents.Has(anonServer, "t1")
&& keyEvents.Has(onB, "t1") && keyEvents.Has(keyServer, "t1"));
// The next generation drops EqA's reference; the address space still wires the alarm into EqA.
Deploy(state, "rev-2", grants, EqB);
rig.Project(native: true, State("t2"));
await RecordedEvents.WaitUntilAsync(() => keyEvents.Has(onB, "t2") && keyEvents.Has(keyServer, "t2"));
await Task.Delay(TimeSpan.FromMilliseconds(700), ct);
anonEvents.Has(onA, "t2").ShouldBeFalse("the folder the generation dropped must not receive the alarm");
anonEvents.Has(anonServer, "t2").ShouldBeFalse("nor may that folder's grant admit it through the Server object");
// ConditionRefresh on the stale folder respects the same rule; the still-referenced folder replays it.
await RefreshAsync(anonymous, anonSub, ct);
await RefreshAsync(keyed, keySub, ct);
await RecordedEvents.WaitUntilAsync(() =>
anonEvents.HasType(onA, ObjectTypeIds.RefreshEndEventType)
&& keyEvents.ConditionEvents(onB, "t2").Count == 2);
await Task.Delay(TimeSpan.FromMilliseconds(300), ct);
anonEvents.Has(onA, "t2").ShouldBeFalse("a refresh must not replay the alarm to the dropped folder");
anonEvents.Has(anonServer, "t2").ShouldBeFalse();
// Restoring the reference restores the feed on the next event — no client action, no stale cached deny.
Deploy(state, "rev-3", grants, EqA, EqB);
rig.Project(native: true, State("t3"));
await RecordedEvents.WaitUntilAsync(() =>
anonEvents.Has(onA, "t3") && anonEvents.Has(anonServer, "t3") && keyEvents.Has(onB, "t3"));
await anonymous.CloseAsync(ct);
await keyed.CloseAsync(ct);
}
private static AlarmConditionSnapshot State(string message) =>
new(true, false, false, true, AlarmShelvingKind.Unshelved, 700, message);
private static void Deploy(DataPlaneAuthorityState state, string revision, NodeAcl[] grants, params string[] referencing) =>
state.Apply(
ServerEventRig.Cluster, revision, [ServerEventRig.Key()], grants, ServerEventRig.ScopePaths(),
ServerEventRig.EquipmentOwnerPaths(), ServerEventRig.ScriptedAlarmOwners(), ServerEventRig.FolderScopes(),
new Dictionary<string, IReadOnlySet<string>> { [ServerEventRig.RawAlarmPath] = referencing.ToHashSet() });
private static NodeAcl KeyEquipmentGrant(string equipment) => new()
{
NodeAclId = $"acl-key-{equipment}",
ClusterId = ServerEventRig.Cluster,
Principal = ServerEventRig.KeyPrincipal,
ScopeKind = NodeAclScopeKind.Equipment,
ScopeId = $"eq-{equipment}",
PermissionFlags = NodePermissions.ReadOnly,
};
private static async Task RefreshAsync(ISession session, Subscription subscription, CancellationToken ct) =>
await session.CallAsync(
ObjectTypeIds.ConditionType, MethodIds.ConditionType_ConditionRefresh, ct, subscription.Id);
}
@@ -127,7 +127,8 @@ internal sealed class ServerEventRig : IAsyncDisposable
{
var state = new DataPlaneAuthorityState();
state.Apply(
Cluster, "rev-1", keys, grants, scopePaths, equipmentOwnerPaths, ScriptedAlarmOwners(), FolderScopes());
Cluster, "rev-1", keys, grants, scopePaths, equipmentOwnerPaths, ScriptedAlarmOwners(), FolderScopes(),
TagReferences());
Nm.DataPlaneAuthority = state;
Nm.Authorizer = new DataPlaneAuthorizer(
state, new TriePermissionEvaluator(state.Tries), enabled, NullLogger.Instance, TimeProvider.System);
@@ -163,7 +164,7 @@ internal sealed class ServerEventRig : IAsyncDisposable
PermissionFlags = permissions,
};
private static IReadOnlyDictionary<AclScopeRef, IReadOnlyList<NodeAclPath>> ScopePaths() =>
public static IReadOnlyDictionary<AclScopeRef, IReadOnlyList<NodeAclPath>> ScopePaths() =>
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>
{
[new AclScopeRef(NodeAclScopeKind.Equipment, $"eq-{EqA}")] = [new NodeAclPath([NodeAclRealms.Uns, EqA])],
@@ -195,6 +196,13 @@ internal sealed class ServerEventRig : IAsyncDisposable
[EqB] = new(new NodeAclPath([NodeAclRealms.Uns, EqB]), [EqB]),
};
/// <summary>
/// The rig's deployed UNS references (Gitea #826): its native alarm's raw tag is projected into both equipment —
/// the folders <see cref="MaterialiseNative"/> wires it into, so per-folder delivery of it is current.
/// </summary>
public static IReadOnlyDictionary<string, IReadOnlySet<string>> TagReferences() =>
new Dictionary<string, IReadOnlySet<string>> { [RawAlarmPath] = new HashSet<string> { EqA, EqB } };
/// <summary>The rig's deployed scripted-alarm owners: its one scripted alarm belongs to <see cref="EqA"/>.</summary>
public static IReadOnlyDictionary<string, string> ScriptedAlarmOwners() =>
new Dictionary<string, string> { [ScriptedAlarmId] = EqA };
@@ -210,6 +210,65 @@ public sealed class UnsFolderScopeWireTests
await session.CloseAsync(ct);
}
/// <summary>
/// Gitea #826 — the same stale window seen by a DIRECT event item on the old owner's equipment folder, which the
/// SDK feeds through its per-folder fan-out rather than the Server object. The old owner's folder subscription
/// receives neither the moved alarm's live events nor its ConditionRefresh replay (EventId included), while its
/// correctly placed alarm keeps arriving on the same item (positive control). After the rebuild re-materialises
/// the alarm under its deployed owner, the new owner's folder subscription receives it.
/// </summary>
[Fact]
public async Task A_moved_alarm_stops_reaching_its_old_folders_subscribers_until_the_rebuild_places_it()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("Uns826FolderMoved", encrypted: false, ct);
rig.KeyRoles = [];
Topology(rig, pumpLine: Line1);
// The key holds the OLD owner (Pump); anonymous holds the NEW one (Fan). The generation already moved Alarm.
Install(rig, pumpLine: Line1, Deployed(alarmOwner: Fan),
EquipmentGrant(Pump, Operator), AnonymousGrant(NodeAclScopeKind.Equipment, Fan));
using var oldOwner = await rig.ConnectAsync(anonymous: false, ct);
using var newOwner = await rig.ConnectAsync(anonymous: true, ct);
var oldEvents = new RecordedEvents();
var oldSubscription = await RecordedEvents.SubscribeAsync(oldOwner, oldEvents, ct);
var pumpFolder = RecordedEvents.AddEventItem(oldSubscription, Uns(oldOwner, Pump));
await oldSubscription.ApplyChangesAsync(ct);
pumpFolder.Status.Error.ShouldBeNull();
var newEvents = new RecordedEvents();
var newSubscription = await RecordedEvents.SubscribeAsync(newOwner, newEvents, ct);
var fanFolder = RecordedEvents.AddEventItem(newSubscription, Uns(newOwner, Fan));
await newSubscription.ApplyChangesAsync(ct);
fanFolder.Status.Error.ShouldBeNull();
var pre = new AlarmConditionSnapshot(true, false, false, true, AlarmShelvingKind.Unshelved, 700, "base");
Project(rig, Alarm, pre with { Message = "moved" }); // reported first: the control arrives after its verdict
Project(rig, PumpLo, pre with { Message = "control" });
await RecordedEvents.WaitUntilAsync(() => oldEvents.Has(pumpFolder, "control"));
await Task.Delay(TimeSpan.FromMilliseconds(700), ct);
oldEvents.Has(pumpFolder, "moved").ShouldBeFalse("the moved alarm must not reach its old owner's folder item");
// ConditionRefresh on the folder item replays the placed alarm and withholds the moved one.
await RefreshAsync(oldOwner, oldSubscription, ct);
await RecordedEvents.WaitUntilAsync(() =>
oldEvents.HasType(pumpFolder, ObjectTypeIds.RefreshEndEventType)
&& oldEvents.ConditionEvents(pumpFolder, "control").Count == 2);
oldEvents.Has(pumpFolder, "moved").ShouldBeFalse("a refresh must not replay the moved alarm to the old folder");
// The rebuild places it under its deployed owner.
((ISurgicalAddressSpaceSink)rig.Sink).RemoveAlarmConditionNode(Alarm, AddressSpaceRealm.Uns).ShouldBeTrue();
rig.Sink.MaterialiseAlarmCondition(Alarm, Fan, "hi", "AlarmCondition", 500, AddressSpaceRealm.Uns);
rig.Nm.CompleteAddressSpaceApply();
Project(rig, Alarm, pre with { Message = "placed" });
Project(rig, PumpLo, pre with { Message = "control-2" });
await RecordedEvents.WaitUntilAsync(() =>
newEvents.Has(fanFolder, "placed") && oldEvents.Has(pumpFolder, "control-2"));
oldEvents.Has(pumpFolder, "placed").ShouldBeFalse();
await oldOwner.CloseAsync(ct);
await newOwner.CloseAsync(ct);
}
/// <summary>
/// An EQUIPMENT moved to another line by the generation while its folder still hangs under the old line: the live
/// folder ancestry disagrees with the generation's, so the folder, everything it owns, its scripted alarm (read
@@ -294,6 +353,34 @@ public sealed class UnsFolderScopeWireTests
await session.CloseAsync(ct);
}
/// <summary>
/// Gitea #826 (secondary edge of #808): an Area NAMED exactly like one of its equipment's opaque ids. That
/// equipment's reference variable (<c>s=&lt;AreaName&gt;/Line/Equipment/Name</c>) then starts with the
/// equipment's own id, which the id rule alone read as folder-owned — losing its Tag-grant match. The variable
/// is now known to be a reference by the Organizes edge the reference pass wires to its raw node, so the Tag
/// grant reaches it; the equipment folder itself stays denied to that grant (control).
/// </summary>
[Fact]
public async Task A_reference_variable_under_an_area_named_like_its_equipment_id_keeps_its_tag_grant()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("Uns826AreaNamedLikeId", encrypted: false, ct);
rig.KeyRoles = [];
Topology(rig, pumpLine: Line1);
var raw = rig.EnsureRawVariable("flow", "Double", writable: false);
var reference = $"{Pump}/Line1/Pump/Flow"; // the Area's NAME is Pump's id
rig.Sink.EnsureVariable(reference, Pump, "Flow", "Double", writable: false, AddressSpaceRealm.Uns);
rig.Sink.AddReference(reference, AddressSpaceRealm.Uns, raw, AddressSpaceRealm.Raw);
Install(rig, pumpLine: Line1, Deployed(), areaName: Pump, tagArea: Pump, TagGrant());
using var session = await rig.ConnectAsync(anonymous: false, ct);
(await ReadAsync(session, Uns(session, reference), Attributes.DisplayName, ct)).ShouldBe(StatusCodes.Good);
(await ReadAsync(session, Uns(session, Pump), Attributes.DisplayName, ct)).ShouldBe(StatusCodes.BadUserAccessDenied);
(await ReadAsync(session, Uns(session, PumpSpeed), Attributes.DisplayName, ct)).ShouldBe(StatusCodes.BadUserAccessDenied);
await session.CloseAsync(ct);
}
/// <summary>
/// Review of #808 (cache poisoning): the resolved-scope cache keys are NUL-prefixed, so a client that first
/// Reads the nonexistent <c>s="\0Area1\0Line1\0Pump"</c> — the exact cache key of the real Pump folder — must
@@ -481,13 +568,19 @@ public sealed class UnsFolderScopeWireTests
/// has not caught up with when it differs from the live <c>Area1</c>).</summary>
private static void Install(
ServerEventRig rig, string pumpLine, IReadOnlyDictionary<string, string> deployedOwners, string areaName,
params NodeAcl[] grants)
params NodeAcl[] grants) =>
Install(rig, pumpLine, deployedOwners, areaName, tagArea: "Area1", grants);
/// <summary>As above, with the Tag grant's UNS projection under the Area NAMED <paramref name="tagArea"/>.</summary>
private static void Install(
ServerEventRig rig, string pumpLine, IReadOnlyDictionary<string, string> deployedOwners, string areaName,
string tagArea, params NodeAcl[] grants)
{
var resolver = Resolver(pumpLine, areaName);
var scopePaths = new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>(resolver.Resolve(grants))
{
// A Tag grant's UNS projection (the resolver would derive it from raw rows this rig does not model).
[new AclScopeRef(NodeAclScopeKind.Tag, FlowTagId)] = [new NodeAclPath([NodeAclRealms.Uns, "Area1", "Line1", "Pump", "Flow"])],
[new AclScopeRef(NodeAclScopeKind.Tag, FlowTagId)] = [new NodeAclPath([NodeAclRealms.Uns, tagArea, "Line1", "Pump", "Flow"])],
};
NodeAclPath One(NodeAclScopeKind kind, string id) => resolver.ResolveOne(kind, id).ShouldHaveSingleItem();
@@ -535,6 +628,20 @@ public sealed class UnsFolderScopeWireTests
PermissionFlags = flags,
};
private static NodeAcl AnonymousGrant(NodeAclScopeKind kind, string scopeId) => new()
{
NodeAclId = $"anon-{scopeId}",
ClusterId = ServerEventRig.Cluster,
Principal = OpcUaPrincipals.Anonymous,
ScopeKind = kind,
ScopeId = scopeId,
PermissionFlags = NodePermissions.ReadOnly,
};
private static async Task RefreshAsync(ISession session, Subscription subscription, CancellationToken ct) =>
await session.CallAsync(
ObjectTypeIds.ConditionType, MethodIds.ConditionType_ConditionRefresh, ct, subscription.Id);
private static List<AlarmCommand> Route(ServerEventRig rig)
{
var routed = new List<AlarmCommand>();
@@ -312,4 +312,64 @@ public sealed class DeploymentArtifactScopePathTests
projection.UnsFolderScopes.Keys.ShouldBe(["UL-ok"]);
}
/// <summary>
/// Gitea #826 — the projection says which equipment each ALARM-BEARING raw tag is projected into, keyed on the
/// RawPath the same resolver builds (a native alarm's <c>ConditionId</c>), so the node manager can tell a native
/// alarm's still-referenced equipment folders from one whose reference the generation dropped. Plain value tags
/// are never looked up and are left out (review: memory).
/// </summary>
[Fact]
public void The_projection_carries_each_alarm_bearing_raw_tags_referencing_equipment_under_its_raw_path()
{
var projection = DeploymentArtifact.ParseDataPlaneAuthority(Encoding.UTF8.GetBytes(AlarmArtifact), NodeId);
const string hot = "Plant/Line1/ModbusDrv/dev1/Fast/Hot";
projection.TagReferencingEquipment.Keys.ShouldBe([hot], "the plain Speed tag is not alarm-bearing");
projection.TagReferencingEquipment[hot].Order(StringComparer.Ordinal).ShouldBe(["EQ-mixer", "EQ-oven"]);
var snapshot = new DataPlaneAuthorityState().Apply(
"c1", "rev-1", projection.Keys, projection.Grants, projection.ScopePaths, projection.EquipmentScopePaths,
projection.ScriptedAlarmOwners, projection.UnsFolderScopes, projection.TagReferencingEquipment);
snapshot.IsTagReferencedBy(hot, "EQ-oven").ShouldBeTrue();
snapshot.IsTagReferencedBy(hot, "eq-MIXER").ShouldBeTrue("equipment ids compare as identifiers");
snapshot.IsTagReferencedBy(hot, "EQ-other").ShouldBeFalse();
snapshot.IsTagReferencedBy("Plant/Line1/ModbusDrv/dev1/Fast/Speed", "EQ-mixer").ShouldBeFalse();
new DataPlaneAuthorityState().Apply("c1", "rev-1", [], [], projection.ScopePaths)
.IsTagReferencedBy(hot, "EQ-mixer").ShouldBeFalse("an absent map references nothing (fail closed)");
}
// The fixture's topology plus an alarm-bearing Hot tag referenced by two equipment; Speed stays a plain value.
private const string AlarmArtifact = """
{
"RawFolders": [
{"RawFolderId":"RF-plant","ClusterId":"c1","ParentRawFolderId":null,"Name":"Plant"},
{"RawFolderId":"RF-line1","ClusterId":"c1","ParentRawFolderId":"RF-plant","Name":"Line1"}
],
"DriverInstances": [
{"DriverInstanceId":"DI-modbus","ClusterId":"c1","RawFolderId":"RF-line1","Name":"ModbusDrv"}
],
"Devices": [{"DeviceId":"DV-1","DriverInstanceId":"DI-modbus","Name":"dev1"}],
"TagGroups": [{"TagGroupId":"TG-fast","DeviceId":"DV-1","ParentTagGroupId":null,"Name":"Fast"}],
"Tags": [
{"TagId":"TAG-speed","DeviceId":"DV-1","TagGroupId":"TG-fast","Name":"Speed"},
{"TagId":"TAG-hot","DeviceId":"DV-1","TagGroupId":"TG-fast","Name":"Hot",
"TagConfig":"{\"alarm\":{\"alarmType\":\"OffNormalAlarm\"}}"}
],
"UnsAreas": [{"UnsAreaId":"UA-w","ClusterId":"c1","Name":"West"}],
"UnsLines": [{"UnsLineId":"UL-1","UnsAreaId":"UA-w","Name":"L1"}],
"Equipment": [
{"EquipmentId":"EQ-mixer","UnsLineId":"UL-1","Name":"Mixer"},
{"EquipmentId":"EQ-oven","UnsLineId":"UL-1","Name":"Oven"}
],
"UnsTagReferences": [
{"UnsTagReferenceId":"REF-1","EquipmentId":"EQ-mixer","TagId":"TAG-speed"},
{"UnsTagReferenceId":"REF-2","EquipmentId":"EQ-mixer","TagId":"TAG-hot"},
{"UnsTagReferenceId":"REF-3","EquipmentId":"EQ-oven","TagId":"TAG-hot"}
],
"NodeAcls": [
{"NodeAclId":"acl-eq","ClusterId":"c1","Principal":"p","ScopeKind":4,"ScopeId":"EQ-mixer","PermissionFlags":16}
]
}
""";
}
@@ -0,0 +1,164 @@
using System.Text.Json;
using Akka.Actor;
using Akka.TestKit;
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Engines;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
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.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Heidenhain;
using ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests.Simulator;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
/// <summary>
/// lmxopcua#831 — a Heidenhain controller alarm reaches its Part 9 condition END TO END: the REAL
/// <see cref="HeidenhainDriver"/> against the in-process LSV2 simulator (replaying the captured iTNC 530 alarm
/// record), fed the raw tags exactly as the deployment artifact delivers them, raising into the REAL
/// <see cref="DriverHostActor"/>, whose projector must turn it into an Active and then an inactive condition at
/// the tag's RawPath (the FOCAS #647 lesson: a test that stops at the driver's event cannot see a routing miss).
/// </summary>
public sealed class HeidenhainNativeAlarmEndToEndTests : RuntimeActorTestBase
{
private static readonly NodeId TestNode = NodeId.Parse("heidenhain-alarm-e2e");
private static readonly RevisionHash Rev = RevisionHash.Parse(new string('a', 64));
private const string DriverId = "drv-hh";
private const string ExpectedRawPath = "Plant/Hh/m1/cnc_alarms";
/// <summary>Java fixture <c>hermle49.27</c>: class 7, group 4, number -1, "Run test of cutout channels".</summary>
private static readonly byte[] Golden =
Convert.FromHexString("00070004ffffffff52756e2074657374206f66206375746f7574206368616e6e656c7300");
[Fact]
public async Task A_controller_alarm_activates_then_clears_the_condition_at_the_RawPath()
{
var db = NewInMemoryDbFactory();
var blob = BuildArtifact();
var (host, publish) = SpawnHostAndApply(db, Seed(db, blob));
var rawTags = RawTagsFor(blob);
rawTags.Select(t => t.RawPath).ShouldBe([ExpectedRawPath]);
var control = new SimulatedControl();
var active = true;
control.Runtime[27] = () => active ? SimReply.Ok("S_RI", Golden) : SimReply.Refuse(57);
control.Runtime[28] = () => SimReply.Refuse(57);
await using var sim = Lsv2Simulator.WithControl(control);
await using var driver = new HeidenhainDriver(new HeidenhainDriverOptions
{
Devices = [new HeidenhainDeviceOptions { Host = "127.0.0.1", Port = sim.Port, DeviceName = "m1" }],
RawTags = rawTags,
TimeoutMs = 500,
Polling = new HeidenhainPollingOptions { AlarmMs = 100 },
}, DriverId);
driver.OnAlarmEvent += (_, e) => host.Tell(new DriverInstanceActor.AttributeAlarmPublished(DriverId, e));
await driver.InitializeAsync("{}", CancellationToken.None);
#pragma warning disable OTOPCUA0001 // routing under test, not resilience wrapping (the FOCAS e2e precedent)
await driver.SubscribeAlarmsAsync([.. rawTags.Select(t => t.RawPath)], CancellationToken.None);
#pragma warning restore OTOPCUA0001
var raised = publish.FishForMessage<OpcUaPublishActor.AlarmStateUpdate>(_ => true, TimeSpan.FromSeconds(5),
cancellationToken: TestContext.Current.CancellationToken);
raised.AlarmNodeId.ShouldBe(ExpectedRawPath);
raised.Realm.ShouldBe(AddressSpaceRealm.Raw);
raised.State.Active.ShouldBeTrue();
raised.State.Acknowledged.ShouldBeFalse();
raised.State.Severity.ShouldBe((ushort)800);
raised.State.Message.ShouldStartWith("-1 Run test of cutout channels");
active = false;
var cleared = publish.FishForMessage<OpcUaPublishActor.AlarmStateUpdate>(u => !u.State.Active, TimeSpan.FromSeconds(5),
cancellationToken: TestContext.Current.CancellationToken);
cleared.AlarmNodeId.ShouldBe(ExpectedRawPath);
control.Violations.ShouldBeEmpty();
sim.Requests.Select(r => r.Command).Distinct().ShouldBeSubsetOf(new[] { "A_LG", "R_VR", "R_RI" });
}
private static List<RawTagEntry> RawTagsFor(byte[] blob)
{
using var artifact = DeploymentArtifact.Open(blob);
var spec = artifact.ParseDriverInstances().Single(s => s.DriverInstanceId == DriverId);
using var doc = JsonDocument.Parse(spec.DriverConfig);
return JsonSerializer.Deserialize<List<RawTagEntry>>(
doc.RootElement.GetProperty("RawTags").GetRawText(),
new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;
}
private static byte[] BuildArtifact() => JsonSerializer.SerializeToUtf8Bytes(new
{
RawFolders = new[] { new { RawFolderId = "rf-plant", ParentRawFolderId = (string?)null, Name = "Plant", ClusterId = "c1" } },
DriverInstances = new[]
{
// Enabled=false: the host spawns no driver — the test drives its own instance against the simulator.
new { DriverInstanceId = DriverId, RawFolderId = "rf-plant", Name = "Hh", DriverType = "Heidenhain", DriverConfig = "{}", ClusterId = "c1", Enabled = false },
},
Devices = new[]
{
new { DeviceId = "dev-m1", DriverInstanceId = DriverId, Name = "m1", DeviceConfig = JsonSerializer.Serialize(new { Host = "127.0.0.1" }) },
},
TagGroups = Array.Empty<object>(),
Tags = new[]
{
new
{
TagId = "tag-alarms",
DeviceId = "dev-m1",
TagGroupId = (string?)null,
Name = "cnc_alarms",
DataType = "Boolean",
AccessLevel = 0,
TagConfig = JsonSerializer.Serialize(new
{
address = "ALARM:*",
dataType = "Boolean",
alarm = new { alarmType = "AlarmCondition", severity = 800 },
}),
},
},
});
private static DeploymentId Seed(IDbContextFactory<OtOpcUaConfigDbContext> db, byte[] blob)
{
var id = DeploymentId.NewId();
using var ctx = db.CreateDbContext();
ctx.Deployments.Add(new Deployment
{
DeploymentId = id.Value,
RevisionHash = Rev.Value,
Status = DeploymentStatus.Sealed,
CreatedBy = "test",
SealedAtUtc = DateTime.UtcNow,
ArtifactBlob = blob,
});
ctx.SaveChanges();
return id;
}
private (IActorRef Actor, TestProbe Publish) SpawnHostAndApply(IDbContextFactory<OtOpcUaConfigDbContext> db, DeploymentId deploymentId)
{
var coordinator = CreateTestProbe();
var publish = this.CreateCleanOutcomePublishProbe();
var actor = Sys.ActorOf(DriverHostActor.Props(
db, TestNode, coordinator.Ref,
localRoles: new HashSet<string> { "driver" },
dependencyMux: CreateTestProbe().Ref,
opcUaPublishActor: publish.Ref,
virtualTagEvaluator: NullVirtualTagEvaluator.Instance,
virtualTagHostOverride: CreateTestProbe().Ref));
actor.Tell(new DispatchDeployment(deploymentId, Rev, CorrelationId.NewId()));
coordinator.ExpectMsg<ApplyAck>(TimeSpan.FromSeconds(5)).Outcome.ShouldBe(ApplyAckOutcome.Applied);
publish.ExpectMsg<OpcUaPublishActor.RebuildAddressSpace>(TimeSpan.FromSeconds(5));
return (actor, publish);
}
}
@@ -667,12 +667,13 @@ public sealed class OpcUaPublishActorDeferredWriteTests : RuntimeActorTestBase
IReadOnlyDictionary<AclScopeRef, IReadOnlyList<NodeAclPath>> scopePaths,
IReadOnlyDictionary<string, NodeAclPath>? equipmentScopePaths = null,
IReadOnlyDictionary<string, string>? scriptedAlarmOwners = null,
IReadOnlyDictionary<string, UnsFolderScope>? unsFolderScopes = null)
IReadOnlyDictionary<string, UnsFolderScope>? unsFolderScopes = null,
IReadOnlyDictionary<string, IReadOnlySet<string>>? tagReferencingEquipment = null)
{
Interlocked.Increment(ref _applies);
return new DataPlaneAuthorityState().Apply(
clusterId, revision, keys, grants, scopePaths, equipmentScopePaths, scriptedAlarmOwners,
unsFolderScopes);
unsFolderScopes, tagReferencingEquipment);
}
}