Files
Marc Schier fde50c5700 Enforce ActivateSession transfer and reconnect security (OPC 10000-4 §5.7.3.1) (#4050)
# Description

This draft isolates the Session/ActivateSession, reconnect, and
distributed Session security work split from #4021.

### Failure

- `ActivateSession` could transfer a Session to a new SecureChannel
without consistently enforcing the original client certificate,
MessageSecurityMode, SecurityPolicy, and exact OPC `ClientUserId`
semantics.
- Missing or legacy distributed Session security state did not provide
enough information to validate transfer safely.
- Malformed or reused nonces, concurrent activation, and cancellation
could leave activation state inconsistent.
- Client reconnect could treat recoverable Session-loss/security
responses as fatal, reuse a Session after client-certificate rotation,
or report a managed channel ready before Session recreation completed.

### Fix

- Serialize activation, consume server nonces once, validate application
signatures and user tokens asynchronously, and enforce transfer
continuity against the original channel and authenticated identity.
- Persist versioned transfer-security state for distributed Sessions and
fail closed when certificate, identity, activation, or nonce state is
absent or invalid.
- Validate server signatures/nonces on the client, recreate Sessions for
certificate rotation and recoverable activation failures, and await
participant recreation before transitioning the managed channel to
`Ready`.
- Make the restart recovery integration test use bounded reconnect
cycles instead of a fixed startup delay.

### Specification

- OPC 10000-4 §5.7.2.2 — CreateSession signatures and nonces.
- OPC 10000-4 §5.7.3.1 — ActivateSession identity continuity and
SecureChannel transfer.
- OPC 10000-4 §6.1.8 — application nonce generation, validation, and
reuse requirements.

### Validation

- `git diff --check`
- Release `net10.0`: `Opc.Ua.Redundancy.Server.Tests` 567/567 plus the
targeted server Session, Subscription transfer, ClientUserId, client
reconnect and certificate rotation suites pass.
- Release `net48`: the same redundancy suite (567/567) and the targeted
Session/Subscription suites pass.
- Full `Opc.Ua.Server.Tests` run on `net10.0`: 3633/3634. The single
failure,
`ServerFluentApiHostingTests.ConfigureApplicationBuildsSharedClientAndServerConfigurationAsync`,
reproduces identically on the unmodified commit and is a local
certificate-store path issue rather than a regression.

These were targeted validation runs; no long-soak result is claimed.
2026-07-28 12:07:02 +02:00

124 lines
4.3 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.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Opc.Ua.Identity;
using Opc.Ua.Server;
using Quickstarts.ReferenceServer;
namespace Opc.Ua.Client.TestFramework
{
public sealed class TokenValidatorMock : ITokenValidator, IDisposable
{
public const string DefaultIssuer = "urn:opcfoundation:tests:jwt";
public const string DefaultSubject = "local-issued-token-user";
public IssuedIdentityTokenHandler LastIssuedToken { get; set; }
public string? Issuer { get; set; } = DefaultIssuer;
public string? Subject { get; set; } = DefaultSubject;
public void Dispose()
{
LastIssuedToken = null;
}
public IUserIdentity ValidateToken(IssuedIdentityTokenHandler issuedToken)
{
LastIssuedToken = issuedToken.Copy();
var claims = new Dictionary<string, object?>();
if (Issuer != null)
{
claims["iss"] = Issuer;
}
if (Subject != null)
{
claims["sub"] = Subject;
}
return new JwtUserIdentity(
issuedToken,
claims,
[],
[],
Issuer,
Subject);
}
}
/// <summary>
/// Adapts the legacy quickstart token validator to the P5 identity-registry surface.
/// </summary>
public sealed class MockJwtAuthenticator : IUserTokenAuthenticator
{
private readonly ITokenValidator m_validator;
public MockJwtAuthenticator(ITokenValidator validator)
{
m_validator = validator ?? throw new ArgumentNullException(nameof(validator));
}
public UserTokenType TokenType => UserTokenType.IssuedToken;
public string? IssuedTokenProfileUri => Profiles.JwtUserToken;
public async ValueTask<AuthenticationResult> AuthenticateAsync(
AuthenticationContext context,
CancellationToken ct = default)
{
ct.ThrowIfCancellationRequested();
if (context.TokenHandler is not IssuedIdentityTokenHandler issuedToken ||
issuedToken.IssuedTokenType != IssuedTokenType.JWT)
{
return AuthenticationResult.NotHandled;
}
return await new ValueTask<AuthenticationResult>(AuthenticateJwt(issuedToken))
.ConfigureAwait(false);
}
private AuthenticationResult AuthenticateJwt(IssuedIdentityTokenHandler issuedToken)
{
try
{
return AuthenticationResult.Accept(m_validator.ValidateToken(issuedToken));
}
catch (ServiceResultException ex)
{
return AuthenticationResult.Reject(ex.Result);
}
}
}
}