Files
Marc SchierandCopilot 1f6700c30b Fail closed when reconnect cannot preserve endpoint security (#4809)
# Description

It was reported that endpoint refresh during reconnect
(`UpdateBeforeConnect` / reconnect endpoint update) could silently
change a connection's security configuration (e.g. from `SignAndEncrypt`
to a different mode/policy) without the application knowing.

Investigation showed the hard downgrade paths had already been fixed,
but the legacy `SessionReconnectHandler` still had a composite-score
fallback that could select a *different* security mode/policy when the
original combination was no longer offered by the (unauthenticated)
discovery reply. A stronger mode could offset a weaker or deprecated
policy in that score. Managed failover/alternate-network endpoints also
had no explicit mode/policy guard.

Changes:
- **`SessionReconnectHandler`**: removed `SelectFallbackEndpoint` and
the alternate-policy fallback. If the exact mode/policy is unavailable,
reconnect fails (logged as an error) instead of changing security.
- **`ManagedSession`**: added a mode/policy mismatch check; mismatched
alternate-network endpoints, reactivation targets and
failover/recreation targets are rejected with `BadSecurityModeRejected`
/ `BadSecurityPolicyRejected` before a channel is opened.
- Endpoint refresh for **certificate rotation is retained**; new server
certificates are still subject to normal trust validation.
- **Docs** (`docs/Sessions.md`): documents exact mode/policy
preservation during recovery and that `UpdateBeforeConnect` does not
authorize security negotiation. Changing policy requires explicit
reconfiguration and a new connection.
- **Tests**: replaced fallback-selection tests with a fail-closed legacy
reconnect test; added managed alternate-endpoint policy mismatch and
failover mode mismatch tests.

Validation:
- `dotnet test tests/Opc.Ua.Client.Tests/Opc.Ua.Client.Tests.csproj -f
net10.0 --filter
"FullyQualifiedName~SessionReconnectHandlerTests|FullyQualifiedName~ManagedSessionTests"`
— passed (48/48)
- `dotnet test tests/Opc.Ua.Core.Tests/Opc.Ua.Core.Tests.csproj -f
net10.0 --filter "FullyQualifiedName~ConfiguredEndpointTests"` — passed
(46/46)
- Full UA.slnx suite and net48 tests: not run locally.

## Related Issues

- Reported security concern: reconnect endpoint refresh could change the
session's security configuration without notifying the application.

## Checklist

