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
This commit is contained in:
+71
-10
@@ -3,7 +3,9 @@ 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;
|
||||
|
||||
@@ -35,7 +37,22 @@ internal sealed class SecureOpcUaTestServer : IAsyncDisposable
|
||||
/// <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 async Task<SecureOpcUaTestServer> StartAsync(params X509Certificate2[] trustedClients)
|
||||
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();
|
||||
@@ -47,7 +64,8 @@ internal sealed class SecureOpcUaTestServer : IAsyncDisposable
|
||||
foreach (var c in trustedClients)
|
||||
await File.WriteAllBytesAsync(Path.Combine(trustedCerts, $"{c.Thumbprint}.der"), c.RawData);
|
||||
|
||||
var config = new ApplicationConfiguration
|
||||
var telemetry = DefaultTelemetry.Create(_ => { });
|
||||
var config = new ApplicationConfiguration(telemetry)
|
||||
{
|
||||
ApplicationName = "SB121TestServer",
|
||||
ApplicationUri = $"urn:localhost:SB121TestServer:{port}",
|
||||
@@ -70,30 +88,35 @@ internal sealed class SecureOpcUaTestServer : IAsyncDisposable
|
||||
TransportQuotas = new TransportQuotas { OperationTimeout = 15_000 },
|
||||
ServerConfiguration = new ServerConfiguration
|
||||
{
|
||||
BaseAddresses = { url },
|
||||
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 = { new UserTokenPolicy(UserTokenType.Anonymous) },
|
||||
],
|
||||
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 telemetry = DefaultTelemetry.Create(_ => { });
|
||||
var app = new ApplicationInstance(config, telemetry)
|
||||
{
|
||||
ApplicationName = config.ApplicationName,
|
||||
ApplicationType = ApplicationType.Server,
|
||||
};
|
||||
await app.CheckApplicationInstanceCertificatesAsync(silent: true, lifeTimeInMonths: 12);
|
||||
await app.StartAsync(new StandardServer());
|
||||
await app.StartAsync(new TestServer(telemetry, apiKey));
|
||||
|
||||
var cert = X509CertificateLoader.LoadCertificate(
|
||||
config.SecurityConfiguration.ApplicationCertificate.Certificate.RawData);
|
||||
// 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);
|
||||
}
|
||||
|
||||
@@ -105,6 +128,44 @@ internal sealed class SecureOpcUaTestServer : IAsyncDisposable
|
||||
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);
|
||||
|
||||
Reference in New Issue
Block a user