Files
UA-.NETStandard/docs/KeyCredentialService.md
5899354441 Clarify documentation, migration guidance, and SDK selection (#4823)
# 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>
2026-10-21 10:10:55 +02:00

399 lines
16 KiB
Markdown

# KeyCredentialService Developer Guide
OPC 10000-12 §8 defines the **KeyCredentialService**. A Global Discovery
Server (GDS) uses it to issue and manage credentials, such as usernames and
passwords, API keys, or tokens, for applications that authenticate to
services outside OPC UA. Examples include Message Queuing Telemetry
Transport (MQTT) brokers and REST APIs.
> **Scope note:** This service issues credentials for resources outside
> **OPC UA**, such as MQTT brokers and REST APIs. See `ResourceUri`
> and `ProfileUris` on `KeyCredentialServiceType`. The optional bridge
> authenticator described below is **EXPERIMENTAL** under the vendor URI
> `urn:opcfoundation:netstandard:profile:authentication:keycredential`;
> it is **not** an OPC UA Part 6 §6.5.3 conformance claim. For
> standards-conformant OPC UA session authentication, use
> [AuthorizationService](AuthorizationService.md) with JSON Web Tokens
> (JWT) and the [Identity Providers](IdentityProviders.md) infrastructure.
## Contents
- [Architecture](#architecture)
- [Client API](#client-api)
- [KeyCredentialServiceClient](#keycredentialserviceclient)
- [Discovering the Service NodeId](#discovering-the-service-nodeid)
- [Server-Side: Implementing a Provider](#server-side-implementing-a-provider)
- [IKeyCredentialRequestStore](#ikeycredentialrequeststore)
- [Built-in Implementation](#built-in-implementation)
- [Writing a Custom Implementation](#writing-a-custom-implementation)
- [Wiring into the GDS Server](#wiring-into-the-gds-server)
- [Decision matrix: Push vs Pull vs Bridge](#decision-matrix-push-vs-pull-vs-bridge)
- [Hybrid (Push + Pull)](#hybrid-push--pull)
- [Resource Server Push Binding](#resource-server-push-binding)
- [Experimental KeyCredential Issued-Token Bridge](#experimental-keycredential-issued-token-bridge)
- [Audit Events](#audit-events)
- [End-to-End Example](#end-to-end-example)
## Architecture
```mermaid
flowchart LR
client["OPC UA Client<br/>(or application)"]
subgraph gds["GDS Server"]
manager["ApplicationsNodeManager"]
requests["IKeyCredentialRequestStore"]
secrets["ISecretStore"]
manager --> requests --> secrets
end
client -->|StartRequest| manager
manager -->|request ID| client
client -->|FinishRequest| manager
manager -->|credential when ready| client
client -->|Revoke| manager
```
## Client API
### KeyCredentialServiceClient
A thin client proxy for the three KeyCredentialService methods. Requires
an active `ISession` and the `NodeId` of the KeyCredentialService
instance in the server's address space.
```csharp
using Opc.Ua.Gds.Client;
// After connecting a session to the GDS server:
var kcClient = new KeyCredentialServiceClient(session, serviceNodeId);
// 1. Request a new credential
NodeId requestId = await kcClient.StartRequestAsync(
applicationUri: "urn:my-app",
publicKey: myPublicKey,
securityPolicyUri: null, // server chooses
requestedRoles: default); // server chooses
// 2. Finish (collect) the credential
var (credentialId, credentialSecret, thumbprint, policyUri, grantedRoles)
= await kcClient.FinishRequestAsync(requestId, cancelRequest: false);
// Use credentialId + credentialSecret to authenticate to the
// target service (MQTT broker, REST API, etc.)
// 3. Revoke when no longer needed
await kcClient.RevokeAsync(credentialId);
```
### Discovering the Service NodeId
The KeyCredentialService instance is typically found under the
server's `Directory` or `ServerConfiguration` node. Browse for
objects of type `KeyCredentialServiceType` (namespace 0):
```csharp
// Browse the server for KeyCredentialServiceType instances
var browser = new Browser(session);
// ... or use the well-known NodeId if your GDS exposes one.
```
## Server-Side: Implementing a Provider
### IKeyCredentialRequestStore
The server-side abstraction for the credential lifecycle:
```csharp
public interface IKeyCredentialRequestStore
{
// Begin a new credential request. Returns a request ID.
NodeId StartRequest(
string applicationUri,
ByteString publicKey,
string? securityPolicyUri,
ArrayOf<NodeId> requestedRoles);
// Complete or cancel a request. Returns issued credential data.
KeyCredentialRequestState FinishRequest(
NodeId requestId,
bool cancelRequest,
out string? credentialId,
out ByteString credentialSecret,
out string? certificateThumbprint,
out string? securityPolicyUri,
out ArrayOf<NodeId> grantedRoles);
// Revoke a previously issued credential.
void Revoke(string credentialId);
}
```
### Built-in Implementation
`InMemoryKeyCredentialRequestStore` provides a ready-to-use
in-process implementation. It auto-approves requests and generates
random 32-byte secrets.
**With ISecretStore integration** — credential secrets are persisted
through any `ISecretStore` backend (Key Vault, DPAPI, etc.):
```csharp
// Use the default in-memory secret store
var store = new InMemoryKeyCredentialRequestStore();
// Or plug in a production secret store
ISecretStore vault = new MyKeyVaultSecretStore("KeyCredential");
var store = new InMemoryKeyCredentialRequestStore(vault);
```
### Writing a Custom Implementation
For production systems with approval workflows:
```csharp
public class DatabaseKeyCredentialStore : IKeyCredentialRequestStore
{
private readonly IDbConnection _db;
public NodeId StartRequest(
string applicationUri,
ByteString publicKey,
string? securityPolicyUri,
ArrayOf<NodeId> requestedRoles)
{
// 1. Insert a pending request into the database
// 2. Return the generated request ID
// 3. Optionally notify an admin for approval
var id = _db.InsertPendingRequest(applicationUri, publicKey);
return new NodeId(id);
}
public KeyCredentialRequestState FinishRequest(
NodeId requestId,
bool cancelRequest,
out string? credentialId, ...)
{
var record = _db.GetRequest(requestId);
if (record.State == "Pending")
{
// Still awaiting approval
credentialId = null;
// ... set other out params to defaults
return KeyCredentialRequestState.New;
}
// Return the approved credential
credentialId = record.CredentialId;
// ...
return KeyCredentialRequestState.Completed;
}
public void Revoke(string credentialId)
{
_db.RevokeCredential(credentialId);
// Optionally notify the target service to invalidate
}
}
```
### Wiring into the GDS Server
Set the `KeyCredentialRequestStore` property on the
`ApplicationsNodeManager` (done via `GlobalDiscoverySampleServer`
or a custom server):
```csharp
// In your INodeManagerFactory or server setup:
var appNodeManager = new ApplicationsNodeManager(server, configuration, ...);
appNodeManager.KeyCredentialRequestStore =
new InMemoryKeyCredentialRequestStore(mySecretStore);
```
## Decision matrix: Push vs Pull vs Bridge
| Model | Primary actor | Use when | Standard / conformance posture |
|---|---|---|---|
| Pull (`KeyCredentialServiceType`) | Client/application asks a GDS to issue a credential. | The GDS owns approval and issuance; the caller later retrieves the issued secret with `FinishRequest`. | OPC 10000-12 §8 KeyCredentialService. |
| Push (`KeyCredentialConfigurationFolderType`) | Administrator or provisioning agent writes credentials to a resource server. | A resource server must store, rotate, or delete credentials locally through `CreateCredential`, `UpdateCredential`, and `DeleteCredential`. | OPC 10000-12 §8 Push model; enabled with `WithKeyCredentialPush()`. |
| Bridge (`KeyCredentialBridgeAuthenticator`) | OPC UA client presents a KeyCredential proof as an issued identity token. | Closed deployments need an interim bridge between GDS-issued secrets and UA session authentication. | **Experimental vendor extension only; not a Part 6 §6.5.3 conformance claim.** |
### Hybrid (Push + Pull)
- Enable both models when a GDS issues credentials (Pull) and hosts the Push subject. Admin tools can push
freshly issued credentials to target resource servers in one round-trip.
- For wiring in the same process, use `services.AddOpcUa().AddGdsServer(...).WithKeyCredentialPush()`.
The Pull side stays on the GDS, and the Push side is enabled on the same node so admin clients write
credentials directly to the GDS's resource-server view.
- For wiring across processes, the GDS uses the default Pull path (`InMemoryKeyCredentialRequestStore`),
while each resource server enables Push with `WithKeyCredentialPush()`. The admin tool reads from the
GDS and writes to each resource server.
- The bridge authenticator is independent of Push/Pull: it lets the resource server accept KeyCredential
blobs as a UA identity. The hybrid model addresses issuance and distribution; the bridge addresses
consumption.
## Resource Server Push Binding
A regular OPC UA resource server can opt in to the Part 12 §8 Push model
with `WithKeyCredentialPush()`. The binding mounts on the standard
`ServerConfiguration/KeyCredentialConfiguration` folder by default and
stores secrets through `IKeyCredentialStore` (default:
`InMemoryKeyCredentialStore` backed by `ISecretStore`).
```csharp
using Microsoft.Extensions.DependencyInjection;
using Opc.Ua;
using Opc.Ua.Server.Hosting;
services.AddOpcUa()
.AddServer(options =>
{
options.ApplicationUri = "urn:my-resource-server";
options.ProductUri = "uri:my-company:resource-server";
options.EndpointUrls.Add("opc.tcp://localhost:4840");
})
.WithKeyCredentialPush();
```
Production deployments should register an `IKeyCredentialStore` backed by
a durable secret store before calling `WithKeyCredentialPush()`.
The standard folder remains in namespace 0. Created and restored credential
instances use a nonstandard namespace owned by the binding node manager
(the diagnostics namespace for `ConfigurationNodeManager`), so their
properties and methods are addressable through Read, Browse, and Call.
Descendant NodeIds are allocated per instance through the configured factory,
so creating another credential does not alias an existing credential's properties.
Use the returned `CredentialNodeId` and browse its children rather than
assuming a namespace index. A custom folder keeps its own namespace;
standalone bindings using `KeyCredentialPushSubject.NamespaceUri` must
register that namespace with their hosting node manager.
`GetEncryptingKey` returns an application certificate from the server's active
certificate registry. `UpdateCredential` decrypts a UA Binary
`RsaEncryptedSecret` before passing the usable secret to `IKeyCredentialStore`.
It verifies the declared policy, certificate thumbprint, envelope, signature
and timestamp; invalid input never reaches the store. Both methods require
the SecurityAdmin role and an encrypted SecureChannel.
The envelope nonce is deliberately not compared with a session nonce:
outside `ActivateSession`, OPC UA Part 4 Table 185 requires the receiver not
to check it.
The push binding accepts `Basic256Sha256`, `Aes128_Sha256_RsaOaep` and
`Aes256_Sha256_RsaPss`. Restrict or reorder these through
`KeyCredentialPushOptions.AllowedSecurityPolicyUris`; the first entry is the
default for `GetEncryptingKey`. ECC/RSA-DH policies are explicitly rejected
with `BadSecurityPolicyRejected`: this binding does not provide the required
ephemeral-key exchange. Omitting the policy **and** certificate thumbprint
retains the standard clear-secret-over-encrypted-channel mode. Supplying a
policy never causes ciphertext to be stored as if it were a plaintext secret.
For direct construction, the original constructor remains available and
`ConfigurationNodeManager.BindKeyCredentialPushAsync` supplies the server's
registry. A standalone caller can instead pass an `ICertificateRegistry`
and `ISecurityPolicyRegistry` to the additional constructor. Temporary decode
buffers are cleared; the credential record handed to a custom store remains
valid if that store retains it.
## Experimental KeyCredential Issued-Token Bridge
> **WARNING — EXPERIMENTAL**: `KeyCredentialBridgeAuthenticator` is a
> vendor extension under
> `urn:opcfoundation:netstandard:profile:authentication:keycredential`.
> It is **not** a Part 6 §6.5.3 conformance claim. Deployments that
> claim OPC UA conformance **MUST NOT** use this bridge as their
> standards-conformant user-token mechanism. Use it only in closed
> deployments where the GDS, resource server, and clients are controlled
> by the same operator.
The bridge lets a server validate a JSON issued-token payload containing
a `credentialId`, nonce timestamp, and HMAC proof. The server looks up
the credential in `IKeyCredentialStore`, validates the proof with the
stored secret, and returns an identity populated from the credential's
subject claims.
Client-side, `GdsKeyCredentialAccessTokenProvider` adapts a
`KeyCredentialServiceClient` to `IAccessTokenProvider`, so the standard
`IssuedTokenIdentityProvider` can materialize a UA `IssuedIdentityToken`
for the bridge profile.
The bridge token payload carries a `"version"` field. It versions this vendor
extension's own JSON payload, and has no OPC UA counterpart: Part 6 §6.5.3 and
the GDS KeyCredential services define neither this payload nor a version field.
The server accepts `"version": 2` only, whose HMAC proof covers a non-empty
`aud` that must exactly match the resource server's `ApplicationUri`, so a proof
minted for one server is rejected by another.
The provider implements `IEndpointAccessTokenProvider`. Normal identity
selection forwards the selected endpoint automatically, including for the
vendor bridge profile. The audience is the first non-blank value of metadata
`Audience`, metadata `ResourceUri`, or `endpoint.Server.ApplicationUri`.
Thus a policy containing only `{"authorityUri":"urn:example:gds"}` still binds
the proof to the target resource server, never to the GDS authority or client
application. Explicit audience/resource metadata must identify that same server.
```csharp
var identities = new IssuedTokenIdentityProvider(
keyCredentialProvider, GdsKeyCredentialAccessTokenProvider.ProfileUri);
// Direct acquisition outside normal identity selection also supplies the target.
using AccessToken token = await keyCredentialProvider.AcquireAsync(
metadata, targetEndpoint, cancellationToken);
```
The metadata-only acquisition overload requires an explicit non-blank audience
or resource URI. If none is available, acquisition fails before requesting or
reading credential secrets instead of emitting an unusable unbound token.
## Audit Events
All KeyCredentialService operations emit audit events automatically:
| Operation | Audit Event Type |
|-----------|-----------------|
| StartRequest | `KeyCredentialRequestedAuditEventType` |
| FinishRequest | `KeyCredentialDeliveredAuditEventType` |
| Revoke | `KeyCredentialRevokedAuditEventType` |
Credential secrets are **never** included in audit payloads.
## End-to-End Example
```csharp
// ── Server Side ──────────────────────────────────────
// 1. Create the credential store
var secretStore = new InMemorySecretStore("KeyCredentials");
var kcStore = new InMemoryKeyCredentialRequestStore(secretStore);
// 2. Create the GDS server with credential support
var gdsServer = new GlobalDiscoverySampleServer(
database, requestStore, certGroup, userDb, telemetry);
// 3. After server starts, wire the store
// (done automatically by ApplicationsNodeManager when
// KeyCredentialRequestStore is set before CreateAddressSpace)
// ── Client Side ──────────────────────────────────────
// 1. Connect to the GDS
var gdsClient = new GlobalDiscoveryServerClient(config);
await gdsClient.ConnectAsync(gdsEndpointUrl);
// 2. Find the KeyCredentialService node
// (browse or use a well-known NodeId)
// 3. Create the client proxy
var kcClient = new KeyCredentialServiceClient(
gdsClient.Session, serviceNodeId);
// 4. Request → Finish → Use → Revoke
NodeId reqId = await kcClient.StartRequestAsync(
"urn:my-mqtt-bridge", default, null, default);
var (credId, secret, _, _, _) =
await kcClient.FinishRequestAsync(reqId, false);
// Use credId/secret to connect to MQTT broker...
// When done:
await kcClient.RevokeAsync(credId);
```