- [ ] I have signed the
[CLA](https://opcfoundation.org/license/cla/ContributorLicenseAgreementv1.0.pdf)
and read the
[CONTRIBUTING](https://github.com/OPCFoundation/UA-.NETStandard/blob/master/CONTRIBUTING.md)
doc.
- [x] I have added tests that prove my fix is effective or that my
feature works and increased code coverage.
- [x] I have added all necessary documentation.
- [x] I have verified that my changes do not introduce (new) build or
analyzer warnings.
- [ ] I ran **all** tests locally using the **UA.slnx** solution against
at least .net **framework** and .net **10**, and all passed.
- [ ] I fixed **all** failing and flaky tests in the CI pipelines and
**all** CodeQL warnings.
- [ ] I have addressed **all** PR feedback received.

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-15 20:33:35 +02:00

441 lines
18 KiB
C#

/* ========================================================================
* Copyright (c) 2005-2025 The OPC Foundation, Inc. All rights reserved.
*
* OPC Foundation MIT License 1.00
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* The complete license agreement can be found here:
* http://opcfoundation.org/License/MIT/1.00/
* ======================================================================*/
using System;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using Opc.Ua.Tests;
namespace Opc.Ua.Client.Tests
{
/// <summary>
/// Unit tests for SessionReconnectHandler, focusing on endpoint refresh behavior
/// when the server's endpoint configuration changes.
/// </summary>
[TestFixture]
[Category("Client")]
[Category("SessionReconnectHandler")]
[SetCulture("en-us")]
[SetUICulture("en-us")]
public sealed class SessionReconnectHandlerTests
{
private ITelemetryContext m_telemetry;
[SetUp]
public void SetUp()
{
m_telemetry = NUnitTelemetryContext.Create();
}
/// <summary>
/// Verifies that the reconnect handler calls UpdateEndpointFromServerAsync
/// when m_updateFromServer is set and session recreation succeeds.
/// </summary>
[Test]
public async Task DoReconnectAsync_WhenUpdateFromServerIsSet_CallsUpdateEndpointFromServerAsync()
{
// Arrange
int updateCallCount = 0;
var mockNewSession = new Mock<ISession>();
var mockFactory = new Mock<ISessionFactory>();
ConfiguredEndpoint configuredEndpoint = CreateConfiguredEndpoint(
MessageSecurityMode.SignAndEncrypt,
SecurityPolicies.Basic256Sha256);
Mock<ISession> mockSession = CreateMockSession(configuredEndpoint, mockFactory);
mockFactory.Setup(f => f.RecreateAsync(mockSession.Object, It.IsAny<CancellationToken>()))
.ReturnsAsync(mockNewSession.Object);
using var handler = new TestableSessionReconnectHandler(
m_telemetry,
(endpoint, connection) =>
{
updateCallCount++;
return Task.CompletedTask;
});
SetSessionHandlerField(handler, "m_reconnectFailed", true);
SetSessionHandlerField(handler, "m_updateFromServer", true);
SetHandlerSession(handler, mockSession.Object);
// Act
bool result = await InvokeDoReconnectAsync(handler).ConfigureAwait(false);
// Assert
Assert.That(result, Is.True);
Assert.That(updateCallCount, Is.EqualTo(1));
Assert.That(handler.Session, Is.SameAs(mockNewSession.Object));
}
/// <summary>
/// Verifies that DoReconnectAsync does not call UpdateEndpointFromServerAsync
/// when m_updateFromServer is false.
/// </summary>
[Test]
public async Task DoReconnectAsync_WhenUpdateFromServerIsFalse_SkipsEndpointUpdate()
{
// Arrange
int updateCallCount = 0;
var mockNewSession = new Mock<ISession>();
var mockFactory = new Mock<ISessionFactory>();
ConfiguredEndpoint configuredEndpoint = CreateConfiguredEndpoint(
MessageSecurityMode.None,
SecurityPolicies.None);
Mock<ISession> mockSession = CreateMockSession(configuredEndpoint, mockFactory);
mockFactory.Setup(f => f.RecreateAsync(mockSession.Object, It.IsAny<CancellationToken>()))
.ReturnsAsync(mockNewSession.Object);
using var handler = new TestableSessionReconnectHandler(
m_telemetry,
(endpoint, connection) =>
{
updateCallCount++;
return Task.CompletedTask;
});
SetSessionHandlerField(handler, "m_reconnectFailed", true);
SetSessionHandlerField(handler, "m_updateFromServer", false);
SetHandlerSession(handler, mockSession.Object);
// Act
bool result = await InvokeDoReconnectAsync(handler).ConfigureAwait(false);
// Assert
Assert.That(result, Is.True);
Assert.That(updateCallCount, Is.Zero);
}
/// <summary>
/// Verifies that when UpdateEndpointFromServerAsync fails with a ServiceResultException,
/// the session recreation is skipped, m_updateFromServer is set for the next attempt,
/// and false is returned.
/// </summary>
[Test]
public async Task DoReconnectAsync_WhenUpdateEndpointFails_SetsUpdateFromServerAndReturnsFalse()
{
// Arrange
var mockFactory = new Mock<ISessionFactory>();
ConfiguredEndpoint configuredEndpoint = CreateConfiguredEndpoint(
MessageSecurityMode.SignAndEncrypt,
SecurityPolicies.Aes256_Sha256_RsaPss);
Mock<ISession> mockSession = CreateMockSession(configuredEndpoint, mockFactory);
using var handler = new TestableSessionReconnectHandler(
m_telemetry,
(endpoint, connection) =>
throw new ServiceResultException(StatusCodes.BadNoCommunication));
SetSessionHandlerField(handler, "m_reconnectFailed", true);
SetSessionHandlerField(handler, "m_updateFromServer", true);
SetHandlerSession(handler, mockSession.Object);
// Act
bool result = await InvokeDoReconnectAsync(handler).ConfigureAwait(false);
// Assert
Assert.That(result, Is.False);
bool updateFromServer = GetSessionHandlerField<bool>(handler, "m_updateFromServer");
Assert.That(updateFromServer, Is.True);
}
/// <summary>
/// Verifies that UpdateEndpointFromServerAsync is a protected virtual method
/// that can be overridden to customize the endpoint update behavior.
/// </summary>
[Test]
public void UpdateEndpointFromServerAsync_IsProtectedVirtual()
{
MethodInfo method = typeof(SessionReconnectHandler).GetMethod(
"UpdateEndpointFromServerAsync",
BindingFlags.NonPublic | BindingFlags.Instance)!;
Assert.That(method, Is.Not.Null);
Assert.That(method.IsVirtual, Is.True);
Assert.That(method.IsFamily, Is.True); // protected
}
/// <summary>
/// Verifies that UpdateEndpointFromServerAsync accepts a ConfiguredEndpoint
/// and a nullable ITransportWaitingConnection parameter (for reverse connect support).
/// </summary>
[Test]
public void UpdateEndpointFromServerAsync_HasCorrectSignature()
{
MethodInfo method = typeof(SessionReconnectHandler).GetMethod(
"UpdateEndpointFromServerAsync",
BindingFlags.NonPublic | BindingFlags.Instance)!;
Assert.That(method, Is.Not.Null);
ParameterInfo[] parameters = method.GetParameters();
Assert.That(parameters, Has.Length.EqualTo(2));
Assert.That(parameters[0].ParameterType, Is.EqualTo(typeof(ConfiguredEndpoint)));
Assert.That(parameters[1].ParameterType, Is.EqualTo(typeof(ITransportWaitingConnection)));
}
/// <summary>
/// Verifies that <see cref="SessionReconnectHandler.BeginReconnect(ISession,int,EventHandler)"/>
/// throws <see cref="NotSupportedException"/> when given an
/// <see cref="ISession"/> that is not a <see cref="Session"/>
/// (or a derived type). The handler drives
/// <see cref="ISessionFactory.RecreateAsync(ISession,CancellationToken)"/>
/// and the underlying transport channel directly, which only
/// makes sense for the legacy <see cref="Session"/> class.
/// Facade implementations (e.g. <see cref="ManagedSession"/>)
/// run their own reconnect state machine and must not be
/// passed in.
/// </summary>
[Test]
public void BeginReconnect_WithNonSessionImplementation_ThrowsNotSupportedException()
{
var mockSession = new Mock<ISession>();
mockSession.SetupGet(s => s.SessionId).Returns(NodeId.Null);
using var handler = new SessionReconnectHandler(m_telemetry);
Assert.That(
() => handler.BeginReconnect(
mockSession.Object,
1000,
(_, _) => { }),
Throws.TypeOf<NotSupportedException>());
}
/// <summary>
/// Verifies that the reverse-connect overload also rejects
/// non-<see cref="Session"/> implementations of
/// <see cref="ISession"/> with <see cref="NotSupportedException"/>.
/// </summary>
[Test]
public void BeginReconnect_ReverseConnect_WithNonSessionImplementation_ThrowsNotSupportedException()
{
var mockSession = new Mock<ISession>();
mockSession.SetupGet(s => s.SessionId).Returns(NodeId.Null);
using var handler = new SessionReconnectHandler(m_telemetry);
Assert.That(
() => handler.BeginReconnect(
mockSession.Object,
null,
1000,
(_, _) => { }),
Throws.TypeOf<NotSupportedException>());
}
/// <summary>
/// Verifies that passing <see langword="null"/> as the session
/// remains supported as a cancellation signal and does not
/// trigger the type check.
/// </summary>
[Test]
public void BeginReconnect_WithNullSession_DoesNotThrowAndStaysReady()
{
using var handler = new SessionReconnectHandler(m_telemetry);
SessionReconnectHandler.ReconnectState state = handler.BeginReconnect(
null!,
1000,
(_, _) => { });
Assert.That(state, Is.EqualTo(SessionReconnectHandler.ReconnectState.Ready));
}
/// <summary>
/// Verifies that a failed exact-security endpoint refresh prevents
/// recreation under a different security configuration.
/// </summary>
[Test]
public async Task DoReconnectAsync_WhenEndpointSecurityConfigurationIsUnavailable_DoesNotRecreateSession()
{
// Arrange
var mockFactory = new Mock<ISessionFactory>();
ConfiguredEndpoint configuredEndpoint = CreateConfiguredEndpoint(
MessageSecurityMode.SignAndEncrypt,
SecurityPolicies.Basic256Sha256);
Mock<ISession> mockSession = CreateMockSession(configuredEndpoint, mockFactory);
var discoveredEndpoint = new EndpointDescription
{
SecurityMode = MessageSecurityMode.SignAndEncrypt,
SecurityPolicyUri = SecurityPolicies.Aes256_Sha256_RsaPss
};
using var handler = new ControlledDiscoverySessionReconnectHandler(
m_telemetry,
discoveredEndpoint);
SetSessionHandlerField(handler, "m_reconnectFailed", true);
SetSessionHandlerField(handler, "m_updateFromServer", true);
SetHandlerSession(handler, mockSession.Object);
// Act
bool result = await InvokeDoReconnectAsync(handler).ConfigureAwait(false);
// Assert
Assert.That(result, Is.False);
Assert.That(handler.Session, Is.SameAs(mockSession.Object));
Assert.That(configuredEndpoint.Description.SecurityMode, Is.EqualTo(MessageSecurityMode.SignAndEncrypt));
Assert.That(
configuredEndpoint.Description.SecurityPolicyUri,
Is.EqualTo(SecurityPolicies.Basic256Sha256));
mockFactory.Verify(
factory => factory.RecreateAsync(
mockSession.Object,
It.IsAny<CancellationToken>()),
Times.Never);
}
private static ConfiguredEndpoint CreateConfiguredEndpoint(
MessageSecurityMode securityMode,
string securityPolicyUri)
{
return new ConfiguredEndpoint(null!, new EndpointDescription
{
EndpointUrl = "opc.tcp://localhost:4840",
SecurityMode = securityMode,
SecurityPolicyUri = securityPolicyUri
});
}
private static Mock<ISession> CreateMockSession(
ConfiguredEndpoint configuredEndpoint,
Mock<ISessionFactory> mockFactory)
{
var mockSession = new Mock<ISession>();
mockSession.SetupGet(s => s.ConfiguredEndpoint).Returns(configuredEndpoint);
mockSession.SetupGet(s => s.SessionFactory).Returns(mockFactory.Object);
mockSession.SetupGet(s => s.SessionId).Returns(NodeId.Null);
return mockSession;
}
private static Task<bool> InvokeDoReconnectAsync(SessionReconnectHandler handler)
{
MethodInfo method = typeof(SessionReconnectHandler)
.GetMethod("DoReconnectAsync", BindingFlags.NonPublic | BindingFlags.Instance)
?? throw new InvalidOperationException("DoReconnectAsync method not found");
return (Task<bool>)method.Invoke(handler, null)!;
}
private static void SetSessionHandlerField(
SessionReconnectHandler handler,
string fieldName,
object value)
{
FieldInfo field = typeof(SessionReconnectHandler)
.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance)
?? throw new InvalidOperationException($"Field {fieldName} not found");
field.SetValue(handler, value);
}
private static void SetHandlerSession(SessionReconnectHandler handler, ISession session)
{
PropertyInfo prop = typeof(SessionReconnectHandler)
.GetProperty("Session", BindingFlags.Public | BindingFlags.Instance)
?? throw new InvalidOperationException("Session property not found");
MethodInfo setter = prop.GetSetMethod(nonPublic: true)
?? throw new InvalidOperationException("Session property setter not found");
setter.Invoke(handler, [session]);
}
private static T GetSessionHandlerField<T>(SessionReconnectHandler handler, string fieldName)
{
FieldInfo field = typeof(SessionReconnectHandler)
.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance)
?? throw new InvalidOperationException($"Field {fieldName} not found");
return (T)field.GetValue(handler)!;
}
/// <summary>
/// A testable subclass of SessionReconnectHandler that replaces the
/// UpdateEndpointFromServerAsync with a user-supplied delegate, enabling
/// unit tests to control the behavior without requiring network access.
/// </summary>
private sealed class TestableSessionReconnectHandler : SessionReconnectHandler
{
private readonly Func<ConfiguredEndpoint, ITransportWaitingConnection, Task> _updateDelegate;
public TestableSessionReconnectHandler(
ITelemetryContext telemetry,
Func<ConfiguredEndpoint, ITransportWaitingConnection, Task> updateDelegate)
: base(telemetry)
{
_updateDelegate = updateDelegate;
}
protected override Task UpdateEndpointFromServerAsync(
ConfiguredEndpoint endpoint,
ITransportWaitingConnection? connection = null)
{
return _updateDelegate(endpoint, connection!);
}
}
private sealed class ControlledDiscoverySessionReconnectHandler : SessionReconnectHandler
{
private readonly EndpointDescription m_discoveredEndpoint;
public ControlledDiscoverySessionReconnectHandler(
ITelemetryContext telemetry,
EndpointDescription discoveredEndpoint)
: base(telemetry)
{
m_discoveredEndpoint = discoveredEndpoint;
}
internal override Task UpdateFromServerAsync(
ConfiguredEndpoint endpoint,
ITransportWaitingConnection? connection,
MessageSecurityMode securityMode,
string securityPolicyUri)
{
typeof(ConfiguredEndpoint)
.GetProperty(nameof(ConfiguredEndpoint.DiscoveryEndpoints))!
.SetValue(endpoint, new ArrayOf<EndpointDescription>(
new[] { m_discoveredEndpoint }.AsMemory()));
if (securityPolicyUri != m_discoveredEndpoint.SecurityPolicyUri)
{
throw new ServiceResultException(StatusCodes.BadSecurityPolicyRejected);
}
endpoint.Description.SecurityPolicyUri = securityPolicyUri;
return Task.CompletedTask;
}
}
}
}