Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion src/Opc.Ua.Client/CoreClientUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,8 @@ public static async ValueTask<IList<string>> DiscoverServersAsync(
/// With <paramref name="useSecurity"/> set, an endpoint without
/// message security is never returned, except an HTTPS endpoint with
/// SecurityMode None when the discovery URL is HTTPS (TLS protects it)
/// and no endpoint with message security matches.</returns>
/// and no endpoint with message security matches. An endpoint of the
/// OpenAPI mapping (REST) is never returned.</returns>
public static EndpointDescription? SelectEndpoint(
ApplicationConfiguration configuration,
Uri url,
Expand All @@ -311,6 +312,15 @@ public static async ValueTask<IList<string>> DiscoverServersAsync(
{
EndpointDescription endpoint = endpoints[ii];

// A Session cannot be created over the OpenAPI mapping (Part 6
// §G.3), a REST binding that shares the URL and the message
// security mode of the binary HTTPS endpoint. Select by
// TransportProfileUri (Part 4 §5.5.4) instead of by list order.
if (IsOpenApiEndpoint(endpoint))
{
continue;
}

// check for a match on the URL scheme.
if (endpoint.EndpointUrl != null &&
endpoint.EndpointUrl.StartsWith(url.Scheme, StringComparison.Ordinal))
Expand Down Expand Up @@ -383,6 +393,7 @@ public static async ValueTask<IList<string>> DiscoverServersAsync(
{
bool tlsDiscovery = IsHttpsScheme(url.Scheme);
selectedEndpoint = endpoints.Find(e =>
!IsOpenApiEndpoint(e) &&
e.EndpointUrl?.StartsWith(url.Scheme, StringComparison.Ordinal) == true &&
(!useSecurity ||
IsSecureMode(e.SecurityMode) ||
Expand All @@ -401,6 +412,16 @@ private static bool IsSecureMode(MessageSecurityMode mode)
return mode is MessageSecurityMode.Sign or MessageSecurityMode.SignAndEncrypt;
}

/// <summary>
/// Whether the endpoint uses the OpenAPI mapping (HTTPS or WSS)
/// rather than a transport a Session can be created over.
/// </summary>
private static bool IsOpenApiEndpoint(EndpointDescription endpoint)
{
return Profiles.IsHttpsOpenApi(endpoint.TransportProfileUri) ||
Profiles.IsWssOpenApi(endpoint.TransportProfileUri);
}

/// <summary>
/// Whether the URI scheme is carried over TLS (https or opc.https).
/// </summary>
Expand Down
36 changes: 35 additions & 1 deletion src/Opc.Ua.Client/Session/Session.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1577,7 +1577,7 @@ private async Task OpenCoreAsync(
lock (m_lock)
{
// save session id and cookie in base
base.SessionCreated(sessionId, sessionCookie);
SessionCreated(sessionId, sessionCookie);
}

m_logger.RevisedSessionTimeoutValueSessionTimeout(m_sessionTimeout, SessionId);
Expand Down Expand Up @@ -4775,6 +4775,39 @@ private async ValueTask StartKeepAliveTimerAsync()
}
}

/// <inheritdoc/>
public override void SessionCreated(NodeId sessionId, NodeId sessionCookie)
{
base.SessionCreated(sessionId, sessionCookie);
if (!sessionCookie.IsNull)
{
m_hadSession = true;
}
}

/// <inheritdoc/>
/// <remarks>
/// A request with a null authenticationToken is a session-less
/// invocation (OPC 10000-4 §6.3.1). Once this Session has been
/// created, a request without token is not sent: after the Session
/// was closed, it fails locally with Bad_SessionIdInvalid instead of
/// reaching the Server as a session-less invocation. CreateSession
/// and ActivateSession are not affected.
/// </remarks>
protected override void UpdateRequestHeader(IServiceRequest request, bool useDefaults)
{
base.UpdateRequestHeader(request, useDefaults);

if (m_hadSession &&
request.RequestHeader.AuthenticationToken.IsNull &&
request is not (CreateSessionRequest or ActivateSessionRequest))
{
throw ServiceResultException.Create(
StatusCodes.BadSessionIdInvalid,
"The Session has been closed.");
}
}

/// <inheritdoc/>
protected override void RequestCompleted(
IServiceRequest request,
Expand Down Expand Up @@ -6755,6 +6788,7 @@ public BackgroundWorkScope(Session owner)
/// </summary>
protected int m_keepAliveGuardBand = 1000;

private volatile bool m_hadSession;
private readonly Lock m_lock = new();
private readonly List<Subscription> m_subscriptions = [];
private uint m_maxRequestMessageSize;
Expand Down
143 changes: 143 additions & 0 deletions tests/Opc.Ua.Client.Tests/CoreClientUtilsSelectEndpointTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
/* ========================================================================
* 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 NUnit.Framework;
using Opc.Ua.Tests;

namespace Opc.Ua.Client.Tests
{
/// <summary>
/// <c>CoreClientUtils.SelectEndpoint</c> selects by TransportProfileUri
/// (OPC 10000-4 §5.5.4) and never returns an endpoint of the OpenAPI
/// mapping (OPC 10000-6 §G.3), whatever the order of the endpoints
/// returned by GetEndpoints.
/// </summary>
[TestFixture]
[Category("Client")]
[SetCulture("en-us")]
[SetUICulture("en-us")]
public sealed class CoreClientUtilsSelectEndpointTests
{
private static readonly Uri s_httpsUrl = new("https://localhost:4843/");
private static readonly Uri s_wssUrl = new("opc.wss://localhost:4843/");

[Test]
public void SelectEndpointSkipsTheOpenApiEndpointListedFirst()
{
EndpointDescription openApi = CreateEndpoint(s_httpsUrl, Profiles.HttpsOpenApiTransport);
EndpointDescription binary = CreateEndpoint(s_httpsUrl, Profiles.HttpsBinaryTransport);

EndpointDescription? selected = CoreClientUtils.SelectEndpoint(
null!,
s_httpsUrl,
[openApi, binary],
useSecurity: false,
NUnitTelemetryContext.Create());

Assert.That(selected, Is.SameAs(binary));
}

[Test]
public void SelectEndpointWithSecurityFallbackSkipsTheOpenApiEndpoint()
{
// No endpoint signs, so the HTTPS fallback for useSecurity applies.
EndpointDescription openApi = CreateEndpoint(s_httpsUrl, Profiles.HttpsOpenApiTransport);
EndpointDescription binary = CreateEndpoint(s_httpsUrl, Profiles.HttpsBinaryTransport);

EndpointDescription? selected = CoreClientUtils.SelectEndpoint(
null!,
s_httpsUrl,
[openApi, binary],
useSecurity: true,
NUnitTelemetryContext.Create());

Assert.That(selected, Is.SameAs(binary));
}

[Test]
public void SelectEndpointSkipsTheWssOpenApiEndpoint()
{
EndpointDescription openApi = CreateEndpoint(s_wssUrl, Profiles.WssOpenApiTransport);
EndpointDescription binary = CreateEndpoint(s_wssUrl, Profiles.UaWssTransport);

EndpointDescription? selected = CoreClientUtils.SelectEndpoint(
null!,
s_wssUrl,
[openApi, binary],
useSecurity: false,
NUnitTelemetryContext.Create());

Assert.That(selected, Is.SameAs(binary));
}

[TestCase(false)]
[TestCase(true)]
public void SelectEndpointReturnsNullWhenOnlyOpenApiEndpointsMatch(bool useSecurity)
{
EndpointDescription? selected = CoreClientUtils.SelectEndpoint(
null!,
s_httpsUrl,
[CreateEndpoint(s_httpsUrl, Profiles.HttpsOpenApiTransport)],
useSecurity,
NUnitTelemetryContext.Create());

Assert.That(selected, Is.Null);
}

[Test]
public void SelectEndpointKeepsTheFirstBinaryEndpointWithoutTransportProfile()
{
// Endpoints without TransportProfileUri are still selected by URL
// scheme and mode, as before.
EndpointDescription first = CreateEndpoint(s_httpsUrl, null);
EndpointDescription second = CreateEndpoint(s_httpsUrl, Profiles.HttpsBinaryTransport);

EndpointDescription? selected = CoreClientUtils.SelectEndpoint(
null!,
s_httpsUrl,
[first, second],
useSecurity: false,
NUnitTelemetryContext.Create());

Assert.That(selected, Is.SameAs(first));
}

private static EndpointDescription CreateEndpoint(Uri url, string? transportProfileUri)
{
return new EndpointDescription
{
EndpointUrl = url.ToString(),
SecurityMode = MessageSecurityMode.None,
SecurityPolicyUri = SecurityPolicies.None,
TransportProfileUri = transportProfileUri
};
}
}
}
125 changes: 125 additions & 0 deletions tests/Opc.Ua.Client.Tests/Session/SessionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1228,6 +1228,87 @@ public async Task CloseAsyncShouldHandleErrorsDuringCloseAsync()
sut.Channel.Verify();
}

/// <summary>
/// A request with a null authenticationToken is a session-less
/// invocation (OPC 10000-4 §6.3.1). A closed Session must not send
/// one through the channel it keeps open.
/// </summary>
[Test]
public async Task RequestAfterCloseFailsLocallyWithBadSessionIdInvalidAsync()
{
using var sut = SessionMock.Create();
sut.SetConnectedAndResponsive();
CancellationToken ct = CancellationToken.None;
SetupCloseSession(sut);
List<ReadRequest> sent = SetupRead(sut);

StatusCode closed = await sut.CloseAsync(closeChannel: false, ct).ConfigureAwait(false);

Assert.That(closed, Is.EqualTo(StatusCodes.Good));
ServiceResultException? sre = Assert.ThrowsAsync<ServiceResultException>(
async () => await ReadServerStateAsync(sut, ct).ConfigureAwait(false));
Assert.That(sre!.StatusCode, Is.EqualTo(StatusCodes.BadSessionIdInvalid));
Assert.That(sent, Is.Empty, "The request must not reach the channel.");
}

[Test]
public async Task ActivateSessionIsStillSentAfterCloseAsync()
{
using var sut = SessionMock.Create();
sut.SetConnectedAndResponsive();
CancellationToken ct = CancellationToken.None;
SetupCloseSession(sut);
sut.Channel
.Setup(c => c.SendRequestAsync(
It.IsAny<ActivateSessionRequest>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(new ActivateSessionResponse())
.Verifiable(Times.Once);

await sut.CloseAsync(closeChannel: false, ct).ConfigureAwait(false);
ActivateSessionResponse response = await sut.ActivateSessionAsync(
null,
new SignatureData(),
default,
default,
new ExtensionObject(),
new SignatureData(),
ct).ConfigureAwait(false);

Assert.That(response, Is.Not.Null);
sut.Channel.Verify();
}

[Test]
public async Task RequestAfterANewSessionIsCreatedCarriesItsTokenAsync()
{
using var sut = SessionMock.Create();
sut.SetConnectedAndResponsive();
CancellationToken ct = CancellationToken.None;
SetupCloseSession(sut);
List<ReadRequest> sent = SetupRead(sut);

await sut.CloseAsync(closeChannel: false, ct).ConfigureAwait(false);
sut.SessionCreated(NodeId.Parse("s=second"), NodeId.Parse("s=auth2"));
await ReadServerStateAsync(sut, ct).ConfigureAwait(false);

Assert.That(sent, Has.Count.EqualTo(1));
Assert.That(sent[0].RequestHeader.AuthenticationToken, Is.EqualTo(NodeId.Parse("s=auth2")));
}

[Test]
public async Task RequestBeforeASessionIsCreatedIsNotRefusedAsync()
{
using var sut = SessionMock.Create();
CancellationToken ct = CancellationToken.None;
List<ReadRequest> sent = SetupRead(sut);

await ReadServerStateAsync(sut, ct).ConfigureAwait(false);

Assert.That(sent, Has.Count.EqualTo(1));
Assert.That(sent[0].RequestHeader.AuthenticationToken.IsNull, Is.True);
}

[Test]
public async Task DisposeAsyncSendsCloseSessionAsync()
{
Expand Down Expand Up @@ -2842,5 +2923,49 @@ private static ArrayOf<DataValue> CreateOperationLimitsRead(uint operationLimit,
new DataValue(new Variant(1000u)) // MaxSelectClauseParameters
];
}

private static void SetupCloseSession(SessionMock sut)
{
sut.Channel
.Setup(c => c.SendRequestAsync(
It.IsAny<CloseSessionRequest>(),
It.IsAny<CancellationToken>()))
.Returns(new ValueTask<IServiceResponse>(new CloseSessionResponse
{
ResponseHeader = new ResponseHeader { ServiceResult = StatusCodes.Good }
}));
}

private static List<ReadRequest> SetupRead(SessionMock sut)
{
var sent = new List<ReadRequest>();
sut.Channel
.Setup(c => c.SendRequestAsync(
It.IsAny<ReadRequest>(),
It.IsAny<CancellationToken>()))
.Callback((IServiceRequest request, CancellationToken _) => sent.Add((ReadRequest)request))
.Returns(new ValueTask<IServiceResponse>(new ReadResponse
{
ResponseHeader = new ResponseHeader { ServiceResult = StatusCodes.Good },
Results = [new DataValue(new Variant((int)ServerState.Running))]
}));
return sent;
}

private static async Task ReadServerStateAsync(SessionMock sut, CancellationToken ct)
{
await sut.ReadAsync(
null,
0,
TimestampsToReturn.Neither,
[
new ReadValueId
{
NodeId = VariableIds.Server_ServerStatus_State,
AttributeId = Attributes.Value
}
],
ct).ConfigureAwait(false);
}
}
}
Loading
Loading