diff --git a/.claude/rules/drivers.md b/.claude/rules/drivers.md index 4c267ace9..978b9049c 100644 --- a/.claude/rules/drivers.md +++ b/.claude/rules/drivers.md @@ -216,6 +216,12 @@ host logger factory (wired in `DriverFactoryBootstrap`; the FOCAS and TwinCAT fa Secondary's claim takes the Primary's over instead of coexisting (never make it random again). The claim subscribes to its own STATE topic and re-asserts over an OFFLINE it did not publish (older/equal ts ⇒ republish; newer ⇒ fresh claim with a newer ts; ≤ 1 per 2 s). +- **Galaxy secured writes (#1017):** `MxAccess.SecuredWrites` = `Refuse` (default, #991 local `BadUserAccessDenied`) | + `ApiKeyIdentity` — a SecuredWrite runs as the CALLING key's own `/api-keys` Galaxy identity (no fallback account; + anonymous/no identity ⇒ refused): own plain-advised handle → `AuthenticateUser` every write → `WriteSecured(id, 0)`; + gateway key needs `invoke:secure`. VerifiedWrite is refused in every mode (no verifier in an OPC UA Write — by + design). The caller rides `WriteCaller` → `RouteNodeWrite`/`WriteAttribute.Caller` → `ICallerAwareWritable`; the gRPC + data-connection write path carries no caller yet. Not live-gated. `docs/drivers/Galaxy.md` §Secured writes. - **No driver-side history (#655):** `IHistoryProvider`, `DriverCapability.HistoryRead`, `HistoryReadStatusException` and the OpcUaClient history passthrough are deleted — nothing ever dispatched HistoryRead to a driver; it is served only by the server-wide `IHistorianDataSource`. `isHistorized` on an OpcUaClient tag means OtOpcUa records it, not that upstream diff --git a/docs/Configuration.md b/docs/Configuration.md index 99c1c6210..2319daa46 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -459,7 +459,7 @@ The Galaxy/MxAccess connection settings are **not an `appsettings` section.** Th | Record | Key fields (default) | Meaning | |---|---|---| | `GalaxyGatewayOptions` (`Gateway`) | `Endpoint`; `ApiKeySecretRef`; `UseTls` (`true`); `CaCertificatePath` (`null`); `ConnectTimeoutSeconds` (`10`); `DefaultCallTimeoutSeconds` (`30`); `StreamTimeoutSeconds` (`0` = unlimited); `KeepAlivePingDelaySeconds` (`15`, `0` = no pings); `KeepAlivePingTimeoutSeconds` (`10`) — HTTP/2 keep-alive on the driver's gateway channels, so a silently dead connection faults the event stream (#991 G-19) | mxaccessgw gateway connection. `ApiKeySecretRef` supports `secret:galaxy/` (or `secret:otopcua/galaxy/`) / `env:OTOPCUA_GALAXY_` (or legacy `env:GALAXY_MXGW_`) / `dev:KEY` / literal forms (resolved at `InitializeAsync`); prefer `secret:` in production. Any other `secret:`/`env:` reference and every `file:` reference is refused at save, deploy (`CredentialReferenceOutOfScope`), Test Connect, browse and resolve — #815, see `docs/security.md` §"Credential references are namespaced per driver". Never store a cleartext key. | -| `GalaxyMxAccessOptions` (`MxAccess`) | `ClientName`; `PublishingIntervalMs` (`1000`); `WriteUserId` (`0` = anonymous; the user a raw `Write` carries; SecuredWrite/VerifiedWrite attributes are refused `BadUserAccessDenied`); `EventPumpChannelCapacity` (`50000`) | MXAccess client identity + tuning. `ClientName` **must be unique per OtOpcUa instance** (redundancy pairs enforce this). | +| `GalaxyMxAccessOptions` (`MxAccess`) | `ClientName`; `PublishingIntervalMs` (`1000`); `WriteUserId` (`0` = anonymous; the user a raw `Write` carries); `SecuredWrites` (`Refuse` = SecuredWrite attributes refused `BadUserAccessDenied`; `ApiKeyIdentity` = written as the calling API key's Galaxy identity via `AuthenticateUser` + `WriteSecured`, gateway key needs `invoke:secure` — #1017; VerifiedWrite always refused); `EventPumpChannelCapacity` (`50000`) | MXAccess client identity + tuning. `ClientName` **must be unique per OtOpcUa instance** (redundancy pairs enforce this). | | `GalaxyRepositoryOptions` (`Repository`) | `DiscoverPageSize` (`5000`); `WatchDeployEvents` (`true`) | Galaxy Repository browse paging + deploy-event watching. | | `GalaxyReconnectOptions` (`Reconnect`) | `InitialBackoffMs` (`500`); `MaxBackoffMs` (`30000`); `ReplayOnSessionLost` (`true`) | In-driver reconnect-supervisor backoff. | | (top-level) | `ProbeTimeoutSeconds` (`30`, range 1–60) | AdminUI Test-Connect probe timeout. | diff --git a/docs/drivers/Galaxy.md b/docs/drivers/Galaxy.md index 0c55ceb9f..2fbb15641 100644 --- a/docs/drivers/Galaxy.md +++ b/docs/drivers/Galaxy.md @@ -82,7 +82,7 @@ Project root files: `DriverConfig` JSON binds to `Config/GalaxyDriverOptions.cs`. The four sections are: - **`Gateway`** — endpoint, API key secret ref (`secret:galaxy/` · `secret:otopcua/galaxy/` · `env:OTOPCUA_GALAXY_` · legacy `env:GALAXY_MXGW_` · `dev:KEY` · literal; anything else, incl. `file:`, is refused — #815 (an already-deployed driver keeps resolving a pre-#815 ref on init and every gateway reconnect in deprecated warn-only mode until its next deploy), [`docs/security.md`](../security.md) §"Credential references are namespaced per driver"), TLS knobs, connect/call/stream timeouts. `StreamTimeoutSeconds = 0` keeps the long-lived `StreamEvents` RPC open for the driver's lifetime. `KeepAlivePingDelaySeconds` (`15`) / `KeepAlivePingTimeoutSeconds` (`10`) — HTTP/2 keep-alive pings on every gateway channel (#991 G-19, below); `0` disables them. Both have AdminUI fields in the driver form's connection panel (#1045 — the form used to drop them on save, resetting a `0` opt-out to the default). The form now overlays only the keys it edits onto the stored JSON (`GalaxyDriverForm.OwnedPaths` + `DriverConfigJsonOverlay`), so a key it does not model survives a save; a new form field must add its path there. -- **`MxAccess`** — `ClientName` (must be unique per OtOpcUa instance — redundancy pairs enforce uniqueness at install time), `PublishingIntervalMs` (forwarded as `buffered_update_interval_ms` on subscribe), `WriteUserId` — the user id a raw `Write` carries (secured/verified writes are refused, see below), `EventPumpChannelCapacity` (default 50_000 — one second of headroom at 50k tags / 1Hz; tune via the `galaxy.events.dropped` metric). +- **`MxAccess`** — `ClientName` (must be unique per OtOpcUa instance — redundancy pairs enforce uniqueness at install time), `PublishingIntervalMs` (forwarded as `buffered_update_interval_ms` on subscribe), `WriteUserId` — the user id a raw `Write` carries; `SecuredWrites` — `Refuse` (default) | `ApiKeyIdentity` (#1017, [Secured writes under the caller's Galaxy identity](#secured-writes-under-the-callers-galaxy-identity-1017)), `EventPumpChannelCapacity` (default 50_000 — one second of headroom at 50k tags / 1Hz; tune via the `galaxy.events.dropped` metric). - **`Repository`** — `DiscoverPageSize`, `WatchDeployEvents`. - **`Reconnect`** — `InitialBackoffMs`, `MaxBackoffMs`, `ReplayOnSessionLost` (default `true`: after a gateway session is recreated, re-issue `SubscribeBulk` for every tracked subscription; `false` leaves them stranded — Bad + Degraded, see [Reconnect + Replay](#reconnect--replay)). - **`AlarmAck`** (optional, lmxopcua#749) — `FallbackUser`, `FallbackDomain`, `FallbackPasswordSecretRef`. See [Alarm acknowledge credential](#alarm-acknowledge-credential). `ConfirmTimeoutMs` (default `10000`, max `120000`, `0` = do not wait, negative = default; #869) — see [Ack confirmation](#ack-confirmation-869). @@ -187,6 +187,64 @@ the fallback secret must exist on the node that serves the OPC UA session and ho driver; on a split admin/driver topology create them on the driver nodes too (`/admin/secrets` or the `secret` CLI) under exactly those names. +### Secured writes under the caller's Galaxy identity (#1017) + +ArchestrA classifies some attributes **SecuredWrite** (the writer must authenticate) or **VerifiedWrite** (a second, +verifying user must authenticate too). MXAccess writes them with `AuthenticateUser(user, password)` → user id → +`WriteSecured(current user, verifier user)`. mxaccessgw exposes both commands unchanged (scope **`invoke:secure`**), +and its 2026-11-13 capture shows the sequence committing: an item **plain**-advised by the writing registration, +`AuthenticateUser`, then `WriteSecured(userId, 0)` (`docs/LiveCaptures-2026-11-13.md` §4 in mxaccessgw — on +`MxSecurityOperate` UDAs; 36 more secured writes in §5). No gateway change is needed for SecuredWrite. + +**Opt-in, per driver: `MxAccess.SecuredWrites`** — `Refuse` (default; the #991 local `BadUserAccessDenied`) or +`ApiKeyIdentity` (AdminUI driver form, MXAccess panel, "Secured writes"). The factory refuses any other value. + +**Whose identity.** The OPC UA data plane is machine-to-machine: a session is an API key or anonymous, and carries +no Galaxy password. A SecuredWrite therefore runs as **the calling key's own Galaxy identity** — the account mapped +to the key on AdminUI `/api-keys` (the same `otopcua/apikeys//galaxy-ack-{user,password}` secrets an +alarm acknowledge from that key uses; `IGalaxyAckCredentialResolver.ResolveKeyIdentityAsync`). Unlike the ack there +is **no fallback account**: an anonymous session, a key with no identity, or a key whose identity is broken (user +without a password secret, unreadable store) is refused `BadUserAccessDenied` and nothing reaches the gateway — a +secured write is never attributed to a shared account. OtOpcUa's own `WriteOperate` gate / ACL runs first, as for +every write; the Galaxy then enforces the account's own permission on the attribute (MXAccess 1016 +`UserNotHavingAccessRights` ⇒ `BadUserAccessDenied`). + +**How the write reaches the driver.** `OtOpcUaNodeManager.OnEquipmentTagWrite` builds a `WriteCaller(principal, +apiKeyId)` from the session identity → `IOpcUaNodeWriteGateway.WriteAsync(…, caller, …)` → `RouteNodeWrite.Caller` → +`DriverInstanceActor.WriteAttribute.Caller` → `ICallerAwareWritable.WriteAsync(writes, caller, ct)` (a new optional +`Core.Abstractions` capability; every other driver keeps `IWritable`). `GalaxyDriver` hands its writer a lazily +resolved identity source only in `ApiKeyIdentity` mode with a caller present; the writer resolves it at most once +per batch and only when a SecuredWrite tag is in the batch. + +**The wire sequence** (`GatewayGalaxyDataWriter.WriteSecuredOneAsync`): the writer's own item handle for the secured +path (separate from the raw path's supervisory-advised handle — MXAccess allows one advise mode per handle), plain +`Advise` once per handle per session (a failed advise fails the write closed, `BadCommunicationError`, like the raw +path) → `AuthenticateUser(DOMAIN\user, password)` on **every** write (no cached user id: MXAccess's user-id lifetime +is unverified, and a rotated or revoked identity must take effect on the next write) → `WriteSecured(current = that +id, verifier = 0)`, its correlated `OnWriteComplete` translated exactly like a raw write. A non-OK `AuthenticateUser` +or user id 0 ⇒ `BadUserAccessDenied` with no `WriteSecured`. The password goes only into the `AuthenticateUser` +command: every log line names the user, never the password, and gateway text is scrubbed of it. A gRPC +`PermissionDenied` (the driver's gateway key lacks `invoke:secure`) ⇒ `BadUserAccessDenied` with a Warning naming the +scope. + +**VerifiedWrite stays refused, in every mode — by design, not a gap.** It needs a second, *verifying* user; MXAccess +refuses one with no verifier (1008) and one whose verifier is the writer (8018), both live-captured. An OPC UA Write +carries one caller and no verifier, and storing a verifier credential per key would let one client satisfy the +two-person rule alone. Supporting it would need a verifier carried in the request (e.g. a Method with both +identities) — a product decision, not plumbing. + +**Not covered (yet):** writes over the gRPC data connection (`DataConnectionGrpcService` → `RouteRichWrite`) carry no +caller, so a SecuredWrite there is refused as before even in `ApiKeyIdentity` mode. Not live-gated. + +**Live-gate checklist (mxaccessgw + a Galaxy with a SecuredWrite UDA):** the driver's gateway key holds +`invoke:secure`; map a Galaxy account to an API key on `/api-keys`; set `SecuredWrites = ApiKeyIdentity`; write the +attribute through that key ⇒ value commits, Good, and the Galaxy/Historian attributes the write to the mapped user; +the same write anonymously / through a key with no identity ⇒ `BadUserAccessDenied`, nothing in the gateway log; a +wrong password ⇒ `BadUserAccessDenied` naming the user, password absent from every log; an account without the +attribute's permission ⇒ `BadUserAccessDenied` (1016); a VerifiedWrite attribute ⇒ `BadUserAccessDenied` with no +gateway traffic; a raw (FreeAccess) write on the same attribute's object still commits (the two handles coexist); +a gateway reconnect re-adds + re-advises the secured handle. + Full per-field descriptions live in `Config/GalaxyDriverOptions.cs`. The full JSON skeleton is reproduced in [docs/v2/driver-specs.md §1](../v2/driver-specs.md). ## Reconnect + Replay @@ -238,13 +296,14 @@ Every (re)open of `StreamAlarms` replays the gateway's active-alarm snapshot. `G - **A dropped change is re-read (#991 G-4).** MXAccess sends a value only when it changes, so a data change the full channel drops (newest-dropped) used to leave its tag at the previous value, Good, until the attribute next changed. The pump records the item handles of dropped data changes and, once its channel has drained (so the resync is not lost to the same congestion), the driver re-advises exactly those tags — an advise is answered with the current value — rebinds them, and releases the superseded handles. One coalescing background worker; serialised with the replay-gap re-snapshot. The `galaxy.events.dropped` counter is unchanged; each burst logs one Warning ("re-reading them") and one Information line with the re-advised count. **Rate-limited (#991 review):** passes are at least 5 s apart and drops reported meanwhile coalesce into the next pass — repeated overflow bursts used to start a pass as soon as the previous one ended, re-advising (and pushing initial values into) the very channel that was overflowing. **A pass whose gateway session is gone no longer dials:** a reconnect completing between two subscriptions of a re-advise pass (resync, replay-gap re-snapshot, reconnect replay) used to send the next SubscribeBulk to the NEW session under the OLD session number; the rebind refused it and those live advises were never bound or released (then duplicated by the new session's replay). They cannot simply be released afterwards — once the session has moved, which session issued a reply's handles is ambiguous and old numbers are reused (#861) — so the pass stops before dialling. - **OPC DA limit bits do not warn (#991 G-2).** `StatusCodeMap.FromQualityByte` masks the two limit bits (`QQSSSSLL`) before its table lookup, so `Good | LowLimited` (0xC1) and friends map like the unlimited quality. A byte still unlisted after the mask logs one Warning per distinct value per process — it used to log one per event on the pump's dispatch thread, enough to back the channel up into drops. - **The deploy watcher paces every stream end (#991 G-3).** A `WatchDeployEvents` stream the gateway completes cleanly is re-subscribed after the same capped exponential backoff as a faulted one (1 s doubling to 30 s), and the backoff resets only after a stream stayed open 60 s — an event alone (the bootstrap every stream delivers) no longer resets it. It used to re-open immediately, hammering a gateway that ends its streams after the bootstrap. -- **Secured / verified writes are REFUSED `BadUserAccessDenied`, locally (#991 G-1 + review).** The driver has no - ArchestrA user identity: no `AuthenticateUser` flow, no supervisory advise for a secured item, and a gateway key would - additionally need `invoke:secure`. G-1 briefly routed SecuredWrite / VerifiedWrite attributes to `WriteSecured`, which - therefore could never succeed, and the gateway's refusal surfaced as `BadCommunicationError` (a comms fault). Until a - real per-caller identity flow exists (follow-up — like the #749 ack credential) a write to such an attribute returns - `BadUserAccessDenied` before anything reaches the wire (no AddItem / advise / Write; one Warning per attribute; no - health impact). The per-tag classification map that makes the refusal local is still **seeded for the authored tags** +- **Secured / verified writes are REFUSED `BadUserAccessDenied` by default, locally (#991 G-1 + review); a SecuredWrite + can opt in to the caller's identity (#1017, [below](#secured-writes-under-the-callers-galaxy-identity-1017)).** By + default the driver has no ArchestrA user identity to write under. G-1 briefly routed SecuredWrite / VerifiedWrite + attributes to `WriteSecured` with no `AuthenticateUser`, which therefore could never succeed, and the gateway's refusal + surfaced as `BadCommunicationError` (a comms fault). With `MxAccess.SecuredWrites = Refuse` (the default) a write to + such an attribute returns `BadUserAccessDenied` before anything reaches the wire (no AddItem / advise / Write; one + Warning per attribute; no health impact); a VerifiedWrite is refused in every mode. The per-tag classification map that + makes the refusal local (and routes an opted-in SecuredWrite) is still **seeded for the authored tags** at `InitializeAsync` and on every deploy-watcher rediscovery, in the background, by one rooted depth-0 `DiscoverHierarchy` per authored object (`Browse/GatewayGalaxyAttributeSecuritySource`, 4 concurrent; cost tracks the authored objects, not the Galaxy) — only `DiscoverAsync` filled it before, and the runtime never calls that on a served diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/IOpcUaNodeWriteGateway.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/IOpcUaNodeWriteGateway.cs index 17a10b80d..47ca9a3c3 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/IOpcUaNodeWriteGateway.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/IOpcUaNodeWriteGateway.cs @@ -22,6 +22,23 @@ public interface IOpcUaNodeWriteGateway /// Cancellation token. /// A task resolving to the device-write outcome. Task WriteAsync(string nodeId, object? value, AddressSpaceRealm realm, CancellationToken ct); + + /// + /// #1017 — carrying WHO wrote + /// (the session's principal + API key id), so a driver whose device enforces per-user write permission + /// () can act on it. The default + /// implementation drops the caller — a gateway that cannot carry it behaves exactly as before. + /// + /// The full ns-qualified node id being written. + /// The value the client wrote. + /// The namespace realm of . + /// Who issued the write; null when unknown. + /// Cancellation token. + /// A task resolving to the device-write outcome. + Task WriteAsync( + string nodeId, object? value, AddressSpaceRealm realm, + ZB.MOM.WW.OtOpcUa.Core.Abstractions.WriteCaller? caller, CancellationToken ct) + => WriteAsync(nodeId, value, realm, ct); } /// Outcome of routing an inbound node write to the backing driver. diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/ICallerAwareWritable.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/ICallerAwareWritable.cs new file mode 100644 index 000000000..f2e1ddb99 --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/ICallerAwareWritable.cs @@ -0,0 +1,31 @@ +namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions; + +/// +/// Who issued a write (#1017): the authenticated data-plane principal and, for a key-bearing session, the +/// public id of the API key it authenticated with. Carries no secret. null = an +/// anonymous session (or a write with no client session behind it). +/// +/// The ACL principal (e.g. the key's principal, or anonymous); null when unknown. +/// The authenticating API key's public id; null for anonymous. +public sealed record WriteCaller(string? Principal, string? ApiKeyId); + +/// +/// Optional companion to for a driver whose device enforces a per-USER write +/// permission and can therefore act on the caller's identity (#1017 — the Galaxy driver's SecuredWrite +/// attributes, written under the calling API key's Galaxy account). The runtime calls this overload instead +/// of whenever the write carries a . It must keep +/// every other behaviour of ; a caller the driver cannot map is refused +/// per write (e.g. BadUserAccessDenied), never silently written under another identity. +/// +public interface ICallerAwareWritable : IWritable +{ + /// Write a batch on behalf of ; one result per request, in order. + /// Pairs of full reference + value to write. + /// Who issued the write. + /// Cancellation token; the driver should abort the batch if cancelled. + /// One per requested write, in the same order. + Task> WriteAsync( + IReadOnlyList writes, + WriteCaller caller, + CancellationToken cancellationToken); +} diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Contracts/GalaxyDriverOptions.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Contracts/GalaxyDriverOptions.cs index 729f3de91..a19fb2b7c 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Contracts/GalaxyDriverOptions.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Contracts/GalaxyDriverOptions.cs @@ -176,7 +176,34 @@ public sealed record GalaxyMxAccessOptions( string ClientName, int PublishingIntervalMs = 1000, int WriteUserId = 0, - [Range(1, int.MaxValue)] int EventPumpChannelCapacity = 50_000); + [Range(1, int.MaxValue)] int EventPumpChannelCapacity = 50_000) +{ + /// + /// How a write to a SecuredWrite attribute is handled (#1017). Default + /// — refused BadUserAccessDenied locally (#991). A + /// VerifiedWrite attribute is refused in every mode. + /// + public GalaxySecuredWriteMode SecuredWrites { get; init; } = GalaxySecuredWriteMode.Refuse; +} + +/// How the Galaxy driver handles a write to a SecuredWrite attribute (#1017). +/// Always (de)serialised as its NAME, whatever the caller's serializer options: the driver factory parses +/// the string, and the browser/probe deserialise the options with options that may lack an enum converter. +[System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))] +public enum GalaxySecuredWriteMode +{ + /// Refuse it BadUserAccessDenied before anything reaches the gateway (the #991 behaviour). + Refuse, + + /// + /// Write it as the CALLING session's API key's Galaxy identity — the account mapped to the key on AdminUI + /// /api-keys (the same identity a native alarm acknowledge from that key uses, + /// ): AuthenticateUser then WriteSecured. Anonymous + /// sessions and keys with no (or a broken) identity are refused; there is NO driver fallback account for + /// writes. Needs the driver's gateway API key to hold the invoke:secure scope. + /// + ApiKeyIdentity, +} /// /// Galaxy Repository browse-side knobs consumed by PR 4.1's GalaxyDiscoverer. diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs index 367bfce8e..74de232e0 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs @@ -38,7 +38,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy; /// /// public sealed class GalaxyDriver - : IDriver, ITagDiscovery, IReadable, IWritable, ISubscribable, IRediscoverable, IHostConnectivityProbe, IAlarmSource, IAlarmInitialStateSignal, IAlarmAcknowledgePreflight, IAlarmAcknowledgeConfirmation, ISkippedTagReporter, IDisposable, IAsyncDisposable + : IDriver, ITagDiscovery, IReadable, IWritable, ICallerAwareWritable, ISubscribable, IRediscoverable, IHostConnectivityProbe, IAlarmSource, IAlarmInitialStateSignal, IAlarmAcknowledgePreflight, IAlarmAcknowledgeConfirmation, ISkippedTagReporter, IDisposable, IAsyncDisposable { /// Authored tags this driver could not dial — a TagConfig with no usable /// attributeRef has no MXAccess address to bind. @@ -396,7 +396,7 @@ public sealed class GalaxyDriver /// /// Test-visible ctor — inject custom seams so , - /// , , and + /// , , and /// can be exercised against canned data without /// building real gRPC channels. /// @@ -908,7 +908,7 @@ public sealed class GalaxyDriver /// /// #991 G-1 — one security seed pass: fetch the authored objects' attributes and record each authored tag's - /// under its RawPath, the key resolves against. + /// under its RawPath, the key resolves against. /// Before this the map was filled only by , which the runtime never calls on a /// served driver. Never throws; a failed or late pass leaves the map as it was (FreeAccess for anything /// unseen, i.e. the raw path). @@ -2380,6 +2380,25 @@ public sealed class GalaxyDriver /// public Task> WriteAsync( IReadOnlyList writes, CancellationToken cancellationToken) + => WriteCoreAsync(writes, caller: null, cancellationToken); + + /// + /// #1017 — on behalf of + /// . With MxAccess.SecuredWrites = ApiKeyIdentity a SecuredWrite attribute is + /// written as the caller's API key's own Galaxy identity (no fallback account); otherwise — and for every + /// VerifiedWrite attribute — it is refused BadUserAccessDenied as before. Non-secured tags are + /// unaffected by the caller. + /// + /// Pairs of full reference (RawPath) + value. + /// Who issued the write. + /// Cancellation token. + /// One result per request, in order. + public Task> WriteAsync( + IReadOnlyList writes, WriteCaller caller, CancellationToken cancellationToken) + => WriteCoreAsync(writes, caller ?? throw new ArgumentNullException(nameof(caller)), cancellationToken); + + private Task> WriteCoreAsync( + IReadOnlyList writes, WriteCaller? caller, CancellationToken cancellationToken) { ObjectDisposedException.ThrowIf(_disposed, this); ArgumentNullException.ThrowIfNull(writes); @@ -2403,8 +2422,17 @@ public sealed class GalaxyDriver var dialledWrites = new List(writes.Count); foreach (var w in writes) dialledWrites.Add(w with { FullReference = ToAttributeRef(w.FullReference) }); + // #1017: only an opted-in driver with a known caller carries an identity source; the writer resolves it + // lazily (at most once per batch, only for a SecuredWrite tag). Key-only — never the ack fallback account. + Func>? securedCredential = null; + if (caller is not null && _options.MxAccess.SecuredWrites == GalaxySecuredWriteMode.ApiKeyIdentity) + { + var apiKeyId = caller.ApiKeyId; + securedCredential = ct => _ackCredentialResolver.ResolveKeyIdentityAsync(apiKeyId, ct); + } + return _dataWriter.WriteAsync( - dialledWrites, attributeRef => ResolveSecurity(ToRawPath(attributeRef)), cancellationToken); + dialledWrites, attributeRef => ResolveSecurity(ToRawPath(attributeRef)), securedCredential, cancellationToken); } // ===== ISubscribable (PR 4.4) ===== diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriverFactoryExtensions.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriverFactoryExtensions.cs index 52b606c2a..e2c63b8fd 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriverFactoryExtensions.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriverFactoryExtensions.cs @@ -115,7 +115,10 @@ public static class GalaxyDriverFactoryExtensions $"Galaxy driver '{driverInstanceId}' missing required MxAccess.ClientName"), PublishingIntervalMs: dto.MxAccess.PublishingIntervalMs ?? 1000, WriteUserId: dto.MxAccess.WriteUserId ?? 0, - EventPumpChannelCapacity: dto.MxAccess.EventPumpChannelCapacity ?? 50_000), + EventPumpChannelCapacity: dto.MxAccess.EventPumpChannelCapacity ?? 50_000) + { + SecuredWrites = ParseSecuredWrites(dto.MxAccess.SecuredWrites, driverInstanceId), + }, Repository: new GalaxyRepositoryOptions( DiscoverPageSize: dto.Repository?.DiscoverPageSize ?? 5000, WatchDeployEvents: dto.Repository?.WatchDeployEvents ?? true), @@ -143,6 +146,24 @@ public static class GalaxyDriverFactoryExtensions private static string? NullIfBlank(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + /// + /// #1017: MxAccess.SecuredWrites — absent/blank = . An + /// unknown value fails the driver config loudly rather than silently refusing (a misspelt opt-in would + /// otherwise look like a Galaxy permission problem). + /// + internal static GalaxySecuredWriteMode ParseSecuredWrites(string? value, string driverInstanceId) + { + if (string.IsNullOrWhiteSpace(value)) return GalaxySecuredWriteMode.Refuse; + var text = value.Trim(); + if (!int.TryParse(text, out _) + && Enum.TryParse(text, ignoreCase: true, out var mode) + && Enum.IsDefined(mode)) + return mode; + throw new InvalidOperationException( + $"Galaxy driver '{driverInstanceId}' has an unknown MxAccess.SecuredWrites value '{text}' " + + $"(expected {string.Join(" | ", Enum.GetNames())})."); + } + private static readonly JsonSerializerOptions JsonOptions = new() { PropertyNameCaseInsensitive = true, @@ -218,6 +239,8 @@ public static class GalaxyDriverFactoryExtensions public int? WriteUserId { get; init; } /// Gets or sets the event pump channel capacity. public int? EventPumpChannelCapacity { get; init; } + /// Gets or sets the SecuredWrite handling (#1017): Refuse (default) or ApiKeyIdentity. + public string? SecuredWrites { get; init; } } /// Repository configuration section. diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GalaxyAckCredentialResolver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GalaxyAckCredentialResolver.cs index 77b2ad751..932a0608b 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GalaxyAckCredentialResolver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GalaxyAckCredentialResolver.cs @@ -46,7 +46,7 @@ internal sealed class GalaxyAckCredentialResolver : IGalaxyAckCredentialResolver string? keyNote = null; if (!string.IsNullOrWhiteSpace(apiKeyId)) { - var keyResult = await ResolveKeyIdentityAsync(apiKeyId, cancellationToken).ConfigureAwait(false); + var keyResult = await ResolveMappedKeyIdentityAsync(apiKeyId, cancellationToken).ConfigureAwait(false); if (keyResult.Credential is not null) return keyResult; // A key whose identity is half-configured (user without password, unreadable secret) is // refused outright — silently acknowledging as the fallback account would record the wrong @@ -66,8 +66,30 @@ internal sealed class GalaxyAckCredentialResolver : IGalaxyAckCredentialResolver "in AdminUI /api-keys or configure the driver's fallback ack account."); } + /// + public async Task ResolveKeyIdentityAsync(string? apiKeyId, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(apiKeyId)) + { + return GalaxyAckCredentialResolution.Refused( + "the session is anonymous (no API key), and a secured write runs only as the calling key's own Galaxy identity"); + } + + var keyResult = await ResolveMappedKeyIdentityAsync(apiKeyId, cancellationToken).ConfigureAwait(false); + if (keyResult.Credential is not null || keyResult.RefusalReason is not null) + { + return keyResult.RefusalReason is null + ? keyResult + : GalaxyAckCredentialResolution.Refused(keyResult.RefusalReason.Replace( + "the acknowledge was not sent", "the write was not sent", StringComparison.Ordinal)); + } + + return GalaxyAckCredentialResolution.Refused( + $"API key '{apiKeyId}' has no Galaxy identity (AdminUI /api-keys); a secured write has no fallback account."); + } + // Returns Resolved, Refused (mapped but broken), or (null, null) = "no identity mapped". - private async Task ResolveKeyIdentityAsync(string apiKeyId, CancellationToken ct) + private async Task ResolveMappedKeyIdentityAsync(string apiKeyId, CancellationToken ct) { string userName, passwordName; try diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GatewayGalaxyDataWriter.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GatewayGalaxyDataWriter.cs index 92344e07e..c9c45a01e 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GatewayGalaxyDataWriter.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GatewayGalaxyDataWriter.cs @@ -13,10 +13,11 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime; /// Production over . /// For each batch entry: lazy-AddItem to obtain the MXAccess item handle, encode /// the value via , supervisory-advise + Write, and translate the -/// reply's MxStatusProxy into an OPC UA . A SecuredWrite / -/// VerifiedWrite attribute (per-tag ) is refused -/// BadUserAccessDenied without a round trip — the driver has no ArchestrA identity to -/// write it under (#991 review G-1). +/// reply's MxStatusProxy into an OPC UA . A SecuredWrite attribute +/// (per-tag ) is written as the caller's Galaxy identity when the +/// driver supplies one (#1017: own plain-advised handle → AuthenticateUser → WriteSecured), +/// and refused BadUserAccessDenied without a round trip otherwise (#991 review G-1); a +/// VerifiedWrite attribute is always refused that way (no verifying user). /// /// /// Item handle cache survives across writes — repeated writes to the same tag avoid @@ -41,6 +42,11 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter private readonly ConcurrentDictionary _supervisedHandles = new(); // Attributes whose secured/verified-write refusal has been logged (once per attribute, #991 review G-1). private readonly ConcurrentDictionary _securedRefusalWarned = new(StringComparer.OrdinalIgnoreCase); + // #1017: the secured path's OWN item handles, PLAIN-advised (AuthenticateUser + WriteSecured commits through a + // plain advise — live-captured, mxaccessgw docs/LiveCaptures-2026-11-13.md §4). Kept apart from _itemHandles, + // whose handles are supervisory-advised for the raw path: MXAccess allows one advise mode per handle. + private readonly ConcurrentDictionary _securedItemHandles = new(StringComparer.OrdinalIgnoreCase); + private readonly ConcurrentDictionary _securedAdvisedHandles = new(); private int _addItemCallCount; // Write failure-visibility meters (archreview 06/S-1). Reuse the pump's meter name so the single host @@ -73,6 +79,8 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter { _itemHandles.Clear(); _supervisedHandles.Clear(); + _securedItemHandles.Clear(); + _securedAdvisedHandles.Clear(); } // ===== Test seams (internal — not part of the public contract) ===== @@ -109,10 +117,25 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter } /// - public async Task> WriteAsync( + public Task> WriteAsync( IReadOnlyList writes, Func securityResolver, CancellationToken cancellationToken) + => WriteCoreAsync(writes, securityResolver, securedCredential: null, cancellationToken); + + /// + Task> IGalaxyDataWriter.WriteAsync( + IReadOnlyList writes, + Func securityResolver, + Func>? securedCredential, + CancellationToken cancellationToken) + => WriteCoreAsync(writes, securityResolver, securedCredential, cancellationToken); + + private async Task> WriteCoreAsync( + IReadOnlyList writes, + Func securityResolver, + Func>? securedCredential, + CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(writes); ArgumentNullException.ThrowIfNull(securityResolver); @@ -125,7 +148,7 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter // Bind the per-batch MX write operations behind the internal IMxWriteOps seam (see below) so the // whole write pipeline is unit-testable without the sealed SDK session (archreview 06/S-1). var ops = new SessionMxWriteOps(session, serverHandle); - return await WriteBatchAsync(ops, writes, securityResolver, cancellationToken).ConfigureAwait(false); + return await WriteBatchAsync(ops, writes, securityResolver, cancellationToken, securedCredential).ConfigureAwait(false); } /// @@ -142,10 +165,12 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter /// Per-tag classification resolver. /// The cancellation token. /// One result per request, in input order. + /// The caller's Galaxy identity source for secured writes (#1017); null = none. internal Task> WriteBatchForTestAsync( IMxWriteOps ops, IReadOnlyList writes, - Func securityResolver, CancellationToken ct) - => WriteBatchAsync(ops, writes, securityResolver, ct); + Func securityResolver, CancellationToken ct, + Func>? securedCredential = null) + => WriteBatchAsync(ops, writes, securityResolver, ct, securedCredential); /// /// Run a batch as one lane per distinct tag (OrdinalIgnoreCase): writes to the SAME tag @@ -155,11 +180,21 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter /// private async Task> WriteBatchAsync( IMxWriteOps ops, IReadOnlyList writes, - Func securityResolver, CancellationToken ct) + Func securityResolver, CancellationToken ct, + Func>? securedCredential = null) { var results = new WriteResult[writes.Count]; if (writes.Count == 0) return results; + // #1017: the caller's identity is resolved at most ONCE per batch, and only when a secured tag needs it. + Func>? batchCredential = null; + if (securedCredential is not null) + { + var once = new Lazy>( + () => securedCredential(ct), LazyThreadSafetyMode.ExecutionAndPublication); + batchCredential = _ => once.Value; + } + // Group request indices by tag, first-seen order preserved so the lane start order is // deterministic and a same-tag sequence keeps its authored order. var lanes = new Dictionary>(StringComparer.OrdinalIgnoreCase); @@ -203,7 +238,7 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter foreach (var i in lane) { results[i] = await WriteOneAsync(ops, writes[i], - securityResolver(writes[i].FullReference), ct).ConfigureAwait(false); + securityResolver(writes[i].FullReference), ct, batchCredential).ConfigureAwait(false); } } } @@ -216,29 +251,38 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter /// The tag's security classification. /// The cancellation token. /// The translated write result. + /// The caller's Galaxy identity source for a SecuredWrite (#1017); null = none. internal Task WriteOneForTestAsync( - IMxWriteOps ops, WriteRequest request, SecurityClassification classification, CancellationToken ct) - => WriteOneAsync(ops, request, classification, ct); + IMxWriteOps ops, WriteRequest request, SecurityClassification classification, CancellationToken ct, + Func>? securedCredential = null) + => WriteOneAsync(ops, request, classification, ct, securedCredential); private async Task WriteOneAsync( IMxWriteOps ops, WriteRequest request, - SecurityClassification classification, CancellationToken ct) + SecurityClassification classification, CancellationToken ct, + Func>? securedCredential = null) { - if (NeedsSecuredWrite(classification)) + if (classification is SecurityClassification.VerifiedWrite) { - // #991 review (G-1): REFUSED, before anything reaches the wire. A SecuredWrite/VerifiedWrite attribute - // needs a real ArchestrA identity — AuthenticateUser (+ a verifier for VerifiedWrite), the item advised - // for that user, and a gateway key holding invoke:secure — none of which this driver has. Routing it to - // WriteSecured could only fail, and the gateway's refusal surfaced as BadCommunicationError (a comms - // fault). Until a per-caller identity flow exists this is an access refusal: no health impact. - if (_securedRefusalWarned.TryAdd(request.FullReference, 0)) + // #991 review (G-1) / #1017: ALWAYS refused, before anything reaches the wire. A VerifiedWrite needs a + // SECOND, verifying user (MXAccess refuses one with no verifier — 1008 — and one whose verifier is the + // writer — 8018, both live-captured). An OPC UA Write carries one caller, never a verifier; a stored + // verifier credential would let one client satisfy the two-person rule alone. + return RefuseSecured(request.FullReference, classification, + "a VerifiedWrite needs a second, verifying user, which an OPC UA write cannot carry"); + } + + if (classification is SecurityClassification.SecuredWrite) + { + if (securedCredential is null) { - _logger.LogWarning( - "GalaxyDriver write to {FullRef} refused BadUserAccessDenied — the attribute is {Classification} and the " + - "driver has no ArchestrA user identity to write it under (logged once per attribute).", - request.FullReference, classification); + // #991 review (G-1): no caller identity is in play (the driver's MxAccess.SecuredWrites is Refuse, + // or the write carries no caller) — an access refusal, no health impact. + return RefuseSecured(request.FullReference, classification, + "the driver has no ArchestrA user identity to write it under (MxAccess.SecuredWrites = Refuse, or no caller)"); } - return new WriteResult(StatusCodeMap.BadUserAccessDenied); + + return await WriteSecuredOneAsync(ops, request, securedCredential, ct).ConfigureAwait(false); } try @@ -289,8 +333,183 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter } } - private static bool NeedsSecuredWrite(SecurityClassification classification) => - classification is SecurityClassification.SecuredWrite or SecurityClassification.VerifiedWrite; + private WriteResult RefuseSecured(string fullRef, SecurityClassification classification, string why) + { + if (_securedRefusalWarned.TryAdd(fullRef, 0)) + { + _logger.LogWarning( + "GalaxyDriver write to {FullRef} refused BadUserAccessDenied — the attribute is {Classification} and {Why} " + + "(logged once per attribute).", + fullRef, classification, why); + } + return new WriteResult(StatusCodeMap.BadUserAccessDenied); + } + + /// + /// #1017 — a SecuredWrite under the CALLER's Galaxy identity: the writer's own plain-advised handle → + /// AuthenticateUser(DOMAIN\user, password) → WriteSecured(current = that user, verifier = 0), the + /// sequence mxaccessgw live-captured committing (docs/LiveCaptures-2026-11-13.md §4). The password goes only + /// into the AuthenticateUser command; nothing here logs it, and gateway text is scrubbed of it. + /// Authenticates on EVERY write (no cached user id): MXAccess's user-id lifetime is unverified, and a rotated + /// or revoked identity must take effect on the next write. + /// + private async Task WriteSecuredOneAsync( + IMxWriteOps ops, WriteRequest request, + Func> securedCredential, CancellationToken ct) + { + GalaxyAckCredentialResolution resolution; + try + { + resolution = await securedCredential(ct).ConfigureAwait(false); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } + catch (Exception ex) + { + _logger.LogWarning( + "GalaxyDriver secured write to {FullRef} refused BadUserAccessDenied — resolving the caller's Galaxy identity failed ({ExceptionType}).", + request.FullReference, ex.GetType().Name); + return new WriteResult(StatusCodeMap.BadUserAccessDenied); + } + + if (resolution.Credential is not { } credential) + { + _logger.LogWarning( + "GalaxyDriver secured write to {FullRef} refused BadUserAccessDenied — {Reason}", + request.FullReference, resolution.RefusalReason ?? "no Galaxy identity for the caller"); + return new WriteResult(StatusCodeMap.BadUserAccessDenied); + } + + var password = credential.Password; + try + { + var mxValue = MxValueEncoder.Encode(request.Value); + var itemHandle = await EnsureSecuredItemHandleAsync(ops, request.FullReference, ct).ConfigureAwait(false); + if (!await EnsurePlainAdvisedAsync(ops, itemHandle, ct).ConfigureAwait(false)) + { + WriteAdviseFailed.Add(1); + return new WriteResult(StatusCodeMap.BadCommunicationError); + } + + var authReply = await ops.InvokeAsync(new MxCommandRequest + { + SessionId = ops.SessionId, + ClientCorrelationId = Guid.NewGuid().ToString("N"), + Command = new MxCommand + { + Kind = MxCommandKind.AuthenticateUser, + AuthenticateUser = new AuthenticateUserCommand + { + ServerHandle = ops.ServerHandle, + VerifyUser = credential.DisplayName, + VerifyUserPassword = password, + }, + }, + }, ct).ConfigureAwait(false); + + var userId = authReply.AuthenticateUser?.UserId ?? 0; + if (authReply.ProtocolStatus is { } authProto && authProto.Code != ProtocolStatusCode.Ok || userId == 0) + { + _logger.LogWarning( + "GalaxyDriver secured write to {FullRef} refused BadUserAccessDenied — MXAccess did not authenticate " + + "Galaxy user {GalaxyUser} ({Code}, native 0x{Hresult:X8}: {Message})", + request.FullReference, credential.DisplayName, authReply.ProtocolStatus?.Code, authReply.Hresult, + GatewayGalaxyAlarmAcknowledger.Scrub(authReply.ProtocolStatus?.Message ?? authReply.DiagnosticMessage, password)); + return new WriteResult(StatusCodeMap.BadUserAccessDenied); + } + + var writeReply = await ops.InvokeAsync(new MxCommandRequest + { + SessionId = ops.SessionId, + ClientCorrelationId = Guid.NewGuid().ToString("N"), + Command = new MxCommand + { + Kind = MxCommandKind.WriteSecured, + WriteSecured = new WriteSecuredCommand + { + ServerHandle = ops.ServerHandle, + ItemHandle = itemHandle, + CurrentUserId = userId, + VerifierUserId = 0, + Value = mxValue, + }, + }, + }, ct).ConfigureAwait(false); + + return TranslateReply(writeReply, request.FullReference); + } + catch (ArgumentException ex) + { + _logger.LogWarning( + "GalaxyDriver secured write rejected — unsupported value type for {FullRef} ({ExceptionType})", + request.FullReference, ex.GetType().Name); + return new WriteResult(StatusCodeMap.BadInternalError); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; } + catch (Exception ex) when (IsCallerRefused(ex)) + { + // The gateway refused the CALLER — typically the driver's API key lacks invoke:secure. + _logger.LogWarning( + "GalaxyDriver secured write to {FullRef} refused by the gateway ({Reason}) — BadUserAccessDenied. " + + "Secured writes need the gateway key to hold the invoke:secure scope.", + request.FullReference, ((RpcException)UnwrapRpc(ex)!).StatusCode); + return new WriteResult(StatusCodeMap.BadUserAccessDenied); + } + catch (Exception ex) + { + // Type + scrubbed message only: an exception on this path could carry the AuthenticateUser request. + _logger.LogWarning( + "GalaxyDriver secured write failed for {FullRef} ({ExceptionType}: {Message})", + request.FullReference, ex.GetType().Name, GatewayGalaxyAlarmAcknowledger.Scrub(ex.Message, password)); + return new WriteResult(StatusCodeMap.BadCommunicationError); + } + } + + private async Task EnsureSecuredItemHandleAsync(IMxWriteOps ops, string fullRef, CancellationToken ct) + { + if (_securedItemHandles.TryGetValue(fullRef, out var existing)) return existing; + var handle = await ops.AddItemAsync(fullRef, ct).ConfigureAwait(false); + Interlocked.Increment(ref _addItemCallCount); + _securedItemHandles[fullRef] = handle; + return handle; + } + + /// Plain-advise the secured path's handle once per session (MXAccess refuses writes to an unadvised + /// item). false = the advise failed and the write must fail closed. + private async Task EnsurePlainAdvisedAsync(IMxWriteOps ops, int itemHandle, CancellationToken ct) + { + if (!_securedAdvisedHandles.TryAdd(itemHandle, 0)) return true; + + MxCommandReply reply; + try + { + reply = await ops.InvokeAsync(new MxCommandRequest + { + SessionId = ops.SessionId, + ClientCorrelationId = Guid.NewGuid().ToString("N"), + Command = new MxCommand + { + Kind = MxCommandKind.Advise, + Advise = new AdviseCommand { ServerHandle = ops.ServerHandle, ItemHandle = itemHandle }, + }, + }, ct).ConfigureAwait(false); + } + catch + { + _securedAdvisedHandles.TryRemove(itemHandle, out _); + throw; + } + + if (reply.ProtocolStatus is { } proto && proto.Code != ProtocolStatusCode.Ok) + { + _securedAdvisedHandles.TryRemove(itemHandle, out _); + _logger.LogWarning( + "GalaxyDriver advise for a secured write failed for item {ItemHandle}: {Code} {Message}", + itemHandle, proto.Code, proto.Message); + return false; + } + + return true; + } /// Whether (or an inner exception) is the gateway refusing the caller. internal static bool IsCallerRefused(Exception ex) => diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/IGalaxyAckCredentialResolver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/IGalaxyAckCredentialResolver.cs index 4e43fdefc..9d4d182d6 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/IGalaxyAckCredentialResolver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/IGalaxyAckCredentialResolver.cs @@ -15,4 +15,15 @@ internal interface IGalaxyAckCredentialResolver /// Cancels secret resolution. /// The resolved credential or the refusal reason. Task ResolveAsync(string? apiKeyId, CancellationToken cancellationToken); + + /// + /// #1017 — the identity a SECURED WRITE from runs as: the key's own Galaxy + /// identity only. Unlike there is NO fallback account — an anonymous session or a + /// key without (or with a broken) identity is refused, so a secured write is never attributed to a shared + /// account. Never throws for a missing or unreadable credential. + /// + /// The authenticating API key id, or null (anonymous). + /// Cancels secret resolution. + /// The resolved credential or the refusal reason. + Task ResolveKeyIdentityAsync(string? apiKeyId, CancellationToken cancellationToken); } diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/IGalaxyDataWriter.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/IGalaxyDataWriter.cs index db0f6a83e..240838ccb 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/IGalaxyDataWriter.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/IGalaxyDataWriter.cs @@ -4,9 +4,9 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime; /// /// Driver-side seam for batched writes. Production implementation decides by -/// : SecuredWrite / VerifiedWrite are refused -/// BadUserAccessDenied (no ArchestrA identity to write them under — #991 review G-1), -/// everything else goes supervisory-advise + raw Write. Tests substitute a fake to record routing +/// : SecuredWrite goes AuthenticateUser + WriteSecured under the +/// caller's Galaxy identity when one is supplied (#1017) and is otherwise refused BadUserAccessDenied +/// (#991 review G-1); VerifiedWrite is always refused; everything else goes supervisory-advise + raw Write. Tests substitute a fake to record routing /// decisions without touching real gw infrastructure. /// public interface IGalaxyDataWriter @@ -31,6 +31,24 @@ public interface IGalaxyDataWriter Func securityResolver, CancellationToken cancellationToken); + /// + /// #1017 — + /// with the CALLER's Galaxy identity for SecuredWrite tags: resolves it + /// (at most once per batch, only when a SecuredWrite tag is present); null = no identity (secured writes refused). + /// VerifiedWrite is refused either way. The default implementation ignores the identity (refuses). + /// + /// Pairs of full reference + value to write. + /// Per-tag classification resolver. + /// The caller's Galaxy identity source, or null. + /// Aborts the in-flight batch. + /// One per request entry, in input order. + internal Task> WriteAsync( + IReadOnlyList writes, + Func securityResolver, + Func>? securedCredential, + CancellationToken cancellationToken) + => WriteAsync(writes, securityResolver, cancellationToken); + /// Drop cached gateway item handles + supervisory-advise state. Call after a session /// reconnect — the prior handles are dead, so the next write must re-AddItem + re-AdviseSupervisory. void InvalidateHandleCaches(); diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/TracedGalaxyDataWriter.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/TracedGalaxyDataWriter.cs index 40365263c..d6a8c3fb8 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/TracedGalaxyDataWriter.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/TracedGalaxyDataWriter.cs @@ -14,10 +14,25 @@ internal sealed class TracedGalaxyDataWriter(IGalaxyDataWriter inner, string cli public void InvalidateHandleCaches() => inner.InvalidateHandleCaches(); /// - public async Task> WriteAsync( + public Task> WriteAsync( IReadOnlyList writes, Func securityResolver, CancellationToken cancellationToken) + => TraceAsync(writes, securityResolver, () => inner.WriteAsync(writes, securityResolver, cancellationToken)); + + /// + Task> IGalaxyDataWriter.WriteAsync( + IReadOnlyList writes, + Func securityResolver, + Func>? securedCredential, + CancellationToken cancellationToken) + => TraceAsync(writes, securityResolver, + () => inner.WriteAsync(writes, securityResolver, securedCredential, cancellationToken)); + + private async Task> TraceAsync( + IReadOnlyList writes, + Func securityResolver, + Func>> write) { using var activity = GalaxyTelemetry.ActivitySource.StartActivity("galaxy.write"); activity?.SetTag("galaxy.client", clientName); @@ -44,8 +59,7 @@ internal sealed class TracedGalaxyDataWriter(IGalaxyDataWriter inner, string cli try { - var results = await inner.WriteAsync(writes, securityResolver, cancellationToken) - .ConfigureAwait(false); + var results = await write().ConfigureAwait(false); activity?.SetTag("galaxy.success_count", results.Count(r => r.StatusCode < 0x80000000u)); return results; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/ApiKeys.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/ApiKeys.razor index fa07106d6..e1804140a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/ApiKeys.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/ApiKeys.razor @@ -64,6 +64,8 @@ the Historian records it as the operator. Stored encrypted in the Secrets store (otopcua/apikeys/@(_ackEditKeyId)/galaxy-ack-*), never in the database. Keys without an identity use the Galaxy driver's fallback account; with neither, acknowledges are refused. + A Galaxy driver set to Secured writes = API key identity also writes SecuredWrite + attributes as this account (#1017) — with no fallback: a key without an identity cannot make secured writes. On a split admin/driver topology the two secrets must also exist on the driver nodes.
diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/Drivers/Forms/GalaxyDriverForm.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/Drivers/Forms/GalaxyDriverForm.razor index f4c78be4e..1cdba33a3 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/Drivers/Forms/GalaxyDriverForm.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/Drivers/Forms/GalaxyDriverForm.razor @@ -98,6 +98,20 @@
@if (_fieldEditContext is not null) { }
Default 50000. Raise if events.dropped appears.
+
+ + + + + +
+ How a write to a SecuredWrite attribute is handled (#1017). Refuse answers + BadUserAccessDenied. API key identity authenticates as the Galaxy account mapped to the + session's key on API keys and issues WriteSecured; anonymous sessions and keys + without an identity are refused (no fallback account). The gateway key needs invoke:secure. + VerifiedWrite attributes are always refused. +
+
@@ -239,6 +253,7 @@ "gateway.connectTimeoutSeconds", "gateway.defaultCallTimeoutSeconds", "gateway.streamTimeoutSeconds", "gateway.keepAlivePingDelaySeconds", "gateway.keepAlivePingTimeoutSeconds", "mxAccess.clientName", "mxAccess.publishingIntervalMs", "mxAccess.writeUserId", "mxAccess.eventPumpChannelCapacity", + "mxAccess.securedWrites", "repository.discoverPageSize", "repository.watchDeployEvents", "reconnect.initialBackoffMs", "reconnect.maxBackoffMs", "reconnect.replayOnSessionLost", "probeTimeoutSeconds", @@ -318,6 +333,7 @@ public int MxPublishingIntervalMs { get; set; } = 1000; public int MxWriteUserId { get; set; } = 0; public int MxEventPumpChannelCapacity { get; set; } = 50_000; + public GalaxySecuredWriteMode MxSecuredWrites { get; set; } = GalaxySecuredWriteMode.Refuse; // GalaxyRepositoryOptions public int RepositoryDiscoverPageSize { get; set; } = 5000; @@ -359,6 +375,7 @@ MxPublishingIntervalMs = mx.PublishingIntervalMs, MxWriteUserId = mx.WriteUserId, MxEventPumpChannelCapacity = mx.EventPumpChannelCapacity, + MxSecuredWrites = mx.SecuredWrites, RepositoryDiscoverPageSize = repo.DiscoverPageSize, RepositoryWatchDeployEvents = repo.WatchDeployEvents, ReconnectInitialBackoffMs = rc.InitialBackoffMs, @@ -387,7 +404,10 @@ ClientName: MxClientName, PublishingIntervalMs: MxPublishingIntervalMs, WriteUserId: MxWriteUserId, - EventPumpChannelCapacity: MxEventPumpChannelCapacity), + EventPumpChannelCapacity: MxEventPumpChannelCapacity) + { + SecuredWrites = MxSecuredWrites, + }, Repository: new GalaxyRepositoryOptions( DiscoverPageSize: RepositoryDiscoverPageSize, WatchDeployEvents: RepositoryWatchDeployEvents), diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index dfa68f3ce..92b5a3616 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -3557,7 +3557,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage var clientUserId = identity is { Principal.Length: > 0 } ? identity.Principal : identity?.DisplayName; return DispatchDeviceWrite(gateway, nodeKey, nodeBareId, nodeRealm, optimisticValue, priorValue, priorStatus, clientUserId, - (node as EquipmentVariableState)?.ActiveWriteStamp); + (node as EquipmentVariableState)?.ActiveWriteStamp, + // #1017: WHO wrote rides to the driver, so a per-user device permission (Galaxy SecuredWrite) can act on it. + identity is null ? null : new WriteCaller(identity.Principal.Length > 0 ? identity.Principal : null, identity.ApiKeyId)); } /// @@ -3578,12 +3580,14 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage internal ServiceResult DispatchDeviceWrite( IOpcUaNodeWriteGateway gateway, string nodeKey, string nodeBareId, AddressSpaceRealm nodeRealm, object? optimisticValue, object? priorValue, StatusCode priorStatus, string? clientUserId, - EquipmentVariableState.WriteStamp? writeStamp = null) + EquipmentVariableState.WriteStamp? writeStamp = null, WriteCaller? caller = null) { Task dispatch; try { - dispatch = gateway.WriteAsync(nodeKey, optimisticValue, nodeRealm, CancellationToken.None); + dispatch = caller is null + ? gateway.WriteAsync(nodeKey, optimisticValue, nodeRealm, CancellationToken.None) + : gateway.WriteAsync(nodeKey, optimisticValue, nodeRealm, caller, CancellationToken.None); } catch (Exception ex) { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/ActorNodeWriteGateway.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/ActorNodeWriteGateway.cs index a24629a9e..e905ac899 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/ActorNodeWriteGateway.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/ActorNodeWriteGateway.cs @@ -1,6 +1,7 @@ using Akka.Actor; using Microsoft.Extensions.Logging; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; namespace ZB.MOM.WW.OtOpcUa.Runtime.Drivers; @@ -44,7 +45,12 @@ public sealed class ActorNodeWriteGateway : IOpcUaNodeWriteGateway } /// - public async Task WriteAsync(string nodeId, object? value, AddressSpaceRealm realm, CancellationToken ct) + public Task WriteAsync(string nodeId, object? value, AddressSpaceRealm realm, CancellationToken ct) + => WriteAsync(nodeId, value, realm, caller: null, ct); + + /// + public async Task WriteAsync( + string nodeId, object? value, AddressSpaceRealm realm, WriteCaller? caller, CancellationToken ct) { var driverHost = _resolveDriverHost(); if (driverHost is null) @@ -56,7 +62,7 @@ public sealed class ActorNodeWriteGateway : IOpcUaNodeWriteGateway try { var result = await driverHost.Ask( - new DriverHostActor.RouteNodeWrite(nodeId, value, realm), _askTimeout, ct).ConfigureAwait(false); + new DriverHostActor.RouteNodeWrite(nodeId, value, realm, caller), _askTimeout, ct).ConfigureAwait(false); if (!result.Success) _logger.LogWarning("Operator write to {NodeId} rejected: {Reason}", nodeId, result.Reason); return new NodeWriteOutcome(result.Success, result.Reason); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs index f8f85c14a..6265084d3 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs @@ -695,7 +695,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn /// /// The folder-scoped equipment-variable NodeId the operator wrote to. /// The value to write (the driver coerces it to the attribute's data type). - public sealed record RouteNodeWrite(string NodeId, object? Value, AddressSpaceRealm Realm); + public sealed record RouteNodeWrite(string NodeId, object? Value, AddressSpaceRealm Realm, WriteCaller? Caller = null); /// Reply to : the outcome of forwarding the write to the driver /// (or a gate/lookup failure that never reached the driver). @@ -2613,7 +2613,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn var replyTo = Sender; var askDeadline = new CancellationTokenSource(_writeBounds.HostAsk, _writeClock); entry.Actor.Ask( - new DriverInstanceActor.WriteAttribute(target.RawPath, msg.Value!, _writeClock.GetTimestamp()), + new DriverInstanceActor.WriteAttribute(target.RawPath, msg.Value!, _writeClock.GetTimestamp(), msg.Caller), System.Threading.Timeout.InfiniteTimeSpan, askDeadline.Token) .ContinueWith( diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs index d1dc07942..cc060687f 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs @@ -136,7 +136,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers /// stamps it so the time the write spends in this actor's MAILBOX counts against the queue budget too: a write /// delayed there (behind a hanging alarm subscribe, say) and then started could otherwise still be running /// when the host's Ask fires (lmxopcua#777). - public sealed record WriteAttribute(string TagId, object Value, long? IssuedAt = null); + public sealed record WriteAttribute(string TagId, object Value, long? IssuedAt = null, WriteCaller? Caller = null); public sealed record WriteAttributeResult(bool Success, string? Reason); internal sealed record WriteAttributeWithOutcome(WriteAdmissionTicket Ticket, WriteClaim Claim); /// @@ -1669,7 +1669,11 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers var attempt = invoker.ExecuteWriteAsync( hostKey, isIdempotent: false, - async ct => await writable.WriteAsync(request, ct), + // #1017: a write that carries its caller reaches a driver that can act on it (the Galaxy driver's + // SecuredWrite attributes) through ICallerAwareWritable; every other driver/write is unchanged. + async ct => msg.Caller is { } caller && writable is ICallerAwareWritable callerAware + ? await callerAware.WriteAsync(request, caller, ct) + : await writable.WriteAsync(request, ct), cts.Token).AsTask(); IReadOnlyList results; try diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GalaxyDriverSecuredWriteIdentityTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GalaxyDriverSecuredWriteIdentityTests.cs new file mode 100644 index 000000000..a82439885 --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GalaxyDriverSecuredWriteIdentityTests.cs @@ -0,0 +1,123 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config; +using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime; + +namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime; + +/// +/// #1017 — the driver hands its writer the CALLER's Galaxy identity source only when +/// MxAccess.SecuredWrites = ApiKeyIdentity AND the write carries a caller; the source resolves the key's +/// own identity ( — never the ack fallback). +/// +public sealed class GalaxyDriverSecuredWriteIdentityTests +{ + private static GalaxyDriverOptions Opts(GalaxySecuredWriteMode mode) => new( + new GalaxyGatewayOptions("https://mxgw.test:5001", "key"), + new GalaxyMxAccessOptions("OtOpcUa-A") { SecuredWrites = mode }, + new GalaxyRepositoryOptions(WatchDeployEvents: false), + new GalaxyReconnectOptions()) + { + RawTags = [new RawTagEntry("Plant/Tank1/SP", """{"attributeRef":"Tank1.SP"}""", false)], + }; + + private sealed class IdentityRecordingWriter : IGalaxyDataWriter + { + public List>?> Sources { get; } = []; + + public Task> WriteAsync( + IReadOnlyList writes, Func securityResolver, + CancellationToken cancellationToken) + { + Sources.Add(null); + return Task.FromResult>([.. writes.Select(_ => new WriteResult(StatusCodeMap.Good))]); + } + + Task> IGalaxyDataWriter.WriteAsync( + IReadOnlyList writes, Func securityResolver, + Func>? securedCredential, CancellationToken cancellationToken) + { + Sources.Add(securedCredential); + return Task.FromResult>([.. writes.Select(_ => new WriteResult(StatusCodeMap.Good))]); + } + + public void InvalidateHandleCaches() { } + } + + private static (GalaxyDriver Driver, IdentityRecordingWriter Writer, FixedAckCredentialResolver Resolver) Build( + GalaxySecuredWriteMode mode) + { + var writer = new IdentityRecordingWriter(); + var resolver = FixedAckCredentialResolver.Fallback(); + var driver = new GalaxyDriver("g", Opts(mode), hierarchySource: null, dataWriter: writer, ackCredentialResolver: resolver); + return (driver, writer, resolver); + } + + [Fact] + public async Task ApiKeyIdentity_mode_with_a_caller_passes_a_key_only_identity_source() + { + var (driver, writer, resolver) = Build(GalaxySecuredWriteMode.ApiKeyIdentity); + + await ((ICallerAwareWritable)driver).WriteAsync( + [new WriteRequest("Plant/Tank1/SP", 1.0)], new WriteCaller("svc-mes", "0a1b2c3d4e5f6071"), + TestContext.Current.CancellationToken); + + var source = writer.Sources.ShouldHaveSingleItem().ShouldNotBeNull(); + var resolution = await source(TestContext.Current.CancellationToken); + resolution.Credential.ShouldNotBeNull(); + resolver.SecuredWriteKeyIds.ShouldBe(["0a1b2c3d4e5f6071"]); + resolver.RequestedKeyIds.ShouldBeEmpty("a secured write never uses the ack resolution (with its fallback)"); + } + + [Fact] + public async Task ApiKeyIdentity_mode_for_an_anonymous_caller_resolves_a_refusal() + { + var (driver, writer, resolver) = Build(GalaxySecuredWriteMode.ApiKeyIdentity); + + await driver.WriteAsync([new WriteRequest("Plant/Tank1/SP", 1.0)], new WriteCaller("anonymous", null), + TestContext.Current.CancellationToken); + + var resolution = await writer.Sources.ShouldHaveSingleItem().ShouldNotBeNull()(TestContext.Current.CancellationToken); + resolution.Credential.ShouldBeNull(); + resolver.SecuredWriteKeyIds.ShouldBe([null]); + } + + [Fact] + public async Task Refuse_mode_passes_no_identity_source_even_with_a_caller() + { + var (driver, writer, _) = Build(GalaxySecuredWriteMode.Refuse); + + await driver.WriteAsync([new WriteRequest("Plant/Tank1/SP", 1.0)], new WriteCaller("svc", "0a1b2c3d4e5f6071"), + TestContext.Current.CancellationToken); + + writer.Sources.ShouldHaveSingleItem().ShouldBeNull(); + } + + [Fact] + public async Task A_write_without_a_caller_passes_no_identity_source() + { + var (driver, writer, _) = Build(GalaxySecuredWriteMode.ApiKeyIdentity); + + await driver.WriteAsync([new WriteRequest("Plant/Tank1/SP", 1.0)], TestContext.Current.CancellationToken); + + writer.Sources.ShouldHaveSingleItem().ShouldBeNull(); + } + + [Theory] + [InlineData(null, GalaxySecuredWriteMode.Refuse)] + [InlineData("", GalaxySecuredWriteMode.Refuse)] + [InlineData("refuse", GalaxySecuredWriteMode.Refuse)] + [InlineData("ApiKeyIdentity", GalaxySecuredWriteMode.ApiKeyIdentity)] + [InlineData("apikeyidentity", GalaxySecuredWriteMode.ApiKeyIdentity)] + public void The_factory_parses_SecuredWrites(string? value, GalaxySecuredWriteMode expected) + => GalaxyDriverFactoryExtensions.ParseSecuredWrites(value, "g").ShouldBe(expected); + + [Theory] + [InlineData("ApiKey")] + [InlineData("1")] + [InlineData("Fallback")] + public void The_factory_refuses_an_unknown_SecuredWrites_value(string value) + => Should.Throw(() => GalaxyDriverFactoryExtensions.ParseSecuredWrites(value, "g")) + .Message.ShouldContain("SecuredWrites"); +} diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GatewayGalaxyDataWriterSecuredWriteTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GatewayGalaxyDataWriterSecuredWriteTests.cs new file mode 100644 index 000000000..8f99e160f --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GatewayGalaxyDataWriterSecuredWriteTests.cs @@ -0,0 +1,287 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.MxGateway.Contracts.Proto; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime; + +namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime; + +/// +/// #1017 — a SecuredWrite attribute is written under the CALLER's Galaxy identity (the session's API key identity, +/// resolved by the driver and handed to the writer): the writer's own plain-advised handle → +/// AuthenticateUser(DOMAIN\user, password) → WriteSecured(current = that user, verifier = 0). +/// No usable identity (no resolver, a refused resolution, an authentication MXAccess rejects) is still the #991 +/// local BadUserAccessDenied refusal, and a VerifiedWrite is ALWAYS refused (no second, verifying identity). +/// +[Collection(ProcessWideTelemetryCollection.Name)] +public sealed class GatewayGalaxyDataWriterSecuredWriteTests +{ + private const string Password = "S3cr3t-pw!"; + private const int AuthenticatedUserId = 4242; + + private static GatewayGalaxyDataWriter NewWriter(CapturingLogger? logger = null) + => new(new GalaxyMxSession(new Config.GalaxyMxAccessOptions(ClientName: "OtOpcUa-Test")), writeUserId: 0, logger); + + private static Func> Identity( + string user = "op", string? domain = "PLANT", string password = Password) => + _ => Task.FromResult(GalaxyAckCredentialResolution.Resolved( + new GalaxyAckCredential(user, domain, password, GalaxyAckCredentialSource.ApiKey))); + + private static MxCommandReply Ok() => new() { ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok } }; + + private static SecuredFakeOps HappyOps() => new() + { + InvokeResponder = r => r.Command.Kind switch + { + MxCommandKind.AuthenticateUser => new MxCommandReply + { + ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok }, + AuthenticateUser = new AuthenticateUserReply { UserId = AuthenticatedUserId }, + }, + MxCommandKind.WriteSecured => new MxCommandReply + { + ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok }, + Statuses = { new MxStatusProxy { Success = 1, Category = MxStatusCategory.Ok } }, + }, + _ => Ok(), + }, + }; + + [Fact] + public async Task SecuredWrite_with_a_caller_identity_authenticates_then_writes_secured_on_a_plain_advised_handle() + { + var ops = HappyOps(); + var logger = new CapturingLogger(); + var writer = NewWriter(logger); + + var result = await writer.WriteOneForTestAsync( + ops, new WriteRequest("Tank.SetPoint", 12.5), SecurityClassification.SecuredWrite, CancellationToken.None, + Identity()); + + result.StatusCode.ShouldBe(StatusCodeMap.Good); + ops.AddItemRefs.ShouldBe(["Tank.SetPoint"]); + ops.RawWriteHandles.ShouldBeEmpty(); // never the supervisory raw path + ops.Invokes.Select(i => i.Command.Kind).ShouldBe( + [MxCommandKind.Advise, MxCommandKind.AuthenticateUser, MxCommandKind.WriteSecured]); + + var advise = ops.Invokes[0].Command.Advise; + advise.ServerHandle.ShouldBe(ops.ServerHandle); + advise.ItemHandle.ShouldBe(ops.NextHandle); + + var auth = ops.Invokes[1].Command.AuthenticateUser; + auth.ServerHandle.ShouldBe(ops.ServerHandle); + auth.VerifyUser.ShouldBe("PLANT\\op"); + auth.VerifyUserPassword.ShouldBe(Password); + + var write = ops.Invokes[2].Command.WriteSecured; + write.ItemHandle.ShouldBe(ops.NextHandle); + write.CurrentUserId.ShouldBe(AuthenticatedUserId); + write.VerifierUserId.ShouldBe(0); + write.Value.ShouldNotBeNull(); + + logger.AllText.ShouldNotContain(Password); + } + + [Fact] + public async Task SecuredWrite_reuses_the_advised_handle_but_authenticates_every_write() + { + var ops = HappyOps(); + var writer = NewWriter(); + + await writer.WriteOneForTestAsync(ops, new WriteRequest("T.A", 1), SecurityClassification.SecuredWrite, CancellationToken.None, Identity()); + await writer.WriteOneForTestAsync(ops, new WriteRequest("T.A", 2), SecurityClassification.SecuredWrite, CancellationToken.None, Identity()); + + ops.AddItemRefs.Count.ShouldBe(1); + ops.Invokes.Count(i => i.Command.Kind == MxCommandKind.Advise).ShouldBe(1); + ops.Invokes.Count(i => i.Command.Kind == MxCommandKind.AuthenticateUser).ShouldBe(2); + ops.Invokes.Count(i => i.Command.Kind == MxCommandKind.WriteSecured).ShouldBe(2); + } + + /// The secured handle is NOT the raw path's supervisory handle (one advise mode per handle). + [Fact] + public async Task SecuredWrite_uses_its_own_handle_apart_from_the_supervisory_raw_handle() + { + var ops = HappyOps(); + var writer = NewWriter(); + writer.SeedHandleCachesForTest("T.A", itemHandle: 99, supervised: true); + + await writer.WriteOneForTestAsync(ops, new WriteRequest("T.A", 1), SecurityClassification.SecuredWrite, CancellationToken.None, Identity()); + + ops.AddItemRefs.ShouldBe(["T.A"]); // a fresh handle for the secured path + ops.Invokes.Single(i => i.Command.Kind == MxCommandKind.WriteSecured).Command.WriteSecured.ItemHandle.ShouldBe(ops.NextHandle); + ops.Invokes.ShouldNotContain(i => i.Command.Kind == MxCommandKind.AdviseSupervisory); + } + + [Fact] + public async Task SecuredWrite_without_an_identity_source_is_refused_without_touching_the_wire() + { + var ops = HappyOps(); + + var result = await NewWriter().WriteOneForTestAsync( + ops, new WriteRequest("T.A", 1), SecurityClassification.SecuredWrite, CancellationToken.None, securedCredential: null); + + result.StatusCode.ShouldBe(StatusCodeMap.BadUserAccessDenied); + ops.AddItemRefs.ShouldBeEmpty(); + ops.Invokes.ShouldBeEmpty(); + } + + [Fact] + public async Task SecuredWrite_with_a_refused_identity_is_refused_without_touching_the_wire_and_logs_the_reason() + { + var ops = HappyOps(); + var logger = new CapturingLogger(); + + var result = await NewWriter(logger).WriteOneForTestAsync( + ops, new WriteRequest("T.A", 1), SecurityClassification.SecuredWrite, CancellationToken.None, + _ => Task.FromResult(GalaxyAckCredentialResolution.Refused("API key 'k1' has no Galaxy identity"))); + + result.StatusCode.ShouldBe(StatusCodeMap.BadUserAccessDenied); + ops.AddItemRefs.ShouldBeEmpty(); + ops.Invokes.ShouldBeEmpty(); + logger.AllText.ShouldContain("has no Galaxy identity"); + } + + /// A VerifiedWrite needs a second, verifying user — never supplied, so it stays refused even WITH an identity. + [Fact] + public async Task VerifiedWrite_is_refused_even_with_an_identity() + { + var ops = HappyOps(); + var resolved = 0; + + var result = await NewWriter().WriteOneForTestAsync( + ops, new WriteRequest("T.A", 1), SecurityClassification.VerifiedWrite, CancellationToken.None, + ct => { resolved++; return Identity()(ct); }); + + result.StatusCode.ShouldBe(StatusCodeMap.BadUserAccessDenied); + ops.Invokes.ShouldBeEmpty(); + ops.AddItemRefs.ShouldBeEmpty(); + resolved.ShouldBe(0); + } + + [Theory] + [InlineData(true)] // MXAccess rejected the credential: no user id + [InlineData(false)] // protocol-level failure + public async Task An_authentication_MXAccess_rejects_is_BadUserAccessDenied_and_nothing_is_written(bool zeroUserId) + { + var ops = new SecuredFakeOps + { + InvokeResponder = r => r.Command.Kind == MxCommandKind.AuthenticateUser + ? zeroUserId + ? new MxCommandReply { ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok }, AuthenticateUser = new AuthenticateUserReply { UserId = 0 } } + : new MxCommandReply { ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.MxaccessFailure, Message = $"bad credential {Password}" }, Hresult = unchecked((int)0x80070005) } + : Ok(), + }; + var logger = new CapturingLogger(); + + var result = await NewWriter(logger).WriteOneForTestAsync( + ops, new WriteRequest("T.A", 1), SecurityClassification.SecuredWrite, CancellationToken.None, Identity()); + + result.StatusCode.ShouldBe(StatusCodeMap.BadUserAccessDenied); + ops.Invokes.ShouldNotContain(i => i.Command.Kind == MxCommandKind.WriteSecured); + logger.AllText.ShouldContain("PLANT\\op"); + logger.AllText.ShouldNotContain(Password); + } + + /// A failed plain advise fails the write CLOSED (no AuthenticateUser, no WriteSecured), like the raw path. + [Fact] + public async Task A_failed_advise_fails_closed_before_authenticating() + { + var ops = new SecuredFakeOps + { + InvokeResponder = r => r.Command.Kind == MxCommandKind.Advise + ? new MxCommandReply { ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.MxaccessFailure, Message = "E_INVALIDARG" } } + : Ok(), + }; + + var result = await NewWriter().WriteOneForTestAsync( + ops, new WriteRequest("T.A", 1), SecurityClassification.SecuredWrite, CancellationToken.None, Identity()); + + result.StatusCode.ShouldBe(StatusCodeMap.BadCommunicationError); + ops.Invokes.Select(i => i.Command.Kind).ShouldBe([MxCommandKind.Advise]); + } + + /// MXAccess refusing the user's rights on the secured write (1016) is an access refusal. + [Fact] + public async Task A_secured_write_MXAccess_refuses_for_rights_is_BadUserAccessDenied() + { + var ops = new SecuredFakeOps + { + InvokeResponder = r => r.Command.Kind switch + { + MxCommandKind.AuthenticateUser => new MxCommandReply { ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok }, AuthenticateUser = new AuthenticateUserReply { UserId = 7 } }, + MxCommandKind.WriteSecured => new MxCommandReply + { + ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok }, + Statuses = { new MxStatusProxy { Success = 0, Category = MxStatusCategory.SecurityError, Detail = 1016 } }, + }, + _ => Ok(), + }, + }; + + var result = await NewWriter().WriteOneForTestAsync( + ops, new WriteRequest("T.A", 1), SecurityClassification.SecuredWrite, CancellationToken.None, Identity()); + + result.StatusCode.ShouldBe(StatusCodeMap.BadUserAccessDenied); + } + + /// A whole batch resolves the caller's identity ONCE, however many secured tags it carries. + [Fact] + public async Task A_batch_resolves_the_identity_once() + { + var ops = HappyOps(); + var resolved = 0; + var writer = NewWriter(); + + var results = await writer.WriteBatchForTestAsync(ops, + [new WriteRequest("T.A", 1), new WriteRequest("T.B", 2), new WriteRequest("T.C", 3)], + _ => SecurityClassification.SecuredWrite, CancellationToken.None, + ct => { Interlocked.Increment(ref resolved); return Identity()(ct); }); + + results.ShouldAllBe(r => r.StatusCode == StatusCodeMap.Good); + resolved.ShouldBe(1); + } + + /// Invalidation (a reconnect) forgets the secured handles too, so a fresh session re-adds + re-advises. + [Fact] + public async Task InvalidateHandleCaches_forgets_secured_handles() + { + var ops = HappyOps(); + var writer = NewWriter(); + await writer.WriteOneForTestAsync(ops, new WriteRequest("T.A", 1), SecurityClassification.SecuredWrite, CancellationToken.None, Identity()); + + writer.InvalidateHandleCaches(); + await writer.WriteOneForTestAsync(ops, new WriteRequest("T.A", 2), SecurityClassification.SecuredWrite, CancellationToken.None, Identity()); + + ops.AddItemRefs.Count.ShouldBe(2); + ops.Invokes.Count(i => i.Command.Kind == MxCommandKind.Advise).ShouldBe(2); + } + + private sealed class SecuredFakeOps : IMxWriteOps + { + public string SessionId => "sess-1"; + public int ServerHandle => 100; + public int NextHandle { get; init; } = 7; + public List AddItemRefs { get; } = new(); + public List Invokes { get; } = new(); + public List RawWriteHandles { get; } = new(); + public Func? InvokeResponder { get; init; } + + public Task AddItemAsync(string fullRef, CancellationToken ct) + { + AddItemRefs.Add(fullRef); + return Task.FromResult(NextHandle); + } + + public Task InvokeAsync(MxCommandRequest request, CancellationToken ct) + { + lock (Invokes) Invokes.Add(request); + return Task.FromResult(InvokeResponder?.Invoke(request) ?? new MxCommandReply()); + } + + public Task WriteRawAsync(int itemHandle, MxValue value, int userId, CancellationToken ct) + { + RawWriteHandles.Add(itemHandle); + return Task.FromResult(new MxCommandReply()); + } + } +} diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/TestAckCredentials.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/TestAckCredentials.cs index 90f3d46ce..5c8c39a1b 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/TestAckCredentials.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/TestAckCredentials.cs @@ -30,4 +30,16 @@ internal sealed class FixedAckCredentialResolver : IGalaxyAckCredentialResolver ? GalaxyAckCredentialResolution.Refused("test refusal") : GalaxyAckCredentialResolution.Resolved(_credential)); } + + /// Gets the key ids a secured write resolved for (#1017), in order. + public List SecuredWriteKeyIds { get; } = []; + + /// + public Task ResolveKeyIdentityAsync(string? apiKeyId, CancellationToken cancellationToken) + { + SecuredWriteKeyIds.Add(apiKeyId); + return Task.FromResult(_credential is null || apiKeyId is null + ? GalaxyAckCredentialResolution.Refused("test refusal (no key identity)") + : GalaxyAckCredentialResolution.Resolved(_credential)); + } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/GalaxyDriverPageFormSerializationTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/GalaxyDriverPageFormSerializationTests.cs index 4bf9a907e..e3de7744b 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/GalaxyDriverPageFormSerializationTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/GalaxyDriverPageFormSerializationTests.cs @@ -350,6 +350,29 @@ public sealed class GalaxyDriverPageFormSerializationTests back.MxAccess.ClientName.ShouldBe("OtOpcUa-A"); } + /// + /// #1017: MxAccess.SecuredWrites round-trips through the form and is saved as a STRING the driver + /// factory parses (it refuses an unknown value, and a numeric enum would be unknown). + /// + [Fact] + public void FormModel_RoundTrips_SecuredWrites_as_a_string() + { + var original = new GalaxyDriverOptions( + new GalaxyGatewayOptions("https://gw:5001", "env:K"), + new GalaxyMxAccessOptions("OtOpcUa") { SecuredWrites = GalaxySecuredWriteMode.ApiKeyIdentity }, + new GalaxyRepositoryOptions(), + new GalaxyReconnectOptions()); + + var form = GalaxyDriverForm.GalaxyFormModel.FromRecord(original); + form.MxSecuredWrites.ShouldBe(GalaxySecuredWriteMode.ApiKeyIdentity); + new GalaxyDriverForm.GalaxyFormModel().MxSecuredWrites.ShouldBe(GalaxySecuredWriteMode.Refuse); + + var json = GalaxyDriverForm.Serialize(form.ToRecord(), originalJson: null); + json.ShouldContain("\"securedWrites\":\"ApiKeyIdentity\""); + JsonSerializer.Deserialize(json, new JsonSerializerOptions(_pageOpts) { Converters = { new JsonStringEnumConverter() } })! + .MxAccess.SecuredWrites.ShouldBe(GalaxySecuredWriteMode.ApiKeyIdentity); + } + /// /// lmxopcua#1045 guard: every leaf the form's record serialises must be an owned path, or an edit to it is /// silently discarded by the overlay on save (rawTags is authored elsewhere and deliberately not owned). diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerKeyUsabilityGateTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerKeyUsabilityGateTests.cs index 00c08f637..c00f8b8b0 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerKeyUsabilityGateTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerKeyUsabilityGateTests.cs @@ -5,6 +5,7 @@ using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; using ZB.MOM.WW.OtOpcUa.Configuration.Enums; using ZB.MOM.WW.OtOpcUa.Core.Authorization; using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; @@ -232,15 +233,53 @@ public sealed class NodeManagerKeyUsabilityGateTests : IDisposable return errors; } + /// + /// #1017: the dispatched write carries WHO wrote — the session's principal and API key id — so a driver whose + /// device enforces per-user write permission (Galaxy SecuredWrite) can act as that caller. Anonymous carries + /// the anonymous principal and no key. + /// + [Fact] + public async Task The_dispatched_write_carries_the_sessions_principal_and_key() + { + var (host, server) = await BootAsync(); + try + { + var nm = server.NodeManager!; + var gateway = new RecordingWriteGateway(); + nm.NodeWriteGateway = gateway; + Wire(nm, new FakeClock(Start), Key(expiresUtc: null)); + var nodeId = Writable(nm, "Plant/Modbus/dev1/Setpoint"); + + Write(nm, KeyIdentity(OpcUaDataPlaneRoles.WriteOperate), nodeId, 1f)[0].StatusCode.Code.ShouldBe(StatusCodes.Good.Code); + var anonymous = new RoleCarryingUserIdentity( + new AnonymousIdentityToken(), [OpcUaDataPlaneRoles.WriteOperate], OpcUaPrincipals.Anonymous, apiKeyId: null); + Write(nm, anonymous, nodeId, 2f)[0].StatusCode.Code.ShouldBe(StatusCodes.Good.Code); + + gateway.Callers.Count.ShouldBe(2); + gateway.Callers[0].ShouldBe(new WriteCaller(Principal, KeyId)); + gateway.Callers[1].ShouldBe(new WriteCaller(OpcUaPrincipals.Anonymous, null)); + } + finally { await host.DisposeAsync(); } + } + /// Records what actually reached the device. private sealed class RecordingWriteGateway : IOpcUaNodeWriteGateway { public List Writes { get; } = []; + public List Callers { get; } = []; public Task WriteAsync( string nodeId, object? value, AddressSpaceRealm realm, CancellationToken ct) + => WriteAsync(nodeId, value, realm, caller: null, ct); + + public Task WriteAsync( + string nodeId, object? value, AddressSpaceRealm realm, WriteCaller? caller, CancellationToken ct) { - lock (Writes) Writes.Add(nodeId); + lock (Writes) + { + Writes.Add(nodeId); + Callers.Add(caller); + } return Task.FromResult(new NodeWriteOutcome(true, null)); } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/ActorNodeWriteGatewayTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/ActorNodeWriteGatewayTests.cs index 7370bdf3e..ca38efc3c 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/ActorNodeWriteGatewayTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/ActorNodeWriteGatewayTests.cs @@ -37,6 +37,27 @@ public sealed class ActorNodeWriteGatewayTests : RuntimeActorTestBase outcome.Reason.ShouldBeNull(); } + /// #1017: the caller-carrying overload puts the caller on the RouteNodeWrite; the plain one carries none. + [Fact] + public async Task The_caller_rides_the_route_message() + { + var probe = CreateTestProbe(); + IOpcUaNodeWriteGateway gateway = new ActorNodeWriteGateway(resolveDriverHost: () => probe.Ref, NullLogger.Instance); + var caller = new ZB.MOM.WW.OtOpcUa.Core.Abstractions.WriteCaller("scadabridge", "0a1b2c3d4e5f6071"); + + var withCaller = gateway.WriteAsync("eq-1/speed", 1.0, AddressSpaceRealm.Uns, caller, CancellationToken.None); + probe.ExpectMsg(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken) + .Caller.ShouldBe(caller); + probe.Reply(new DriverHostActor.NodeWriteResult(true, null)); + (await withCaller).Success.ShouldBeTrue(); + + var without = gateway.WriteAsync("eq-1/speed", 2.0, AddressSpaceRealm.Uns, CancellationToken.None); + probe.ExpectMsg(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken) + .Caller.ShouldBeNull(); + probe.Reply(new DriverHostActor.NodeWriteResult(true, null)); + (await without).Success.ShouldBeTrue(); + } + /// Probe replies failure → the outcome carries the same (false, reason) verbatim. [Fact] public async Task Failure_reply_maps_to_failure_outcome_with_reason() diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorWriteRoutingTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorWriteRoutingTests.cs index 27ac44291..287c8fa01 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorWriteRoutingTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorWriteRoutingTests.cs @@ -87,6 +87,31 @@ public sealed class DriverHostActorWriteRoutingTests : RuntimeActorTestBase }, duration: Timeout, cancellationToken: TestContext.Current.CancellationToken); } + /// + /// #1017: a RouteNodeWrite that carries its caller reaches a caller-aware driver through + /// with that caller; one without a caller keeps the plain + /// path (positive control). + /// + [Fact] + public void The_writes_caller_reaches_a_caller_aware_driver() + { + var db = NewInMemoryDbFactory(); + var recorder = new RecordingDriverFactory("Modbus"); + var deploymentId = SeedV3Deployment(db, RevA); + var actor = SpawnHostAndApply(db, deploymentId, recorder); + var caller = new WriteCaller("scadabridge", "0a1b2c3d4e5f6071"); + + RouteWriteUntilAccepted(actor, $"ns=2;s={RawPath}", 1.0, AddressSpaceRealm.Raw, caller); + RouteWriteUntilAccepted(actor, $"ns=2;s={RawPath}", 2.0, AddressSpaceRealm.Raw); + + AwaitAssert(() => + { + recorder.Callers.Count.ShouldBe(2); + recorder.Callers[0].ShouldBe(caller); + recorder.Callers[1].ShouldBeNull(); + }, duration: Timeout, cancellationToken: TestContext.Current.CancellationToken); + } + /// /// Routes a write, retrying until the host accepts it, and fails with the host's own rejection /// Reason if it never does. @@ -113,14 +138,14 @@ public sealed class DriverHostActorWriteRoutingTests : RuntimeActorTestBase /// The value to write. /// The address-space realm the NodeId belongs to. private void RouteWriteUntilAccepted( - IActorRef actor, string nodeId, object value, AddressSpaceRealm realm) + IActorRef actor, string nodeId, object value, AddressSpaceRealm realm, WriteCaller? caller = null) { var lastReason = "(no reply)"; AwaitAssert( () => { var asker = CreateTestProbe(); - actor.Tell(new DriverHostActor.RouteNodeWrite(nodeId, value, realm), asker.Ref); + actor.Tell(new DriverHostActor.RouteNodeWrite(nodeId, value, realm, caller), asker.Ref); var result = asker.ExpectMsg(TimeSpan.FromSeconds(1)); lastReason = result.Reason ?? "(none)"; result.Success.ShouldBeTrue($"host kept rejecting the write; last reason: {lastReason}"); @@ -393,6 +418,9 @@ public sealed class DriverHostActorWriteRoutingTests : RuntimeActorTestBase /// The writes the spawned driver received. public IReadOnlyList Writes => _driver.Writes; + /// The caller each write carried (#1017). + public IReadOnlyList Callers => _driver.Callers; + /// public IDriver? TryCreate(string driverType, string driverInstanceId, string driverConfigJson) { @@ -406,9 +434,12 @@ public sealed class DriverHostActorWriteRoutingTests : RuntimeActorTestBase } /// An + that records every write and returns Good. - private sealed class RecordingDriver : IDriver, IWritable + private sealed class RecordingDriver : IDriver, ICallerAwareWritable { private readonly ConcurrentQueue _writes = new(); + private readonly ConcurrentQueue _callers = new(); + /// The caller each write carried (null = the plain IWritable overload), in order (#1017). + public IReadOnlyList Callers => _callers.ToArray(); /// public string DriverInstanceId { get; private set; } = string.Empty; /// @@ -429,7 +460,15 @@ public sealed class DriverHostActorWriteRoutingTests : RuntimeActorTestBase public Task> WriteAsync( IReadOnlyList writes, CancellationToken cancellationToken) { - foreach (var w in writes) _writes.Enqueue(w); + foreach (var w in writes) { _writes.Enqueue(w); _callers.Enqueue(null); } + return Task.FromResult>( + writes.Select(_ => new WriteResult(0u)).ToArray()); + } + /// + public Task> WriteAsync( + IReadOnlyList writes, WriteCaller caller, CancellationToken cancellationToken) + { + foreach (var w in writes) { _writes.Enqueue(w); _callers.Enqueue(caller); } return Task.FromResult>( writes.Select(_ => new WriteResult(0u)).ToArray()); }