33 Commits

Author SHA1 Message Date
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
Marc Schier 14e995c1d0 Restructure test projects for faster CI (#3767)
Rebalance the heavy test projects of the OPC UA .NET Standard stack so CI test execution can run cleanly in parallel.

### New test projects (Tests/Opc.Ua.<X>.Tests/)
| Project | Files | Sources |
|---|---:|---|
| Opc.Ua.Sessions.Tests | 11 | Conformance/SessionServices (plural to avoid Session namespace collision) |
| Opc.Ua.Subscriptions.Tests | 25 | SubscriptionServices + MonitoredItemServices |
| Opc.Ua.History.Tests | 27 | AlarmsAndConditions, HistoricalAccess, DataAccess, FileSystem |
| Opc.Ua.Lds.Tests | 15 | Discovery, DiscoveryServices, Miscellaneous |
| Opc.Ua.Core.Security.Tests | 39 | Security, Auditing |
| Opc.Ua.InformationModel.Tests | 53 | InformationModel, AddressSpaceModel, AttributeServices, ViewServices, MethodServices, NodeManagement, AliasName |
| Opc.Ua.Core.Encoders.Tests | 11 | Encoder tests extracted from Core.Tests |
| Opc.Ua.Gds.Tests (existing) | +5 | new GDS tests |

### New helper class libraries (Tests/Opc.Ua.<X>.TestFramework/ + Tests/Opc.Ua.Test.Common/)
* Opc.Ua.Client.TestFramework - ClientFixture, ClientTestFramework, ClientTestServerQuotas, ClientTestServices, SessionMock, InProcessCertificateProvider, TestableSession*, Traceable*, Extensions, ReferenceServerWithLimits, Constants, TestFixture, SessionPublishHelper, Mock/MockResponseController.
* Opc.Ua.Server.TestFramework - ServerFixture, ServerFixtureUtils, ServerTestServices, CommonTestWorkers.
* Opc.Ua.Core.TestFramework - EncoderCommon, JsonValidationData, JsonEncodingType, CertificateValidatorAlternate, TestUtils, TemporaryCertificateManager, ApplicationTestData, ApplicationTestDataGenerator.
* Opc.Ua.Test.Common - Logging.cs (the canonical NUnitTelemetryContext helper, moved out of Tests/Common/).

All TestFramework helpers were extracted via `git mv` from the legacy Opc.Ua.Client.Tests / Opc.Ua.Server.Tests / Opc.Ua.Core.Tests projects (no copy-paste).

### Server-side production-code fixes
1. `MasterNodeManager.ValidateMonitoredItem{Create,Modify}Request` - now capture and check the filter validation result (was discarded into `_`).
2. `MasterNodeManager.ReadAsync` - assign `value = values[ii] = value.WithXxxTimestamp(MinValue)` so timestamp filtering survives the DataValue readonly-struct conversion.
3. `ApplicationsDatabaseBase.{FindApplications,QueryApplications,ServerCapabilities}` - Part 12 spec compliance: allow empty applicationUri, allow applicationType==3 for DiscoveryServer, allow empty ServerCapabilities.
4. `LinqApplicationsDatabase.{FindApplications,QueryApplications}` - empty filter returns all entries; pagination `nextRecordId` off-by-one fix.

### CI flake guards
* `FastKeepAliveCallbackAsync` - relaxed timing threshold and Assert.Ignore on slow CI runners.
* `SecurityCertValidationTests` - Assert.Ignore on BadConnectionClosed/BadRequestTimeout/BadSecureChannelClosed from server channel exhaustion on Azure Linux runners.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-05-24 06:23:16 +02:00
Marc Schier 889572472f Convert DataValue from class to readonly struct for further GC relief (#3796)
Convert `DataValue` from a mutable reference type (`class`) to a `readonly struct` to eliminate per-allocation GC pressure on every attribute read, subscription publish, and history sample.

### Key API changes (user-visible)

| Before | After | Pattern |
|---|---|---|
| `class DataValue` | `readonly struct DataValue : INullable` | Foundation |
| `Equals(DataValue?)` / `operator ==(DataValue?, DataValue?)` | `Equals(DataValue)` / `operator ==(DataValue, DataValue)` | Value semantics |
| `IEncoder.WriteDataValue(string?, DataValue?)` | `IEncoder.WriteDataValue(string?, DataValue)` | Non-nullable wire API |
| `IDecoder.ReadDataValue(...) -> DataValue?` | `IDecoder.ReadDataValue(...) -> DataValue` | Same |
| `IDataChangeMonitoredItemQueue.PeekLast/Oldest()` | `TryPeekLastValue/Oldest(out DataValue)` | TryGet pattern |
| `IAggregateCalculator.GetProcessedValue(bool)` | `TryGetProcessedValue(bool, out DataValue)` | Same |
| `IUaPubSubDataStore.ReadPublishedDataItem(...)` | `TryReadPublishedDataItem(NodeId, uint, out DataValue)` | Same |
| `Dictionary<uint, DataValue?>` (NodeCacheContext) | `Dictionary<uint, DataValue>` | Default + IsNull |
| `IHistoryDataSource.FirstRaw/NextRaw` | `TryFirstRaw/TryNextRaw(out DataValue)` | TryGet pattern |
| `NodeState.ReadAttribute(... DataValue)` | `NodeState.ReadAttribute(... ref DataValue)` | Sync mutation via ref |
| `NodeState.ReadAttributeAsync(... DataValue)` | `NodeState.ReadAttributeAsync(...) -> ValueTask<(ServiceResult, DataValue)>` | Async return tuple |
| `obj as DataValue` (heterogeneous Dictionary<string, object>) | `obj is DataValue dv ? dv : default(DataValue)` | Safe struct cast |
| `Assert.That(dv, Is.Not.Null)` (tests) | `Assert.That(dv.IsNull, Is.False)` | Struct test pattern |
| `[Obsolete] Value` setter, all property setters | Removed; use ctor or `With*()` | Immutability |
| `[DataContract]` + `[DataMember]` | Removed; surrogate via `SerializableDataValue` + `DataValueSurrogateProvider` | Serialization |

### Wire format

Wire format is **byte-identical** to the previous class-based implementation across binary / JSON / XML encoders. Default DataValue (`.IsNull == true`) is treated as the equivalent of the old null reference (writes JSON `null`, binary `byte 0`, XML omitted element).

### Why TryGet pattern (instead of leaving `DataValue?`)

For methods that previously returned `DataValue?` to signal "no value available" (queue peek, aggregate result, data store lookup, history navigation), the conversion to `bool TryGet(out DataValue)` matches BCL conventions (`Dictionary.TryGetValue`, `Queue.TryPeek`, `Int32.TryParse`) and gives the caller an explicit "may be absent" affordance without `Nullable<DataValue>` overhead.

### Breaking changes summary

- `DataValue` is now a `readonly struct` - boxing/unboxing semantics change for callers using `object`-typed APIs.
- `IEncoder.WriteDataValue` / `IDecoder.ReadDataValue` / `ReadDataValueArray` interface signatures lose the `Nullable` wrapper.
- `IDataChangeMonitoredItemQueue.PeekLastValue` / `PeekOldestValue` -> `TryPeekLastValue` / `TryPeekOldestValue` (out parameter).
- `IAggregateCalculator.GetProcessedValue` -> `TryGetProcessedValue` (out parameter).
- `IUaPubSubDataStore.ReadPublishedDataItem` -> `TryReadPublishedDataItem` (out parameter).
- `NodeState.ReadAttribute` takes `ref DataValue`; `ReadAttributeAsync` returns `ValueTask<(ServiceResult, DataValue)>`.
- `DataValue` property setters removed (use constructor + `With*` mutators).
2026-05-23 11:38:49 +02:00
Marc Schier 70b4498db8 Certificate manager and ref counted certificate type (#3688)
* New certificate and secrete abstraction with certificate infrastructure and certificate/secret stores. 
* leak testing for certificate resources to validate new ref counting in every test assembly
* Migration guide updated and documentation added for all
* Remove IDisposable from Nodestate and UserIdentity.
* UserCertificateTokenHandler now just points into certificate registry/stores, no dispose required
* Fix CA2000 warnings and cleanup of other diagnostics, increase warning levels in .editorconfig
2026-05-12 07:56:38 +02:00
Copilot 54cc3d88b1 Prepare for C# 15 union types: UnionAttribute polyfill, TryGetValue rename, HasValue (#3727) 2026-05-02 18:33:46 +02:00
Marc Schier fd41681f4b Add support to publish OPC UA applications as Native AOT (#3633)
* make most ptojects aot compatible
* Remove newtonsoft
* Migrate all projects from Mono.Options to System.CommandLine 2.0.5
* Fix array clone
* Replace serializers for storage using new attribute driven  type geberator
* Add new AOT integration tests covering all functional areas
* Documentation updates
2026-04-13 20:52:29 +02:00
Marc Schier 5a1e547250 Code cleanup and modernization of test assertions to comply with project standards. (#3631) 2026-03-19 21:09:40 +01:00
Marc Schier 03777ecb09 New Json decoder/encoders, array/matrix abstractions, ByteString, and more. (#3619)
- **Collections overhaul** — new/rewritten collection types (`ArrayOf`, `Collections` commits)
- **`Variant` builder/accessor** — new APIs for constructing and accessing Variants
- **`NodeId` operators made explicit** — breaking change for implicit conversions
- **Version bumped to 1.6** with preview build support
- **NumericRange** uses Variant
- **object** type accessors and general usage removed.

### 🏗️ Infrastructure
- Build config updated; `.NET 10` targeting
- InternalsVisibleTo moved to `.csproj`
- Pipeline/CI adjustments
2026-03-18 12:23:30 +01:00
Marc Schier f66ceffd75 Immutable built in types and code generation (#3534)
Generate stack and application code using source generators
Change built in types to readonly structs
  Update localized text implementation to use JSON text serializer
  Status code with symbolic names
  Immutable node ids
  No boxing for all built in types <= 8 bytes in Variant.
Split user identity token and token handling via token handler
Add migration guide for breaking changes
2026-02-12 16:27:07 +01:00
Marc Schier 2960388560 Update headers and license files (#3388)
Update license headers to copy right year 2025, replace RCL/GPL headers with MIT, replace the nuget license with MIT (via license expression).
2025-12-04 19:44:40 +01:00
Marc Schier 1c178402ad Refactor client state persistence and add more tests (#3303)
* State handling and better serialization
* Nullable for almost everything  inclient library
* Additional testing of session
2025-11-01 17:18:48 +01:00
Marc Schier ff0095c93d Make GDS tests stable and add better logging to unit tests (#3271)
- Allow setting ReturnDiagnostics on the session factory to ensure the diagnostic settings are part of "Create" also.  Set them to SymbolicIdAndText by default.
- Better logging in unit tests, now also logs to progress including exception traces, also prefixes SERVER and TEST on console to attach the logs to the server or client side.
- GDS client stability improvements to ensure client reliably reconnects between calls when connection is lost.
- Do not dispose the application certificate when it is updated from GDS client to avoid existing sessions to crash with CryptographicException.  This needs more improvements later on because it is rather hacky today.
- Remove the certificate cache in CertificateFactory (as per discussion and agreement) which allowed re-enabling the older UserIdentity API
- Logging improvements here and there to analyze issues in unit tests better
2025-10-20 18:02:45 +02:00
Marc Schier 8e7a73c7df Introduce telemetry context and proper use of ILogger (#3213) 2025-09-25 20:25:31 +02:00
Marc Schier 25ba2a2d08 Make sync client api obsolete (#3174) 2025-08-27 06:05:36 -07:00
Marc Schier 9830e5d53e Enable roslynizer and fix all analyzer issues (#3157)
* Fix warnings and suggestions
* Enable roslynator
2025-08-16 04:10:24 -07:00
dependabot[bot] 60689c9431 Bump NUnit from 3.14.0 to 4.1.0 (#2535)
* Bump NUnit from 3.14.0 to 4.1.0

Bumps [NUnit](https://github.com/nunit/nunit) from 3.14.0 to 4.1.0.
- [Release notes](https://github.com/nunit/nunit/releases)
- [Changelog](https://github.com/nunit/nunit/blob/master/CHANGES.md)
- [Commits](https://github.com/nunit/nunit/compare/v3.14.0...4.1.0)

---
updated-dependencies:
- dependency-name: NUnit
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

* fix Build by adding: using Assert = NUnit.Framework.Legacy.ClassicAssert;

Co-authored-by: Roman Ettlinger <romanett98@gmail.com>
2024-04-22 13:29:30 +02:00
bhnaphade 4c58c1ff16 Improve JsonEncoder.EscapeString and fix test warnings for ToString() (#2527)
Update the function to improve performance. 
Fix test code warnings (CA1305) related to ToString() method

Based on the results of the benchmark runs, `EscapeStringLegacyPlus` was picked for all platforms that do not support `StreamWriter.Write(ReadOnlySpan<char>)`, e.g. .NET Framework. There is a slight improvement for the cases which require a 4 digit hex encoding.
For platforms that support Span end to end `EscapeStringSpanCharsInline` was picked. The functions tries to optimize how often the underlying StreamWriter is called by combining calls to Write into to slices. It was also noted that up to three character strings, it performs better to do single character writes than calling with a small string.
2024-02-21 13:59:16 +01:00
bhnaphade 08c83c2f5b Trace information propagation Client to Server side (#2442)
Update OPC UA stack to pass activity trace information from client to server
2024-01-16 22:22:59 +01:00
Martin Regen 71ad9afd1c Nested complex types which contain structure derived from an abstract type are not correctly encoded (#2349)
- bug: if the nested complex type is derived from an abstract type like a Union, the decoder uses the abstract type instead of the actual type to decode
- fix: the loop to determine the supertype of the type to be decoded stops too early and returns an invalid type reference, e.g. for Unions. Instead the loop will now continue until a valid BuiltInType or a Structure or Enumeration type is found.
2023-10-26 11:06:26 +02:00
Martin Regen d47bc853da Various async improvements and minor issues found in IOP testing (#2346)
- improve various log messages, comments etc.
- multiple internal improvements in naming convention handling of async functions
- add FetchSuperTypesAsync
- replace new UTFEncoding() with Encoding.UTF8 singleton
2023-10-20 21:29:03 +02:00
Martin Regen 1e535dda09 Support client activities on all target platforms (#2256)
- Add the system diagnostics library for unsupported target platforms
- Integrate in clientfixture by adding IDisposable to support to enable/disable the activity tracing
- fix Traceable session dispose issue, do not null the disposed session
2023-08-10 09:48:36 +02:00
bhnaphade cfb3ac49bf Support ActivitySource in OPC UA client to enable tracing (.NET6) (#2251)
- Add traceable client session with factory to support ActivitySource on .NET 6
- Only traces the public API calls, inner calls are not yet supported.
- Uses the name: Opc.Ua.Client-TraceableSession-ActivitySource
2023-08-04 12:11:05 +02:00
Martin Regen fe1255298d TestData sample structure compliance (#2175)
- The StructureValue DataType value has a Method and event as childs, but it may only have variables / properties.
- Uses latest generated code from Modelcompiler which fixes issues with child variables read/write/monitoring.
2023-06-14 16:46:06 +02:00
Martin Regen 043a56c3f2 Deprecate .NET framework 4.6.2 support, sync with samples repo (#2165)
- Deprecate support for Nuget package support of .NET Framework 4.6.2
- Bump sample applications to 4.8
- update some copyright headers / supporting files (editorconfig etc.)
- fix a few warnings
- fix an issue with `SessionReconnectHandler`, in certain combination of reconnect period and exponential backoff the .NET sample app never reconnected.
2023-05-31 18:53:56 +02:00
Martin Regen b5d4dd79cf Check DiscoveryOnly before the message is parsed. (#2112)
A discovery only channel only accepts discovery service calls. The type of service call should be checked before the message is parsed. 
- Add a check for discovery message before the chunks are decoded.
- Add a check that discovery service call are below a restricted message size (e.g. 64k).
- Add a test case.
2023-04-11 08:20:28 +02:00
Martin Regen 241583def4 Add structure to Quickstart server TestData (#2008)
- Rebuild designs with latest ModelCompiler (docker)
- Add the scalar value datatype as structure with properties
- Uses update to Modelcompiler: https://github.com/mregen/UA-ModelCompiler/tree/structures2
2023-03-17 10:44:50 -07:00
Marc Schier 65f9757b91 Add an API to ComplexTypeSystem to retrieve data type definitions used during loading (#2039)
The changes add an API to ComplexTypeSystem to retrieve data type definitions that were created during type building to leverage them to build DataSetMetaDataType for OPC UA PubSub.  

The changes include the following:

* Combine all conversion of enumerations into EnumDefinition and use the resulting to build the type
* Remove all other API from the type builder interface and implementation. 
  > The assumption is that these interfaces are used internally and removal will not cause a breaking change.
* Combine everything previously covered elsewhere into existing AddEnumType function.
* Add a NodeIdDictionary cache and fill that cache during load, as well as API to retrieve the data type definitions
2023-01-09 16:08:06 +01:00
Ivan van Heerden 1f2a30d7ca Add abstraction 'ISession' for Session object in the Client library (#1702)
Expose an 'ISession' interface as abstraction to ease unit testing. 

Breaking changes are kept to minimal impact, but some changes maybe required to use ISession objects instead of Session.

Note: ISessionClientMethods is hand created, not yet by ModelCompiler
2022-10-07 20:11:53 +02:00
Martin Regen cfc68eeb10 Use .NET analyzers instead of Roslynator, fix warnings, no bug fixes (#1729)
-use latests analyzers in .NET instead of Roslynator.
-fix warnings and formatting, no bug fixes!
2022-03-14 16:39:09 +01:00
Martin Regen 7d9be41cf5 Doc updates and fixes for .368 preview, ref server improvements (#1695)
- Doc, docs, docs updates for new 368 support
- fix a missing null pointer check when ConditionRefresh is run
- Ref server: move NodeManager factory API to StandardServer, decoupling the NodeManager implementation from Ref server
- Ref server: add shadow mode flag, to allow to map a docker configuration in a mapped folder.
- Ref server: sample batch files how to run Github CR and local docker images
- Improve some misleading 'delete application certificate' log messages.
2022-02-11 09:19:40 +01:00
Martin Regen fa6099b7ee Support semantic logging (#1648)
- For EventSource and legacy logger refactor logging to support the built in LogValueFormatter, which provides the format strings suitable for `string.Format`.
- **Breaking change**: For `TraceEvent` this is a breaking change, because there is no implementation yet to support to provide the reformatted format string. With this implementation if a logging framework is used which supports the semantic logging, there is no issue. With frameworks which do not understand semantic logging strings(e.g. log4net) it is a breaking change, string.format will throw exceptions --> move to ILogger hook using `SetLogger`. 
- **Warning**: When Microsoft.Extensions.Logger based loggers are used, format strings must follow this convention:
i) All variable entries must follow order and count up, e.g. "{0} -- {1}" etc., no mix of "{2}--{0}"
ii) in the same way the args must follow this strict ordering. 
- Format strings will be changed by future PR to include the semantic values.
2022-01-12 14:51:22 +01:00
Martin Regen 2430a651ea Enforce Roslynator checks in CI build (#1608)
- The ci pass includes Roslynator checks, fails on warnings
- Fix all existing warnings
2021-11-24 14:44:31 +01:00
Martin Regen 3b233c6f55 Bug fixes in ref server and more tests cases (#1590)
- fix the complex types of the test nodeset (requires https://github.com/OPCFoundation/UA-ModelCompiler/pull/96)
- improve some client / server tests
- add tests for complex types datatype definition integrity on ref server, validate bsd and xml dictionaries in the test server (open issue:  https://mantis.opcfoundation.org/view.php?id=7393, xml validation always failing)
- improve server fixture, to allow for custom config changes 
- fix an issue that caused kestrel not start on windows/.NET Core 3.1 and above, when a new certificate was issued, thereby ignoring all https client tests.
2021-11-11 06:39:23 +01:00