305 Commits

Author SHA1 Message Date
Marc Schier a81d981755 dotnet format sweep (whitespace, IDE, RCS) + code-style enforcer agent fix (#3865)
# Description

Pure code-style sweep across the repo — no behavioral changes. Drives
`dotnet format` info-level diagnostics down on a large slice of the
codebase (Stack, Libraries, Tests, Tools).

Six commits, applied bottom-up in safety order so each batch leaves the
build green:

1. **`style: fix whitespace and final-newline formatting (WHITESPACE,
FINALNEWLINE)`**
   197 hits across ~30 files; pure mechanical cleanup.

2. **`style: apply dotnet format style fixes (IDE rules)`**
IDE-rule batch via `dotnet format style --severity info` —
`var`/explicit type, simplify names, collection expressions, expression
bodies, unused usings, etc.

3. **`style: apply dotnet format analyzers fixes (RCS blank-line
formatting)`**
   Roslynator formatting (RCS0xxx) blank-line and punctuation rules.

4. **`style: convert comments to doc comments and inline local vars
(RCS1181, RCS1124)`**
24 files. RCS1181 promotes `// summary`-style comments above
public/internal members to `/// <summary>` doc comments; RCS1124 inlines
locals used exactly once. Generated `Tools/` files were reverted to keep
the source-generator outputs deterministic.

5. **`docs(agent): correct --diagnostics flag form and verify Roslynator
4.x code fixers`**
Updates `.github/agents/opc-ua-codestyle-enforcer.agent.md` with two
corrections discovered while running this sweep:
- `dotnet format --diagnostics "RULE1 RULE2"` (single quoted,
space-separated) silently fixes nothing on `dotnet format` 10.x — it
parses as one unknown ID and exits 0. The correct form is `--diagnostics
RULE1 --diagnostics RULE2 …`, repeated per rule.
- Roslynator 4.15.0 **does** ship code fixers for
RCS1078/1118/1124/1140/1142/1181/1221/1260 (the previous "no auto-fixer"
list was outdated). RCS1140/1142 default to `Hidden` so need `--severity
info` to surface and fire; RCS1078 requires
`roslynator_empty_string_style = field` (already set in
`.editorconfig`). Only NUnit4002/2046/2010 genuinely lack auto-fixers in
this stack.

6. **`style: format new code from master merge (dotnet format sweep)`**
After merging master into the branch (commit `e3ebc8742`), re-ran the
same three-phase format sweep on the 151 .cs files brought in by the
merge, scoped per project via repeated `--include`. 81 files changed;
same rule families as commits 1–4.
- Hand-fixed `Tests/Opc.Ua.MigrationAnalyzer.Tests/AnalyzerHarness.cs`
for `RCS1174` (redundant `async`/`await` removal) because the auto-fixer
didn't apply for that specific case.
   - Reverted files that the formatter would break:
- `Libraries/Opc.Ua.Server/Server/ServerInternalData.cs` — multi-TFM
analysis disagreement injected `<<<<<<<` / `=======` / `>>>>>>>`
markers.
-
`Tools/Opc.Ua.MigrationAnalyzer.Core/{Core/Stack/Client/ChannelBase.cs,
Core/Stack/Types/IUserIdentityTokenHandler.cs,
Client/Session/Session.cs}` — IDE0005 removed `using
Opc.Ua.Security.Certificates` that IS used (the files are 1.5.378
reference fixtures for the analyzer).
- `Tests/Opc.Ua.Gds.Tests/PushTest.cs` — IDE0002 over-simplified
`OpcUa.ObjectTypeIds` to `ObjectTypeIds`, which then resolves to a
conflicting type.

### What this PR does **not** touch

- No behavioral or semantic logic changes.
- No `.editorconfig` rule promotions (rules stay at their current
severities; this is a backlog-burndown pass, not a rule tightening).
- Generated source under `Tools/` is intentionally excluded.
- Higher-risk rule families (`RCS1090`/`CA2007` `ConfigureAwait`,
`RCS1249` null-forgiving cleanup, `IDE0270`/`IDE0059`) are left for
follow-up sweeps because they need per-TFM build verification or
semantic review.

## Related Issues

_No tracking issue — this is a non-functional style sweep and the
agent-doc correction is a follow-up to the same work. Happy to open one
if the maintainers prefer._

## Checklist

- [ ] 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. _(N/A — style-only, no
behavioral change)_
- [x] I have added all necessary documentation. _(agent doc updated with
the two corrections)_
- [x] I have verified that my changes do not introduce (new) build or
analyzer warnings. _(verified clean on `net10.0` and `net48`; only
pre-existing `NETSDK1005`/`NETSDK1207` failures on Tools/AOT projects)_
- [ ] I ran **all** tests locally using the **UA.slnx** solution against
at least .net **framework** and .net **10**, and all passed. _(build
verified on net10 and net48 per batch; full test suite not yet run
locally — relying on CI)_
- [ ] I fixed **all** failing and flaky tests in the CI pipelines and
**all** CodeQL warnings.
- [ ] I have addressed **all** PR feedback received.

---------

Co-authored-by: agent <agent@local>
2026-06-10 08:35:44 +02:00
Marc Schier 15eb55c46e Cert rotation: force renegotiate (#3562) + auto-detect on client (#3160) (#3849)
# Description

Implements the OPC UA Part 12 §7.10.9 contract on the server (fixes
#3562) AND the client-side counterpart for immediate detection of
own-cert / trust-list / CRL changes (fixes #3160).

## Server side (#3562)

Per Part 12 §7.10.9 the server _shall_ "force existing SecureChannels
affected by the changes to renegotiate" once the `ApplyChanges` method
response has been delivered. Previously the server reloaded the
certificate but did not cut affected channels; clients kept using the
old cert until natural rekey, and the code carried an explicit `TODO`
next to a 1-second `Task.Delay` hack in
`ConfigurationNodeManager.ApplyChanges`.

Key server changes:

* **New optional capability interface**
`Opc.Ua.ITransportListenerCertificateRotation` (single method
`CloseChannelsForCertificate(Certificate)`) — implemented by
`TcpTransportListener` and `HttpsTransportListener`. Custom transport
listeners can opt in without breaking `ITransportListener`.
* **TCP path**: new internal
`TcpListenerChannel.TryCloseForCertificateRotation(oldThumbprint, out
globalChannelId)` matches the channel's negotiated `ServerCertificate`
by thumbprint, sends `BadCertificateInvalid`, and calls
`ChannelFaulted()` to actually close the socket.
`TcpTransportListener.CloseChannelsForCertificate` snapshots
`m_channels` outside `m_lock` to avoid lock inversion, invokes the
per-channel helper, returns cut global channel ids. **The listener
socket stays bound** — clients can reconnect immediately.
* **HTTPS path**: HTTPS owns the cert at the Kestrel/HTTP.sys listener
level, so a `Stop()`+`Start()` cycle is the only practical
force-renegotiate. Moved out of `CertificateUpdate` (which now does only
the soft fan-out) into `CloseChannelsForCertificate` so the staging
event no longer disrupts in-flight requests prematurely.
* **`ConfigurationNodeManager.ApplyChanges`** rewritten:
- Captures the per-group pre-transaction certificate (preserved across
multi-stage transactions per Part 12 §7.10.2) and the staged
`UpdateCertificateData`.
- Schedules a deferred apply: waits for the response to flush, re-syncs
the registry via `CertificateManager.UpdateAsync`, then calls
`CloseChannelsForCertificate` on every listener that implements the
capability.
- **Configurable grace period**: new
`IConfigurationNodeManager.ApplyChangesGracePeriod` (default 250 ms,
negative clamped to zero). Hosts running over higher-latency
administrative links can raise it.
- Exposes
`IConfigurationNodeManager.DrainPendingApplyChangesAsync(CancellationToken)`
for tests/hosts to deterministically await rotation.
  - Removes the explicit 1-second `Task.Delay` TODO hack.
* **`Opc.Ua.Server.ITransportListenerRegistryProvider`** — narrow opt-in
interface on `ServerInternalData` exposing the live transport listener
list. Lets `ConfigurationNodeManager` drive the fan-out without
expanding `IServerInternal` (binary compat for mocked test fixtures).
* **Sessions are NOT closed**. Per spec, the cut is on the SecureChannel
only; existing `Session.IsSecureChannelValid` + `Session.Activate`
rebind handles transfer over the new channel.

## Client side (#3160)

The client SDK previously had no automatic detection of changes to its
own certificate, trust list, or CRL — users had to call
`Session.ReloadInstanceCertificateAsync` manually and trigger a
reconnect. The spec-mandated `ApplicationCertificateUpdated`,
`TrustListUpdated`, and `CrlUpdated` enum values existed but only the
first was being emitted by `CertificateManager`.

Key client/shared changes:

* **`CertificateManager` now emits `TrustListUpdated` and `CrlUpdated`**
from `WriteTrustListAsync` (per mask) and from
`TrustListTransaction.CommitAsync` (after the atomic apply). The new
internal `NotifyTrustListChanged` also invalidates cached
peer/user/HTTPS validation cores so subsequent validations pick up the
fresh trust state.
* **`ManagedSession.AutoReconnectOnCertificateChange`** opt-in property
(default `false` for backwards compat). When `true`, `ManagedSession`
subscribes to `CertificateManager.CertificateChanges` on construction
and, on the three relevant kinds:
- Calls `Session.ReloadInstanceCertificateAsync` on
`ApplicationCertificateUpdated` so the next ActivateSession is signed
with the rotated client cert.
- Triggers a reconnect via the state machine so the new state is
honoured within milliseconds rather than at the next
`SecurityTokenLifetime` rekey.
* **`ManagedSession.ApplicationCertificateChanged`** event surfaces
every observed change regardless of the auto-reconnect policy for
diagnostics or custom rotation logic.
* Subscription is disposed by the existing `Dispose` / `DisposeAsync`
paths.

```csharp
using var managed = await ManagedSession.CreateAsync(
    configuration, endpoint, sessionFactory);
managed.AutoReconnectOnCertificateChange = true;

managed.ApplicationCertificateChanged += (sender, e) =>
{
    Console.WriteLine($"observed {e.Kind} on {e.TrustList}");
};
```

## Tests

| Suite | net10.0 | net48 |
|---|---|---|
| `TransportListenerCertificateRotationTests` (new, 6 tests) | ✅ | ✅ |
| `CertificateManagerTests` (4 new event tests) | ✅ 22/22 | ✅ 4/4 |
| `PushCertManagement` | 50/53 ✅ | 50/53 ✅ |
| `GDS PushTest` (focused subset) | 15/15 ✅ | 16/16 ✅ |
| `Opc.Ua.Server.Tests` (focused subset) | 38/38 ✅ | 38/38 ✅ |
| `GDS PushTest` (full) | 313/338 ✅ | — |

Skips are pre-existing (cert-type mismatches, optional methods) — no
regressions.

New integration test
`PushTest.ApplyChangesForcesChannelRenegotiateAsync` positively asserts
the stale channel fails with a recognized channel-invalidation status
after `ApplyChanges`, and that a fresh reconnect succeeds with the
rotated cert.

## Documentation

- `Docs/CertificateManager.md` — new sections:
- "Server-Side Certificate Rotation via Push (OPC UA Part 12 §7.10.9)" —
`ITransportListenerCertificateRotation` contract + custom listener
example.
- "Client-Side Auto-Detection of Certificate Changes (issue #3160)" —
`AutoReconnectOnCertificateChange` + `ApplicationCertificateChanged`
event + the three covered scenarios.

## Related Issues

- Fixes #3562
- Fixes #3160

## Checklist

- [ ] 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 focused tests locally using the **UA.slnx** projects against
.net **framework 4.8** and .net **10**, and all passed. _(Full UA.slnx
test run delegated to CI.)_
- [ ] I fixed **all** failing and flaky tests in the CI pipelines and
**all** CodeQL warnings.
- [ ] I have addressed **all** PR feedback received.
2026-06-08 12:19:49 +02:00
Marc Schier 4756e7c245 DI (OPC 10000-100) with samples (Pump, SW Update), fluent API gap closures and model dependency implementation (#3808)
This PR implements the **OPC UA Device Integration (DI, OPC 10000-100)**
companion-spec library trio (`Opc.Ua.Di` / `Opc.Ua.Di.Server` /
`Opc.Ua.Di.Client`) plus a worked example
(`Applications/MinimalPumpServer`) demonstrating the OPC 40223 Pumps
companion specification end-to-end with full simulation. It also closes
11 fluent-API gaps in `Opc.Ua.Server.Fluent`, three source-generator
bugs, integrates the DI layer into the unified `services.AddOpcUa()`
Microsoft.Extensions DI hosting pattern, and adds 250+ new tests.

**Worked example — `Applications/MinimalPumpServer/`**
- AOT-compatible console host using `Host.CreateApplicationBuilder` +
`AddOpcUa()`.
- `PumpNodeManager` inherits from `DiNodeManager`; multi-namespace (DI +
Machinery + Pumps) via runtime NodeSet2 loading and
`ModelLoaderBuilder`.
- Demonstrates declarative second-pump creation via
`.ConfigureDevicesFor<PumpNodeManager>(...)` and software-package
seeding from the same configurator.
- Full simulation: pressure, temperatures, power, flow, efficiency,
level, cavitation/overheat fault injection, alarm setup, NAMUR-style
supervision.

**Documentation**
- `Docs/Opc.Ua.Di/` — README, DeviceBuilder, Hosting, LockService,
SoftwareUpdate, ClientHelpers (6 new developer guides).
- `Docs/Opc.Ua.Di/ComplianceMatrix.md` — every DI declaration mapped to
In-v1 / Generated / Deferred / Excluded.
- `Docs/CompanionSpecLibraries.md` — packaging guide for new
companion-spec libraries.
- `Docs/FluentApiGaps.md` — historical record of G1–G11.
- `Docs/SourceGeneratedNodeManagers.md` updated for richer node
managers.
- `Docs/plans/StateMachineBuilder.md` — deferred state-machine builder
design.
2026-06-04 05:57:57 +02:00
Suciu Mircea Adrian 82993d0b6f Allow application certificate lookup to use entries configured with abstract ApplicationCertificateType only as fallback candidates. (#3752)
## Proposed changes

Tries to rectify inconsistent behavior:
`SecurityConfiguration::BuilldSupportedSecurityPolicies()` advertises
RSA policies if ApplicationCertificateType is set as CertificateType,
while ApplicationCertificateType is not used when finding actual
certificates.

Use CertificateIdentifier::SetCertificate(certificate) to recalculate
the CertificateType whenever the identifier receives a X509Certificate2.

Removed stale if case` if (certType ==
ObjectTypeIds.ApplicationCertificateType)` from
`SecurityConfiguration::FindApplicationCertificateAsync`, since
`CertificateIdentifier.MapSecurityPolicyToCertificateTypes(securityPolicy)`
never returned 'ApplicationCertificateType' and it was confusing and
misleading because it suggested support for abstract
ApplicationCertificateType, but normal policy lookup did not actually go
through it.

Allow application certificate lookup to use entries configured with
abstract ApplicationCertificateType as fallback candidates.
The fallback loads the candidate certificate first, then validates it
against the concrete type required by the selected security policy.

'ApplicationCertificateType' is not a concrete certificate profile and
should not be prefered in configuration, even if older configurations
may use it. Previously, such entries could be missed during certificate
lookup because the selected security policy maps to a concrete type.

## Related Issues

- Fixes #3644

## Types of changes

What types of changes does your code introduce?
_Put an `x` in the boxes that apply. You can also fill these out after
creating the PR._

- [ ] Bugfix (non-breaking change which fixes an issue)
- [x] Enhancement (non-breaking change which adds functionality)
- [ ] Test enhancement (non-breaking change to increase test coverage)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected, requires version increase of
Nuget packages)
- [ ] Documentation Update (if none of the other choices apply)

## Checklist

_Put an `x` in the boxes that apply. You can also fill these out after
creating the PR. If you're unsure about any of them, don't hesitate to
ask. We're here to help! This is simply a reminder of what we are going
to look for before merging your code._

- [ ] I have read the
[CONTRIBUTING](https://github.com/OPCFoundation/UA-.NETStandard/blob/master/CONTRIBUTING.md)
doc.
- [ ] I have signed the
[CLA](https://opcfoundation.org/license/cla/ContributorLicenseAgreementv1.0.pdf).
- [ ] I ran tests locally with my changes, all passed.
- [ ] I fixed all failing tests in the CI pipelines. 
- [ ] I fixed all introduced issues with CodeQL and LGTM.
- [ ] I have added tests that prove my fix is effective or that my
feature works and increased code coverage.
- [ ] I have added necessary documentation (if appropriate).
- [ ] Any dependent changes have been merged and published in downstream
modules.

## Further comments

If this is a relatively large or complex change, kick off the discussion
by explaining why you chose the solution you did and what alternatives
you considered, etc...
2026-06-04 05:56:37 +02:00
Marc Schier dbc09b8e22 Adopt System.TimeProvider across the stack (fixes #2458) (#3829)
# Description

Adopt
[`System.TimeProvider`](https://learn.microsoft.com/dotnet/api/system.timeprovider)
across the stack so that every place that creates timers, runs duration
math, or schedules periodic work is mockable, deterministic in tests,
and immune to wall-clock changes.

The migration touches Core, Core.Types, Server, Client, PubSub,
Configuration, Gds (server + client), Lds, and the Quickstarts/Console
reference apps. Per-component changes follow the same pattern:

1. Add a `private readonly TimeProvider m_timeProvider;` field.
2. Accept a nullable `TimeProvider? timeProvider = null` as the **last**
constructor parameter (new overload; legacy constructor stays for binary
compatibility and delegates with `timeProvider: null`).
3. Initialise the field with `m_timeProvider = timeProvider ??=
TimeProvider.System;`.
4. Replace `new Timer(...)`, `Stopwatch`, `HiResClock.*`,
`DateTime.UtcNow`-based duration math, and `Task.Delay(delay, ct)` in
timing loops with the matching `m_timeProvider` API (`CreateTimer`,
`GetTimestamp` / `GetElapsedTime`, `GetUtcNow().UtcDateTime`,
`Task.Delay(delay, m_timeProvider, ct)`).
5. Wire the provider through DI: `AddOpcUaServerBuilder` /
`AddOpcUaClientBuilder` register `TimeProvider.System` via
`TryAddSingleton<TimeProvider>()` so tests can swap in
`Microsoft.Extensions.Time.Testing.FakeTimeProvider`.

`HiResClock` itself is kept (so the
`ApplicationConfiguration.DisableHiResClock` schema flag still
round-trips), but **every public member** is now `[Obsolete]` with a
single shared message pointing to the new migration-guide section. The
few internal call sites that still need to set/read `HiResClock` are
wrapped with `#pragma warning disable CS0618`.

### Highlights per component

- **Core / Stack** — `Opc.Ua.Core`, `Opc.Ua.Core.Types`, channel
pipeline (`UaSCBinaryClientChannel`, `ChannelToken`,
`UaSCBinaryChannel`), `ApplicationConfiguration`, certificate
validators, `JwksIssuerKeyResolver`, `TimeProviderExtensions` polyfills
(`GetTimestampMilliseconds`, `GetTickCount`,
`CancellationTokenSource(timeout, timeProvider)`, `Task.Delay(delay,
provider, ct)` polyfill for older TFMs).
- **Server** — session lockout, subscription pipeline
(publish/sample/keep-alive/lifetime), `MonitoredItemQueue`, alarm
sampling rate, `IntervalRunner`, server diagnostics, configuration state
machines, hosted services.
- **Client** — `Session`, managed/V2 subscription engines, reconnect
handlers, channel keep-alive, periodic publishing, complex-type
discovery polling.
- **PubSub** — `IntervalRunner` pipeline, message-receive timers,
MQTT/UDP keep-alive, publishers/readers.
- **Gds / Lds** — `LdsServer`, `LinqApplicationsDatabase` expiry
housekeeping, GDS clients (push, pull), `DirectoryCertificateStore`,
`ConnectionStateMachine`, classic subscription engine.
- **Quickstarts / Console samples** — `SampleNodeManager`,
`ReferenceNodeManager`, `AlarmNodeManager`, `BoilerState`,
`MemoryBufferState`, `PublishedValuesWrites`. Samples resolve via
`(Server as ITimeProviderProvider)?.TimeProvider ?? TimeProvider.System`
so existing ctor signatures stay binary-compatible.
- **Tests** — `Opc.Ua.PubSub.Tests` adds `IntervalRunnerTests`; existing
`SubscriptionTests`, `UaPublisherTests`, and `TestDataSystem` move off
`HiResClock`. Added `Microsoft.Extensions.TimeProvider.Testing` package
for `FakeTimeProvider` (project-load warning surfaces on net48/net472
only — runtime is .NET 8+).

### Migration guide

New section [**Time and Timer abstraction
(`TimeProvider`)**](Docs/MigrationGuide.md#time-and-timer-abstraction-timeprovider)
documents:

- The canonical replacement table (`HiResClock.UtcNow` →
`timeProvider.GetUtcNow().UtcDateTime`, `HiResClock.TickCount64` →
`timeProvider.GetTimestamp()`, `new Timer` → `timeProvider.CreateTimer`,
`Task.Delay(delay, ct)` → `Task.Delay(delay, timeProvider, ct)`, …).
- The `TimeProvider? timeProvider = null` + `??=` constructor pattern.
- DI wiring and how to swap in `FakeTimeProvider` in tests.
- Before/after snippets for `HiResClock.TickCount64`,
`HiResClock.UtcNow`, and `new Timer(...)`.

## Related Issues

- Fixes #2458

## 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.
2026-06-03 22:38:32 +02:00
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 e1b9cea3ea Reduce sync-over-async in non-obsolete server APIs + post-merge code style cleanup (#3806)
## Proposed changes

Reduces sync-over-async in non-obsolete server APIs, removes stale
`#region/#endregion` noise from the test suite, and fixes analyzer/test
fallout from merging the Part 11 Historical Access framework (#3797).
Follow-up review feedback is included: `FileSystemNodeManager` is now
based on `AsyncCustomNodeManager`.

### Sync-over-async reduction (~24 `GetAwaiter().GetResult()` sites)

**Server-side:**
- `TrustList`: async `OnCallAsync` handlers added; sync `OnCall`
handlers retained as compat shims so legacy `CustomNodeManager2`
subclasses that host the TrustList but do not implement
`ICallAsyncNodeManager` keep working through `MethodState.Call`.
- `GDS ApplicationsNodeManager`: `RequestAccessToken`,
`KeyCredentialStart/FinishRequest`, and `Revoke` moved to `OnCallAsync`.
- `IKeyCredentialRequestStore`: interface + in-memory implementation
converted to async; `FinishKeyCredentialRequestResult` record carries
the previous out-set. Tests in `Tests/Opc.Ua.Gds.Tests/` updated to the
new async API.
- `FileSystem`:
- `DirectoryObjectState` methods (`CreateDirectory` / `CreateFile` /
`Delete` / `MoveOrCopy`) use `OnCallAsync`.
- `FileSystemNodeManager` now derives from `AsyncCustomNodeManager` and
overrides async address-space/node-resolution paths
(`CreateAddressSpaceAsync`, `DeleteAddressSpaceAsync`,
`GetManagerHandleAsync`, `ValidateNodeAsync`) to avoid sync-over-async
in dynamic node validation.
- `FileSystemNodeManagerFactory` now supports async creation
(`IAsyncNodeManagerFactory`) while retaining sync factory compatibility.
- Reference server registration of the FileSystem node manager is
aligned to the async node manager list.
- `ConfigurationNodeManager` namespace lookup uses sync
`GetManagerHandle` to keep the remaining `GetResult` inside the
documented `SyncNodeManagerAdapter` bridge.
- `ServerBase`: new `OnServerStartingAsync`; `StartAsync` now awaits it.
- `StandardServer.CreateMasterNodeManagerAsync` added; sync wrapper kept
for backward compatibility.
- `IServerInternal.CloseSession` marked `[Obsolete]`
(`CloseSessionAsync` exists).
- `IMasterNodeManager.RemoveReferences` marked `[Obsolete]`; in-tree
sync callers remain with scoped `CS0618` pragmas + TODO.

**Stack:**
- `EncryptedSecret`: added `VerifyHeaderForEccAsync` / `DecryptAsync` /
`TryDecryptAsync`; `UserNameIdentityTokenHandler.DecryptAsync` awaits
ECC validation.
- `CertificatePasswordProvider` ctor: `GetResult` fallback replaced with
explicit `InvalidOperationException`.

### Code-style and post-merge cleanup

- Removed unused `#region`/`#endregion` directives across test files.
- Restored green build state after Part 11 merge fallout fixes
(production + analyzer + test cleanup from earlier commits in this PR).

### CI / validation notes

- This PR branch surfaced runtime regressions introduced by Part 11
after the build-breaker was fixed (outside scope of this
async/code-style cleanup).
- Follow-up feedback change validation for `FileSystemNodeManager`:
- `dotnet build Libraries/Opc.Ua.Server/Opc.Ua.Server.csproj -f net10.0
--no-restore` ✅
- `dotnet test Tests/Opc.Ua.Server.Tests/Opc.Ua.Server.Tests.csproj -f
net10.0 --filter FileSystemNodeIdTests` ✅
- `dotnet test Tests/Opc.Ua.History.Tests/Opc.Ua.History.Tests.csproj -f
net10.0 --filter FileSystemSmokeTests` ✅ (test skipped in environment)

## Related Issues

- None.

## Types of changes

- [ ] Bugfix (non-breaking change which fixes an issue)
- [x] Enhancement (non-breaking change which adds functionality)
- [x] Test enhancement (non-breaking change to increase test coverage)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected, requires version increase of
Nuget packages)
- [ ] Documentation Update (if none of the other choices apply)

## Checklist

- [x] I have read the
[CONTRIBUTING](https://github.com/OPCFoundation/UA-.NETStandard/blob/master/CONTRIBUTING.md)
doc.
- [x] I have signed the
[CLA](https://opcfoundation.org/license/cla/ContributorLicenseAgreementv1.0.pdf).
- [x] I ran tests locally with my changes, all passed.
- [ ] I fixed all failing tests in the CI pipelines.
- [ ] I fixed all introduced issues with CodeQL and LGTM.
- [x] I have added tests that prove my fix is effective or that my
feature works and increased code coverage.
- [x] I have added necessary documentation (if appropriate).
- [x] Any dependent changes have been merged and published in downstream
modules.
2026-05-27 06:48:30 +02:00
Marc Schier eb40a59566 More format and diagnostic fixes (#3780)
Drive the solution to zero warnings / zero errors with analyzers on,
promote the consistently-fixed rules to error, and lock in coverage
on the only line of new logic.
2026-05-26 06:06:09 +02:00
Marc Schier 3e5f129c6f Enable nullable in Stack, Libraries (9), and Applications projects (#3732) 2026-05-17 12:55:24 +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
Marc Schier bd4543e961 ManagedSession, Pluggable Subscription engine, and fluent builder + DI (#3730)
- Add new managed session, wrapping session and providing connection management and failover handling
- Add new Subscription engine that can act as alternative to current engine, but is based on channels with worker tasks
- Add a fluent builder for managed session clients
- Replace NodeCache with LruNodeCache, rename ILruNodeCache and LruNodeCache to INodeCache and NodeCache
- Update migration guide and document new functionality.
2026-05-05 19:09:07 +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 d14cd10a86 Model dependency annotations using source generator + flaky test fixes (#3687)
* Fix publish/dispose race that hangs Client tests

Subscription.Dispose pre-disposed m_publishTimer and m_messageWorkerCts
before calling ResetPublishTimerAndWorkerState, causing Cancel() to throw
ObjectDisposedException and leaving the publish worker stuck. Removed the
duplicate disposal so the reset method is the single owner of those resources,
and guarded Cancel/Dispose with try/catch ObjectDisposedException for defense
in depth.

Session.OnPublishComplete could run after Session.Dispose disposed
m_reconnectLock, throwing ObjectDisposedException from SemaphoreSlim.Wait()
and re-arming via the throttle path indefinitely. Added an early Disposed
guard, wrapped Wait/Release in try/catch ObjectDisposedException, and added
a Disposed guard in QueueBeginPublish so the throttle cannot reschedule
publishes after disposal.

Fixes the macOS net10.0 hang seen in Azure pipeline build 13257
(TransferSubscriptionAsync, ReconnectWithSavedSessionSecretsAsync).

* fix lockout test and use UserName token for SuccessfulAuthenticationClearsFailedAttempts test

After c1e11b1ab made anonymous activations no-op for clearing the lockout
counter, the test must use a real (non-anonymous) credential to demonstrate
that successful authentication resets failed attempts. Use user1/password
with PolicyId=1 (UserName_1 in the reference server config).

* Fix DirectoryCertificateStore cache staleness across instances

When two DirectoryCertificateStore instances point at the same directory (e.g. a CertificateValidator's internal store and a separate store opened by a caller), the directory LastWriteTimeUtc seen by one DirectoryInfo handle does not reliably reflect modifications made through another handle on Windows, even after Refresh(). The mtime-based cache check therefore returned stale entries indefinitely, causing VerifyRejectedCertsDoNotOverflowStoreAsync to flake when the test fixture's RejectedStore failed to observe deletes performed by the validator's internal store.

Add a cheap on-disk file count cross-check in the cache-hit branch: if the count of cert files on disk does not match the cached entry count, force a reload. This avoids re-parsing every certificate when nothing has changed but reliably detects external modifications.

* test: fix keep-alive mock to return Int32 ServerState

The mock for the Server_ServerStatus_State read returned new Variant(0u)
(UInt32). The keep-alive worker expects Int32 (ServerState enum is
wire-encoded as Int32), so ClientBase.ValidateDataValue logged a
BadTypeMismatch warning on every keep-alive throughout the test run.

Real servers always emit Int32 for enum variables (BinaryEncoder
downgrades the enum encoding byte to Int32), so the warning was purely a
test-mock artifact. Switch the mock to new Variant((int)ServerState.Running)
to eliminate the spurious warnings.

* Source generator: emit and consume ModelDependencyAttribute. Emit one [assembly: ModelDependencyAttribute(...)] per model the
  generated assembly emits and per upstream model it transitively
  consumes (new ModelDependencyGenerator in
  Tools/Opc.Ua.SourceGeneration.Core).
* Replace the unused PEReader-based ReferenceMetadataScanner with a
  Roslyn IAssemblySymbol.GetAttributes() scan
  (ReferencedModelDependencyScanner in
  Tools/Opc.Ua.SourceGeneration). Hooks the per-symbol incremental
  cache, works for both PortableExecutableReference and
  CompilationReference, AOT-safe.
* Wire the scanner result through ModelSourceGenerator into
  ModelCompilation. The reduced URI-keyed map is passed to the public
  Generators.GenerateCode extension methods.
* NodesetFileCollection.GetDesignFileListForModel now consults the
  referenced-model map, so transitive nodeset dependencies that are
  satisfied by a referenced assembly no longer raise the
  missing-dependency error.
* Override resolution: when a local AdditionalFile and a referenced
  assembly both declare the same model URI under the same C# prefix
  the local generation is silently skipped (avoids CS0101); different
  prefixes still generate so downstream consumers can intentionally
  override types under a different namespace.
* New diagnostics MODELGEN010 (override skipped) and MODELGEN012
  (multiple referenced assemblies provide same model URI -> tie-break
  on highest version+publication date).
* Bump asserted GeneratedSources counts in ModelGeneratorTests for the
  new *.ModelDependencies.g.cs files (one per generated model).
* Fix unrelated CS1574 broken cref in NodeId.TryParseLongForm xmldoc
  that was blocking the Opc.Ua.Types build.
* Document the new flow in Docs/ModelDependencies.md.
* tests for ModelDependencyAttribute flow

* Refactor recently added "parsing" constructors to ParseLongForm static method. Method delegates to Parse(IServiceMessageContext)

NodeId, ExpandedNodeId and QualifiedName ParseLongForm overloads are now thin wrappers around Parse(context, options) using NodeIdParsingOptions with RequireResolvedUris=true and updateTables=false. Adds the FallbackToStringIdentifier opt-in to preserve the legacy lenient quirk for callers that need it (off by default for strict parity).

Tests for the refactored long-form parsers were added to the existing per-type test fixtures.

* Update nuget dependencies to latest
2026-04-22 10:15:12 +02:00
Copilot 319ea88726 [Server/Client] Support RSAEncryptedSecret format and unify EncryptedSecret RSA/ECC API with legacy .NET and test compatibility (#3678)
* Initial plan

* feat(server): support RSAEncryptedSecret username token decryption

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/f79e2eec-5b14-4ffb-8ee0-2906a95e56fd

Co-authored-by: marcschier <11168470+marcschier@users.noreply.github.com>

* test: add RSAEncryptedSecret username token coverage and harden parsing

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/f79e2eec-5b14-4ffb-8ee0-2906a95e56fd

Co-authored-by: marcschier <11168470+marcschier@users.noreply.github.com>

* feat(client): use RSAEncryptedSecret for long username passwords

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/4b5a3cbb-9110-4fe5-907d-7b8ffccf2a16

Co-authored-by: marcschier <11168470+marcschier@users.noreply.github.com>

* fix(core): add framework-compatible zeroing and SHA1 hash helpers

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/732365b9-45fe-4c20-bfa9-b6b7dc9ad4e4

Co-authored-by: marcschier <11168470+marcschier@users.noreply.github.com>

* fix(core): tighten crypto helper compatibility guards

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/732365b9-45fe-4c20-bfa9-b6b7dc9ad4e4

Co-authored-by: marcschier <11168470+marcschier@users.noreply.github.com>

* chore(core): simplify zero-memory preprocessor guard

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/732365b9-45fe-4c20-bfa9-b6b7dc9ad4e4

Co-authored-by: marcschier <11168470+marcschier@users.noreply.github.com>

* test(core): add legacy-framework crypto polyfills in username token tests

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/87851fe9-59ab-453b-a0a7-7cb3134e4e0d

Co-authored-by: marcschier <11168470+marcschier@users.noreply.github.com>

* chore(test): rename RNG local for readability

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/87851fe9-59ab-453b-a0a7-7cb3134e4e0d

Co-authored-by: marcschier <11168470+marcschier@users.noreply.github.com>

* refactor(core): move RSAEncryptedSecret handling into EncryptedSecret

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/1a47ef6e-03ba-413c-8aee-1c03f870d3fe

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* chore(core): polish EncryptedSecret RSA refactor review items

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/1a47ef6e-03ba-413c-8aee-1c03f870d3fe

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* refactor(core): add RSA EncryptedSecret factory and clarify timestamp guard

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/1a47ef6e-03ba-413c-8aee-1c03f870d3fe

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* refactor(core): unify EncryptedSecret API for RSA and ECC

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/09578bca-fa2d-4916-8bd3-8d68470e91e1

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* refactor(core): add unified TryDecrypt handling and ECC failure test

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/09578bca-fa2d-4916-8bd3-8d68470e91e1

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* chore(core): refine unified TryDecrypt exception handling

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/09578bca-fa2d-4916-8bd3-8d68470e91e1

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* docs(core): clarify unified EncryptedSecret API behavior

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/09578bca-fa2d-4916-8bd3-8d68470e91e1

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* chore(core): improve ECC decrypt diagnostics and docs

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/09578bca-fa2d-4916-8bd3-8d68470e91e1

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* chore(core): polish unified API wording and ECC test naming

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/09578bca-fa2d-4916-8bd3-8d68470e91e1

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* chore(core): remove TryDecrypt magic number and simplify ECC error text

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/09578bca-fa2d-4916-8bd3-8d68470e91e1

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* chore(core): consolidate TryDecrypt catches with exception filter

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/09578bca-fa2d-4916-8bd3-8d68470e91e1

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: marcschier <11168470+marcschier@users.noreply.github.com>
Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>
2026-04-21 05:03:00 +02:00
Marc Schier 6c8c1a6d29 Enable dispose analyzers CA2000 and CA2213 and fix all issues (#3670) 2026-04-17 13:39:34 +02:00
Marc Schier d1883832e1 Secure channel enhancements 2025 11 (Take 3) (#3665)
* merged security changes

* Tailor SecurityPolicyUri for format expected in s_securityPolicyUriToInfo

* Enhance security policy handling and key computation logic

* Merge SecurityEnhancements.

* Add support for SessionTransferToken. Removed obsolete SoftwareCertificate code.

* Fix NonceLength for None.

* Add support for RSA_DH, more fixes from IOP testings.

* Finish implementation of SecureChannelEnhancements.

* Rename EccUtils.cs to CryptoUtils.cs

* Address feedback from reviewers.

* Fix CoPilot flagged spelling errors.

* Rename EccUtils to CryptoUtils

* Update version from 1.5.378-preview to 1.5.378

* Fix unit tests.

* Allow SignatureData.Algorithm to be NULL or Empty.

* Fix issue with BrainPool_p256r1_ChaChaPoly

* Fix RSA_DH_AesGcm

* Fix OSC/padding by deriving HMAC keys, tightening symmetric size math, and correcting ECC_brainpoolP384r1/Basic128Rsa15 IV, signature, padding, and nonce parameters.

* Policies without asymmetric encryption (ECC) return the plaintext when encrypting user tokens; this prevents null payloads from causing BadIdentityTokenInvalid.

* Reserve outer CBC padding for avoiding SymetricEncryptAndSign->AddPadding to overwrite next fields (signature)

* Nonce stored as byte array in SessionConfiguration; Sesion snapshot restores ServerNonce and reconstructs ECC ephemeral key Nonce from bytes and policy

* Added _AesGcm and _ChaChaPoly variants to BuildSupportedSecurityPolicies() for all six ECC certificate types (nistP256, nistP384, brainpoolP256r1, brainpoolP384r1, curve25519, curve448) to SecurityConfiguration. Added Sign and SignAndEncrypt endpoints for the four ECC AesGcm/ChaChaPoly policy pairs (nistP256, nistP384, brainpoolP256r1, brainpoolP384r1) to ServerFixture.

* make ephemeralKeyPolicyUri nullable

* GenerateSecret also for NET7 and NET8

* Adjust Basic128Rsa15 policy properties for backword compatibility

* Exclude unsuported AEAD policies from .NET Framework client tests

* Addapt to new changes (still build fail)

* Addapt code to make it compile

* Fixed failing build on net48 (by ignoring potential null ref which is not reported on other newer targets)

* Preserve the certificate reference in Clone() so copied handlers can still sign

* Remove extra code and addapt to existing master configuration settings

* Filter *_AesGcm and *_ChaChaPoly security policies based on actual runtime support, so unsupported AEAD policies are not advertised or selected on older frameworks

* Expand ECC/RSA policy test coverage and keep Basic128Rsa15 nonce length backward-compatible

* Fix ReconnectSessionOnAlternateChannel _AES and _ChaCha policies

* Fixed IgnoreIfPolicyNotAdvertised so it now fetches endpoints on-demand (instead of relying on Endpoints being preloaded by earlier tests), which avoids false ignores when running tests directlyy

* Merge with commit 5e627f2ca1 from secure-channel-enhancements-2025-11 branch

* minor log mesatge formating

* Fix ClientLockoutTests

* Add ServerFixture policies upfront only if framework and runtime capability supports them

* A few cosmetic/config changes as review sugested

* Moved the session/security handling from StandardServer into a dedicated helper

* use X509IdentityTokenHandler from secure-channel-enhancements-2025-11

* Removed unused Opc.Ua.Types.UnitTests.csproj

* test(client): fix Basic128Rsa15 reconnect token-policy coverage

Advertise an explicit Basic128Rsa15 user token policy in the test fixture and tighten the reconnect test preconditions for non-advertised policies.

* test(client): fix session nonce persistence test helpers

Replace the generic reflection helpers in SessionTests with explicit client/server nonce accessors that match the actual field types.

Add a short Session comment to explain why client and server nonces currently use different representations.

* Merge branch 'master' into secure-channel-enhancements-2025-11-merge5

Merge with latest master and fix conflicts.

* Removed unused Opc.Ua.Types.UnitTests.csproj

* test(client): fix Basic128Rsa15 reconnect token-policy coverage

Advertise an explicit Basic128Rsa15 user token policy in the test fixture and tighten the reconnect test preconditions for non-advertised policies.

* test(client): fix session nonce persistence test helpers

Replace the generic reflection helpers in SessionTests with explicit client/server nonce accessors that match the actual field types.

Add a short Session comment to explain why client and server nonces currently use different representations.

* Build fixes

* Fix build

* update

* Minor updates

* Fix tests

* Add code to check all Endpoints.

* Update Design files to 1.05.7

* Run code fixers, add missing docs

* Fix build

* Revert removal of using

* Increase build timeout

---------

Co-authored-by: mrsuciu <Mircea-Adrian.Suciu@Softing.com>
Co-authored-by: Randy Armstrong <randy@sparhawksoftware.com>
2026-04-16 18:56:42 +00:00
Marc Schier 64ca85fce3 Increase code coverage across solution (#3662)
Add additional tests to increase code coverage across the solution
2026-04-14 13:32:10 +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
Copilot edbbfa3532 Add tests for ServerBase with multiple IP addresses on the same port & improve CI Stability (#3650)
* Add tests for server with multiple IP addresses on same port

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/adce15e6-8c71-4ba9-8581-cb526b274dfe

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* Fix flaky RequestQueueTests by using separate CancellationTokenSources per wait

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/85e9cbc6-7d42-4e6b-8cbe-725b732c72a2

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* Fix flaky VerifyRejectedCertsDoNotOverflowStoreAsync test

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/a75f2420-077e-4022-8f73-17b52d6de841

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* Fix race in RequestQueueTests: await req3 completion before asserting status code

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/43e310a1-bcf1-45fd-84f1-f5266b1e855d

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* Fix flaky TransferSubscriptionOnlyAsync(DisconnectedRepublishDelayedAck): poll for republished notifications and use GreaterThanOrEqualTo assertion

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/266c66da-e8dc-450f-925a-e3c1c50100b3

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* Fix ShortHaulStabilityTestAsync: wait for initial subscription notifications before starting writes, reset counters for clean measurement window

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/44e73c6c-3620-4e88-9f4c-852a9fe58d94

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* Fix TransferSubscriptionOnlyAsync(DisconnectedRepublishDelayedAck,False,False): extend republish polling to all sendInitialValues combinations

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/e5775ceb-1441-4bef-a9b7-7e80d5a9fb72

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* Fix TransferSubscriptionOnlyAsync(DisconnectedRepublishDelayedAck,False,*): restrict republish poll and expected count to sendInitialValues=True

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/dbee6fa2-6ea3-4086-b36e-263288cfdf31

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* Fix RequestQueue race: increment m_totalThreadCount before Task.Run to prevent spurious worker spawning

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/380346b7-7b31-4390-9438-3725028a0831

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>
2026-04-07 12:45:02 +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
romanett c19e83b63d Refactor MonitoredItem.ValueChanged & cert validation (#3592)
Refactored MonitoredItem.ValueChanged for correctness, performance, and comprehensive test coverage, including improved deadband and array handling. Rewrote equality logic for Variants and arrays. Made certificate validation thread-safe using ConcurrentDictionary and proper semaphore usage. Added extensive unit tests and benchmarks for value change detection.
2026-03-04 20:22:28 +01:00
KircMax 42addbb5f7 Add possibility for Sub-CA to be revoked, Removed auto-creation of empty crl for revokecertificate call with CA (#3547)
* add revoke sub ca possible ->

* cert group tests

* fix revoking for sub-cas

* do not use bouncycastle
add test for Test_Root_CA_throws_Exception + throw if applicable
use LoadCrlCreateEmptyIfNonExistantAsync

* remove allowance for initialcrl to be null

* unify with first check for self-signed certificate

* warning -> use StringComparison.Ordinal
2026-02-17 06:27:10 +01:00
Marc Schier 601cabf86f Replace all use of object in code and API with Variant (#3550) 2026-02-15 06:19:38 +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
KircMax f77e96ea97 add FindIssuerCAByKeyIdentifierAsync (#3535)
* add FindIssuerCAByKeyIdentifierAsync

* remove unnecessary using for Org.BouncyCastle.Asn1.X9
2026-02-10 13:20:43 +01:00
Marc Schier 43ce7ed229 Code clean up and improvements (#3532)
This pull request modernizes the OPC UA .NET codebase and tests, removes .NET Standard 2.0 support from certificate/security code, and updates test code to use C# 12 and .NET 8+ features for clarity and maintainability.
- Certificate and BouncyCastle interop files (e.g., CertificateBuilder.cs, X509Extensions.cs, X509SignatureFactory.cs) are refactored to drop NETSTANDARD2_0 support and use modern .NET APIs and conditional compilation.
- Test code across the codebase is updated to use default, strongly-typed Parse methods, collection expressions, and improved async/await patterns.
- Exception handling and assertions in tests are modernized, and test method naming is made consistent with Async suffixes.
- The project and build files are updated to clarify Roslynator analyzer usage and remove obsolete netstandard tags.
- General code and test cleanup includes improved null safety, type safety, and removal of deprecated or unused code.
2026-02-09 13:37:06 +01:00
Robert Richter 6d539c9e92 fix minor xml docs copy error (#3518) 2026-02-06 11:49:10 +01:00
wxmayifei 6ab1bf7a5d fix format string (#3441) 2026-01-08 21:16:37 +09:00
romanett 1e6a043597 Fix MinNonceLength for SecurityPolicies.Basic128Rsa15 (#3410) 2025-12-12 10:38:50 +02: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
Suciu Mircea Adrian 03d5d691e5 Normalize distinguished name field abbreviations for platform compatibility of attribute State/ProvinceName (#3358)
* Normalize distinguished name field abbreviations for platform compatibility of attribute State/ProvinceName

* Fix warning ca1845

* netstandard2.1 doesn’t support string.Concat with spans.
2025-11-27 09:38:11 +02:00
romanett 0e4b4619c8 Obsolete Sync Certificate Validator Methods (#3338)
* Obsolete Sync Certificate Validator Methods

* Update Tests

* Use HttpClientHandler directly instead of relying on reflection
2025-11-15 07:04:58 +01:00
Marc Schier 35db52a7a6 Move from .net 9 to .net 10 SDK and build new target framework .net 10 (#3333) 2025-11-13 10:45:47 +01:00
Marc Schier 712e770fbe Restructure core and built in types into base assembly and nuget (#3326)
This change adds a **new Opc.Ua.Types** nuget that contains core types that do not rely on generated code.  Why the name?  Because almost all code that was in the Types subfolder is part of it, and because we do not want to change the name of the Opc.Ua.Core nuget/assembly because code relies on it.  Any other name like base or bootstrap felt out of place due to the current structure already defining the name "types".  Key design is to depend on only a small set of libraries with limited transitive dependencies, that includes hashcode, logging.abstraction, and for non standard20 builds System.Text.Json (needed for localizedText mul parsing).  Also, key is to support .netstd 2.0 to support source generators and to allow removal of EEC_SUPPORT defines by removing std2.0 from core and all libraries.

The changes are mostly restructuring, and thus small but contain some key changes:

- **Status code** struct now comes with a Symbol field, which is used to carry symbols in case the code is not generated.  Currently (until generated) the status code struct must be manually created with a symbol or the ToSymbolicId extension must be called in the core project.  Future will generate Status code constants just like NodeId that contain the symbol which also removes the reflection-based lookup.  Several tests needed to be adjusted as they checked the status code symbol strings instead of the code.
- **Core identifiers** are copied as they were needed for code to compile, that includes attributes, a subset of status codes and node identifiers.  These will never change so no need to generate them.
- The types folder now contains **encoders**, except for json which is still in core.  Once the json encoder is ported to system.text.json it will also be included and Newtonsoft.Json dropped as dependency (-> #3329).  
- Since types relies on **IOperationContext** and **ISystemContext**, and these export IUserIdentity which relies on crypto, these were split and extended in core with ISessionOperationContext and ISessionSystemContext, which mean changes to ServerSystemContext and introduction of SessionOperationContext and SessionSystemContext classes that extend OperationContext and SystemContext.  Some runtime checks in the server are therefore needed to get at the session and auth info, however, those are anyway optional fields and are not on the critical paths, and thus a type check is in order (and was done in the past already, but against OperationContext class).
- **Manifest resources** are now split between Core (nodeset zip, some generated resoures) and Types (built in bsd/xsds).  This needs to be revisited later if the bsd/xsd need to be regenerated during type generation.  Note that the embedded resource names changed as a result. Since these are only used internally and do not constitute public API this feels reasonable vs duplication of resources in 2 assemblies.
- Reflection however now needs to load not just the built in **encodeables** from Opc.Ua.Types assembly, but also the generated encodeables from Opc.Ua.Core assembly.  For this a new helper Utils method was added to get the Core assembly when linked against Opc.Ua.Core otherwise null.
- Whatever utils methods needed to be split out into the new Opc.Ua.Types assembly, they are now in **CoreUtils** static class in Opc.Ua.Types, and Utils.xxxx forwards to them to ensure minimal changes.  Later we would want to obsolete them in favor of CoreUtils, although it might make sense to split them again into domain specific utilities, such as networking, files, etc
2025-11-10 19:33:24 +01:00
Marc Schier e980d825fa Use connect async instead of BeginConnect (#3321)
* Use Connect async in channels
* Add more logging to debug connectivity issues
2025-11-10 15:44:05 +01:00
Marc Schier b5044212f0 Allow sending while connecting in client channel. (#3315)
- Remove ConnectAsync from lock. Useable means m_channel is set, not useable means it is null.
- Add comments on lock behavior during connection.
- Remove callback log from validator
- Change TCS creation to specify run continuations async
- Fix encoder factory reflecting every time it is created.
2025-11-05 15:37:36 +01:00
Marc Schier bad6bf416b Trace and metrics for send/receive, more test coverage and additional nullable annotations (#3314)
Refactored client-side logic to support batching of service requests, ensuring compliance with operation limits and improving scalability. Added telemetry and activity tracing using `ActivityTraceFlags` for better observability, including metrics collection and logging. Enhanced error handling with descriptive exception messages and improved certificate validation.

Introduced a comprehensive suite of unit tests for `SessionClientBatchTests.cs` and `ClientBaseTests.cs`, covering batching, error scenarios, and edge cases. Added helper classes for testing logging, metrics, and activity tracing. Updated tests to align with modern C# practices, including nullable reference types and collection initializers.

Improved code consistency, readability, and maintainability by standardizing method signatures, simplifying redundant patterns, and removing legacy constructs. Updated XML documentation and added conditional compilation for .NET 8.0+ compatibility.
2025-11-05 11:16:28 +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
Suciu Mircea Adrian 1f47847324 Added RejectCertificateUriMismatch property and explicit ApplicationUri validation after certificates are loaded (#3244)
* Added RejectCertificateUriMismatch property and explicit ApplicationUri validation after certificates are loaded

* Perform duplicate detection on thumbprint only

* Ported handle multiple ApplictionUri, removed assign ApplictionUri from certificate

* Missing letter

* Fixed LoadPrivateKeyAsync when no applicationUri is passed.

* Add tests for validating certificates with multiple AplicationUris on ApplicationInstance level and server side

* Renamed into CheckOrCreateCertificateAsync, logged Certificate, improved tests

* Added retry logic for transient connect errors in CreateSessionApplicationUriValidationTests

* Added TODO log when telemetry instance available

* Removed unused ValidateServerCertificateApplicationUri(X509Certificate2 serverCertificate)
2025-10-31 14:17:31 +01:00
Marc Schier fab6f2ac1a [Client] Obsolete APM calls (#3282)
* Refactor for robustness and async improvements

Refactored code to enhance robustness and maintainability by enabling nullable reference types and using `async`/`await` for asynchronous operations. Updated exception handling to use `BadNotConnected()` for more accurate error states. Removed unused code and improved test files to align with these changes. Introduced `OpenInternalAsync` for better channel management and handled on-demand connection creation in `SendRequestAsync`.

* Obsolete APM
* Remove WCF remainders, channel clean up and initial cut at Channel factory
* Clean up copyright notice formatting
* Make connect async in Socket and abstract bindings for easier testing
* Fix unit tests

These changes enhance robustness, maintainability, and correctness of channel and task management.

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Roman Ettlinger <romanett98@gmail.com>
2025-10-24 13:37:59 +02:00
Marc Schier f8042e445c Check bounds for switched on values and roslyn cleanup (#3264) 2025-10-21 09:28:19 +02:00
Suciu Mircea Adrian 8152feec71 Allow non OPC-UA conform SubjectName values to AddSecurityConfigurationStores (#3229)
* Replace fuzzy search with SimpleName search if comparing DistinguishedName fails.

* Added mandatory Organization Name attribute to SetSuitableDefaults().
Added Test for the special case.

* Added missing O attribute to CompareDistinguishedName call

* Update test

* CertificateIdentifier.Find will pick the certificate with the longest duration

* Find only valid certificates.

* Prioritizes CA-signed certificates over self-signed certificates

* Update Tests/Opc.Ua.Configuration.Tests/ApplicationInstanceTests.cs

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Select longest remaining validity if valid, or least expired if all expired

* Renamings

* Improved comments, improved algo clarity and taken into account more possible cases of prioritization depending on cert validity

* Comment corrected

---------

Co-authored-by: romanett <romanett98@gmail.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-10-21 09:26:29 +03: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
Copilot 8c9ccc4477 Replace deprecated Uri.DnsSafeHost with Uri.IdnHost (#3256)
* Replace deprecated Uri.DnsSafeHost with Uri.IdnHost across codebase

Co-authored-by: marcschier <11168470+marcschier@users.noreply.github.com>

* Update Kestrel.Core package version to 2.3.6
* Fix privateKeyPassword handling in GDS client

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: marcschier <11168470+marcschier@users.noreply.github.com>
Co-authored-by: Marc Schier <marcschier@hotmail.com>
Co-authored-by: Marc Schier <marcschier@users.noreply.github.com>
2025-10-16 08:18:04 +02:00
Marc Schier e505800c74 Refactor string usage for secrets (#394) (#3250)
* Refactor string usage for secrets (#394)

Strings are immutable and the lifetime of secrets can not be controlled.
Use byte[] or char[] instead of strings for secrets, which can be erased
after use.

* Clear pw

---------

Co-authored-by: Martin Regen <7962757+mregen@users.noreply.github.com>
2025-10-12 03:00:36 +02:00
Marc Schier 01ffcee410 Immutable Encodeable factory and lookup performance improvements (#3241) 2025-10-08 09:45:32 +02:00
Marc Schier 95201819a1 More missing obsoleted API to support better porting (#3237) 2025-10-06 12:06:33 +02:00
Marc Schier 845c31d33b Add API back as Obsolete for samples to compile (almost) unchanged. (#3234)
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-10-03 14:20:21 +02:00
Marc Schier 8e7a73c7df Introduce telemetry context and proper use of ILogger (#3213) 2025-09-25 20:25:31 +02:00