Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests/Adapters/SecureOpcUaTestServer.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
8.4 KiB
C#

using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using Opc.Ua;
using Opc.Ua.Configuration;
using Opc.Ua.Identity;
using Opc.Ua.Server;
using Opc.Ua.Server.Hosting;
namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Adapters;
/// <summary>
/// An in-process OPC Foundation <see cref="StandardServer"/> exposing None, Sign and
/// SignAndEncrypt (Basic256Sha256) endpoints with STRICT client trust
/// (<c>AutoAcceptUntrustedCertificates = false</c>) and its own temp PKI — the Gitea #121
/// counterpart for real mutual-trust tests of <c>RealOpcUaClient</c>.
/// </summary>
internal sealed class SecureOpcUaTestServer : IAsyncDisposable
{
private readonly ApplicationInstance _app;
private readonly string _pkiRoot;
private SecureOpcUaTestServer(ApplicationInstance app, string pkiRoot, string url, X509Certificate2 certificate)
{
_app = app;
_pkiRoot = pkiRoot;
Url = url;
Certificate = certificate;
}
/// <summary>The endpoint URL (localhost, so the server certificate's domain matches).</summary>
public string Url { get; }
/// <summary>The server's application certificate (public part).</summary>
public X509Certificate2 Certificate { get; }
/// <summary>Starts a server that trusts exactly <paramref name="trustedClients"/>.</summary>
/// <param name="trustedClients">Client certificates the server's trusted peer store holds at start.</param>
/// <returns>The running server.</returns>
public static Task<SecureOpcUaTestServer> StartAsync(params X509Certificate2[] trustedClients) =>
StartCoreAsync(apiKey: null, trustedClients);
/// <summary>
/// Starts a server that also admits the UserName <c>apikey</c> with exactly
/// <paramref name="apiKey"/> as its password (ScadaBridge#125), and refuses any other password
/// with <c>BadIdentityTokenRejected</c> once it has decrypted the token. The UserName token
/// policy is Basic256Sha256, so the password is encrypted on every channel, None included.
/// </summary>
/// <param name="apiKey">The one password the server accepts.</param>
/// <param name="trustedClients">Client certificates the server's trusted peer store holds at start.</param>
/// <returns>The running server.</returns>
public static Task<SecureOpcUaTestServer> StartWithApiKeyAsync(string apiKey, params X509Certificate2[] trustedClients) =>
StartCoreAsync(apiKey, trustedClients);
private static async Task<SecureOpcUaTestServer> StartCoreAsync(string? apiKey, X509Certificate2[] trustedClients)
{
var pkiRoot = Path.Combine(Path.GetTempPath(), "sb121-server", Guid.NewGuid().ToString("N"));
var port = FreePort();
var url = $"opc.tcp://localhost:{port}/sb121";
// Trust is written BEFORE start, so no test depends on trust-list cache refresh timing.
var trustedCerts = Path.Combine(pkiRoot, "trusted", "certs");
Directory.CreateDirectory(trustedCerts);
foreach (var c in trustedClients)
await File.WriteAllBytesAsync(Path.Combine(trustedCerts, $"{c.Thumbprint}.der"), c.RawData);
var telemetry = DefaultTelemetry.Create(_ => { });
var config = new ApplicationConfiguration(telemetry)
{
ApplicationName = "SB121TestServer",
ApplicationUri = $"urn:localhost:SB121TestServer:{port}",
ApplicationType = ApplicationType.Server,
SecurityConfiguration = new SecurityConfiguration
{
ApplicationCertificate = new CertificateIdentifier
{
StoreType = CertificateStoreType.Directory,
StorePath = Path.Combine(pkiRoot, "own"),
SubjectName = "CN=SB121TestServer",
CertificateType = ObjectTypeIds.RsaSha256ApplicationCertificateType,
},
TrustedPeerCertificates = new CertificateTrustList { StorePath = Path.Combine(pkiRoot, "trusted") },
TrustedIssuerCertificates = new CertificateTrustList { StorePath = Path.Combine(pkiRoot, "issuers") },
RejectedCertificateStore = new CertificateTrustList { StorePath = Path.Combine(pkiRoot, "rejected") },
AutoAcceptUntrustedCertificates = false,
AddAppCertToTrustedStore = false,
},
TransportQuotas = new TransportQuotas { OperationTimeout = 15_000 },
ServerConfiguration = new ServerConfiguration
{
BaseAddresses = [url],
SecurityPolicies =
[
new ServerSecurityPolicy { SecurityMode = MessageSecurityMode.None, SecurityPolicyUri = SecurityPolicies.None },
new ServerSecurityPolicy { SecurityMode = MessageSecurityMode.Sign, SecurityPolicyUri = SecurityPolicies.Basic256Sha256 },
new ServerSecurityPolicy { SecurityMode = MessageSecurityMode.SignAndEncrypt, SecurityPolicyUri = SecurityPolicies.Basic256Sha256 },
],
UserTokenPolicies = apiKey is null
? [new UserTokenPolicy(UserTokenType.Anonymous)]
: [new UserTokenPolicy(UserTokenType.Anonymous),
new UserTokenPolicy(UserTokenType.UserName) { SecurityPolicyUri = SecurityPolicies.Basic256Sha256 }],
},
};
await config.ValidateAsync(ApplicationType.Server);
var app = new ApplicationInstance(config, telemetry)
{
ApplicationName = config.ApplicationName,
ApplicationType = ApplicationType.Server,
};
await app.CheckApplicationInstanceCertificatesAsync(silent: true, lifeTimeInMonths: 12);
await app.StartAsync(new TestServer(telemetry, apiKey));
// SDK 2: the loaded application certificate lives in the certificate manager, not on the identifier.
using var entry = config.CertificateManager.AcquireApplicationCertificateByType(
ObjectTypeIds.RsaSha256ApplicationCertificateType)
?? throw new InvalidOperationException("The test server has no application certificate.");
var cert = X509CertificateLoader.LoadCertificate(entry.Certificate.RawData);
return new SecureOpcUaTestServer(app, pkiRoot, url, cert);
}
/// <inheritdoc />
public async ValueTask DisposeAsync()
{
try { await _app.StopAsync(); } catch { /* best-effort */ }
Certificate.Dispose();
try { Directory.Delete(_pkiRoot, recursive: true); } catch { /* best-effort */ }
}
/// <summary>A <see cref="StandardServer"/> that registers the API-key authenticator before it starts.</summary>
private sealed class TestServer : StandardServer
{
public TestServer(ITelemetryContext telemetry, string? apiKey) : base(telemetry)
{
if (apiKey is not null)
AddPreStartupTask(new RegisterAuthenticator(new ApiKeyAuthenticator(apiKey)));
}
}
private sealed class RegisterAuthenticator(IUserTokenAuthenticator authenticator) : IServerPreStartupTask
{
public ValueTask OnServerStartingAsync(IServerContext server, CancellationToken cancellationToken = default)
{
((IServerInternal)server).IdentityRegistry.Register(authenticator);
return ValueTask.CompletedTask;
}
}
private sealed class ApiKeyAuthenticator(string apiKey) : IUserTokenAuthenticator
{
public UserTokenType TokenType => UserTokenType.UserName;
public string? IssuedTokenProfileUri => null;
public ValueTask<AuthenticationResult> AuthenticateAsync(AuthenticationContext context, CancellationToken ct = default)
{
if (context.TokenHandler is not UserNameIdentityTokenHandler userName)
return ValueTask.FromResult(AuthenticationResult.NotHandled);
var accepted = userName.UserName == "apikey"
&& userName.DecryptedPassword is { } password
&& System.Text.Encoding.UTF8.GetString(password) == apiKey;
return ValueTask.FromResult(accepted
? AuthenticationResult.Accept(new UserIdentity(userName))
: AuthenticationResult.Reject(new ServiceResult(StatusCodes.BadIdentityTokenRejected)));
}
}
private static int FreePort()
{
var l = new TcpListener(IPAddress.Loopback, 0);
l.Start();
var port = ((IPEndPoint)l.LocalEndpoint).Port;
l.Stop();
return port;
}
}