# 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>
# 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.
# 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.
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.
* role management compliant with OPC UA Part 18
Server-side:
- New IRoleManager / RoleManager with spec-correct status codes
(Bad_AlreadyExists, Bad_NodeIdUnknown, Bad_RequestNotAllowed,
Bad_NotFound) for every mutator per Part 18 4.2 / 4.4.
- Pre-populate default identities for the three reserved well-known
roles per Part 18 4.3 (Anonymous, AuthenticatedUser,
TrustedApplication).
- Reject mutations on reserved roles with Bad_RequestNotAllowed.
- Validate IdentityMappingRuleType per Part 18 4.4.3 (empty criteria
for Anonymous/AuthenticatedUser/TrustedApplication; upper-case hex
for Thumbprint; Name=Value grammar for X509Subject).
- Honour Part 18 4.4.2 default-field-as-wildcard EndpointType
comparisons; tighten TrustedApplication/Application rules to
require trusted certificate + signed channel.
- Introduce CustomConfiguration flag per Part 18 4.4.1.
- Add IRoleManager.RoleConfigurationChanged event raised after every
successful mutation per Part 18 4.4.1.
- Make RoleEntry an immutable snapshot.
Address-space binding (typed proxies):
- RoleStateBinding switched from stringly-typed OnCallMethod2 plumbing
to the source-generated typed proxies (RoleSetState, RoleState,
AddRoleMethodState, AddIdentityMethodState, ...).
- DiagnosticsNodeManager.AddBehaviourToPredefinedNodeAsync upgrades
passive BaseObjectState nodes of RoleSetType / RoleType to the
typed RoleSetState / RoleState proxies at predefined-node load time.
- New RoleAuthorizationGate.CheckAdmin centralizes SecurityAdmin role
plus SignAndEncrypt enforcement per Part 18 4.2 / 4.4 / 5.2.
- Bound writable ApplicationsExclude / EndpointsExclude /
CustomConfiguration with the same auth gate.
- Raise RoleMappingRuleChangedAuditEventType from every successful
mutator (Part 18 4.5) via the existing AuditEvents helper.
Client library:
- New Opc.Ua.Client.Roles.RoleManagementClient + IRoleManagementClient
+ RoleInfo + SessionRoleExtensions.OpenRoleManagementClient.
- Covers list / read / add / remove role, identity, application,
endpoint operations plus Set*Exclude via Write Service.
Tests:
- New RoleManagerTests.cs - 37 NUnit tests for pre-populated roles,
reserved-role immutability, spec-correct status codes, criteria
validation, ResolveGrantedRoles, exclude semantics,
CustomConfiguration, AddRole well-known NodeId reuse, and
RoleConfigurationChanged event.
Documentation:
- Rewrite Docs/RoleBasedUserManagement.md as a Part 18 compliance
reference (status-code matrix, client examples, known limitations).
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
* Add Part 18 5 UserManagement implementation
Server-side:
- New IUserManagement interface (Opc.Ua.Server.UserManagement) modelling
Part 18 5.2.1 surface: PasswordLength, PasswordOptions, PasswordRestrictions,
SnapshotUsers, AddUser, ModifyUser, RemoveUser, ChangePassword,
MustChangePassword, IsUserActive, UserDeactivated event.
- Default UserManagement implementation wraps the existing IUserDatabase
and stores per-user UserConfigurationMask + description in memory.
Validates passwords against PasswordLength + character-class flags
from PasswordOptions; honours Part 18 5.2 result codes
(Bad_AlreadyExists, Bad_NotFound, Bad_OutOfRange, Bad_NotSupported,
Bad_ConfigurationError, Bad_InvalidSelfReference,
Bad_IdentityTokenInvalid).
- ChangePassword clears the MustChangePassword bit on success.
- New UserManagementBinding wires the typed source-generated proxies
(UserManagementState, AddUserMethodState, ModifyUserMethodState,
RemoveUserMethodState, ChangePasswordMethodState) - typed OnCallAsync
delegates everywhere; admin gate via RoleAuthorizationGate.CheckAdmin;
ChangePassword gated via RoleAuthorizationGate.CheckSelfUserName;
closes active sessions for deactivated users via ISessionManager.
- ConfigurationNodeManager.AddBehaviourToPredefinedNodeAsync upgrades
the passive UserManagement object to the typed UserManagementState
proxy at predefined-node load time; CreateServerConfiguration invokes
UserManagementBinding.Bind when an IUserManagement was injected.
- IServerInternal gains UserManagement getter + SetUserManagement
injector.
Tests:
- New Tests/Opc.Ua.Server.Tests/UserManagementTests.cs - 18 NUnit tests
covering AddUser happy path, duplicate / password-length / config-flag
validation, RemoveUser non-existent / self-reference / NoDelete,
ModifyUser self-disable / disable-other UserDeactivated event,
ChangePassword happy path / same-as-old / wrong-old /
MustChangePassword bit clearing / NoChangeByUser rejection,
IsUserActive on disabled vs active users.
Documentation:
- Update Docs/RoleBasedUserManagement.md with a User Management section
including the spec result-code matrix, example wiring code, and
reduce known limitations - UserManagement is no longer a limitation.
* 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
* 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
* 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>
* feat: add TrustedApplication role assignment per OPC UA Part 3 §4.9
- Add Role.TrustedApplication static property to RoleBasedIdentity.cs
- Add SessionManager.AddMandatoryRoles protected virtual method that assigns
TrustedApplication role when session has a ClientCertificate and uses
MessageSecurityMode.Sign or SignAndEncrypt (per OPC UA Part 3 §4.9)
- Call AddMandatoryRoles in ActivateSessionAsync after identity resolution
- Add ObjectIds.WellKnownRole_TrustedApplication to s_kWellKnownRoles in
DiagnosticsNodeManager.cs
- Add TrustedApplicationRoleTests.cs with 7 unit tests (mock-based) and
1 integration test covering positive and negative cases
Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/86ac791b-5af2-48c6-96f9-19838dfbbde0
Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>
* fix: update test assertion messages to use 'should' phrasing per codebase conventions
Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/86ac791b-5af2-48c6-96f9-19838dfbbde0
Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>
* fix: traverse identity chain in GDS AuthorizationHelper for wrapped RoleBasedIdentity
The TrustedApplication role wraps effectiveIdentity in a new RoleBasedIdentity,
which broke GDS SelfAdmin privilege checks that did `is GdsRoleBasedIdentity`.
- Add InnerIdentity property to RoleBasedIdentity to expose the wrapped inner identity
- Update both CheckSelfAdminPrivilege overloads in AuthorizationHelper to traverse
the identity chain, so GdsRoleBasedIdentity is found even when wrapped
Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/e913ca94-56cf-49d4-a823-fe5861aea8aa
Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>
* refactor: use WithAdditionalRoles virtual method to preserve identity type when adding mandatory roles
- InnerIdentity on RoleBasedIdentity is now protected (not public)
- Add public virtual WithAdditionalRoles() to RoleBasedIdentity so subclasses
can preserve their concrete type when additional roles are layered on
- GdsRoleBasedIdentity overrides WithAdditionalRoles to return a new
GdsRoleBasedIdentity with ApplicationId preserved
- SessionManager.AddMandatoryRoles calls WithAdditionalRoles when the identity
is already a RoleBasedIdentity, so GdsRoleBasedIdentity stays as-is
- AuthorizationHelper reverted to original simple 'is GdsRoleBasedIdentity'
check (no chain traversal needed)
Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/c2854f1f-e220-43d9-aa10-c2c4dca59fd6
Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>
* fix: treat BadRequestInterrupted as expected transient error in ConnectionStabilityTest
During secure channel renewal with a short token lifetime (10s), in-flight
write requests can be interrupted with BadRequestInterrupted. This is expected
behavior during the channel transition and should not count as a test failure.
Added a specific catch clause for ServiceResultException with BadRequestInterrupted
that logs it as informational rather than adding to the error list.
Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/d58e5ecd-34de-4a6f-b060-ad6f804f8a7d
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>
Co-authored-by: Roman Ettlinger <romanett98@gmail.com>
Use RequestLifetime throughout the server stack for unified request lifetime and cancellation management. Update all service method signatures, OperationContext, and request processing logic to use RequestLifetime, enabling precise tracking of cancellation reasons with UA StatusCodes. Remove obsolete synchronous request handling and legacy delegates. Update code generation, tests, and interfaces to support the new model. This change improves cancellation, timeout, and abort handling, and prepares the server for advanced request management features.
* Refactor MonitoredItem.ValueChanged & cert validation
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.
* Implement DiagnosticsNodeManager using AsyncCustomNodeManager
* Implement CoreNodeManager using AsyncCustomNodeManager
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
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.
* remove all usages of SoftwareCertificates
- Client
- Server
As per spec they are not relevant for security.
If an SDK User wants to use the SoftwareCertificates ActivateSession can be overriden
* remove from SessionClientBatchTests
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
- 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
* Enable Durable Subscriptions (#9)
* [Server] Durable Subscriptions (#2683)
* Implement a system test for DurableSubscriptions (#2839)
* Client Side
Co-authored-by: ALTERNATE-DEV\Archie <archie@dreamsandadventures.ca>
* make a static Method CalculateRevisedQueueSize
* Adress review feedback
* fix FilterRetainTests
* Add MonitoredItem Id to Queues
Use NodeIdDictionary where possible
* make Server return BadIdentityTokenInvalid if use of anonymous identity token is not allowed
* Change Response Code on Client side also to be consistent
* change response code ro BadIdentityTokenRejected
- Port support for ECC NIST/Brainpool profiles from prototyping_ecc branch
- Implement CertProvider to load certs per connection / profile
- Backward compatibility of configuration for existing apps
- SecurityConfiguration specifies app cert types for each profile
- Autodetect the ECC support for brainpool/nist based on platform (mac OS 10 doesn't support brainpool)
- ECC supported on net48 / net5.0 / net 6.0 / netstandard2.1
- ECC supported on windows / linux / macOS (brainpool not < macOS11)
- Self signed certs for each profile are created on start similar to RSA
- RSA only profiles are supported on .NET standard 2.0
Co-authored-by: Martin Regen <mregen@microsoft.com>
Server: Fix a deadlock in the binary channel cleanup (regression from secure channel cleanup)
Server: Use ConcurrentDictionary for sessions and channels to reduce locking overhead
Server: Replace legacy implementation of NodeIdDictionary with standard dictionary, as with IEqualityComparer the look up is much faster than specialized SortedDictionary for each NodeId Type.
Co-authored-by: Luis Cantero <luis@cantero.org>
Added a new method ManagedBrowse to the UA client, which takes care of calling browse next after calling browse, when necessary. It also handles the status codes BadNoContinuationPoint and BadInvalidContinuationPoint.
Added support for the new method in ISession, TraceableSession, Session and SessionAsync.
Use the new methods in the NodeCache and other API that use browse (FetchRefrences etc).
Added unit tests which verify correct behavior of the new methods.
* Added MaxChannelCount and detect and cleanup "stale" channels based on ChannelLifetime
* Add Environment.TickCount as time reference
* Set a socket backlog value to avoid socket open overflow
* Added a ChannelKeepAlive to signal when a session is still active
* Add options to console client to leak channels and run connect loop forever
Co-authored-by: Martin Regen <mregen@microsoft.com>