feat(galaxy): #1017 SecuredWrite attributes can be written as the calling API key's Galaxy identity (opt-in); VerifiedWrite stays refused

- MxAccess.SecuredWrites = Refuse (default, unchanged #991 local BadUserAccessDenied) |
  ApiKeyIdentity. Opted in, a SecuredWrite runs as the calling key's own /api-keys Galaxy
  identity (ResolveKeyIdentityAsync: no fallback account; anonymous / no identity / broken
  identity refused before the wire): own plain-advised handle (apart from the raw path's
  supervisory handle) -> AuthenticateUser every write -> WriteSecured(userId, 0), the sequence
  mxaccessgw live-captured committing. Auth failure / user id 0 -> BadUserAccessDenied; password
  only in the AuthenticateUser command, scrubbed from every log. Identity resolved once per batch.
- VerifiedWrite is refused in every mode: an OPC UA Write carries no verifier (MXAccess refuses
  no verifier 1008 / self-verifier 8018), and a stored verifier would defeat the two-person rule.
- Caller plumbing: WriteCaller + optional ICallerAwareWritable (Core.Abstractions); node manager
  passes principal + key id -> IOpcUaNodeWriteGateway caller overload (default drops it) ->
  RouteNodeWrite.Caller -> WriteAttribute.Caller -> ICallerAwareWritable. The gRPC data-connection
  write path carries no caller yet (secured writes refused there).
- AdminUI Galaxy form 'Secured writes' select (owned path); enum serialises as its name; factory
  refuses an unknown value. Docs: Galaxy.md design + live-gate checklist. Not live-gated.
This commit is contained in:
Joseph Doherty
2026-12-03 15:29:02 -05:00
parent 9496db9357
commit 13521354cc
26 changed files with 1120 additions and 65 deletions
+6
View File
@@ -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
+1 -1
View File
@@ -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/<name>` (or `secret:otopcua/galaxy/<name>`) / `env:OTOPCUA_GALAXY_<NAME>` (or legacy `env:GALAXY_MXGW_<NAME>`) / `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. |
+67 -8
View File
@@ -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/<name>` · `secret:otopcua/galaxy/<name>` · `env:OTOPCUA_GALAXY_<NAME>` · legacy `env:GALAXY_MXGW_<NAME>` · `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/<keyId>/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
@@ -22,6 +22,23 @@ public interface IOpcUaNodeWriteGateway
/// <param name="ct">Cancellation token.</param>
/// <returns>A task resolving to the device-write outcome.</returns>
Task<NodeWriteOutcome> WriteAsync(string nodeId, object? value, AddressSpaceRealm realm, CancellationToken ct);
/// <summary>
/// #1017 — <see cref="WriteAsync(string, object?, AddressSpaceRealm, CancellationToken)"/> carrying WHO wrote
/// (the session's principal + API key id), so a driver whose device enforces per-user write permission
/// (<see cref="ZB.MOM.WW.OtOpcUa.Core.Abstractions.ICallerAwareWritable"/>) can act on it. The default
/// implementation drops the caller — a gateway that cannot carry it behaves exactly as before.
/// </summary>
/// <param name="nodeId">The full ns-qualified node id being written.</param>
/// <param name="value">The value the client wrote.</param>
/// <param name="realm">The namespace realm of <paramref name="nodeId"/>.</param>
/// <param name="caller">Who issued the write; null when unknown.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>A task resolving to the device-write outcome.</returns>
Task<NodeWriteOutcome> WriteAsync(
string nodeId, object? value, AddressSpaceRealm realm,
ZB.MOM.WW.OtOpcUa.Core.Abstractions.WriteCaller? caller, CancellationToken ct)
=> WriteAsync(nodeId, value, realm, ct);
}
/// <summary>Outcome of routing an inbound node write to the backing driver.</summary>
@@ -0,0 +1,31 @@
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions;
/// <summary>
/// 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. <see cref="ApiKeyId" /> null = an
/// anonymous session (or a write with no client session behind it).
/// </summary>
/// <param name="Principal">The ACL principal (e.g. the key's principal, or <c>anonymous</c>); null when unknown.</param>
/// <param name="ApiKeyId">The authenticating API key's public id; null for anonymous.</param>
public sealed record WriteCaller(string? Principal, string? ApiKeyId);
/// <summary>
/// Optional companion to <see cref="IWritable" /> 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 <see cref="IWritable.WriteAsync" /> whenever the write carries a <see cref="WriteCaller" />. It must keep
/// every other behaviour of <see cref="IWritable.WriteAsync" />; a caller the driver cannot map is refused
/// per write (e.g. <c>BadUserAccessDenied</c>), never silently written under another identity.
/// </summary>
public interface ICallerAwareWritable : IWritable
{
/// <summary>Write a batch on behalf of <paramref name="caller" />; one result per request, in order.</summary>
/// <param name="writes">Pairs of full reference + value to write.</param>
/// <param name="caller">Who issued the write.</param>
/// <param name="cancellationToken">Cancellation token; the driver should abort the batch if cancelled.</param>
/// <returns>One <see cref="WriteResult" /> per requested write, in the same order.</returns>
Task<IReadOnlyList<WriteResult>> WriteAsync(
IReadOnlyList<WriteRequest> writes,
WriteCaller caller,
CancellationToken cancellationToken);
}
@@ -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)
{
/// <summary>
/// How a write to a <c>SecuredWrite</c> attribute is handled (#1017). Default
/// <see cref="GalaxySecuredWriteMode.Refuse"/> — refused <c>BadUserAccessDenied</c> locally (#991). A
/// <c>VerifiedWrite</c> attribute is refused in every mode.
/// </summary>
public GalaxySecuredWriteMode SecuredWrites { get; init; } = GalaxySecuredWriteMode.Refuse;
}
/// <summary>How the Galaxy driver handles a write to a <c>SecuredWrite</c> attribute (#1017).</summary>
/// <remarks>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.</remarks>
[System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter<GalaxySecuredWriteMode>))]
public enum GalaxySecuredWriteMode
{
/// <summary>Refuse it <c>BadUserAccessDenied</c> before anything reaches the gateway (the #991 behaviour).</summary>
Refuse,
/// <summary>
/// Write it as the CALLING session's API key's Galaxy identity — the account mapped to the key on AdminUI
/// <c>/api-keys</c> (the same identity a native alarm acknowledge from that key uses,
/// <see cref="GalaxyAckIdentitySecrets"/>): <c>AuthenticateUser</c> then <c>WriteSecured</c>. 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 <c>invoke:secure</c> scope.
/// </summary>
ApiKeyIdentity,
}
/// <summary>
/// Galaxy Repository browse-side knobs consumed by PR 4.1's <c>GalaxyDiscoverer</c>.
@@ -38,7 +38,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy;
/// </para>
/// </remarks>
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
{
/// <summary>Authored tags this driver could not dial — a TagConfig with no usable
/// <c>attributeRef</c> has no MXAccess address to bind.</summary>
@@ -396,7 +396,7 @@ public sealed class GalaxyDriver
/// <summary>
/// Test-visible ctor — inject custom seams so <see cref="DiscoverAsync"/>,
/// <see cref="ReadAsync"/>, <see cref="WriteAsync"/>, and
/// <see cref="ReadAsync"/>, <see cref="WriteAsync(IReadOnlyList{WriteRequest}, CancellationToken)"/>, and
/// <see cref="SubscribeAsync"/> can be exercised against canned data without
/// building real gRPC channels.
/// </summary>
@@ -908,7 +908,7 @@ public sealed class GalaxyDriver
/// <summary>
/// #991 G-1 — one security seed pass: fetch the authored objects' attributes and record each authored tag's
/// <see cref="SecurityClassification"/> under its RawPath, the key <see cref="WriteAsync"/> resolves against.
/// <see cref="SecurityClassification"/> under its RawPath, the key <see cref="WriteAsync(IReadOnlyList{WriteRequest}, CancellationToken)"/> resolves against.
/// Before this the map was filled only by <see cref="DiscoverAsync"/>, 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
/// <inheritdoc />
public Task<IReadOnlyList<WriteResult>> WriteAsync(
IReadOnlyList<WriteRequest> writes, CancellationToken cancellationToken)
=> WriteCoreAsync(writes, caller: null, cancellationToken);
/// <summary>
/// #1017 — <see cref="WriteAsync(IReadOnlyList{WriteRequest}, CancellationToken)"/> on behalf of
/// <paramref name="caller"/>. With <c>MxAccess.SecuredWrites = ApiKeyIdentity</c> 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 <c>BadUserAccessDenied</c> as before. Non-secured tags are
/// unaffected by the caller.
/// </summary>
/// <param name="writes">Pairs of full reference (RawPath) + value.</param>
/// <param name="caller">Who issued the write.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>One result per request, in order.</returns>
public Task<IReadOnlyList<WriteResult>> WriteAsync(
IReadOnlyList<WriteRequest> writes, WriteCaller caller, CancellationToken cancellationToken)
=> WriteCoreAsync(writes, caller ?? throw new ArgumentNullException(nameof(caller)), cancellationToken);
private Task<IReadOnlyList<WriteResult>> WriteCoreAsync(
IReadOnlyList<WriteRequest> writes, WriteCaller? caller, CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
ArgumentNullException.ThrowIfNull(writes);
@@ -2403,8 +2422,17 @@ public sealed class GalaxyDriver
var dialledWrites = new List<WriteRequest>(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<CancellationToken, Task<GalaxyAckCredentialResolution>>? 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) =====
@@ -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();
/// <summary>
/// #1017: <c>MxAccess.SecuredWrites</c> — absent/blank = <see cref="GalaxySecuredWriteMode.Refuse"/>. An
/// unknown value fails the driver config loudly rather than silently refusing (a misspelt opt-in would
/// otherwise look like a Galaxy permission problem).
/// </summary>
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<GalaxySecuredWriteMode>(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<GalaxySecuredWriteMode>())}).");
}
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNameCaseInsensitive = true,
@@ -218,6 +239,8 @@ public static class GalaxyDriverFactoryExtensions
public int? WriteUserId { get; init; }
/// <summary>Gets or sets the event pump channel capacity.</summary>
public int? EventPumpChannelCapacity { get; init; }
/// <summary>Gets or sets the SecuredWrite handling (#1017): <c>Refuse</c> (default) or <c>ApiKeyIdentity</c>.</summary>
public string? SecuredWrites { get; init; }
}
/// <summary>Repository configuration section.</summary>
@@ -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.");
}
/// <inheritdoc />
public async Task<GalaxyAckCredentialResolution> 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<GalaxyAckCredentialResolution> ResolveKeyIdentityAsync(string apiKeyId, CancellationToken ct)
private async Task<GalaxyAckCredentialResolution> ResolveMappedKeyIdentityAsync(string apiKeyId, CancellationToken ct)
{
string userName, passwordName;
try
@@ -13,10 +13,11 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
/// Production <see cref="IGalaxyDataWriter"/> over <see cref="GalaxyMxSession"/>.
/// For each batch entry: lazy-AddItem to obtain the MXAccess item handle, encode
/// the value via <see cref="MxValueEncoder"/>, supervisory-advise + Write, and translate the
/// reply's <c>MxStatusProxy</c> into an OPC UA <see cref="WriteResult"/>. A SecuredWrite /
/// VerifiedWrite attribute (per-tag <see cref="SecurityClassification"/>) is refused
/// <c>BadUserAccessDenied</c> without a round trip — the driver has no ArchestrA identity to
/// write it under (#991 review G-1).
/// reply's <c>MxStatusProxy</c> into an OPC UA <see cref="WriteResult"/>. A SecuredWrite attribute
/// (per-tag <see cref="SecurityClassification"/>) is written as the caller's Galaxy identity when the
/// driver supplies one (#1017: own plain-advised handle → <c>AuthenticateUser</c> → <c>WriteSecured</c>),
/// and refused <c>BadUserAccessDenied</c> without a round trip otherwise (#991 review G-1); a
/// VerifiedWrite attribute is always refused that way (no verifying user).
/// </summary>
/// <remarks>
/// 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<int, byte> _supervisedHandles = new();
// Attributes whose secured/verified-write refusal has been logged (once per attribute, #991 review G-1).
private readonly ConcurrentDictionary<string, byte> _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<string, int> _securedItemHandles = new(StringComparer.OrdinalIgnoreCase);
private readonly ConcurrentDictionary<int, byte> _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
}
/// <inheritdoc />
public async Task<IReadOnlyList<WriteResult>> WriteAsync(
public Task<IReadOnlyList<WriteResult>> WriteAsync(
IReadOnlyList<WriteRequest> writes,
Func<string, SecurityClassification> securityResolver,
CancellationToken cancellationToken)
=> WriteCoreAsync(writes, securityResolver, securedCredential: null, cancellationToken);
/// <inheritdoc />
Task<IReadOnlyList<WriteResult>> IGalaxyDataWriter.WriteAsync(
IReadOnlyList<WriteRequest> writes,
Func<string, SecurityClassification> securityResolver,
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential,
CancellationToken cancellationToken)
=> WriteCoreAsync(writes, securityResolver, securedCredential, cancellationToken);
private async Task<IReadOnlyList<WriteResult>> WriteCoreAsync(
IReadOnlyList<WriteRequest> writes,
Func<string, SecurityClassification> securityResolver,
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? 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);
}
/// <summary>
@@ -142,10 +165,12 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
/// <param name="securityResolver">Per-tag classification resolver.</param>
/// <param name="ct">The cancellation token.</param>
/// <returns>One result per request, in input order.</returns>
/// <param name="securedCredential">The caller's Galaxy identity source for secured writes (#1017); null = none.</param>
internal Task<IReadOnlyList<WriteResult>> WriteBatchForTestAsync(
IMxWriteOps ops, IReadOnlyList<WriteRequest> writes,
Func<string, SecurityClassification> securityResolver, CancellationToken ct)
=> WriteBatchAsync(ops, writes, securityResolver, ct);
Func<string, SecurityClassification> securityResolver, CancellationToken ct,
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential = null)
=> WriteBatchAsync(ops, writes, securityResolver, ct, securedCredential);
/// <summary>
/// Run a batch as one lane per distinct tag (OrdinalIgnoreCase): writes to the SAME tag
@@ -155,11 +180,21 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
/// </summary>
private async Task<IReadOnlyList<WriteResult>> WriteBatchAsync(
IMxWriteOps ops, IReadOnlyList<WriteRequest> writes,
Func<string, SecurityClassification> securityResolver, CancellationToken ct)
Func<string, SecurityClassification> securityResolver, CancellationToken ct,
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? 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<CancellationToken, Task<GalaxyAckCredentialResolution>>? batchCredential = null;
if (securedCredential is not null)
{
var once = new Lazy<Task<GalaxyAckCredentialResolution>>(
() => 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<string, List<int>>(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
/// <param name="classification">The tag's security classification.</param>
/// <param name="ct">The cancellation token.</param>
/// <returns>The translated write result.</returns>
/// <param name="securedCredential">The caller's Galaxy identity source for a SecuredWrite (#1017); null = none.</param>
internal Task<WriteResult> WriteOneForTestAsync(
IMxWriteOps ops, WriteRequest request, SecurityClassification classification, CancellationToken ct)
=> WriteOneAsync(ops, request, classification, ct);
IMxWriteOps ops, WriteRequest request, SecurityClassification classification, CancellationToken ct,
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential = null)
=> WriteOneAsync(ops, request, classification, ct, securedCredential);
private async Task<WriteResult> WriteOneAsync(
IMxWriteOps ops, WriteRequest request,
SecurityClassification classification, CancellationToken ct)
SecurityClassification classification, CancellationToken ct,
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? 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);
}
/// <summary>
/// #1017 — a SecuredWrite under the CALLER's Galaxy identity: the writer's own plain-advised handle →
/// <c>AuthenticateUser(DOMAIN\user, password)</c> → <c>WriteSecured(current = that user, verifier = 0)</c>, the
/// sequence mxaccessgw live-captured committing (docs/LiveCaptures-2026-11-13.md §4). The password goes only
/// into the <c>AuthenticateUser</c> 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.
/// </summary>
private async Task<WriteResult> WriteSecuredOneAsync(
IMxWriteOps ops, WriteRequest request,
Func<CancellationToken, Task<GalaxyAckCredentialResolution>> 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<int> 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;
}
/// <summary>Plain-advise the secured path's handle once per session (MXAccess refuses writes to an unadvised
/// item). <c>false</c> = the advise failed and the write must fail closed.</summary>
private async Task<bool> 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;
}
/// <summary>Whether <paramref name="ex"/> (or an inner exception) is the gateway refusing the caller.</summary>
internal static bool IsCallerRefused(Exception ex) =>
@@ -15,4 +15,15 @@ internal interface IGalaxyAckCredentialResolver
/// <param name="cancellationToken">Cancels secret resolution.</param>
/// <returns>The resolved credential or the refusal reason.</returns>
Task<GalaxyAckCredentialResolution> ResolveAsync(string? apiKeyId, CancellationToken cancellationToken);
/// <summary>
/// #1017 — the identity a SECURED WRITE from <paramref name="apiKeyId"/> runs as: the key's own Galaxy
/// identity only. Unlike <see cref="ResolveAsync"/> 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.
/// </summary>
/// <param name="apiKeyId">The authenticating API key id, or null (anonymous).</param>
/// <param name="cancellationToken">Cancels secret resolution.</param>
/// <returns>The resolved credential or the refusal reason.</returns>
Task<GalaxyAckCredentialResolution> ResolveKeyIdentityAsync(string? apiKeyId, CancellationToken cancellationToken);
}
@@ -4,9 +4,9 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
/// <summary>
/// Driver-side seam for batched writes. Production implementation decides by
/// <see cref="SecurityClassification"/>: SecuredWrite / VerifiedWrite are refused
/// <c>BadUserAccessDenied</c> (no ArchestrA identity to write them under — #991 review G-1),
/// everything else goes supervisory-advise + raw <c>Write</c>. Tests substitute a fake to record routing
/// <see cref="SecurityClassification"/>: SecuredWrite goes <c>AuthenticateUser</c> + <c>WriteSecured</c> under the
/// caller's Galaxy identity when one is supplied (#1017) and is otherwise refused <c>BadUserAccessDenied</c>
/// (#991 review G-1); VerifiedWrite is always refused; everything else goes supervisory-advise + raw <c>Write</c>. Tests substitute a fake to record routing
/// decisions without touching real gw infrastructure.
/// </summary>
public interface IGalaxyDataWriter
@@ -31,6 +31,24 @@ public interface IGalaxyDataWriter
Func<string, SecurityClassification> securityResolver,
CancellationToken cancellationToken);
/// <summary>
/// #1017 — <see cref="WriteAsync(IReadOnlyList{WriteRequest}, Func{string, SecurityClassification}, CancellationToken)"/>
/// with the CALLER's Galaxy identity for SecuredWrite tags: <paramref name="securedCredential"/> 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).
/// </summary>
/// <param name="writes">Pairs of full reference + value to write.</param>
/// <param name="securityResolver">Per-tag classification resolver.</param>
/// <param name="securedCredential">The caller's Galaxy identity source, or null.</param>
/// <param name="cancellationToken">Aborts the in-flight batch.</param>
/// <returns>One <see cref="WriteResult"/> per request entry, in input order.</returns>
internal Task<IReadOnlyList<WriteResult>> WriteAsync(
IReadOnlyList<WriteRequest> writes,
Func<string, SecurityClassification> securityResolver,
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential,
CancellationToken cancellationToken)
=> WriteAsync(writes, securityResolver, cancellationToken);
/// <summary>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.</summary>
void InvalidateHandleCaches();
@@ -14,10 +14,25 @@ internal sealed class TracedGalaxyDataWriter(IGalaxyDataWriter inner, string cli
public void InvalidateHandleCaches() => inner.InvalidateHandleCaches();
/// <inheritdoc />
public async Task<IReadOnlyList<WriteResult>> WriteAsync(
public Task<IReadOnlyList<WriteResult>> WriteAsync(
IReadOnlyList<WriteRequest> writes,
Func<string, SecurityClassification> securityResolver,
CancellationToken cancellationToken)
=> TraceAsync(writes, securityResolver, () => inner.WriteAsync(writes, securityResolver, cancellationToken));
/// <inheritdoc />
Task<IReadOnlyList<WriteResult>> IGalaxyDataWriter.WriteAsync(
IReadOnlyList<WriteRequest> writes,
Func<string, SecurityClassification> securityResolver,
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential,
CancellationToken cancellationToken)
=> TraceAsync(writes, securityResolver,
() => inner.WriteAsync(writes, securityResolver, securedCredential, cancellationToken));
private async Task<IReadOnlyList<WriteResult>> TraceAsync(
IReadOnlyList<WriteRequest> writes,
Func<string, SecurityClassification> securityResolver,
Func<Task<IReadOnlyList<WriteResult>>> 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;
}
@@ -64,6 +64,8 @@
the Historian records it as the operator. Stored encrypted in the Secrets store
(<span class="mono">otopcua/apikeys/@(_ackEditKeyId)/galaxy-ack-*</span>), 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 <em>Secured writes = API key identity</em> also writes <code>SecuredWrite</code>
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.
</div>
<div class="row g-2">
@@ -98,6 +98,20 @@
<div id="@FieldId("field-11-error")" class="field-error">@if (_fieldEditContext is not null) { <ValidationMessage For="@(() => _form.Galaxy.MxEventPumpChannelCapacity)" /> }</div>
<div id="@FieldId("field-11-hint")" class="form-text">Default 50000. Raise if events.dropped appears.</div>
</div>
<div class="col-md-6">
<label for="@FieldId("field-11a")" class="form-label">Secured writes</label>
<InputSelect aria-describedby="@FieldIds("field-11a-hint")" id="@FieldId("field-11a")" @bind-Value="_form.Galaxy.MxSecuredWrites" @bind-Value:after="EmitAsync" class="form-select form-select-sm">
<option value="@GalaxySecuredWriteMode.Refuse">Refuse (default)</option>
<option value="@GalaxySecuredWriteMode.ApiKeyIdentity">Write as the calling API key's Galaxy identity</option>
</InputSelect>
<div id="@FieldId("field-11a-hint")" class="form-text">
How a write to a <code>SecuredWrite</code> attribute is handled (#1017). <em>Refuse</em> answers
<code>BadUserAccessDenied</code>. <em>API key identity</em> authenticates as the Galaxy account mapped to the
session's key on <a href="/apikeys">API keys</a> and issues <code>WriteSecured</code>; anonymous sessions and keys
without an identity are refused (no fallback account). The gateway key needs <code>invoke:secure</code>.
<code>VerifiedWrite</code> attributes are always refused.
</div>
</div>
</div>
</div>
</section>
@@ -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),
@@ -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));
}
/// <summary>
@@ -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<NodeWriteOutcome> 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)
{
@@ -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
}
/// <inheritdoc />
public async Task<NodeWriteOutcome> WriteAsync(string nodeId, object? value, AddressSpaceRealm realm, CancellationToken ct)
public Task<NodeWriteOutcome> WriteAsync(string nodeId, object? value, AddressSpaceRealm realm, CancellationToken ct)
=> WriteAsync(nodeId, value, realm, caller: null, ct);
/// <inheritdoc />
public async Task<NodeWriteOutcome> 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<DriverHostActor.NodeWriteResult>(
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);
@@ -695,7 +695,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
/// </summary>
/// <param name="NodeId">The folder-scoped equipment-variable NodeId the operator wrote to.</param>
/// <param name="Value">The value to write (the driver coerces it to the attribute's data type).</param>
public sealed record RouteNodeWrite(string NodeId, object? Value, AddressSpaceRealm Realm);
public sealed record RouteNodeWrite(string NodeId, object? Value, AddressSpaceRealm Realm, WriteCaller? Caller = null);
/// <summary>Reply to <see cref="RouteNodeWrite"/>: the outcome of forwarding the write to the driver
/// (or a gate/lookup failure that never reached the driver).</summary>
@@ -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<DriverInstanceActor.WriteAttributeResult>(
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(
@@ -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).</param>
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);
/// <summary>
@@ -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<WriteResult> results;
try
@@ -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;
/// <summary>
/// #1017 — the driver hands its writer the CALLER's Galaxy identity source only when
/// <c>MxAccess.SecuredWrites = ApiKeyIdentity</c> AND the write carries a caller; the source resolves the key's
/// own identity (<see cref="IGalaxyAckCredentialResolver.ResolveKeyIdentityAsync"/> — never the ack fallback).
/// </summary>
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<Func<CancellationToken, Task<GalaxyAckCredentialResolution>>?> Sources { get; } = [];
public Task<IReadOnlyList<WriteResult>> WriteAsync(
IReadOnlyList<WriteRequest> writes, Func<string, SecurityClassification> securityResolver,
CancellationToken cancellationToken)
{
Sources.Add(null);
return Task.FromResult<IReadOnlyList<WriteResult>>([.. writes.Select(_ => new WriteResult(StatusCodeMap.Good))]);
}
Task<IReadOnlyList<WriteResult>> IGalaxyDataWriter.WriteAsync(
IReadOnlyList<WriteRequest> writes, Func<string, SecurityClassification> securityResolver,
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential, CancellationToken cancellationToken)
{
Sources.Add(securedCredential);
return Task.FromResult<IReadOnlyList<WriteResult>>([.. 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<InvalidOperationException>(() => GalaxyDriverFactoryExtensions.ParseSecuredWrites(value, "g"))
.Message.ShouldContain("SecuredWrites");
}
@@ -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;
/// <summary>
/// #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 →
/// <c>AuthenticateUser(DOMAIN\user, password)</c> → <c>WriteSecured(current = that user, verifier = 0)</c>.
/// No usable identity (no resolver, a refused resolution, an authentication MXAccess rejects) is still the #991
/// local <c>BadUserAccessDenied</c> refusal, and a VerifiedWrite is ALWAYS refused (no second, verifying identity).
/// </summary>
[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<CancellationToken, Task<GalaxyAckCredentialResolution>> 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);
}
/// <summary>The secured handle is NOT the raw path's supervisory handle (one advise mode per handle).</summary>
[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");
}
/// <summary>A VerifiedWrite needs a second, verifying user — never supplied, so it stays refused even WITH an identity.</summary>
[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);
}
/// <summary>A failed plain advise fails the write CLOSED (no AuthenticateUser, no WriteSecured), like the raw path.</summary>
[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]);
}
/// <summary>MXAccess refusing the user's rights on the secured write (1016) is an access refusal.</summary>
[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);
}
/// <summary>A whole batch resolves the caller's identity ONCE, however many secured tags it carries.</summary>
[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);
}
/// <summary>Invalidation (a reconnect) forgets the secured handles too, so a fresh session re-adds + re-advises.</summary>
[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<string> AddItemRefs { get; } = new();
public List<MxCommandRequest> Invokes { get; } = new();
public List<int> RawWriteHandles { get; } = new();
public Func<MxCommandRequest, MxCommandReply>? InvokeResponder { get; init; }
public Task<int> AddItemAsync(string fullRef, CancellationToken ct)
{
AddItemRefs.Add(fullRef);
return Task.FromResult(NextHandle);
}
public Task<MxCommandReply> InvokeAsync(MxCommandRequest request, CancellationToken ct)
{
lock (Invokes) Invokes.Add(request);
return Task.FromResult(InvokeResponder?.Invoke(request) ?? new MxCommandReply());
}
public Task<MxCommandReply> WriteRawAsync(int itemHandle, MxValue value, int userId, CancellationToken ct)
{
RawWriteHandles.Add(itemHandle);
return Task.FromResult(new MxCommandReply());
}
}
}
@@ -30,4 +30,16 @@ internal sealed class FixedAckCredentialResolver : IGalaxyAckCredentialResolver
? GalaxyAckCredentialResolution.Refused("test refusal")
: GalaxyAckCredentialResolution.Resolved(_credential));
}
/// <summary>Gets the key ids a secured write resolved for (#1017), in order.</summary>
public List<string?> SecuredWriteKeyIds { get; } = [];
/// <inheritdoc />
public Task<GalaxyAckCredentialResolution> 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));
}
}
@@ -350,6 +350,29 @@ public sealed class GalaxyDriverPageFormSerializationTests
back.MxAccess.ClientName.ShouldBe("OtOpcUa-A");
}
/// <summary>
/// #1017: <c>MxAccess.SecuredWrites</c> 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).
/// </summary>
[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<GalaxyDriverOptions>(json, new JsonSerializerOptions(_pageOpts) { Converters = { new JsonStringEnumConverter() } })!
.MxAccess.SecuredWrites.ShouldBe(GalaxySecuredWriteMode.ApiKeyIdentity);
}
/// <summary>
/// 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 (<c>rawTags</c> is authored elsewhere and deliberately not owned).
@@ -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;
}
/// <summary>
/// #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.
/// </summary>
[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(); }
}
/// <summary>Records what actually reached the device.</summary>
private sealed class RecordingWriteGateway : IOpcUaNodeWriteGateway
{
public List<string> Writes { get; } = [];
public List<WriteCaller?> Callers { get; } = [];
public Task<NodeWriteOutcome> WriteAsync(
string nodeId, object? value, AddressSpaceRealm realm, CancellationToken ct)
=> WriteAsync(nodeId, value, realm, caller: null, ct);
public Task<NodeWriteOutcome> 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));
}
}
@@ -37,6 +37,27 @@ public sealed class ActorNodeWriteGatewayTests : RuntimeActorTestBase
outcome.Reason.ShouldBeNull();
}
/// <summary>#1017: the caller-carrying overload puts the caller on the RouteNodeWrite; the plain one carries none.</summary>
[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<DriverHostActor.RouteNodeWrite>(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<DriverHostActor.RouteNodeWrite>(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken)
.Caller.ShouldBeNull();
probe.Reply(new DriverHostActor.NodeWriteResult(true, null));
(await without).Success.ShouldBeTrue();
}
/// <summary>Probe replies failure → the outcome carries the same (false, reason) verbatim.</summary>
[Fact]
public async Task Failure_reply_maps_to_failure_outcome_with_reason()
@@ -87,6 +87,31 @@ public sealed class DriverHostActorWriteRoutingTests : RuntimeActorTestBase
}, duration: Timeout, cancellationToken: TestContext.Current.CancellationToken);
}
/// <summary>
/// #1017: a RouteNodeWrite that carries its caller reaches a caller-aware driver through
/// <see cref="ICallerAwareWritable"/> with that caller; one without a caller keeps the plain
/// <see cref="IWritable"/> path (positive control).
/// </summary>
[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);
}
/// <summary>
/// Routes a write, retrying until the host accepts it, and fails with the host's own rejection
/// <c>Reason</c> if it never does.
@@ -113,14 +138,14 @@ public sealed class DriverHostActorWriteRoutingTests : RuntimeActorTestBase
/// <param name="value">The value to write.</param>
/// <param name="realm">The address-space realm the NodeId belongs to.</param>
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<DriverHostActor.NodeWriteResult>(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
/// <summary>The writes the spawned driver received.</summary>
public IReadOnlyList<WriteRequest> Writes => _driver.Writes;
/// <summary>The caller each write carried (#1017).</summary>
public IReadOnlyList<WriteCaller?> Callers => _driver.Callers;
/// <inheritdoc />
public IDriver? TryCreate(string driverType, string driverInstanceId, string driverConfigJson)
{
@@ -406,9 +434,12 @@ public sealed class DriverHostActorWriteRoutingTests : RuntimeActorTestBase
}
/// <summary>An <see cref="IDriver"/> + <see cref="IWritable"/> that records every write and returns Good.</summary>
private sealed class RecordingDriver : IDriver, IWritable
private sealed class RecordingDriver : IDriver, ICallerAwareWritable
{
private readonly ConcurrentQueue<WriteRequest> _writes = new();
private readonly ConcurrentQueue<WriteCaller?> _callers = new();
/// <summary>The caller each write carried (null = the plain IWritable overload), in order (#1017).</summary>
public IReadOnlyList<WriteCaller?> Callers => _callers.ToArray();
/// <inheritdoc />
public string DriverInstanceId { get; private set; } = string.Empty;
/// <inheritdoc />
@@ -429,7 +460,15 @@ public sealed class DriverHostActorWriteRoutingTests : RuntimeActorTestBase
public Task<IReadOnlyList<WriteResult>> WriteAsync(
IReadOnlyList<WriteRequest> 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<IReadOnlyList<WriteResult>>(
writes.Select(_ => new WriteResult(0u)).ToArray());
}
/// <inheritdoc />
public Task<IReadOnlyList<WriteResult>> WriteAsync(
IReadOnlyList<WriteRequest> writes, WriteCaller caller, CancellationToken cancellationToken)
{
foreach (var w in writes) { _writes.Enqueue(w); _callers.Enqueue(caller); }
return Task.FromResult<IReadOnlyList<WriteResult>>(
writes.Select(_ => new WriteResult(0u)).ToArray());
}