mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-18 22:55:08 +08:00
fuzzing
89 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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>
|
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
ce9b2b4bff |
[Server] Load existing users through IUserDatabase.GetUsers (#3811)
**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. |
||
|
|
e49d17d706 |
[Server] Make MonitoredNode aware of IAsyncNodeManager and introduce channel-based queueing under load (#3804)
## Proposed changes This PR updates the server monitored-item pipeline to be `IAsyncNodeManager`-aware and introduces channel-based FIFO queueing in the monitored-node path to improve behavior under load. It also includes follow-up fixes from review/CI feedback: - Adjusted `AsyncCustomNodeManagerTests.WriteAsync_PublishesValueToMonitoredItemQueueAsync` to account for channel-based delivery timing/coalescing while still asserting the written value is observed. - Merged latest `master` into this branch and resolved merge conflicts (notably in `ConfigurationNodeManager`), keeping async address-space lookup behavior intact. - Applied small compile-safety corrections needed for successful validation. |
||
|
|
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. |
||
|
|
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. |
||
|
|
51bcd4272a |
GDS Part 12 Full Compliance (#3795)
* GDS: Authorization & SecureChannel hardening (Part 12 §6.5, §7.2, §7.6)
* Fix OnGetCertificates self-admin authorization: pass applicationId to
HasAuthorization so ApplicationSelfAdmin can read its own certificates per
OPC 10000-12 §7.6.10 (was rejecting self-admin pull-management callers).
* Fix OnUnregisterApplicationAsync self-admin authorization: also pass
applicationId (was silently failing the self-admin branch).
* OnUpdateApplication: accept ApplicationSelfAdmin and ApplicationAdmin in
addition to DiscoveryAdmin per §6.5.7. Add self-admin role-permission shim.
* OnGetCertificateStatus: accept CertificateAuthorityAdmin / SelfAdmin /
ApplicationAdmin per §7.6.12 (was using AuthenticatedUserOrSelfAdmin which
is more permissive than spec).
* Introduce ApplicationAdmin privilege (Part 12 §7.2):
- Add GdsRole.ApplicationAdmin static privilege.
- Extend GdsRoleBasedIdentity with AdministeredApplicationIds and a new
constructor accepting the list. WithAdditionalRoles preserves it.
- AuthorizationHelper.HasAuthorization recognises the privilege: alone
when no applicationId is supplied (e.g. RegisterApplication) and
membership-tested against AdministeredApplicationIds otherwise.
- HasTrustListAccess honours the ApplicationAdmin privilege for the
administered applications' trust lists.
- New role lists: DiscoveryAdminOrAppAdmin (RegisterApplication),
DiscoveryAdminOrSelfAdminOrAppAdmin (Update/UnregisterApplication),
CertificateAuthorityAdminOrSelfAdminOrAppAdmin (cert management).
* SecureChannel result-code alignment (Part 12 method tables):
- HasAuthenticatedSecureChannel throws BadSecurityModeInsufficient (was
BadUserAccessDenied).
- Adds requireEncryption flag so callers can demand SignAndEncrypt
(used by future StartNewKeyPairRequest/FinishRequest tightening).
- Sign and SignAndEncrypt are now both accepted as 'authenticated'.
* Tests:
- Register the GDS namespace in AuthorizationHelperTests SetUp so
GDS-namespace role NodeIds do not collide on NodeId.Null with
privilege roles.
- Update HasAuthenticatedSecureChannelThrowsForNonSecureChannel to
expect BadSecurityModeInsufficient.
- Add HasAuthenticatedSecureChannelDoesNotThrowForSign and
HasAuthenticatedSecureChannelWithRequireEncryptionThrowsForSign.
- Add ApplicationAdmin coverage: SucceedsForAdministeredApp,
ThrowsForUnmanagedApp, SucceedsForRegisterApplication,
ThrowsWithEmptyAdministeredList.
- Add NewRoleListsAreCorrectlyPopulated regression test.
The framework already enforces SigningRequired/EncryptionRequired via
DefaultAccessRestrictions in OpcUaGdsModel.xml, returning
BadSecurityModeInsufficient at request dispatch time
(MasterNodeManager.ValidateAccessRestrictions). The model declares the
correct restriction on every admin method, so explicit handler-level
checks would be redundant. Verified manually against §6.5.6, §6.5.7,
§6.5.8, §7.6.4-7.6.10 and §7.6.12.
23 Authorization unit tests pass. 181 unit + 420 integration GDS tests
pass on net10.0; build clean on net48 and net10.0.
* GDS: Audit event correctness (Part 12 7.6, 7.9)
* Fix audit-event ordering: emit CertificateRequestedAuditEvent AFTER the
method outcome is known. Previously the event was raised before
authorization with Status=true, so any failed call appeared in audit as
a successful certificate request and any authorization-denied call
generated a misleading 'success' audit trail.
- OnStartNewKeyPairRequest: refactor to try/catch/finally, emit audit
once with auditException reflecting either the captured throw, the
bad ServiceResult, or null on success.
- OnStartSigningRequestAsync: add the audit emission (previously
missing entirely - 7.9.3 requires it) using the same pattern.
* Redact privateKeyPassword from audit InputArguments. The previous
ApplicationsNodeManager.cs:1206-1223 included the raw password string
as a Variant in the audit event payload, leaking the secret into any
downstream audit sink. The password is now replaced with
AuditEvents.RedactedPrivateKeyPassword (placeholder string).
* OnFinishRequestAsync: build the audit InputArguments from only the
actual method inputs (applicationId, requestId) per 7.6.6 method
signature. Previously the implementation appended the returned
Certificate / PrivateKey / IssuerCertificates to InputArguments, which
leaked the returned PrivateKey into audit payloads.
* Raise CertificateRevokedAuditEventType in OnRevokeCertificate on
success and failure per 7.6.9. The event type was defined in the
model (OpcUaGdsModel.xml:543) but never emitted. Refactored
OnRevokeCertificate with try/catch/finally; sync-over-async (.Result)
is preserved here and addressed separately in Track C (c-revoke-async).
* AuditEvents helper:
- New ReportCertificateRevokedAuditEvent extension method, mirroring
the existing CertificateRequested/Delivered helpers, with an
Exception parameter that drives Status (true on success, false on
failure).
- New RedactedPrivateKeyPassword and RedactedPrivateKey constants
documented as the canonical placeholders. Class-level remarks
instruct callers to redact sensitive arguments before invoking the
helpers.
* Tests:
- AuditEventsTests: lock the placeholder values
(RedactedPrivateKeyPassword and RedactedPrivateKey) so they remain
stable for downstream audit-sink filters.
- Existing 181 unit + 420 integration GDS tests pass on net10.0; build
clean on net48 and net10.0.
b-keycred-audit and b-token-audit remain pending pending Track E and F
respectively (KeyCredentialService and AuthorizationService handlers).
* GDS: Directory / Pull Management correctness gaps (Part 12 6.5, 7.6)
* OnRevokeCertificate converted to async OnRevokeCertificateAsync; uses
await instead of sync-over-async .Result, accepts the method-call
cancellation token, and is now wired through OnCallAsync to integrate
with the async dispatch path. RevokeCertificateAsync helper takes an
optional CancellationToken so callers (OnUnregisterApplicationAsync,
OnRevokeCertificateAsync) can forward it.
* OnCheckRevocationStatusAsync now computes the ValidityTime per
OPC 10000-12 7.6.11. The previous implementation always returned
DateTime.MinValue. The new implementation enumerates the CRLs in the
trusted-issuer store and uses the earliest NextUpdate as ValidityTime
when the chain validates. On Bad results (chain validation failed)
ValidityTime remains DateTime.MinValue so callers re-check
immediately.
* OnFinishRequestAsync returns the issuer chain via a new
BuildIssuerCertificateChain helper. The previous implementation
returned only the immediate signing CA, which is incomplete for
multi-tier CAs per OPC 10000-12 7.6.6. The helper uses
ICertificateGroup.Certificates (in-memory) as the X509Chain
ExtraStore and falls back to the immediate issuing CA if chain
building does not yield a chain. The helper is intentionally
synchronous to avoid contending with concurrent SigningRequestAsync /
NewKeyPairRequestAsync writes against the CertificateGroup's
AuthoritiesStore (which caused parameterised PushTest cases to fail
in parallel runs).
* ValidateApplication (ApplicationsDatabaseBase) now enforces the
reverse-connect rules in OPC 10000-12 6.5.5:
- Server / DiscoveryServer DiscoveryUrls must NOT start with the
"rcp+" prefix.
- Client DiscoveryUrls (when non-empty) must all start with "rcp+"
AND ServerCapabilities must include "RCP".
- ClientAndServer must register at least one non-rcp+ Server
DiscoveryUrl; reverse-connect URLs are still permitted alongside
and require the RCP ServerCapability.
Removed the previous blanket rejection of any DiscoveryUrls on
ApplicationType.Client (which contradicted the spec's reverse-connect
registration pattern).
* Tests:
- RegisterApplicationClientWithRcpDiscoveryUrlsAndRcpCapabilityDoesNotThrow
- RegisterApplicationClientWithRcpDiscoveryUrlsAndMissingCapabilityThrows
- RegisterApplicationServerWithRcpDiscoveryUrlThrows
- RegisterApplicationClientAndServerWithMixedUrlsDoesNotThrow
- RegisterApplicationClientAndServerWithOnlyRcpDiscoveryUrlsThrows
All 188 unit + 420 integration GDS tests pass on net10.0; build clean
on net48 and net10.0.
c-redundancy intentionally requires no enforcement: both transparent
(single application with multiple DiscoveryUrls) and non-transparent
(separate applications with NTRS capability) patterns per OPC 10000-12
6.5.6 are admitted by the validator; transparent redundancy is a
registrant convention rather than a server-enforceable invariant.
* Annex D capabilities: Self-advertise the LDS-ME capability identifier
whenever the MulticastExtension is configured. Previously LdsServer
hard-coded ["LDS"] regardless of whether multicast was running, so
FindServersOnNetwork peers could not distinguish LDS from LDS-ME
instances. Refactored the capability computation into a public static
ComputeServerCapabilities(existing, hasMulticast) helper:
- empty input + no multicast -> ["LDS"]
- empty input + multicast -> ["LDS", "LDS-ME"]
- custom seed list with no "LDS" -> "LDS" is appended
- existing "LDS-ME" is not duplicated
OnServerStarting now wires up the multicast layer first so the
capability set reflects the configured topology.
* Annex C / rcp+ reverse-connect preservation: MulticastDiscovery now
carries the OPC 10000-12 6.5.5 rcp+ DiscoveryUrl prefix end-to-end
through mDNS announce / discover.
- TryBuildProfile strips the rcp+ prefix before parsing the
underlying transport URL (Uri parsing on "rcp+opc.tcp://..." is
brittle across runtimes) and emits a dedicated TXT-record key
ReverseConnectTxtKey ("rc") so receivers can reconstruct it
verbatim.
- OnServiceInstanceDiscovered honours the "rc" key when present
and rebuilds the DiscoveryUrl with the rcp+ scheme.
Exposes MulticastDiscovery.OpcUaServiceType,
MulticastDiscovery.ReverseConnectScheme and
MulticastDiscovery.ReverseConnectTxtKey as public constants so
client code and tests can reference the same values used during
registration and discovery.
* RegisterServer2 fallback (4.2.2): verified that LdsServer overrides
both RegisterServerAsync and RegisterServer2Async, so the LDS
accepts both legacy RegisterServer registrations and the modern
RegisterServer2 + MdnsDiscoveryConfiguration path; no code change
required.
* Tests: new LdsServerStaticTests fixture exercising the capability
computation (six matrix cases) and locking in the Annex C / rcp+
constants (one regression test). 195 unit + 420 integration GDS
tests pass on net10.0; build clean on net48 and net10.0.
* Added Opc.Ua.Lds.Server as a ProjectReference of Opc.Ua.Gds.Tests so
the new tests can use the public static surface of LdsServer and
MulticastDiscovery.
* GDS: Push management hardening (Part 12 7.10)
* d-push-client-multitype: Make ServerPushConfigurationClient.ApplicationCertificateType
settable instead of hard-coded to RsaSha256ApplicationCertificateType.
Callers managing ECC, Brainpool or HTTPS certificates can now override
the default before invoking certificate-management methods (or pass an
explicit certificate type to the methods themselves). Removed the
TODO comment that flagged this limitation.
* d-trustlist-ext: Set Writable / UserWritable to true for the
DefaultApplicationGroup / DefaultHttpsGroup / DefaultUserTokenGroup
TrustList instances in the GDS. Per OPC 10000-12 7.8.2.1 a TrustList
that supports CloseAndUpdate / AddCertificate / RemoveCertificate is
writeable; role-based access controls on the individual methods still
enforce who may actually mutate the trust list. The previous values
(false) were misleading to clients browsing the trust-list nodes.
* d-server-cred-audit: Redact the private key from
CertificateUpdateRequestedAuditEventType InputArguments per OPC 10000-12
7.10.3. ConfigurationNodeManager.UpdateCertificateAsync was passing
the raw private-key ByteString into the audit payload, leaking the
secret to any downstream audit sink. The audit payload now uses
Opc.Ua.Server.AuditEvents.RedactedPrivateKey (an empty ByteString)
as the placeholder; the certificate, issuer chain and key format
remain in the payload so administrators can correlate the request.
Also extended Server.ReportCertificateUpdateRequestedAuditEvent with
an optional Exception parameter so callers can raise the event with
Status=false on failure (parity with the GDS-side helpers).
* Build clean on net48 and net10.0. 195 unit + 420 integration GDS
tests pass on net10.0.
Remaining Track D items (d-create-selfsigned, d-confirm-update,
d-managed-apps, d-alarms, d-push-tests) are larger features that
depend on Track H model additions and are not in scope for this
commit; their todos remain pending.
* GDS: Lock in ServerPushConfigurationClient.ApplicationCertificateType behaviour
Adds ServerPushConfigurationClientStaticTests covering the
Track D quick-win (d-push-client-multitype): the property defaults
to RsaSha256ApplicationCertificateType for backwards compatibility
and is now caller-overridable (e.g. for ECC management).
* GDS: Implement CreateSelfSignedCertificate (Part 12 7.10.6)
* Server-side: ConfigurationNodeManager wires the generated
CreateSelfSignedCertificateMethodState.OnCallAsync handler when the
optional method node exists on the ServerConfiguration instance.
The handler:
- Requires SecurityAdmin access (HasApplicationSecureAdminAccess)
- Validates CertificateGroupId / CertificateTypeId via the existing
VerifyGroupAndTypeId helper
- Creates a self-signed certificate using the CertificateFactory
pipeline (RSA with caller-specified key size, or ECC from the
curve mapped by the certificateTypeId)
- Merges DnsNames and IpAddresses into the SAN extension
- Stores the resulting raw data on the existing
CertificateIdentifier so the resolver can materialise it
- Returns the DER-encoded public certificate to the caller
The method is Optional per the spec; servers that load a nodeset
without it simply skip the wire-up (null guard).
* Client-side: IServerPushConfigurationClient extended with
CreateSelfSignedCertificateAsync; ServerPushConfigurationClient
delegates to the generated ServerConfigurationTypeClient proxy
with the standard elevate/revert permission pattern.
* net48 compat: uses new ValueTask<T>(result) instead of
ValueTask.FromResult which is unavailable on .NET Framework 4.8.
|
||
|
|
296a904f34 |
Add full OPC UA Part 18 (Role management) support (#3778)
* 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. |
||
|
|
3e5f129c6f | Enable nullable in Stack, Libraries (9), and Applications projects (#3732) | ||
|
|
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 |
||
|
|
54cc3d88b1 | Prepare for C# 15 union types: UnionAttribute polyfill, TryGetValue rename, HasValue (#3727) | ||
|
|
6c8c1a6d29 | Enable dispose analyzers CA2000 and CA2213 and fix all issues (#3670) | ||
|
|
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
|
||
|
|
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 |
||
|
|
7824e6fdeb |
Enhance role-based access control and add permission tests (#3653)
* 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> |
||
|
|
66f44396ff |
[Server] Improve Request Queue, fix Event handling, add Tests (#3611)
- implement RequestQueue using Channels - add event load test - add event integration test verifying event from server object is received - fix Client Reconnect Test - fix DiagnosticsNodeManager not creating RootNotifier for Server object - add Benchmarks for MonitoredItem.QueueEvent - add serveral UnitTest for DiagnosticsNodeManager 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: Marc Schier <marcschier@users.noreply.github.com> |
||
|
|
5a1e547250 | Code cleanup and modernization of test assertions to comply with project standards. (#3631) | ||
|
|
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
|
||
|
|
a255facf68 |
[Server] Implement DiagnosticsNodeManager using AsyncCustomNodemanager (#3595)
* 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 |
||
|
|
588b7e9237 |
[Server] Implement event-driven RolePermissionsValidation caching in MonitoredNode2 (#3583)
* Initial plan * Implement event-driven RolePermissionsValidation with permission caching in MonitoredNode2 Co-authored-by: romanett <7413710+romanett@users.noreply.github.com> * Add DefaultPermissionsChanged event to IConfigurationNodeManager to handle namespace-level default permission changes Co-authored-by: romanett <7413710+romanett@users.noreply.github.com> * Add test & make validation functional * cover case when DefaultRolePermissions are aded after the node exists * cleanup --------- 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> |
||
|
|
0a4c87cef8 |
[Server] Implement smaller Performance improvements found when profiling (#3584)
* Add namespace index lookup for NamespaceMetadataState Added GetNamespaceMetadataState(ushort) to ConfigurationNodeManager and interface for efficient lookup by namespace index. Switched to ConcurrentDictionary for thread safety. Updated AsyncCustomNodeManager to use index-based lookup. Cleared index cache in Clear method. * Refactor Variant and ServiceResult handling for speed - Use WrappedValue assignment for DataValue in MonitoredNode and NodeState to align with updated Variant usage. - Return ServiceResult objects instead of raw StatusCodes for bad attribute IDs. - Update ServiceResult exception handling: include stack trace only in DEBUG, message only in release. - Optimize StatusCode to ServiceResult conversion by returning static Good/Bad instances. * Add Read Limited load test * Optimize MonitoredItem.IsReadToPublish * Add Subscription unit tests and improve triggering logic Added SubscriptionTests to verify PublishTimerExpired behavior, including timer expiry, monitored item readiness, keep-alive, and triggering scenarios. Updated Subscription.cs only process triggering if triggered items are configured, improving correctness and efficiency. * CR feedback |
||
|
|
8c008a172f |
[Server] Add INodeManager3 with role permission validation. Improve MonitoredNode Datastructures & Locks (#3553)
* Use Interfaces Introduced with 1.5.378 Refactor to use interfaces for node managers and server Replaced concrete types with interfaces (e.g., IMasterNodeManager, ICoreNodeManager, IDiagnosticsNodeManager, IConfigurationNodeManager, IServerBase) across method signatures, properties, and internal structures to improve abstraction and flexibility. * Refactor CoreNodeManager to be Based on CustomNodeManager2 * Add Test * Add INodeManager3 with role permission validation Introduce INodeManager3 interface extending INodeManager2, adding synchronous role permission validation methods. Update all node manager interfaces and classes to use INodeManager3. Extend IAsyncNodeManager with async permission validation methods and update adapters for sync/async bridging. Deprecate FindNodeInAddressSpace in favor of new async FindNodeInAddressSpaceAsync. Refactor MonitoredNode2 to use thread-safe collections and locking for monitored items. Enhance event reporting with security and permission checks. Update constructors and documentation to reflect new interfaces and best practices. * fix comment * fix |
||
|
|
601cabf86f | Replace all use of object in code and API with Variant (#3550) | ||
|
|
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 |
||
|
|
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. |
||
|
|
8966e1d358 |
[Server] Use Classes instead of Interfaces for NodeManagers to ensure compatibility for 1.5.378 (#3497)
* Point to concrete classes instead of interfaces * cleanup |
||
|
|
d71ee2a13a |
Add async callback support to TrustList implementation (#3483)
* Initial plan * Add async callback support to TrustList implementation Co-authored-by: romanett <7413710+romanett@users.noreply.github.com> * Fix redundant security check in OpenAsync Co-authored-by: romanett <7413710+romanett@users.noreply.github.com> * Fix audit logging parameters in RemoveCertificateAsync Co-authored-by: romanett <7413710+romanett@users.noreply.github.com> * Refactor TrustList to use async core implementation with sync wrappers Based on feedback, changed approach: - Make internal implementation async (OpenCoreAsync, etc.) - Sync methods now wrap async using .AsTask().GetAwaiter().GetResult() - Both OnCall and OnCallAsync handlers registered - Eliminates .GetAwaiter().GetResult() in async paths Co-authored-by: romanett <7413710+romanett@users.noreply.github.com> * Add ConfigureAwait(false) to sync wrapper methods Prevents potential deadlocks by adding ConfigureAwait(false) before GetAwaiter().GetResult() in all sync wrapper methods. Also made the pattern consistent across all methods. Co-authored-by: romanett <7413710+romanett@users.noreply.github.com> * Add CancellationToken support to helper methods Updated UpdateStoreCertificatesAsync and UpdateStoreCrlsAsync to properly propagate CancellationToken through all async operations. Ensures consistent async patterns throughout the implementation. 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> |
||
|
|
8b11d2bfa8 |
[Server] Add several interfaces to improve testability & prepare for Dependency Injection (#3448)
* add server interfaces * Add IConfigurationNodeManager, IDiagnosticsNodeManager, IMasterNodeManager, IStandardServer, IApplicationInstance interfaces to Server. Add IMainNodeManagerFactory to create Diagnostics & MainNodeManager * Use IApplicationInstance interface where appropriate * fix review feedback |
||
|
|
a3a6709d6f |
Refactor server for full async subscription management (#3442)
Refactor to make OPC UA server subscription and monitored item management fully asynchronous, improving scalability and responsiveness. All key methods in ISubscription, ISubscriptionManager, and related classes are now async, with synchronous counterparts removed. |
||
|
|
e92e469923 |
[GDS] Add configurable validation limits for trust list file read/write operations (#3411)
* Initial plan * Add trust list file size validation with configurable limits Co-authored-by: romanett <7413710+romanett@users.noreply.github.com> * Fix potential integer overflow in trust list size validation Co-authored-by: romanett <7413710+romanett@users.noreply.github.com> * Fix integer overflow in client trust list read validation Co-authored-by: romanett <7413710+romanett@users.noreply.github.com> * Add comprehensive tests for trust list size validation Add TrustListValidationTest with tests for: - Normal-sized trust lists (verify basic functionality) - Trust lists exceeding 16MB limit (verify BadEncodingLimitsExceeded error) - Trust lists just under limit (~15MB) (verify boundary condition) Co-authored-by: romanett <7413710+romanett@users.noreply.github.com> * Make limits configurable on client side * fix tests --------- 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> |
||
|
|
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). |
||
|
|
0e4b4619c8 |
Obsolete Sync Certificate Validator Methods (#3338)
* Obsolete Sync Certificate Validator Methods * Update Tests * Use HttpClientHandler directly instead of relying on reflection |
||
|
|
35db52a7a6 | Move from .net 9 to .net 10 SDK and build new target framework .net 10 (#3333) | ||
|
|
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 |
||
|
|
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) |
||
|
|
0efd9b2863 |
[Server] Include domains and applicationName in ServerCertificate for CreateSigningRequest Method with parameter regeneratePrivateKey = true (#3263)
* Include domains and applicationName in ServerCertificate for CreateSigningRequestAsync with parameter regeneratePrivateKey = true * Update Libraries/Opc.Ua.Server/Configuration/ConfigurationNodeManager.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> |
||
|
|
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 |
||
|
|
8e7a73c7df | Introduce telemetry context and proper use of ILogger (#3213) | ||
|
|
ca731c3fd8 | [Server] Make IAsyncNodeManager interface composable (#3186) | ||
|
|
a86077ac38 |
Make GDS Tests use ECC for connection. Update Certificate wait check to use polling mechanism. (#3167)
* Update GDS Client to use async Client API * Make GDS Tests use ECC for connection. Update Certifiacte wait check to use polling mechanism * Use Async Server Methods * Add specialized ECC Test procdure * Add Exception handling to allow errors during server application certificate exchange --------- Co-authored-by: Marc Schier <marcschier@users.noreply.github.com> |
||
|
|
fb2a096789 |
Update GDS Client to use async Client API and deprecate sync Calls. (#3164)
* Update GDS Client to use async Client API |
||
|
|
9830e5d53e |
Enable roslynizer and fix all analyzer issues (#3157)
* Fix warnings and suggestions * Enable roslynator |
||
|
|
cae5fb25da |
[Server] Implement Support for Async Method Calls (#3090)
* Implement support for async method Call in the server * Implement Cancellation * Add new generated async supported Endpoints & Server Methods * Make SecureChannelContext AsyncLocal * Implement SubscriptionAsync * Add Async Request Queue * Implement sync calls for async NodeManagers. Add Warning * Use second file for Async Interface |
||
|
|
751d614dc6 | make ICertificateStore use Async suffixes (#3148) | ||
|
|
d4e44c6311 |
Add async suffix to methods returning a Task (#3145)
* Add async suffix to asnyc methods |
||
|
|
7f037ef23e |
Enforce Valid Certificate Store configuration (#3023)
* fix Null Reference Exceptions on nonconfigured certificate stores * try to fix gds tests * Use explicit null check * Validate Certificate Store configuration on startup in SecurityConfiguration.Validate. Remove Obsolete CertificateStore Properties. * remove unecessary fields * fix tests * fix client config * Validate Stores by opening them * fix typo * check stores instead of storepath * fix ClientTest * Add Tests for Validate Mehtod of SecurityConfiguration * Update ApplicationConfiguration xsd to respect stricter validation |
||
|
|
7cbeee7155 |
[Test] Add ECC Certificates to various tests (#2961)
* Generate ECC Certificates in Client Tests * Add more tests * reenable check of certificate * fix tests * Dont use random in test * fix unsupported certificate types * fix Hash algorithm for nistP384 curve on linux as the friendly name is ECDSA_P384 instead of nistP384 * use friendly name by default and add special case only for linux while taking care of nullability * disable special casing for finding correct certificates * fix tests on net 462 * update Certificate Identifier |
||
|
|
493da5d5be |
Extend ServerConfiguration & GDS Server for ECC (#2817)
* update ServerConfiguration Node to support multiple Application Certificates. Trust List Support for User Certificates & Https Certificates * GDS ready for ECC Step1 * fix test * fix build * ensure hash algorithm is set * update configurations to new format, fix minor ecc bugs * implicitly set certificate type of certificate identifier extend CertificateFactory to allow Revocation with ECC Issuer Certificate * Revert "update configurations to new format, fix minor ecc bugs" This reverts commit |