# 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>
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.
# 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.
**User Management Improvements:**
* The `UserManagement` class now loads existing users from the user
database during initialization, ensuring that the in-memory user list
reflects the database state through the abstraction boundary.
* The `IUserDatabase` interface now exposes `GetUsers()`, returning
`UserManagementDataType` records instead of only user names.
* `UserManagement.LoadUsersFromDatabase()` now consumes
`IUserDatabase.GetUsers()` so custom user database implementations can
provide persisted user metadata such as `UserConfiguration` and
`Description`.
* `LinqUserDatabase` implements `GetUsers()` and returns user records
with the stored user name and default user-management metadata.
`JsonUserDatabase` inherits this behavior through `LinqUserDatabase`.
**Address Space Management:**
* The server now properly removes the UserManagement node from the
address space when user management is not enabled, preventing stale or
orphaned nodes.
**Test Coverage Enhancements:**
* Added tests to verify that the UserManagement node is removed when
user management is not present.
* Added tests to confirm that `LinqUserDatabase.GetUsers()` returns the
correct users.
* Added tests to confirm that `UserManagement` starts with all users
from the database, including custom `IUserDatabase` implementations that
return full `UserManagementDataType` metadata.
These changes keep user discovery on the `IUserDatabase` abstraction,
remove the concrete-type dependency from startup, and allow existing
users to be loaded with their associated management metadata.
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
* 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
* Enhance role-based access control and add permission tests
- Improve ValidateRolePermissions logic and add ILogger support for detailed access denial logging
- Expand default roles (add AuthenticatedUser, TrustedApplication)
- Refine RoleBasedIdentity to merge roles and avoid duplicates
- Set UserIdentity default GrantedRoleIds to Anonymous
- Fix MasterNodeManager PrepareValidationCache
- Add comprehensive unit tests for role permission validation and logging
* Fix GDS self-admin role: restore NodeId.Null in GrantedRoleIds for ApplicationSelfAdmin
The RoleBasedIdentity constructor was filtering out roles with null RoleIds
(!role.RoleId.IsNull), which broke the GDS ApplicationSelfAdmin mechanism.
The GDS OnAddSelfAdminUserRolePermissions relies on GrantedRoleIds.Contains(NodeId.Null)
to detect self-admin users (since GdsRole.ApplicationSelfAdmin has RoleId = ExpandedNodeId.Null).
Also remove unused System.Data using statement.
Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/3db86efa-c6d6-4e63-947f-156a88210b58
Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>
* fix build
---------
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: romanett <7413710+romanett@users.noreply.github.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>
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.
- 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
* 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>
-Implement the support for ApplicationSelfAdmin privilege
-implement the workflow in a test to pull the trust list after sucessfully receiving a gds signed certificate.
-this authorization is described here in the OPC Spec: https://reference.opcfoundation.org/GDS/v105/docs/7.6
- move IUserDatabase + RoleBased Identity into standard Server
- subclass SystemConfigurationIdentity from RoleBased Identity for backward compatibility
- add OPC UA Spec Defined Roles to the RoleBasedIdentity