Files
UA-.NETStandard/tests/Opc.Ua.Server.Tests/CustomNodeManagerTests.cs
T
romanett 7212607f16 OPC UA Part 3 compliance: permissions, Write semantics, NodeManagement, NodeSet DataTypes, locales (#4675)
# Description

Fixes the High and Medium findings of an OPC UA Part 3 (OPC 10000-3,
Address Space Model) compliance audit. Each finding was checked against
the full spec text (Parts 3, 4, 5, 6, 14 and 18) before it was fixed.
Every fix comes with regression tests that fail without it.

### Role permissions (Part 3 §8.55, Part 4 §5.12.2.2)
- The type-hierarchy exemption in
`MasterNodeManager.ValidateRolePermissions` /
`ValidateAccessRestrictions` now covers only Browse, Read and
ReadRolePermissions. Type nodes stay visible to generic clients, which
was the intent of #3705; every other permission bit is now enforced on
them.
- `ReceiveEvents` is enforced on the EventType node. The standard
NodeSet grants it on `AuditEventType` and its subtypes only to
SecurityAdmin, so only SecurityAdmin sessions now receive audit events.
- Call checks the `Call` permission and AccessRestrictions on the Object
as well as on the Method.
- When a Call's `methodId` is the Method declaration of the ObjectType,
the Object's Method with the same BrowseName is permission-checked and
invoked. The declaration is used only if the Object has no such Method.
This applies to `AsyncCustomNodeManager`, `CustomNodeManager2` and the
sample node manager.

### Write service (Part 3 §5.6.2, §8.40, §8.57; Part 4 §5.11.4)
- The synchronous `OnWriteValue` path (fluent `OnWrite`) checks DataType
and ValueRank first (`Bad_TypeMismatch`). After an IndexRange write it
merges the slice into the cached value instead of replacing it.
- StatusWrite / TimestampWrite are enforced (`Bad_WriteNotSupported`).
- Undefined enumeration values and invalid OptionSet writes return
`Bad_OutOfRange`. OptionSet writes merge only the valid bits into the
stored value.
- New `ReportPropertyValueChanged` / `ReportSemanticChange` let server
code raise SemanticChangeEvents for changes it makes itself.
- Required follow-up (Part 14 §6.2.11.1): if an external target rejects
a timestamp, the PubSub subscriber's TargetVariables writer retries
without it.

### NodeManagement and Call arguments (Part 3 §5.5.2, §5.7.3, §6.4.2;
Part 4 §5.8, §5.12.2)
- AddNodes creates the Mandatory InstanceDeclarations of the
TypeDefinition and rejects abstract or Interface types
(`Bad_TypeDefinitionInvalid`).
- AddReferences, DeleteReferences and DeleteNodes bump NodeVersion and
raise GeneralModelChangeEvents.
- Clients may omit trailing optional input arguments
(`HasOptionalInputArgumentDescription`).

### NodeSet DataTypes (Part 3 §5.8.3, §8.48; Part 6 Annex F.12)
- `UANodeSet.Import` completes structure definitions with the base
type's fields (base fields first). It creates definitions for structures
without fields and sets `DefaultEncodingId`.
`StructureDefinition.FirstExplicitFieldIndex` marks the subtype's own
fields.
- `DataTypeState` no longer mutates the stored definition on read.

### Locales (Part 3 §5.2.5, §8.5; Part 4 §5.4)
- Read, Browse and data change notifications return the translation that
best matches the session's LocaleIds, or all translations for `mul`. The
selection lives in the server dispatcher and is built on
`ResourceManager`: the new `TranslateValue` calls the overridable
`Translate`.
- Locale ids are matched case-insensitively, and fallback translations
carry their real locale.

### Client complex types (Part 6 §5.1.7)
- The Reflection.Emit builder encodes only `IsOptional` subtyped fields
as ExtensionObject. It also supports OptionSet subtypes: an unsupported
type is skipped instead of aborting the whole load.
- `TypeInfo.GetXmlName` uses the data type's XML name for dynamic
structures and OptionSets (the XML body element was `<Structure>`). Both
builders now produce identical XML.

