Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/RealOpcUaDiscoveryBoundTests.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

86 lines
3.2 KiB
C#

using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.ScadaBridge.Commons.Types.DataConnections;
using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Adapters;
namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Adapters;
/// <summary>
/// Review 2026-10-21 02/P2: OPC UA endpoint discovery ran SYNCHRONOUSLY on a discovery client
/// built with the SDK's default configuration, so neither the connection's
/// <c>OperationTimeoutMs</c> nor the verify probe's budget bounded it — a black-holed endpoint held
/// the caller for the SDK's default operation timeout instead.
/// </summary>
public class RealOpcUaDiscoveryBoundTests
{
/// <summary>
/// A listener that accepts the TCP connection and then never speaks — the protocol-level
/// black hole. The verify probe must give up within (about) its own budget.
/// </summary>
[Fact]
public async Task Verify_AgainstABlackHoledEndpoint_ReturnsWithinItsBudget()
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var held = new List<TcpClient>();
using var stop = new CancellationTokenSource();
_ = Task.Run(async () =>
{
try
{
while (!stop.IsCancellationRequested)
held.Add(await listener.AcceptTcpClientAsync(stop.Token));
}
catch (OperationCanceledException) { }
catch (ObjectDisposedException) { }
});
try
{
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
var config = new OpcUaEndpointConfig
{
EndpointUrl = $"opc.tcp://127.0.0.1:{port}",
OperationTimeoutMs = 60_000,
};
var sw = Stopwatch.StartNew();
var verify = RealOpcUaClient.VerifyEndpointAsync(
config, new OpcUaGlobalOptions(), NullLogger.Instance, TimeSpan.FromSeconds(2), CancellationToken.None);
var result = await verify.WaitAsync(TimeSpan.FromSeconds(20));
sw.Stop();
Assert.False(result.Success);
Assert.True(sw.Elapsed < TimeSpan.FromSeconds(10), $"verify took {sw.Elapsed}");
}
finally
{
stop.Cancel();
listener.Stop();
foreach (var c in held) c.Dispose();
}
}
/// <summary>
/// Cancellation of discovery is never mistaken for "discovery unavailable": the unsecured
/// fallback endpoint is only for a genuine discovery failure, not for an abandoned attempt.
/// </summary>
[Fact]
public async Task CancelledDiscovery_IsNotTreatedAsADiscoveryFailure()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => RealOpcUaClient.DiscoverEndpointAsync(
"opc.tcp://test:4840", Opc.Ua.MessageSecurityMode.None,
async ct =>
{
await Task.Delay(Timeout.Infinite, ct);
return (IReadOnlyList<Opc.Ua.EndpointDescription>)[];
},
cts.Token));
}
}