Files
Marc Schier 0000513cde Pluggable user-identity provider model (#3807)
# Description

Introduces a pluggable user-identity provider model covering all OPC UA
Part 6 §6.5 mechanisms (Anonymous, UserName, X509, IssuedToken/JWT) on
both client and server, with full
`Microsoft.Extensions.DependencyInjection` integration, plus the Part 12
§9 `AuthorizationService` two-phase token-request flow **including
refresh-token rotation**, the Part 12 §8 KeyCredential Push model, and a
clean provider model for OPC 10000-12 §7.2 `ApplicationSelfAdmin`. The
work is split across phase-by-phase commits so it can be reviewed
independently; nothing here changes wire-level behaviour or forces
existing applications to migrate.

### Documentation

All under `Docs/`:

- `IdentityProviders.md` — full developer guide: three-layer model,
recipes, configuration reference, "what gets auto-wired" matrix, JWS
algorithm table, identity-augmenters section, **"Implementing your own
provider"** how-to subsections for Entra / OIDC / Windows / AspNetCore
(sibling files merged in per review feedback).
- `DependencyInjection.md` — `Identity` sections with `appsettings.json`
examples, identity-extension matrix, `WithAuthorizationService` +
`WithKeyCredentialPush` + `AddIdentityAugmenter` extensions documented.
- `RoleBasedUserManagement.md` — claim-criteria callout describing
`IIdentityClaims` probe surface.
- `AuthorizationService.md` — Architecture diagram +
`IAccessTokenProvider` conceptual narrative restored from master; modern
`StartRequestToken` / `FinishRequestToken` flow leads; refresh-token
recipe added.
- `KeyCredentialService.md` — Push model + Pull vs Push vs Bridge
decision matrix + Hybrid (Push + Pull) section; explicit experimental
warning for the bridge.
- `GDS.md` — KeyCredential Push, `StartRequestToken`,
`GdsApplicationSelfAdminProvider`, **shipped Refresh-token support with
rotation policy and audit semantics** all documented.
- `MigrationGuide.md` — User Identity Providers section listing
`[Obsolete]` markers + mechanical recipes; SelfAdmin migration via
`IIdentityAugmenter`; `EnableRefreshTokens` default note.
- `README.md` index entries.

## Checklist

- [x] 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.
- [x] I ran **all** tests locally using the **UA.slnx** solution against
at least .net **framework** and .net **10**, and all passed.
- [x] I fixed **all** failing and flaky tests in the CI pipelines and
**all** CodeQL warnings.
- [x] I have addressed **all** PR feedback received.
2026-06-02 01:14:54 +02:00

712 lines
27 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.IO;
using System.Linq;
using System.Threading.Tasks;
using NUnit.Framework;
using Opc.Ua.Client;
using Opc.Ua.Client.TestFramework;
using Opc.Ua.Export;
namespace Opc.Ua.Sessions.Tests
{
/// <summary>
/// Client NodeSet export tests.
/// </summary>
[TestFixture]
[Category("Client")]
[Category("NodeSetExport")]
[SetCulture("en-us")]
[SetUICulture("en-us")]
[TestFixtureSource(nameof(FixtureArgs))]
public class NodeSetExportTest : ClientTestFramework
{
public static new readonly object[] FixtureArgs =
[
new object[] { Utils.UriSchemeOpcTcp }
];
public NodeSetExportTest(string uriScheme = Utils.UriSchemeOpcTcp)
: base(uriScheme)
{
}
/// <summary>
/// Set up a Server and a Client instance.
/// </summary>
[OneTimeSetUp]
public override Task OneTimeSetUpAsync()
{
SupportsExternalServerUrl = true;
return base.OneTimeSetUpAsync();
}
/// <summary>
/// Tear down the Server and the Client.
/// </summary>
[OneTimeTearDown]
public override Task OneTimeTearDownAsync()
{
return base.OneTimeTearDownAsync();
}
/// <summary>
/// Test setup.
/// </summary>
[SetUp]
public override Task SetUpAsync()
{
return base.SetUpAsync();
}
/// <summary>
/// Test teardown.
/// </summary>
[TearDown]
public override Task TearDownAsync()
{
return base.TearDownAsync();
}
/// <summary>
/// Test exporting nodes to NodeSet2 XML.
/// </summary>
[Test]
public async Task ExportNodesToNodeSet2Async()
{
// Browse to get some nodes
var browser = new Browser(Session)
{
BrowseDirection = BrowseDirection.Forward,
ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences,
IncludeSubtypes = true,
NodeClassMask = 0
};
var nodesToBrowse = new List<NodeId> { ObjectIds.Server };
var allNodes = new List<INode>();
// Browse starting from Server object
ArrayOf<ReferenceDescription> references = await browser.BrowseAsync(nodesToBrowse[0]).ConfigureAwait(false);
// Fetch the actual nodes
foreach (ReferenceDescription reference in references.ToList())
{
INode node = await Session.NodeCache.FindAsync(reference.NodeId).ConfigureAwait(false);
if (node != null)
{
allNodes.Add(node);
}
}
Assert.That(allNodes, Is.Not.Empty, "Should have browsed at least one node");
// Export to NodeSet2
string tempFile = Path.GetTempFileName();
try
{
using (var stream = new FileStream(tempFile, FileMode.Create))
{
var systemContext = new SystemContext(Telemetry)
{
NamespaceUris = Session.NamespaceUris,
ServerUris = Session.ServerUris
};
CoreClientUtils.ExportNodesToNodeSet2(systemContext, allNodes, stream);
}
// Verify the file was created and has content
var fileInfo = new FileInfo(tempFile);
Assert.That(fileInfo.Exists, Is.True, "NodeSet2 file should exist");
Assert.That(fileInfo.Length, Is.GreaterThan(0), "NodeSet2 file should not be empty");
// Try to read it back
using (var stream = new FileStream(tempFile, FileMode.Open))
{
var nodeSet = UANodeSet.Read(stream);
Assert.That(nodeSet, Is.Not.Null, "Should be able to read the exported NodeSet2");
Assert.That(nodeSet.Items, Is.Not.Null, "NodeSet2 should contain items");
Assert.That(nodeSet.Items, Is.Not.Empty, "NodeSet2 should contain at least one node");
}
}
finally
{
if (File.Exists(tempFile))
{
File.Delete(tempFile);
}
}
}
/// <summary>
/// Test exporting different node types to NodeSet2 XML.
/// </summary>
[Test]
public async Task ExportDifferentNodeTypesAsync()
{
var allNodes = new List<INode>();
// Get different types of nodes
// Object node
INode serverNode = await Session.NodeCache.FindAsync(ObjectIds.Server).ConfigureAwait(false);
if (serverNode != null)
{
allNodes.Add(serverNode);
}
// Variable node
INode serverStatusNode = await Session.NodeCache.FindAsync(VariableIds.Server_ServerStatus).ConfigureAwait(false);
if (serverStatusNode != null)
{
allNodes.Add(serverStatusNode);
}
// ObjectType node
INode baseObjectTypeNode = await Session.NodeCache.FindAsync(ObjectTypeIds.BaseObjectType).ConfigureAwait(false);
if (baseObjectTypeNode != null)
{
allNodes.Add(baseObjectTypeNode);
}
// VariableType node
INode baseVariableTypeNode = await Session.NodeCache.FindAsync(VariableTypeIds.BaseVariableType).ConfigureAwait(false);
if (baseVariableTypeNode != null)
{
allNodes.Add(baseVariableTypeNode);
}
Assert.That(allNodes, Is.Not.Empty, "Should have found at least one node");
// Export to NodeSet2
string tempFile = Path.GetTempFileName();
try
{
using (var stream = new FileStream(tempFile, FileMode.Create))
{
var systemContext = new SystemContext(Telemetry)
{
NamespaceUris = Session.NamespaceUris,
ServerUris = Session.ServerUris
};
CoreClientUtils.ExportNodesToNodeSet2(systemContext, allNodes, stream);
}
// Read it back and verify we have different node types
using (var stream = new FileStream(tempFile, FileMode.Open))
{
var nodeSet = UANodeSet.Read(stream);
Assert.That(nodeSet, Is.Not.Null, "Should be able to read the exported NodeSet2");
Assert.That(nodeSet.Items, Is.Not.Null, "NodeSet2 should contain items");
Assert.That(nodeSet.Items, Has.Length.EqualTo(allNodes.Count), "Should have exported all nodes");
// Verify we have different node types
var nodeTypes = nodeSet.Items.Select(n => n.GetType()).Distinct().ToList();
Assert.That(nodeTypes, Has.Count.GreaterThan(1), "Should have multiple node types");
}
}
finally
{
if (File.Exists(tempFile))
{
File.Delete(tempFile);
}
}
}
/// <summary>
/// Test exporting and re-importing nodes.
/// </summary>
[Test]
public async Task ExportAndReimportNodesAsync()
{
var allNodes = new List<INode>();
// Get some nodes
INode serverNode = await Session.NodeCache.FindAsync(ObjectIds.Server).ConfigureAwait(false);
if (serverNode != null)
{
allNodes.Add(serverNode);
}
INode serverStatusNode = await Session.NodeCache.FindAsync(VariableIds.Server_ServerStatus).ConfigureAwait(false);
if (serverStatusNode != null)
{
allNodes.Add(serverStatusNode);
}
Assert.That(allNodes, Is.Not.Empty, "Should have found at least one node");
// Export to NodeSet2
string tempFile = Path.GetTempFileName();
try
{
using (var stream = new FileStream(tempFile, FileMode.Create))
{
var systemContext = new SystemContext(Telemetry)
{
NamespaceUris = Session.NamespaceUris,
ServerUris = Session.ServerUris
};
CoreClientUtils.ExportNodesToNodeSet2(systemContext, allNodes, stream);
}
// Read and import
using (var stream = new FileStream(tempFile, FileMode.Open))
{
var nodeSet = UANodeSet.Read(stream);
var importedNodeStates = new NodeStateCollection();
var localContext = new SystemContext(Telemetry)
{
NamespaceUris = new NamespaceTable()
};
if (nodeSet.NamespaceUris != null)
{
foreach (string namespaceUri in nodeSet.NamespaceUris)
{
localContext.NamespaceUris.Append(namespaceUri);
}
}
nodeSet.Import(localContext, importedNodeStates);
Assert.That(importedNodeStates, Has.Count.EqualTo(allNodes.Count), "Should have imported all nodes");
}
}
finally
{
if (File.Exists(tempFile))
{
File.Delete(tempFile);
}
}
}
/// <summary>
/// Test exporting nodes with default options (no values).
/// </summary>
[Test]
public async Task ExportNodesToNodeSet2_DefaultOptionsAsync()
{
var allNodes = new List<INode>();
// Get variable node that has a value
INode serverStatusNode = await Session.NodeCache.FindAsync(VariableIds.Server_ServerStatus).ConfigureAwait(false);
if (serverStatusNode != null)
{
allNodes.Add(serverStatusNode);
}
// Get another variable
INode stateNode = await Session.NodeCache.FindAsync(VariableIds.Server_ServerStatus_State).ConfigureAwait(false);
if (stateNode != null)
{
allNodes.Add(stateNode);
}
Assert.That(allNodes, Is.Not.Empty, "Should have found at least one node");
DateTime now = DateTime.UtcNow;
// Export with default options
string tempFile = Path.GetTempFileName();
try
{
using (var stream = new FileStream(tempFile, FileMode.Create))
{
var systemContext = new SystemContext(Telemetry)
{
NamespaceUris = Session.NamespaceUris,
ServerUris = Session.ServerUris
};
CoreClientUtils.ExportNodesToNodeSet2(
systemContext,
allNodes,
stream,
NodeSetExportOptions.Default,
lastModified: now);
}
// Read it back and verify values are not exported
using (var stream = new FileStream(tempFile, FileMode.Open))
{
var nodeSet = UANodeSet.Read(stream);
Assert.That(nodeSet, Is.Not.Null, "Should be able to read the exported NodeSet2");
Assert.That(nodeSet.Items, Is.Not.Null, "NodeSet2 should contain items");
// Check that variables don't have values
foreach (UAVariable variable in nodeSet.Items.OfType<UAVariable>())
{
Assert.That(variable.Value, Is.Null, "Value should not be exported with Default options");
}
}
// Verify default file is smaller or equal to complete
var defaultFile = new FileInfo(tempFile);
long defaultSize = defaultFile.Length;
// Export with complete options
string tempFileComplete = Path.GetTempFileName();
try
{
using (var stream = new FileStream(tempFileComplete, FileMode.Create))
{
var systemContext = new SystemContext(Telemetry)
{
NamespaceUris = Session.NamespaceUris,
ServerUris = Session.ServerUris
};
CoreClientUtils.ExportNodesToNodeSet2(
systemContext,
allNodes,
stream,
NodeSetExportOptions.Complete,
lastModified: now);
}
var completeFile = new FileInfo(tempFileComplete);
long completeSize = completeFile.Length;
// Default should be smaller or equal to complete
// (Equal if nodes don't have values to export)
Assert.That(completeSize, Is.GreaterThanOrEqualTo(defaultSize), "Default export should not be larger than Complete");
}
finally
{
if (File.Exists(tempFileComplete))
{
File.Delete(tempFileComplete);
}
}
}
finally
{
if (File.Exists(tempFile))
{
File.Delete(tempFile);
}
}
}
/// <summary>
/// Test exporting nodes with complete options (all metadata).
/// </summary>
[Test]
public async Task ExportNodesToNodeSet2_CompleteOptionsAsync()
{
var allNodes = new List<INode>();
// Get variable node
INode serverStatusNode = await Session.NodeCache.FindAsync(VariableIds.Server_ServerStatus).ConfigureAwait(false);
if (serverStatusNode != null)
{
allNodes.Add(serverStatusNode);
}
Assert.That(allNodes, Is.Not.Empty, "Should have found at least one node");
// Export with complete options
string tempFile = Path.GetTempFileName();
try
{
using (var stream = new FileStream(tempFile, FileMode.Create))
{
var systemContext = new SystemContext(Telemetry)
{
NamespaceUris = Session.NamespaceUris,
ServerUris = Session.ServerUris
};
CoreClientUtils.ExportNodesToNodeSet2(systemContext, allNodes, stream, NodeSetExportOptions.Complete);
}
// Read it back
using (var stream = new FileStream(tempFile, FileMode.Open))
{
var nodeSet = UANodeSet.Read(stream);
Assert.That(nodeSet, Is.Not.Null, "Should be able to read the exported NodeSet2");
Assert.That(nodeSet.Items, Is.Not.Null, "NodeSet2 should contain items");
}
}
finally
{
if (File.Exists(tempFile))
{
File.Delete(tempFile);
}
}
}
/// <summary>
/// Test exporting nodes with custom options.
/// </summary>
[Test]
public async Task ExportNodesToNodeSet2_CustomOptionsAsync()
{
var allNodes = new List<INode>();
// Get variable node
INode serverStatusNode = await Session.NodeCache.FindAsync(VariableIds.Server_ServerStatus).ConfigureAwait(false);
if (serverStatusNode != null)
{
allNodes.Add(serverStatusNode);
}
Assert.That(allNodes, Is.Not.Empty, "Should have found at least one node");
// Export with custom options - values exported
var customOptions = new NodeSetExportOptions
{
ExportValues = true,
ExportParentNodeId = false
};
string tempFile = Path.GetTempFileName();
try
{
using (var stream = new FileStream(tempFile, FileMode.Create))
{
var systemContext = new SystemContext(Telemetry)
{
NamespaceUris = Session.NamespaceUris,
ServerUris = Session.ServerUris
};
CoreClientUtils.ExportNodesToNodeSet2(systemContext, allNodes, stream, customOptions);
}
// Verify the file was created and has content
var fileInfo = new FileInfo(tempFile);
Assert.That(fileInfo.Exists, Is.True, "NodeSet2 file should exist");
Assert.That(fileInfo.Length, Is.GreaterThan(0), "NodeSet2 file should not be empty");
}
finally
{
if (File.Exists(tempFile))
{
File.Delete(tempFile);
}
}
}
/// <summary>
/// Test that default export options preserve backward compatibility.
/// </summary>
[Test]
public async Task ExportNodesToNodeSet2_BackwardCompatibilityAsync()
{
var allNodes = new List<INode>();
// Get some nodes
INode serverNode = await Session.NodeCache.FindAsync(ObjectIds.Server).ConfigureAwait(false);
if (serverNode != null)
{
allNodes.Add(serverNode);
}
Assert.That(allNodes, Is.Not.Empty, "Should have found at least one node");
string tempFile1 = Path.GetTempFileName();
string tempFile2 = Path.GetTempFileName();
try
{
var systemContext = new SystemContext(Telemetry)
{
NamespaceUris = Session.NamespaceUris,
ServerUris = Session.ServerUris
};
// Export without options (backward compatibility)
using (var stream = new FileStream(tempFile1, FileMode.Create))
{
CoreClientUtils.ExportNodesToNodeSet2(systemContext, allNodes, stream);
}
// Export with default options
using (var stream = new FileStream(tempFile2, FileMode.Create))
{
CoreClientUtils.ExportNodesToNodeSet2(systemContext, allNodes, stream, NodeSetExportOptions.Default);
}
// Both should be readable
using (var stream = new FileStream(tempFile1, FileMode.Open))
{
var nodeSet = UANodeSet.Read(stream);
Assert.That(nodeSet, Is.Not.Null, "Should be able to read backward compatible export");
}
using (var stream = new FileStream(tempFile2, FileMode.Open))
{
var nodeSet = UANodeSet.Read(stream);
Assert.That(nodeSet, Is.Not.Null, "Should be able to read default options export");
}
}
finally
{
if (File.Exists(tempFile1))
{
File.Delete(tempFile1);
}
if (File.Exists(tempFile2))
{
File.Delete(tempFile2);
}
}
}
/// <summary>
/// Test exporting with user context option.
/// </summary>
[Test]
public async Task ExportNodesToNodeSet2_UserContextOptionsAsync()
{
var allNodes = new List<INode>();
// Get method node that has UserExecutable
INode getMonitoredItemsNode = await Session.NodeCache.FindAsync(MethodIds.Server_GetMonitoredItems).ConfigureAwait(false);
if (getMonitoredItemsNode != null)
{
allNodes.Add(getMonitoredItemsNode);
}
// Get variable node that has UserAccessLevel
INode serverStatusNode = await Session.NodeCache.FindAsync(VariableIds.Server_ServerStatus).ConfigureAwait(false);
if (serverStatusNode != null)
{
allNodes.Add(serverStatusNode);
}
Assert.That(allNodes, Is.Not.Empty, "Should have found at least one node");
// Export WITHOUT user context
string tempFileNoContext = Path.GetTempFileName();
try
{
using (var stream = new FileStream(tempFileNoContext, FileMode.Create))
{
var systemContext = new SystemContext(Telemetry)
{
NamespaceUris = Session.NamespaceUris,
ServerUris = Session.ServerUris
};
var optionsNoContext = new NodeSetExportOptions
{
ExportValues = false,
ExportParentNodeId = false,
ExportUserContext = false
};
CoreClientUtils.ExportNodesToNodeSet2(systemContext, allNodes, stream, optionsNoContext);
}
// Export WITH user context
string tempFileWithContext = Path.GetTempFileName();
try
{
using (var stream = new FileStream(tempFileWithContext, FileMode.Create))
{
var systemContext = new SystemContext(Telemetry)
{
NamespaceUris = Session.NamespaceUris,
ServerUris = Session.ServerUris
};
var optionsWithContext = new NodeSetExportOptions
{
ExportValues = false,
ExportParentNodeId = false,
ExportUserContext = true
};
CoreClientUtils.ExportNodesToNodeSet2(systemContext, allNodes, stream, optionsWithContext);
}
// Read both files and compare
UANodeSet nodeSetNoContext;
using (var stream = new FileStream(tempFileNoContext, FileMode.Open))
{
nodeSetNoContext = UANodeSet.Read(stream);
Assert.That(nodeSetNoContext, Is.Not.Null, "Should be able to read NodeSet without user context");
}
UANodeSet nodeSetWithContext;
using (var stream = new FileStream(tempFileWithContext, FileMode.Open))
{
nodeSetWithContext = UANodeSet.Read(stream);
Assert.That(nodeSetWithContext, Is.Not.Null, "Should be able to read NodeSet with user context");
}
// Verify that methods in the context version have UserExecutable
List<UAMethod> methodsNoContext = nodeSetNoContext.Items?.OfType<UAMethod>().ToList() ?? [];
List<UAMethod> methodsWithContext = nodeSetWithContext.Items?.OfType<UAMethod>().ToList() ?? [];
Assert.That(methodsWithContext, Has.Count.EqualTo(methodsNoContext.Count), "Should have same number of methods");
// Variables with context should potentially have UserAccessLevel if different from AccessLevel
List<UAVariable> variablesNoContext = nodeSetNoContext.Items?.OfType<UAVariable>().ToList() ?? [];
List<UAVariable> variablesWithContext = nodeSetWithContext.Items?.OfType<UAVariable>().ToList() ?? [];
Assert.That(variablesWithContext, Has.Count.EqualTo(variablesNoContext.Count), "Should have same number of variables");
// File with user context should be larger or equal
var fileNoContext = new FileInfo(tempFileNoContext);
var fileWithContext = new FileInfo(tempFileWithContext);
// Note: Sizes might be equal if UserAccessLevel == AccessLevel for all variables
// The important part is that export completes successfully with both options
Assert.That(fileWithContext.Length, Is.GreaterThan(0), "Export with user context should produce a valid file");
Assert.That(fileNoContext.Length, Is.GreaterThan(0), "Export without user context should produce a valid file");
}
finally
{
if (File.Exists(tempFileWithContext))
{
File.Delete(tempFileWithContext);
}
}
}
finally
{
if (File.Exists(tempFileNoContext))
{
File.Delete(tempFileNoContext);
}
}
}
}
}