Files
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

182 lines
8.2 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.Threading;
using System.Threading.Tasks;
using Opc.Ua;
using Opc.Ua.Server.Fluent;
namespace Quickstarts.ReferenceServer
{
/// <summary>
/// Fluent wiring for the CTT reference server methods.
/// </summary>
/// <remarks>
/// The method nodes and their input/output argument declarations are
/// baked into the NodeSet2 model via <c>&lt;Name&gt;MethodType</c>
/// declaration nodes that the instance methods point at through
/// <c>MethodDeclarationId</c>. The source generator therefore emits a
/// typed <c>OnCall</c> overload for every method, so the call handlers
/// can be expressed as plain lambdas instead of hand-written
/// <c>GenericMethodCalledEventHandler</c> callbacks that unpack and
/// repack <c>Variant</c> arguments by index.
/// </remarks>
public partial class ReferenceNodeManager
{
partial void Configure(IReferenceNodeManagerBuilder builder)
{
// No inputs, no outputs.
builder.CTT.Methods.Methods_Void
.OnCall(() => { });
// float + uint -> float.
builder.CTT.Methods.Methods_Add
.OnCall((value, count) => value + count);
// short * ushort -> int.
builder.CTT.Methods.Methods_Multiply
.OnCall((op1, op2) => op1 * op2);
// int / ushort -> float.
builder.CTT.Methods.Methods_Divide
.OnCall((op1, op2) => op1 / (float)op2);
// short - byte -> short.
builder.CTT.Methods.Methods_Substract
.OnCall((op1, op2) => (short)(op1 - op2));
// string -> string.
builder.CTT.Methods.Methods_Hello
.OnCall(value => "hello " + value);
// string -> void.
builder.CTT.Methods.Methods_Input
.OnCall(_ => { });
// void -> string.
builder.CTT.Methods.Methods_Output
.OnCall(() => "Output");
// Value-write handler for the simulation Enabled control variable.
// The node and its value are baked into the NodeSet2 model; only the
// write behaviour is wired here (Prio 2).
builder.CTT.Scalar.Scalar_Simulation.Scalar_Simulation_Enabled
.OnWrite((context, node, ref value) =>
{
try
{
m_simulationEnabled = (bool)value;
return ServiceResult.Good;
}
catch (Exception e)
{
m_logger.ErrorWritingEnabledVariable(e);
return ServiceResult.Create(e, StatusCodes.Bad, "Error writing Enabled variable.");
}
});
builder.CTT.Scalar.Scalar_Simulation.Scalar_Simulation_Interval
.OnWrite(OnWriteInterval);
// The two event-trigger variables raise a simple event when written.
builder.CTT.NodeIds.NodeIds_Events.NodeIds_Events_TriggerNode01
.OnWrite(RaiseTriggerEventAsync);
builder.CTT.NodeIds.NodeIds_Events.NodeIds_Events_TriggerNode02
.OnWrite(RaiseTriggerEventAsync);
async ValueTask<AttributeWriteResult> RaiseTriggerEventAsync(
ISystemContext context,
NodeState node,
Variant value,
CancellationToken cancellationToken)
{
_ = value;
var e = new BaseEventState(null);
e.Initialize(
context,
node,
EventSeverity.Medium,
new LocalizedText($"Trigger event from '{node.DisplayName.Text}'"));
BaseObjectState notifier = m_historicalEventNotifier ??
throw new ServiceResultException(
StatusCodes.BadConfigurationError,
"The historical CTT event notifier is not configured.");
await notifier.ReportEventAsync(
context,
e,
cancellationToken).ConfigureAwait(false);
return new AttributeWriteResult(ServiceResult.Good);
}
// AccessLevelEx advertises non-atomic read/write on the read/write
// static scalar. It cannot be expressed in the NodeSet2 model (the
// UANodeSet schema has no AccessLevelEx attribute), so it is applied
// here through the fluent .Node escape hatch (Prio 2). The divergent
// UserAccessLevel values, in contrast, are now baked directly into
// the NodeSet2 model (Prio 1) and loaded by the source generator.
// The bits are added to the AccessLevel loaded from the model (and
// the StatusWrite / TimestampWrite bits added after loading), so the
// low byte stays consistent with AccessLevel and UserAccessLevel.
builder.CTT.Scalar.Scalar_Static
.Scalar_Static_NonatomicReadWrite.Node.AccessLevelEx |=
AccessLevels.CurrentReadOrWrite |
(uint)AccessLevelExType.NonatomicRead |
(uint)AccessLevelExType.NonatomicWrite;
// The CTT (Address Space Atomicity 001.js) looks for a non-atomic variable in the
// first 10000 variables of its cache, sorted by NodeId string. The 5000 mass
// variables sort before Scalar_Static_*, so a second non-atomic variable lives in
// the AccessRights folder, which sorts first.
builder.CTT.AccessRights.AccessRights_AccessAll
.AccessRights_AccessAll_NonatomicReadWrite.Node.AccessLevelEx |=
AccessLevels.CurrentReadOrWrite |
(uint)AccessLevelExType.NonatomicRead |
(uint)AccessLevelExType.NonatomicWrite;
}
/// <summary>
/// Registers the periodic value simulation on the fluent builder. The
/// dynamic nodes are collected imperatively in
/// <see cref="RegisterSimulationVariables"/> (they are baked into the
/// NodeSet2 model, but the fluent surface has no per-variable
/// random-value model), while the periodic loop that pushes fresh
/// random values to them is expressed here via
/// <c>Simulation().OnTick(...)</c>. The loop fires at a short fixed
/// resolution and the tick handler applies the writable
/// <c>Scalar_Simulation_Interval</c> value.
/// </summary>
partial void Configure(INodeManagerBuilder builder)
{
builder
.Simulation(s_simulationTickInterval)
.OnTick((_, elapsed, cancellationToken) => RunSimulationStepAsync(elapsed, cancellationToken));
}
}
}