Files
lmxopcua/tests/Client/ZB.MOM.WW.OtOpcUa.Client.Shared.Tests/Fakes/FakeSessionFactory.cs
T
Joseph Doherty be28aa4432 fix(opcua-client): send UserName passwords in the legacy RSA format so 65-char API keys log in to SDK 1.5 servers (#880)
SDK 2.0.1's UserNameIdentityTokenHandler encrypts a password longer than 64 bytes
(a private RsaEncryptedSecretPasswordThreshold, no setting) as an RsaEncryptedSecret
with EncryptionAlgorithm=null. SDK 1.5.378 (.106 and .182) decrypts only the legacy
format under RSA policies; its SecurityPolicies.Decrypt answers a null algorithm with
BadIdentityTokenInvalid ("Unexpected encryption algorithm") before any key check.
Every production API key is 65 chars, so no SDK 2 OtOpcUa client could use one
against QA (b8b4c18f), a rollback target or an older third-party server.

LegacyRsaUserNameIdentityTokenHandler (Driver.OpcUaClient.Session, plugged in through
the public UserIdentity(IUserIdentityTokenHandler) ctor) always uses the legacy
format, RSA-OAEP(len|password|serverNonce) under the server certificate, under an RSA
policy. That is what SDK 2 sends for passwords of 64 bytes or less and what SDK 1.5
clients always send. The legacy format has no size limit (the plaintext is
length-framed over as many RSA blocks as it needs), and an SDK 2 server reads both
formats. Policy None, the ECC policies and a missing certificate go to the SDK
handler unchanged.

OpcUaUserIdentityFactory.UserName is now the one UserName identity the driver, the
AdminUI browse and Client.Shared (CLI/UI) present. Client.Shared references .Session
for it.

Tests: handler unit tests (all three RSA policies, the 1.5-required algorithm URI,
SDK 2 server-side decrypt, the session Copy() keeps the type, None unchanged, and an
SDK control pinning the 64/65-byte switch); a Client.Shared identity test; and an
SDK2<->SDK2 integration test where a 65-char key is admitted in both formats and a
wrong 65-char key reaches the key check (BadIdentityTokenRejected). The #800 Windows
gate's SDK 2 CLI 65-char case now gates against the 1.5 server too.

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

90 lines
4.1 KiB
C#

using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Client.Shared.Adapters;
namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Tests.Fakes;
internal sealed class FakeSessionFactory : ISessionFactory
{
private readonly List<FakeSessionAdapter> _createdSessions = [];
private readonly Queue<FakeSessionAdapter> _sessions = new();
/// <summary>Gets the number of times CreateSessionAsync has been called.</summary>
public int CreateCallCount { get; private set; }
/// <summary>Gets or sets a value indicating whether CreateSessionAsync should throw.</summary>
public bool ThrowOnCreate { get; set; }
/// <summary>Gets the endpoint URL from the last CreateSessionAsync call.</summary>
public string? LastEndpointUrl { get; private set; }
/// <summary>Gets the host-name-validation flag from the last CreateSessionAsync call (#816).</summary>
public bool? LastValidateServerHostName { get; private set; }
/// <summary>Gets the user identity from the last CreateSessionAsync call (#880).</summary>
public UserIdentity? LastIdentity { get; private set; }
/// <summary>
/// Optional gate that, when set, blocks <see cref="CreateSessionAsync" /> until completed.
/// Lets tests hold a failover loop in-flight to exercise re-entrancy.
/// </summary>
public TaskCompletionSource? CreateGate { get; set; }
/// <summary>Completed when a call observes <see cref="CreateGate" />.</summary>
public TaskCompletionSource CreateEntered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
/// <summary>Gets the list of sessions created via CreateSessionAsync.</summary>
public IReadOnlyList<FakeSessionAdapter> CreatedSessions => _createdSessions;
/// <summary>Creates a session asynchronously (fake implementation).</summary>
/// <param name="config">The application configuration.</param>
/// <param name="endpoint">The endpoint description.</param>
/// <param name="sessionName">The session name.</param>
/// <param name="sessionTimeoutMs">The session timeout in milliseconds.</param>
/// <param name="identity">The user identity.</param>
/// <param name="validateServerHostName">The SDK checkDomain flag (#816).</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>A task containing the session adapter.</returns>
public async Task<ISessionAdapter> CreateSessionAsync(
ApplicationConfiguration config, EndpointDescription endpoint, string sessionName,
uint sessionTimeoutMs, UserIdentity identity, bool validateServerHostName, CancellationToken ct)
{
CreateCallCount++;
LastEndpointUrl = endpoint.EndpointUrl ?? string.Empty;
LastValidateServerHostName = validateServerHostName;
LastIdentity = identity;
// One-shot: the gate holds only the call that observed it, so a later call (e.g. a user's Connect while a
// failover is held) runs freely.
if (CreateGate is { } gate)
{
CreateGate = null;
CreateEntered.TrySetResult();
await gate.Task;
}
if (ThrowOnCreate)
throw new InvalidOperationException("FakeSessionFactory configured to fail.");
FakeSessionAdapter session;
if (_sessions.Count > 0)
session = _sessions.Dequeue();
else
session = new FakeSessionAdapter
{
EndpointUrl = endpoint.EndpointUrl ?? string.Empty,
ServerName = endpoint.Server?.ApplicationName.Text ?? "FakeServer",
SecurityMode = endpoint.SecurityMode.ToString(),
SecurityPolicyUri = endpoint.SecurityPolicyUri ?? string.Empty
};
// Ensure endpoint URL matches
session.EndpointUrl = endpoint.EndpointUrl ?? string.Empty;
_createdSessions.Add(session);
return session;
}
/// <summary>
/// Enqueues a session adapter to be returned on the next call to CreateSessionAsync.
/// </summary>
/// <param name="session">The session adapter to enqueue.</param>
public void EnqueueSession(FakeSessionAdapter session)
{
_sessions.Enqueue(session);
}
}