## Behaviour changes
All are documented in `docs/MigrationGuide.md`.
- **Audit events:** only SecurityAdmin receives them. The CTT "Auditing
Connections" unit needs a SecurityAdmin user (e.g. sysadmin);
`AuditingOperationTests` was updated.
- **Write timestamps and status:** clients writing a SourceTimestamp or
a non-Good StatusCode get `Bad_WriteNotSupported` unless the Variable
has StatusWrite/TimestampWrite. No variable in `src/` sets these bits.
- **AddNodes:** it rejects abstract types (including `BaseVariableType`
and `BaseEventType`), and new instances now come with child nodes.
- **Call:** the Object needs the Call permission. The Object's own
Method runs even when the call names the type declaration.

## Not included
- Low-severity findings: missing validation on optional services and
author-side NodeSet rules.
- LocalizedText nested inside structures or Variant arrays, and in
HistoryRead or Call outputs.

## Testing
net10.0, Debug, one suite at a time on the merged branch. All suites
below pass:

| Suite | Passed |
|---|---|
| Types | 11430 |
| Core.Encoders | 2947 |
| Core.Schema | 179 |
| Core.Security | 558 |
| Client | 2761 |
| Server | 8210 |
| InformationModel | 1080 |
| Features | 145 |
| History | 536 |
| Di | 455 |
| Machinery | 167 |
| Robotics | 661 |
| Robotics.Intent | 22 |
| Pumps | 75 |
| Scales | 122 |
| Positioning | 69 |
| ISA95 | 144 |
| Vision | 484 |
| PubSub | 1490 |
| PubSub.Adapter | 151 |
| PubSub.Server | 177 |
| Redundancy.Server | 856 |
| Lds | 173 |
| Configuration | 241 |
| WotCon | 1496 |

- **Client.ComplexTypes:** one test wrote a SourceTimestamp to a
variable without TimestampWrite. It is fixed in this PR, and the suite
has not been re-run since.
- **Core:** 6068 passed, 1 failure in
`ActivityTraceFlags_Metrics_ShouldRecordMetricsOnly`. That telemetry
test passed when re-run alone, so it looks flaky.
- **Still running:** Sessions, Subscriptions (Classic, Durable,
standard) and Interop. Results will follow on this PR.
- `UA.slnx` builds with 0 errors for net10.0 and net48, with no new
analyzer warnings in changed files.

## Related Issues

- Part 3 compliance audit (no tracking issue)

## 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.
- [ ] 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.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 12:43:59 +00:00

339 lines
12 KiB
C#

