mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-25 11:50:03 +08:00
# Description Remove stock phrasing and correct misleading or inconsistent technical documentation. The initial two passes covered 367 Markdown files, followed by an interactive review of 169 editorial flags. The U5 interpretation originally deferred in that review has since received the upstream Mantis answer recorded by #4843; remaining server/spec follow-ups stay explicit in the CTT log. - Correct package responsibilities, migration steps, API names, ownership, protocol descriptions and links. Keep bundled migration guides synchronized. Preserve historical conclusions as historical records with separate re-check notes. - Provide at least two rendered TOC levels throughout `docs/`. Convert appropriate architecture figures to Mermaid without changing code examples, transcripts or historical quotations. - Address the October 19 feedback with concrete setup/migration instructions, corrected certificate paths and PubSub names, shorter repeated caveats, consistent XML comments, and a full review of the Concepts guide. Retain #4839's API corrections. - Integrate #4841's runtime/performance guidance and review incoming/recent prose. Preserve dated measurements rather than claiming new benchmark runs; clarify allocation ratios, startup-only processor settings, JIT warm-up and the benchmark commit's scope. Missing raw measurement artifacts and repeat ranges remain tracked by #4842. - Merge master through `e8c5d800a` in `32c6394b7`. Resolve the CTT log conflict using the updated Mantis states and OPC answers, retaining historical framing and re-checks for C28/C32/C43. - Address the latest naming/index feedback in `adb5bf693`: rename the guides to `docs/WotCon.md` and `docs/WotNodeSetConversion.md`; move the provider and DataType-declaration contracts into the conversion guide and remove `docs/WoT.md`. Rename `samples/DI` to `samples/Di` and `samples/Isa95` to `samples/ISA95`. Add content-index READMEs to Di, FluentApi, ISA95, Lds and PubSub; update solution entries, project references, Docker/CI paths, test fixture paths and documentation links with exact casing. **WoT guide scope.** This branch retains the detailed conversion guide that #4758 had replaced with an anchor stub. Conversion limits, verified document sets, preservation rules and provider ownership now live together in `WotNodeSetConversion.md`; binding/runtime guidance remains in `WotBindings.md` and `WotCon.md`. The design-rationale/test-ledger prose was shortened, the oversized argument-table cell moved into its section, and existing anchors preserved. **SDK policy is a separate, explicit user-directed change.** `global.json` sets a stable minimum of `10.0.400`, `rollForward: latestMajor`, and `allowPrerelease: false`. Newer major SDKs are permitted; CI's explicit SDK pins are unchanged. README, GettingStarted, DeveloperGuide and Recycling instructions reflect the possible analyzer differences. The image-contract regression fix accepts compatible stable SDK images instead of requiring exact equality with the floor. The latest four rename/index threads are resolved after publication. Three older threads remain open: universal obsolete-removal timing, unconditional nonce-strength wording, and a blanket Vision NativeAOT claim. Existing implementation/evidence constraints are explained in their inline replies. The two-level TOCs remain as requested. ## Validation - `git diff --check` and staged diff checks: passed. The untouched upstream AutoID NodeSet retains its provenance bytes, including two existing license-header trailing spaces. - `.\.azurepipelines\validate-migration-plugin.ps1`: passed; 15 bundled migration documents and manifests synchronized. - Documentation/path validation: **101** documents retain two rendered TOC levels (**2,228** entries), with idempotent formatting. **52** new relative links and their anchors passed exact-case checks. No tracked references to the old guide/sample paths remain. Both relocated provider-contract sections are preserved in the destination. - `dotnet sln UA.slnx list`: passed; shows the renamed Di/ISA95 projects and the existing FluentApi/Lds/PubSub projects. Updated solution and pump ProjectReference paths also passed exact-case existence checks. - Latest focused commands, run from the repository root: ```powershell # Passed: 61 channel send-order and reconnect tests. dotnet test tests\Opc.Ua.Core.Tests\Opc.Ua.Core.Tests.csproj -p:CustomTestTarget=net10.0 --filter 'FullyQualifiedName~UaSCBinaryChannelSendOrderTests|FullyQualifiedName~TcpReconnectKeyAgreementTests' --verbosity minimal # Passed: 5 pump datasheet tests; builds the renamed pump sample. dotnet test tests\Opc.Ua.Di.Tests\Opc.Ua.Di.Tests.csproj -p:CustomTestTarget=net10.0 --filter 'FullyQualifiedName~PumpDatasheetConformanceTests' --verbosity minimal # Passed: 4 repository NodeSet path/round-trip tests, including the moved pump models. dotnet test tests\Opc.Ua.Types.Tests\Opc.Ua.Types.Tests.csproj -p:CustomTestTarget=net10.0 --filter 'FullyQualifiedName~RepositorySourceSurvivesSerializedLinkedPartitionsAsync' --verbosity minimal # Passed: build, zero warnings/errors. dotnet build samples\ISA95\MinimalIsa95Server\MinimalIsa95Server.csproj -p:CustomTestTarget=net10.0 -f net10.0 --verbosity minimal # Passed: dependent sample-test project build, zero warnings/errors. dotnet build tests\Opc.Ua.WotCon.Samples.Tests\Opc.Ua.WotCon.Samples.Tests.csproj -p:CustomTestTarget=net10.0 -f net10.0 --verbosity minimal ``` Earlier focused integration checks passed 2,620 tests across AutoID, event queues/scheduling, source generation, MCP/package profiles and WoT. Both reviewed Mermaid diagrams rendered locally without network access. These checks are not a full solution run. The full solution has **not** been rerun for this review. Earlier `dotnet test UA.slnx -p:CustomTestTarget=net10.0 --verbosity quiet` did not pass: three AOT projects rejected VSTest and 20 Vision tests failed during graphics initialization with `OutOfMemoryException`. Remaining long-running tests were stopped at the user's request. A focused Vision rerun passed 558 tests and reproduced those 20 failures. The earlier `dotnet test UA.slnx -p:CustomTestTarget=net48 --verbosity quiet` was blocked by the former SDK pin and was not retried after the policy change. The user approved proceeding with those limitations documented; current remote CI is not claimed green. ## Related Issues - Follow-up #4842 tracks the requested 2.0.2+ benchmark/tuning and diagnostic-tool documentation refresh. #4841 supplies documentation and earlier results, not all newly requested measurements. - #4758 explains the conversion guide's earlier consolidation; the current provider contracts are now consolidated into `WotNodeSetConversion.md`. - #4839 supplies the reviewed API corrections; #4843 supplies the updated CTT issue record. - The original prose cleanup and SDK policy were user-requested without a source issue. No new runtime architecture is introduced by these documentation edits. ## Checklist _Put an `x` in the boxes that apply. You can complete these step by step after opening the PR._ - [ ] 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. - [ ] 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. - [ ] 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. --------- Co-authored-by: Roman Ettlinger <romanett98@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
370 lines
19 KiB
Markdown
370 lines
19 KiB
Markdown
# Role-Based Security (OPC UA Part 18)
|
|
|
|
## Contents
|
|
|
|
- [Overview](#overview)
|
|
- [Server side](#server-side)
|
|
- [IRoleManager](#irolemanager)
|
|
- [Authoring an identity-mapping rule with claims](#authoring-an-identity-mapping-rule-with-claims)
|
|
- [RoleConfigurationChanged event](#roleconfigurationchanged-event)
|
|
- [Typed-proxy address-space binding](#typed-proxy-address-space-binding)
|
|
- [Default impersonation flow](#default-impersonation-flow)
|
|
- [User Management (Part 18 §5)](#user-management-part-18-5)
|
|
- [User name / password storage](#user-name--password-storage)
|
|
- [Client side](#client-side)
|
|
- [Bounded role snapshots](#bounded-role-snapshots)
|
|
- [GDS](#gds)
|
|
- [Known limitations](#known-limitations)
|
|
- [References](#references)
|
|
|
|
## Overview
|
|
|
|
The OPC UA .NET Standard Stack implements the role-based security model from
|
|
[OPC UA Part 18: Role-Based Security (v1.05.06)](https://reference.opcfoundation.org/Core/Part18/v105/docs/)
|
|
together with the well-known roles defined in
|
|
[OPC UA Part 3 4.9.2](https://reference.opcfoundation.org/Core/Part3/v105/docs/4.9.2).
|
|
|
|
The nine well-known roles are pre-registered at server start:
|
|
|
|
| Role | NodeId | Reserved? | Default identities |
|
|
|------|--------|-----------|--------------------|
|
|
| `Anonymous` | `i=15644` | Yes | `Anonymous`, `AuthenticatedUser` |
|
|
| `AuthenticatedUser` | `i=15656` | Yes | `AuthenticatedUser` |
|
|
| `TrustedApplication` | `i=18625` | Yes | `TrustedApplication` |
|
|
| `Observer` | `i=15668` | No | (empty) |
|
|
| `Operator` | `i=15680` | No | (empty) |
|
|
| `Engineer` | `i=16036` | No | (empty) |
|
|
| `Supervisor` | `i=15692` | No | (empty) |
|
|
| `ConfigureAdmin` | `i=15716` | No | (empty) |
|
|
| `SecurityAdmin` | `i=15704` | No | (empty) |
|
|
|
|
Reserved roles cannot be modified or removed per Part 18 4.3 - any attempt to call `AddIdentity`, `AddApplication`, `AddEndpoint`, `RemoveIdentity`, `RemoveApplication`, `RemoveEndpoint`, or `RemoveRole` on them returns `Bad_RequestNotAllowed`.
|
|
|
|
See `src/Opc.Ua.Server/RoleBasedUserManagement/` for the source.
|
|
|
|
## Server side
|
|
|
|
### IRoleManager
|
|
|
|
The `IRoleManager` interface (`Opc.Ua.Server.IRoleManager`) is the server-side extensibility surface. The default implementation `Opc.Ua.Server.RoleManager` is fully in-memory; integrators that need persistence implement `IRoleManager` directly. For DI-hosted servers, register the implementation through `AddRoleManager(instance)` or `AddRoleManager<TManager>()` on the server builder before building the host. For a custom non-DI `StandardServer`, override `CreateRoleManager`.
|
|
|
|
Every mutator returns a `ServiceResult` that mirrors the spec-defined status codes:
|
|
|
|
- `AddIdentity` (4.4.5) - Good or Bad_InvalidArgument / Bad_AlreadyExists / Bad_RequestNotAllowed / Bad_NodeIdUnknown.
|
|
- `RemoveIdentity` (4.4.6) - Good or Bad_NotFound / Bad_RequestNotAllowed / Bad_NodeIdUnknown.
|
|
- `AddApplication` (4.4.7) - Good or Bad_InvalidArgument / Bad_AlreadyExists / Bad_RequestNotAllowed / Bad_NodeIdUnknown.
|
|
- `RemoveApplication` (4.4.8) - Good or Bad_NotFound / Bad_RequestNotAllowed / Bad_NodeIdUnknown.
|
|
- `AddEndpoint` (4.4.9) - Good or Bad_InvalidArgument / Bad_AlreadyExists / Bad_RequestNotAllowed / Bad_NodeIdUnknown.
|
|
- `RemoveEndpoint` (4.4.10) - Good or Bad_NotFound / Bad_RequestNotAllowed / Bad_NodeIdUnknown.
|
|
- `AddRole` (4.2.2) - Good or Bad_InvalidArgument / Bad_AlreadyExists.
|
|
- `RemoveRole` (4.2.3) - Good or Bad_NodeIdUnknown / Bad_RequestNotAllowed.
|
|
- `SetApplicationsExclude` / `SetEndpointsExclude` / `SetCustomConfiguration` - Good or Bad_RequestNotAllowed / Bad_NodeIdUnknown.
|
|
|
|
`IdentityMappingRuleType` is validated per Part 18 4.4.3 before storage:
|
|
|
|
- `Anonymous`, `AuthenticatedUser`, `TrustedApplication` - criteria must be empty.
|
|
- `Thumbprint` - upper-case hexadecimal, no spaces.
|
|
- `X509Subject` - `Name=Value(/Name=Value)*` grammar with names from Part 18 Table 10.
|
|
|
|
`EndpointType` comparisons in identity resolution honour Part 18 4.4.2: fields set to their default value on the rule
|
|
side act as wildcards. A rule may therefore constrain any subset of endpoint fields by assigning non-default values to
|
|
those fields. For example, this rule applies to every endpoint URL that uses `SignAndEncrypt`:
|
|
|
|
```csharp
|
|
IRoleManager roles = server.CurrentInstance.RoleManager;
|
|
|
|
roles.AddEndpoint(
|
|
ObjectIds.WellKnownRole_Engineer,
|
|
new EndpointType
|
|
{
|
|
SecurityMode = MessageSecurityMode.SignAndEncrypt
|
|
});
|
|
```
|
|
|
|
At least one field must be non-default; `AddEndpoint` returns `Bad_InvalidArgument` for a null or completely default
|
|
`EndpointType`.
|
|
|
|
> **Identity-claim criteria support**:
|
|
> - `IdentityCriteriaType.GroupId` probes the returned `IUserIdentity` for `Opc.Ua.Identity.IIdentityClaims` (see [Identity Providers](IdentityProviders.md)) and matches `IIdentityClaims.Groups`.
|
|
> - `IdentityCriteriaType.Role` matches roles asserted **inside the access token** via `IIdentityClaims.Roles`, optionally prefixed by the issuer URI as `iss/roleName`, per Part 18 4.4.4.
|
|
|
|
|
|
### Authoring an identity-mapping rule with claims
|
|
|
|
JWT authenticators that return an identity implementing `IIdentityClaims`
|
|
allow Part 18 rules to match Entra-style claims. The in-box
|
|
`RoleManager` treats entries in a role's `Identities` collection as OR
|
|
criteria, per the standard `IdentityMappingRuleType[]` shape. Add one
|
|
entry for each accepted claim value:
|
|
|
|
```csharp
|
|
IRoleManager roles = server.CurrentInstance.RoleManager;
|
|
|
|
roles.AddIdentity(
|
|
ObjectIds.WellKnownRole_Engineer,
|
|
new IdentityMappingRuleType
|
|
{
|
|
CriteriaType = IdentityCriteriaType.Role,
|
|
Criteria = "https://login.microsoftonline.com/{tenant}/v2.0/OpcUa.Engineer"
|
|
});
|
|
|
|
roles.AddIdentity(
|
|
ObjectIds.WellKnownRole_Engineer,
|
|
new IdentityMappingRuleType
|
|
{
|
|
CriteriaType = IdentityCriteriaType.GroupId,
|
|
Criteria = "00000000-1111-2222-3333-444444444444"
|
|
});
|
|
```
|
|
|
|
The first rule matches an access-token role claim `OpcUa.Engineer` only
|
|
when `IIdentityClaims.Issuer` is the Entra issuer. The second matches a
|
|
`groups` claim containing the Entra group object id. If your policy must
|
|
require both a role and a group simultaneously, implement a custom
|
|
`IRoleManager` (or a custom authorization layer) because the shipped
|
|
`RoleConfigurationOptions` DTO does not define an AND-rule collection.
|
|
|
|
### RoleConfigurationChanged event
|
|
|
|
`IRoleManager.RoleConfigurationChanged` fires after every successful mutation with the role NodeId and a `RoleConfigurationChangeKind`. Integrators can subscribe to:
|
|
|
|
- materialize dynamic-role address-space nodes when `RoleAdded` fires (the default in-memory `RoleManager` does not create address-space nodes for `AddRole` - the well-known roles are already in the standard nodeset);
|
|
- re-evaluate active sessions per Part 18 4.4.1 ("If the configuration of a Role is changed, the Role assignment to active Session shall be re-evaluated and applied");
|
|
- emit audit events beyond the spec-defined `RoleMappingRuleChangedAuditEvent`.
|
|
|
|
### Typed-proxy address-space binding
|
|
|
|
`RoleStateBinding.BindAsync(diagnosticsNodeManager, roleManager, auditServer)` uses the source-generated typed proxies (`RoleSetState`, `RoleState`, `AddIdentityMethodState`, `AddRoleMethodState`, ...). Each typed `OnCallAsync` delegate:
|
|
|
|
1. Enforces `RoleAuthorizationGate.CheckAdmin` (SecurityAdmin role over a `SignAndEncrypt` channel) - returns `Bad_SecurityModeInsufficient` or `Bad_UserAccessDenied` otherwise (Part 18 4.2 / 4.4).
|
|
2. Delegates to `IRoleManager`.
|
|
3. Reports a `RoleMappingRuleChangedAuditEvent` (Part 18 4.5).
|
|
4. Keeps the typed `Identities`, `Applications`, `Endpoints`, `ApplicationsExclude`, `EndpointsExclude` and `CustomConfiguration` property values in sync with the manager via the `RoleConfigurationChanged` event.
|
|
|
|
`DiagnosticsNodeManager.AddBehaviourToPredefinedNodeAsync` upgrades passive `BaseObjectState` instances of `RoleSetType` and `RoleType` to the typed `RoleSetState` and `RoleState` proxies at predefined-node load time.
|
|
|
|
Queued removal retains the exact binding generation and node reference it owns.
|
|
Re-adding a role advances that generation, even when the same well-known NodeId
|
|
and RoleState are reused. Cleanup rechecks the role manager and conditionally
|
|
claims the removed generation before deleting the node. A failed AddRole that
|
|
never acquired a binding cannot delete the foreign node that caused its collision.
|
|
|
|
### Default impersonation flow
|
|
|
|
Per Part 3 4.9 and Part 18 4.3 the default `RoleManager` rules already grant:
|
|
|
|
- `Anonymous` for sessions without authentication;
|
|
- `AuthenticatedUser` for any session with a non-anonymous token;
|
|
- `TrustedApplication` when the session was authenticated with a trusted ApplicationInstance certificate over a signed channel.
|
|
|
|
Any nonempty `Applications` filter requires a signed channel and an
|
|
application certificate, including when `ApplicationsExclude` is true.
|
|
The `Thumbprint` and `X509Subject` identity criteria evaluate the authenticated
|
|
**user** certificate, not the application's channel certificate. `Application`
|
|
and `TrustedApplication` criteria continue to evaluate application identity.
|
|
|
|
Additional identity-mapping rules are evaluated by `IRoleManager.ResolveGrantedRoles` after authentication. New integrations should expose claims through `IIdentityClaims` and add `IdentityMappingRuleType` entries to the role manager.
|
|
|
|
Live role changes are reconciled before the session's next request, including
|
|
`Publish`, and before background event authorization. Event permission-cache
|
|
entries are bound to the current session, effective identity and permission
|
|
versions, so an earlier `ReceiveEvents` approval cannot authorize newly generated
|
|
events after that reconciliation.
|
|
Changed role grants also retire queued events and retransmission messages from
|
|
the previous grants before the session can publish them.
|
|
|
|
### User Management (Part 18 §5)
|
|
|
|
The Part 18 §5 `UserManagementType` is bound to the standard
|
|
`Server.ServerConfiguration.UserManagement` object (NodeId `i=24290`).
|
|
For DI-hosted servers, register `IUserManagement` in the service collection
|
|
before building the host. For a custom non-DI `StandardServer`, override
|
|
`CreateUserManagement`. These startup hooks supply the implementation before
|
|
the configuration node manager binds the address space. The default
|
|
`UserManagement` implementation wraps
|
|
an existing `IUserDatabase` for credential persistence. Built-in
|
|
`LinqUserDatabase` and `JsonUserDatabase` also persist the per-user
|
|
`UserConfigurationMask` and description.
|
|
|
|
The `AddSecureServer` DI preset registers `IUserDatabase` as `LinqUserDatabase`
|
|
and `IUserManagement` as `UserManagement` using `TryAddSingleton`. After calling
|
|
that preset (or registering those services explicitly), the following
|
|
replacement changes the password policy while retaining the registered user
|
|
database. Configure it before building the host:
|
|
|
|
```csharp
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.DependencyInjection.Extensions;
|
|
using Opc.Ua.Server.UserDatabase;
|
|
using Opc.Ua.Server.UserManagement;
|
|
|
|
services.Replace(ServiceDescriptor.Singleton<IUserManagement>(provider =>
|
|
new UserManagement(
|
|
provider.GetRequiredService<IUserDatabase>(),
|
|
passwordLength: new Opc.Ua.Range { Low = 8, High = 256 },
|
|
passwordOptions:
|
|
Opc.Ua.PasswordOptionsMask.SupportDisableUser
|
|
| Opc.Ua.PasswordOptionsMask.SupportInitialPasswordChange
|
|
| Opc.Ua.PasswordOptionsMask.RequiresDigitCharacters)));
|
|
```
|
|
|
|
`IUserDatabase` commits credentials and metadata together, so disabled and
|
|
`MustChangePassword` decisions survive a restart. A custom database implements
|
|
`CreateUser`, `ResetPassword` and `UpdateUserMetadata` alongside the credential
|
|
members; each mutation must be one transaction, and a rejected or failed write
|
|
must leave the live and persisted records unchanged.
|
|
|
|
The reference server rejects disabled accounts during fresh username
|
|
authentication as well as closing their existing sessions. Custom username
|
|
verifiers must check `IUserManagement.IsUserActive` before granting an identity;
|
|
a matching password alone does not authorize a disabled account.
|
|
|
|
`UserManagementBinding.Bind` (called automatically by
|
|
`ConfigurationNodeManager.CreateServerConfiguration` when an
|
|
`IUserManagement` is injected) wires the typed `AddUser`, `ModifyUser`,
|
|
`RemoveUser` and `ChangePassword` method-state proxies, enforces
|
|
`RoleAuthorizationGate.CheckAdmin` on the admin methods (SecurityAdmin +
|
|
SignAndEncrypt) and `RoleAuthorizationGate.CheckSelfUserName` on
|
|
`ChangePassword`, and closes a deactivated user's sessions **and
|
|
subscriptions** through the server's coordinated teardown. `ModifyUser`
|
|
and `RemoveUser` wait for that teardown and return the user-change result.
|
|
A session-close failure is logged; it does not turn a committed user change
|
|
into a failed method result.
|
|
The binding resolves the server's session manager when needed because
|
|
the diagnostics address space is created before the session manager.
|
|
External deactivation notifications are tracked; `DisposeAsync` drains
|
|
accepted work. The master drains configuration shutdown work before acquiring
|
|
the address-space teardown gate, so pending session-close notifications can
|
|
complete without deadlocking shutdown.
|
|
|
|
Spec result codes honoured:
|
|
|
|
| Operation | Failure codes |
|
|
|-----------|---------------|
|
|
| `AddUser` (§5.2.5) | `Bad_AlreadyExists`, `Bad_OutOfRange`, `Bad_NotSupported`, `Bad_ConfigurationError`, `Bad_UserAccessDenied`, `Bad_SecurityModeInsufficient`, `Bad_ResourceUnavailable` |
|
|
| `ModifyUser` (§5.2.6) | `Bad_NotFound`, `Bad_OutOfRange`, `Bad_NotSupported`, `Bad_ConfigurationError`, `Bad_UserAccessDenied`, `Bad_SecurityModeInsufficient`, `Bad_InvalidSelfReference` |
|
|
| `RemoveUser` (§5.2.7) | `Bad_NotFound`, `Bad_UserAccessDenied`, `Bad_NotSupported` (NoDelete), `Bad_SecurityModeInsufficient`, `Bad_InvalidSelfReference` |
|
|
| `ChangePassword` (§5.2.8) | `Bad_IdentityTokenInvalid`, `Bad_OutOfRange`, `Bad_InvalidState`, `Bad_NotSupported` (NoChangeByUser), `Bad_SecurityModeInsufficient`, `Bad_AlreadyExists` (new == old) |
|
|
|
|
### User name / password storage
|
|
|
|
Client `AddUser`, password-bearing `ModifyUser`, and `ChangePassword` operations
|
|
reject non-confidential channels before sending credentials. Their security
|
|
decision and service Call use the same captured session/channel generation;
|
|
unsupported custom session implementations fail with `BadNotSupported`.
|
|
Non-password metadata edits remain available through their ordinary dispatch path.
|
|
|
|
The `IUserDatabase` interface (`Opc.Ua.Server.UserDatabase.IUserDatabase`) remains the extension point for username/password storage. The shipped implementations are:
|
|
|
|
- `LinqUserDatabase` - in-memory.
|
|
- `JsonUserDatabase` - JSON file backed.
|
|
|
|
The JSON testing/sample database publishes a complete temporary snapshot
|
|
through atomic file replacement. Failed writes leave the previous file
|
|
intact, and saves are serialized per database instance. Missing files
|
|
initialize an empty database; malformed or inaccessible files are logged
|
|
and reported as errors instead of silently becoming empty databases.
|
|
Authentication reads committed credential and role records without waiting
|
|
for snapshot I/O; the pending replacement is visible only to snapshot
|
|
persistence until the write succeeds. A failed write never publishes its
|
|
candidate credentials.
|
|
|
|
Self-service password changes verify the captured credential and derive the
|
|
replacement outside the credential-store and metadata-reader locks, retaining
|
|
100,000-iteration PBKDF2-SHA512. The store commits only if the user's identity
|
|
and captured verifier still match, so a concurrent password reset or change
|
|
cannot be overwritten by stale verification. The password and cleared
|
|
`MustChangePassword` flag remain one atomic persisted update, preserving the
|
|
latest other metadata. Management mutations remain serialized separately from
|
|
authentication reads; self-service hashing and snapshot I/O do not hold the
|
|
metadata write lock. Administrative mutations retain their existing metadata
|
|
publication semantics.
|
|
|
|
Password verification uses the shared fixed-time comparison with the
|
|
expected derived-key width and clears working key/password buffers on
|
|
every exit. Unknown users perform bounded dummy-key verification, and
|
|
inactive users still perform credential verification before access is
|
|
denied. This equalizes the expensive verification work; it is not a claim
|
|
that all surrounding application behavior has constant execution time.
|
|
|
|
External implementations may be provided by integrators (e.g. backed by SQL, LDAP, or a vendor-specific store).
|
|
|
|
## Client side
|
|
|
|
`Opc.Ua.Client.Roles.RoleManagementClient` is a strongly-typed async client over the standard `Server.ServerCapabilities.RoleSet` object:
|
|
|
|
```csharp
|
|
using Opc.Ua.Client.Roles;
|
|
|
|
RoleManagementClient client = session.OpenRoleManagementClient();
|
|
|
|
// List every role exposed by the server.
|
|
IReadOnlyList<RoleInfo> roles = await client.ListRolesAsync();
|
|
|
|
// Add a UserName identity rule to the Observer role.
|
|
await client.AddIdentityAsync(
|
|
Opc.Ua.ObjectIds.WellKnownRole_Observer,
|
|
new IdentityMappingRuleType
|
|
{
|
|
CriteriaType = IdentityCriteriaType.UserName,
|
|
Criteria = "alice"
|
|
});
|
|
|
|
// Toggle the ApplicationsExclude flag on the Operator role.
|
|
await client.SetApplicationsExcludeAsync(
|
|
Opc.Ua.ObjectIds.WellKnownRole_Operator, value: false);
|
|
|
|
// Add a custom role under a vendor namespace.
|
|
NodeId newRoleId = await client.AddRoleAsync(
|
|
"OpsLead",
|
|
namespaceUri: "urn:example:roles");
|
|
|
|
// Remove a dynamic role.
|
|
await client.RemoveRoleAsync(newRoleId);
|
|
```
|
|
|
|
`ListRolesAsync` includes both `RoleType` instances and instances of its
|
|
subtypes, resolving derived types through the session's node cache. Other
|
|
object types under the RoleSet are excluded.
|
|
|
|
All mutator methods require the calling session to hold the `SecurityAdmin` role and use a `SignAndEncrypt` secure channel; otherwise the server returns `Bad_UserAccessDenied` / `Bad_SecurityModeInsufficient` which surfaces as a `ServiceResultException`.
|
|
|
|
### Bounded role snapshots
|
|
|
|
Use `new RoleManagementClient(session, maxMappingEntries: 1000)` to limit a role
|
|
snapshot. The limit applies separately to identity, application and endpoint
|
|
mapping collections, before client-side decoded-array/list copies. Zero and the
|
|
existing one-argument constructor preserve legacy behavior. This does not bound
|
|
the separate `ListRolesAsync` traversal.
|
|
|
|
When a target check and subsequent role calls must use the same server session,
|
|
capture a [`SessionRequestContext`](Sessions.md#generation-bound-client-requests)
|
|
first. Resolve the target through `context.Session` and use
|
|
`new RoleManagementClient(context.Session, maxMappingEntries: 1000)` until the
|
|
operation is finished. Recovery then refuses later calls instead of silently
|
|
moving the operation to a replacement session.
|
|
|
|
## GDS
|
|
|
|
The GDS adds the following roles in addition to the standard well-known set:
|
|
|
|
- `DiscoveryAdmin`
|
|
- `SecurityAdmin`
|
|
- `CertificateAuthorityAdmin`
|
|
- `RegistrationAuthorityAdmin`
|
|
- `ApplicationSelfAdmin`
|
|
|
|
See [GdsRole.cs](https://github.com/OPCFoundation/UA-.NETStandard/blob/main/src/Opc.Ua.Gds.Server/RoleBasedUserManagement/GdsRole.cs).
|
|
|
|
## Known limitations
|
|
|
|
- **Integration tests for end-to-end RoleSet / UserManagement scenarios** (e.g. AddRole over the wire followed by browse + AddIdentity + activated session under the new grant) are tracked as a follow-up.
|
|
|
|
## References
|
|
|
|
- [OPC UA Part 18 v1.05.06 - Role-Based Security](https://reference.opcfoundation.org/Core/Part18/v105/docs/)
|
|
- [OPC UA Part 3 4.9 - Well-Known Roles](https://reference.opcfoundation.org/Core/Part3/v105/docs/4.9)
|
|
- `src/Opc.Ua.Server/RoleBasedUserManagement/`
|
|
- `src/Opc.Ua.Client/Roles/`
|
|
- `tests/Opc.Ua.Server.Tests/RoleManagerTests.cs`
|