Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/OpcUaNodeReferenceTests.cs
T
Joseph Doherty a2e9d71824 feat(dcl): move the OPC UA client to OPC Foundation SDK 2.0.1 (#125)
OPCFoundation.NetStandard.Opc.Ua.Client and the test-only .Server move
1.5.378.182 -> 2.0.1, the version OtOpcUa master runs (lmxopcua#782; #799
and #801 closed). Transitive Core/Core.Types/Types/Configuration/
Security.Certificates resolve to 2.0.1.

API breaks fixed in the DCL adapter:
- Built-in types are immutable structs (Variant, DataValue, NodeId,
  LocalizedText, StatusCode, ArrayOf<T>). New OpcUaValueBoundary restores
  the SDK 1.5 CLR shapes for every read, subscription and alarm-event
  value (byte[], UTC DateTime with no-timestamp = MinValue, Guid,
  detached arrays) and builds write variants with SDK 1.5's
  new Variant(object) semantics (byte[] = ByteString scalar).
- StatusCodes members are no longer constants: switches/patterns over
  them (verify-outcome mapping, connection-level classification,
  BadResourceUnavailable) match by value.
- CertificateIdentifier no longer caches a certificate and the
  CertificateValidator/CertificateValidation event is gone: the
  configuration's CertificateManager owns trust lists and the loaded
  application certificate and is disposed with the session; auto-accept
  and the verify probe's capture-and-reject use AcceptError.
- new UserIdentity(X509Certificate2) is gone: X509 user identities use
  X509IdentityTokenHandler with an on-demand PFX provider (still fails
  fast on a missing file/key).
- DefaultSessionFactory takes the telemetry context; collections are
  ArrayOf<T>; EventFilter select clauses and ContentFilter operands are
  built immutably.

UserName identity (lmxopcua#880): SDK 2's default handler sends a
password over 64 bytes - every 65-character OtOpcUa API key - as an
RsaEncryptedSecret that SDK 1.5 servers reject with BadIdentityTokenInvalid
and SDK 2 servers accept only within a 5-minute clock window (#873). The
DCL now always uses LegacyRsaUserNameIdentityTokenHandler (ported from
OtOpcUa be28aa44), i.e. exactly what it sent on SDK 1.5, so it logs in to
both server generations during a mixed rollout.

Tests: the in-process secured test server is ported to SDK 2 and can
admit an API key; new tests cover the handler (mutation-checked: 5 of 7
fail with the SDK default handler), the value boundary, and a 65-char key
end to end over None/Sign/SignAndEncrypt with a wrong key reaching the
key check (BadIdentityTokenRejected).

Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
2026-11-12 22:20:53 -05:00

178 lines
7.4 KiB
C#

using Opc.Ua;
using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Adapters;
namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Adapters;
/// <summary>
/// Stored bindings hard-code a namespace <i>index</i>, which is only
/// meaningful against one server's namespace table. These tests pin the durable
/// <c>nsu=&lt;uri&gt;</c> form and the back-compat of the existing <c>ns=</c> form.
/// </summary>
public class OpcUaNodeReferenceTests
{
// Mirrors an OtOpcUa v3 server: 0=UA (spec), 1=ApplicationUri, 2=raw, 3=uns.
private const string RawUri = "https://zb.com/otopcua/raw";
private const string UnsUri = "https://zb.com/otopcua/uns";
private static NamespaceTable V3Table()
{
var t = new NamespaceTable(); // index 0 = http://opcfoundation.org/UA/
t.Append("urn:localhost:OtOpcUa"); // 1
t.Append(RawUri); // 2
t.Append(UnsUri); // 3
return t;
}
// The v2 server: a single custom namespace, which also landed at index 2.
private static NamespaceTable V2Table()
{
var t = new NamespaceTable();
t.Append("urn:localhost:OtOpcUa"); // 1
t.Append("https://zb.com/otopcua/ns"); // 2
return t;
}
/// <summary>Verifies that the legacy namespace index form still resolves.</summary>
[Fact]
public void Resolve_IndexForm_StillWorks()
{
// Back-compat: every binding in the field today is this shape.
var nodeId = OpcUaNodeReference.Resolve("ns=2;s=pymodbus/plc/HR200", V3Table());
Assert.Equal(2, nodeId.NamespaceIndex);
Assert.Equal("pymodbus/plc/HR200", nodeId.IdentifierAsString);
}
/// <summary>Verifies that the namespace URI form resolves to the server's live namespace index.</summary>
[Fact]
public void Resolve_UriForm_MapsToLiveIndex()
{
var nodeId = OpcUaNodeReference.Resolve($"nsu={RawUri};s=pymodbus/plc/HR200", V3Table());
Assert.Equal(2, nodeId.NamespaceIndex);
Assert.Equal("pymodbus/plc/HR200", nodeId.IdentifierAsString);
}
/// <summary>Verifies that the namespace URI form tracks the index across servers with different namespace tables.</summary>
[Fact]
public void Resolve_UriForm_TracksIndexAcrossServers()
{
// The point of the durable form: same reference, a server that orders its
// namespaces differently, still the right namespace.
var reordered = new NamespaceTable();
reordered.Append("urn:localhost:OtOpcUa"); // 1
reordered.Append("urn:something:else"); // 2 <- pushed raw along
reordered.Append(RawUri); // 3
var v3 = OpcUaNodeReference.Resolve($"nsu={RawUri};s=Tag", V3Table());
var moved = OpcUaNodeReference.Resolve($"nsu={RawUri};s=Tag", reordered);
Assert.Equal(2, v3.NamespaceIndex);
Assert.Equal(3, moved.NamespaceIndex); // followed the URI, not the index
}
/// <summary>Verifies that the index form silently binds to a different namespace after a server upgrade.</summary>
[Fact]
public void Resolve_IndexForm_SilentlyBindsToTheWrongNamespace_AcrossServerUpgrade()
{
// This is the namespace-index hazard, pinned as a characterisation test rather than a wish:
// v2's sole custom namespace and v3's raw namespace BOTH sit at index 2, so a
// v2-era ns=2 binding resolves happily against v3 while meaning something else
// entirely. Nothing in the index form can detect that — which is the whole
// argument for re-authoring bindings in the nsu= form.
const string v2Binding = "ns=2;s=Line1/Pump/Speed";
var againstV2 = OpcUaNodeReference.Resolve(v2Binding, V2Table());
var againstV3 = OpcUaNodeReference.Resolve(v2Binding, V3Table());
Assert.Equal(againstV2.NamespaceIndex, againstV3.NamespaceIndex);
Assert.Equal("https://zb.com/otopcua/ns", V2Table().GetString(againstV2.NamespaceIndex));
Assert.Equal(RawUri, V3Table().GetString(againstV3.NamespaceIndex)); // different namespace, no error
// The durable form fails loudly instead.
var ex = Assert.Throws<ArgumentException>(
() => OpcUaNodeReference.Resolve($"nsu=https://zb.com/otopcua/ns;s=Line1/Pump/Speed", V3Table()));
Assert.Contains("does not publish", ex.Message);
}
/// <summary>Verifies that resolving an unknown namespace URI throws.</summary>
[Fact]
public void Resolve_UnknownNamespaceUri_Throws()
{
var ex = Assert.Throws<ArgumentException>(
() => OpcUaNodeReference.Resolve("nsu=https://example.invalid/nope;s=Tag", V3Table()));
Assert.Contains("NamespaceArray", ex.Message);
}
/// <summary>Verifies that resolving a reference to another server throws.</summary>
[Fact]
public void Resolve_ForeignServerReference_Throws()
{
var ex = Assert.Throws<ArgumentException>(
() => OpcUaNodeReference.Resolve($"svr=1;nsu={RawUri};s=Tag", V3Table()));
Assert.Contains("another server", ex.Message);
}
/// <summary>Verifies that an unparseable reference throws.</summary>
/// <param name="reference">The malformed node reference.</param>
[Theory]
[InlineData("")]
[InlineData(" ;;; not a node id")]
public void Resolve_Unparseable_Throws(string reference)
{
Assert.ThrowsAny<ArgumentException>(() => OpcUaNodeReference.Resolve(reference, V3Table()));
}
/// <summary>Verifies that a server namespace is converted to the durable URI form.</summary>
[Fact]
public void ToDurable_ServerNamespace_EmitsUriForm()
{
var browsed = new ExpandedNodeId("pymodbus/plc/HR200", 2, null, 0);
var durable = OpcUaNodeReference.ToDurable(browsed, V3Table());
Assert.Equal($"nsu={RawUri};s=pymodbus/plc/HR200", durable);
}
/// <summary>Verifies that the standard namespace stays in the short form.</summary>
[Fact]
public void ToDurable_StandardNamespace_StaysShort()
{
// ns=0 is spec-fixed; qualifying it would be noise.
var durable = OpcUaNodeReference.ToDurable(new ExpandedNodeId(85u, 0), V3Table());
Assert.Equal("i=85", durable);
}
/// <summary>Verifies that a durable reference round-trips through resolve.</summary>
[Fact]
public void ToDurable_RoundTripsThroughResolve()
{
// The bug this closes: browse emitted ExpandedNodeId.ToString(), which for a
// URI-carrying reference produced a string NodeId.Parse could not read back.
var table = V3Table();
var browsed = new ExpandedNodeId("Area/Line/Equip/Speed", 0, UnsUri, 0);
var durable = OpcUaNodeReference.ToDurable(browsed, table);
var resolved = OpcUaNodeReference.Resolve(durable, table);
Assert.Equal(3, resolved.NamespaceIndex);
Assert.Equal("Area/Line/Equip/Speed", resolved.IdentifierAsString);
}
/// <summary>Verifies that a URI missing from the namespace table falls back instead of throwing.</summary>
[Fact]
public void ToDurable_UriNotInTable_FallsBackRatherThanThrowing()
{
// Browsing is a discovery path — a namespace we cannot name should degrade to
// the raw string, not abort the browse.
var browsed = new ExpandedNodeId("Tag", 0, "https://example.invalid/nope", 0);
var durable = OpcUaNodeReference.ToDurable(browsed, V3Table());
Assert.Contains("Tag", durable);
}
}