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

199 lines
8.5 KiB
C#

using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Opc.Ua;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Adapters;
namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests;
/// <summary>
/// T17: Unit tests for <see cref="RealOpcUaClient.MapVerifyOutcome"/> — the pure
/// (exception + captured cert) → <see cref="VerifyEndpointResult"/> mapping that backs the
/// OPC UA verify-endpoint probe. These exercise every <see cref="VerifyFailureKind"/>
/// branch WITHOUT a live OPC UA server, so the classification logic is covered
/// deterministically.
/// </summary>
public class VerifyEndpointResultMappingTests
{
/// <summary>
/// Builds a throwaway self-signed certificate so the untrusted-cert branch can be
/// exercised with a real <see cref="X509Certificate2"/> (and real DER bytes) without a
/// live server. Not persisted; only its public fields are asserted.
/// </summary>
private static X509Certificate2 BuildSelfSignedCert(
string subjectName = "CN=ScadaBridge-Verify-Test")
{
using var rsa = RSA.Create(2048);
var request = new CertificateRequest(
subjectName, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
var notBefore = DateTimeOffset.UtcNow.AddMinutes(-5);
var notAfter = DateTimeOffset.UtcNow.AddDays(1);
return request.CreateSelfSigned(notBefore, notAfter);
}
/// <summary>Verifies that a captured certificate with a validation exception maps to an untrusted-certificate result.</summary>
[Fact]
public void CapturedCert_WithValidationException_MapsToUntrustedCertificate()
{
using var cert = BuildSelfSignedCert();
// A certificate-validation rejection surfaces as a ServiceResultException with
// BadCertificateUntrusted; the captured cert is what makes the kind authoritative.
var ex = new ServiceResultException(
StatusCodes.BadCertificateUntrusted, "Certificate is not trusted.");
var result = RealOpcUaClient.MapVerifyOutcome(ex, cert);
Assert.False(result.Success);
Assert.Equal(VerifyFailureKind.UntrustedCertificate, result.FailureKind);
Assert.NotNull(result.Cert);
Assert.Equal(cert.Thumbprint, result.Cert!.Thumbprint);
Assert.Equal(cert.Subject, result.Cert.Subject);
Assert.Equal(cert.Issuer, result.Cert.Issuer);
// The captured DER must round-trip to the original raw bytes verbatim.
Assert.Equal(Convert.ToBase64String(cert.RawData), result.Cert.DerBase64);
Assert.Equal(DateTimeKind.Utc, result.Cert.NotBeforeUtc.Kind);
Assert.Equal(DateTimeKind.Utc, result.Cert.NotAfterUtc.Kind);
Assert.NotNull(result.Error);
}
/// <summary>Verifies that a captured certificate without an exception still maps to an untrusted-certificate result.</summary>
[Fact]
public void CapturedCert_WithoutException_MapsToUntrustedCertificate()
{
// The validator may capture+reject the cert and the SDK then fail with a different
// (or no) exception. A captured cert ALWAYS dominates the classification.
using var cert = BuildSelfSignedCert();
var result = RealOpcUaClient.MapVerifyOutcome(null, cert);
Assert.False(result.Success);
Assert.Equal(VerifyFailureKind.UntrustedCertificate, result.FailureKind);
Assert.NotNull(result.Cert);
Assert.Equal(cert.Thumbprint, result.Cert!.Thumbprint);
}
/// <summary>Verifies that a timeout exception maps to a timeout result.</summary>
[Fact]
public void TimeoutException_MapsToTimeout()
{
var result = RealOpcUaClient.MapVerifyOutcome(new TimeoutException("took too long"), null);
Assert.False(result.Success);
Assert.Equal(VerifyFailureKind.Timeout, result.FailureKind);
Assert.Null(result.Cert);
}
/// <summary>Verifies that an operation-canceled exception maps to a timeout result.</summary>
[Fact]
public void OperationCanceledException_MapsToTimeout()
{
var result = RealOpcUaClient.MapVerifyOutcome(new OperationCanceledException(), null);
Assert.False(result.Success);
Assert.Equal(VerifyFailureKind.Timeout, result.FailureKind);
Assert.Null(result.Cert);
}
/// <summary>Verifies that a ServiceResultException with a bad-request timeout code maps to a timeout result.</summary>
[Fact]
public void ServiceResultException_BadRequestTimeout_MapsToTimeout()
{
var ex = new ServiceResultException(StatusCodes.BadRequestTimeout, "request timed out");
var result = RealOpcUaClient.MapVerifyOutcome(ex, null);
Assert.False(result.Success);
Assert.Equal(VerifyFailureKind.Timeout, result.FailureKind);
}
/// <summary>Verifies that ServiceResultException authentication status codes map to an auth-failed result.</summary>
/// <param name="statusCode">The status code.</param>
[Theory]
[InlineData(nameof(StatusCodes.BadUserAccessDenied))]
[InlineData(nameof(StatusCodes.BadIdentityTokenRejected))]
[InlineData(nameof(StatusCodes.BadIdentityTokenInvalid))]
public void ServiceResultException_AuthCodes_MapToAuthFailed(string statusCode)
{
var ex = new ServiceResultException(Status(statusCode), "access denied");
var result = RealOpcUaClient.MapVerifyOutcome(ex, null);
Assert.False(result.Success);
Assert.Equal(VerifyFailureKind.AuthFailed, result.FailureKind);
Assert.Null(result.Cert);
}
/// <summary>Verifies that ServiceResultException connection status codes map to an unreachable result.</summary>
/// <param name="statusCode">The status code.</param>
[Theory]
[InlineData(nameof(StatusCodes.BadConnectionRejected))]
[InlineData(nameof(StatusCodes.BadNotConnected))]
public void ServiceResultException_ConnectionCodes_MapToUnreachable(string statusCode)
{
var ex = new ServiceResultException(Status(statusCode), "no route");
var result = RealOpcUaClient.MapVerifyOutcome(ex, null);
Assert.False(result.Success);
Assert.Equal(VerifyFailureKind.Unreachable, result.FailureKind);
}
// SDK 2 (ScadaBridge#125): StatusCodes members are StatusCode structs, not constants, so the
// theories name them and resolve the value here.
private static StatusCode Status(string name) =>
(StatusCode)typeof(StatusCodes).GetField(name)!.GetValue(null)!;
/// <summary>Verifies that a socket exception maps to an unreachable result.</summary>
[Fact]
public void SocketException_MapsToUnreachable()
{
var ex = new System.Net.Sockets.SocketException(
(int)System.Net.Sockets.SocketError.ConnectionRefused);
var result = RealOpcUaClient.MapVerifyOutcome(ex, null);
Assert.False(result.Success);
Assert.Equal(VerifyFailureKind.Unreachable, result.FailureKind);
}
/// <summary>Verifies that a socket exception wrapped in a ServiceResultException maps to an unreachable result.</summary>
[Fact]
public void SocketExceptionWrappedInServiceResult_MapsToUnreachable()
{
// The SDK surfaces a refused/DNS connect as a generic ServiceResultException whose
// inner exception is the socket failure; the inner socket cause must dominate.
var inner = new System.Net.Sockets.SocketException(
(int)System.Net.Sockets.SocketError.HostNotFound);
var ex = new ServiceResultException(StatusCodes.BadUnexpectedError, "connect failed", inner);
var result = RealOpcUaClient.MapVerifyOutcome(ex, null);
Assert.False(result.Success);
Assert.Equal(VerifyFailureKind.Unreachable, result.FailureKind);
}
/// <summary>Verifies that a generic exception maps to a server-error result.</summary>
[Fact]
public void GenericException_MapsToServerError()
{
var result = RealOpcUaClient.MapVerifyOutcome(new InvalidOperationException("boom"), null);
Assert.False(result.Success);
Assert.Equal(VerifyFailureKind.ServerError, result.FailureKind);
Assert.Null(result.Cert);
Assert.NotNull(result.Error);
}
/// <summary>Verifies that a null exception with no captured certificate maps to a success result.</summary>
[Fact]
public void NullException_NullCert_MapsToSuccess()
{
var result = RealOpcUaClient.MapVerifyOutcome(null, null);
Assert.True(result.Success);
Assert.Null(result.FailureKind);
Assert.Null(result.Error);
Assert.Null(result.Cert);
}
}