using System;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using Opc.Ua.Server.TestFramework;
using Opc.Ua.Tests;
using Quickstarts.ReferenceServer;
namespace Opc.Ua.Server.Tests
{
/// <summary>
/// Test <see cref="CustomNodeManager2"/>
/// </summary>
[TestFixture]
[Category("CustomNodeManager")]
[SetCulture("en-us")]
[SetUICulture("en-us")]
[Parallelizable]
public class CustomNodeManagerTests
{
/// <summary>
/// Tests the componentCache methods with multiple threads
/// </summary>
[Test]
public async Task TestComponentCacheAsync()
{
ITelemetryContext telemetry = NUnitTelemetryContext.Create();
var fixture = new ServerFixture<StandardServer>(t => new ReferenceServer(t));
try
{
// Arrange
const string ns = "http://test.org/UA/Data/";
StandardServer server = await fixture.StartAsync()
.ConfigureAwait(false);
using var nodeManager = new TestableCustomNodeManger2(server.CurrentInstance, ns);
var baseObject = new BaseObjectState(null);
var nodeHandle = new NodeHandle(
CommonTestWorkers.NodeIdTestSetStatic[0]
.WithNamespaceIndex(0)
.InnerNodeId,
baseObject);
//Act
await RunTaskInParallelAsync(
() => UseComponentCacheAsync(nodeManager, baseObject, nodeHandle),
100)
.ConfigureAwait(false);
//Assert, that entry was deleted from cache after parallel operations on the same node
NodeState handleFromCache = nodeManager.LookupNodeInComponentCache(
nodeManager.SystemContext,
nodeHandle);
Assert.That(handleFromCache, Is.Null);
}
finally
{
await fixture.StopAsync().ConfigureAwait(false);
}
}
/// <summary>
/// Part 4 §5.12.2.2: a Call whose methodId is the Method declaration of the
/// ObjectType resolves to the Method of the Object, so the RolePermissions
/// of the Object's Method are verified and that Method is invoked.
/// </summary>
[Test]
public async Task FindMethodStateResolvesTypeDeclarationToObjectMethodAsync()
{
var fixture = new ServerFixture<StandardServer>(t => new ReferenceServer(t));
try
{
const string ns = "http://test.org/UA/MethodResolution/";
StandardServer server = await fixture.StartAsync()
.ConfigureAwait(false);
using var nodeManager = new TestableCustomNodeManger2(server.CurrentInstance, ns);
ushort index = (ushort)server.CurrentInstance.NamespaceUris.GetIndex(ns);
ServerSystemContext context = nodeManager.SystemContext;
var objectType = new BaseObjectTypeState
{
NodeId = new NodeId("ResolveType", index),
BrowseName = new QualifiedName("ResolveType", index),
SuperTypeId = ObjectTypeIds.BaseObjectType
};
var declaration = new MethodState(objectType)
{
NodeId = new NodeId("ResolveType.Reset", index),
BrowseName = new QualifiedName("Reset", index)
};
objectType.AddChild(declaration);
var instance = new BaseObjectState(null)
{
NodeId = new NodeId("ResolveInstance", index),
BrowseName = new QualifiedName("ResolveInstance", index),
TypeDefinitionId = objectType.NodeId
};
var instanceMethod = new MethodState(instance)
{
NodeId = new NodeId("ResolveInstance.Reset", index),
BrowseName = new QualifiedName("Reset", index)
};
instance.AddChild(instanceMethod);
nodeManager.AddPredefinedNode(context, objectType);
nodeManager.AddPredefinedNode(context, instance);
server.CurrentInstance.TypeTree.AddSubtype(
objectType.NodeId,
ObjectTypeIds.BaseObjectType);
var operationContext = new OperationContext(
new RequestHeader(),
null,
RequestType.Call,
RequestLifetime.None);
MethodState resolved = nodeManager.FindMethodState(
operationContext,
new CallMethodRequest
{
ObjectId = instance.NodeId,
MethodId = declaration.NodeId
});
Assert.That(resolved, Is.SameAs(instanceMethod));
}
finally
{
await fixture.StopAsync().ConfigureAwait(false);
}
}
/// <summary>
/// Tests the Predefined Nodes methods with multiple threads
/// </summary>
[Test]
public async Task TestPredefinedNodesAsync()
{
ITelemetryContext telemetry = NUnitTelemetryContext.Create();
var fixture = new ServerFixture<StandardServer>(t => new ReferenceServer(t));
try
{
// Arrange
const string ns = "http://test.org/UA/Data/";
StandardServer server = await fixture.StartAsync()
.ConfigureAwait(false);
using var nodeManager = new TestableCustomNodeManger2(server.CurrentInstance, ns);
int index = server.CurrentInstance.NamespaceUris.GetIndex(ns);
var baseObject = new DataItemState(null);
NodeId nodeId =
CommonTestWorkers.NodeIdTestSetStatic[0]
.WithNamespaceIndex((ushort)index)
.InnerNodeId;
baseObject.NodeId = nodeId;
//single threaded test
nodeManager.AddPredefinedNode(nodeManager.SystemContext, baseObject);
Assert.That(nodeManager.PredefinedNodes.ContainsKey(nodeId), Is.True);
NodeState nodeState = nodeManager.Find(nodeId);
Assert.That(nodeState, Is.Not.Null);
var handle = nodeManager.GetManagerHandle(nodeId) as NodeHandle;
Assert.That(handle, Is.Not.Null);
nodeManager.DeleteNode(nodeManager.SystemContext, nodeId);
Assert.That(nodeManager.PredefinedNodes, Is.Empty);
nodeState = nodeManager.Find(nodeId);
Assert.That(nodeState, Is.Null);
handle = nodeManager.GetManagerHandle(nodeId) as NodeHandle;
Assert.That(handle, Is.Null);
nodeManager.AddPredefinedNode(nodeManager.SystemContext, baseObject);
nodeManager.DeleteAddressSpace();
Assert.That(nodeManager.PredefinedNodes, Is.Empty);
//Act
await RunTaskInParallelAsync(
() => UsePredefinedNodesAsync(nodeManager, baseObject, nodeId),
100)
.ConfigureAwait(false);
//last operation added the Node back into the dictionary
Assert.That(nodeManager.PredefinedNodes.ContainsKey(nodeId), Is.True);
//delete full adress space
nodeManager.DeleteAddressSpace();
Assert.That(nodeManager.PredefinedNodes, Is.Empty);
}
finally
{
await fixture.StopAsync().ConfigureAwait(false);
}
}
private static Task UsePredefinedNodesAsync(
TestableCustomNodeManger2 nodeManager,
DataItemState baseObject,
NodeId nodeId)
{
nodeManager.AddPredefinedNode(nodeManager.SystemContext, baseObject);
_ = nodeManager.Find(nodeId);
_ = nodeManager.GetManagerHandle(nodeId) as NodeHandle;
nodeManager.DeleteNode(nodeManager.SystemContext, nodeId);
_ = nodeManager.Find(nodeId);
_ = nodeManager.GetManagerHandle(nodeId) as NodeHandle;
nodeManager.AddPredefinedNode(nodeManager.SystemContext, baseObject);
return Task.CompletedTask;
}
/// <summary>
/// Test Methods AddNodeToComponentCache, RemoveNodeFromComponentCache & LookupNodeInComponentCache & verify the node is added to the cache
/// </summary>
private static async Task UseComponentCacheAsync(
TestableCustomNodeManger2 nodeManager,
BaseObjectState baseObject,
NodeHandle nodeHandle)
{
//-- Act
nodeManager.AddNodeToComponentCache(nodeManager.SystemContext, nodeHandle, baseObject);
nodeManager.AddNodeToComponentCache(nodeManager.SystemContext, nodeHandle, baseObject);
NodeState handleFromCache = nodeManager.LookupNodeInComponentCache(
nodeManager.SystemContext,
nodeHandle);
//-- Assert
Assert.That(handleFromCache, Is.Not.Null);
nodeManager.RemoveNodeFromComponentCache(nodeManager.SystemContext, nodeHandle);
handleFromCache = nodeManager.LookupNodeInComponentCache(
nodeManager.SystemContext,
nodeHandle);
Assert.That(handleFromCache, Is.Not.Null);
nodeManager.RemoveNodeFromComponentCache(nodeManager.SystemContext, nodeHandle);
await Task.CompletedTask.ConfigureAwait(false);
}
private static async Task<(bool IsSuccess, Exception Error)> RunTaskInParallelAsync(
Func<Task> task,
int iterations)
{
using var cancellationTokenSource = new CancellationTokenSource();
Exception error = null;
int tasksCompletedCount = 0;
ParallelLoopResult result = Parallel.For(
0,
iterations,
new ParallelOptions(),
async _ =>
{
try
{
await task().ConfigureAwait(false);
}
catch (Exception ex)
{
error = ex;
cancellationTokenSource.Cancel();
}
finally
{
tasksCompletedCount++;
}
});
int spinWaitCount = 0;
const int maxSpinWaitCount = 100;
while (iterations > tasksCompletedCount &&
error is null &&
spinWaitCount < maxSpinWaitCount)
{
await Task.Delay(TimeSpan.FromMilliseconds(100)).ConfigureAwait(false);
spinWaitCount++;
}
return (error == null, error);
}
}
public class TestableCustomNodeManger2 : CustomNodeManager2
{
public TestableCustomNodeManger2(IServerInternal server, params string[] namespaceUris)
: base(server, namespaceUris)
{
}
public new NodeState AddNodeToComponentCache(
ISystemContext context,
NodeHandle handle,
NodeState node)
{
return base.AddNodeToComponentCache(context, handle, node);
}
public new void RemoveNodeFromComponentCache(ISystemContext context, NodeHandle handle)
{
base.RemoveNodeFromComponentCache(context, handle);
}
public new NodeState LookupNodeInComponentCache(ISystemContext context, NodeHandle handle)
{
return base.LookupNodeInComponentCache(context, handle);
}
public new NodeIdDictionary<NodeState> PredefinedNodes => base.PredefinedNodes;
public new virtual void AddPredefinedNode(ISystemContext context, NodeState node)
{
base.AddPredefinedNode(context, node);
}
}
}