Merge Galaxy gRPC write caller (#1074 item 1): data-connection writes carry WriteCaller (+ Origin); secured writes over gRPC only with MxAccess.SecuredWritesOverDataConnections (default off)

This commit is contained in:
Joseph Doherty
2026-12-03 16:56:29 -05:00
17 changed files with 458 additions and 23 deletions
+4 -2
View File
@@ -220,8 +220,10 @@ host logger factory (wired in `DriverFactoryBootstrap`; the FOCAS and TwinCAT fa
`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.
design). The caller rides `WriteCaller` → `RouteNodeWrite`/`WriteAttribute.Caller` → `ICallerAwareWritable`; a gRPC data-connection
write carries the connection's principal + key id from its `DataWriteAdmission` + `WriteCaller.Origin = DataConnection`
(#1074), honoured only with the default-OFF `MxAccess.SecuredWritesOverDataConnections` (a forwarded write runs as the
LINK key's identity); `Origin` is stamped at the receiving seam, `Unspecified` ⇒ no identity. 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
@@ -462,7 +462,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); `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). |
| `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); `SecuredWritesOverDataConnections` (`false`; `true` = `ApiKeyIdentity` also applies to gRPC data-connection writes, as the connection's key — #1074); `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. |
+11
View File
@@ -799,6 +799,17 @@ not see these bits; see "Mixed versions" above.
`otopcua/apikeys/<serviceKeyId>/galaxy-ack-user` and `…/galaxy-ack-password` in the **origin's** secrets store; without
them the #765 preflight refuses `BadUserAccessDenied`.
**Galaxy secured writes over a data connection (#1074) — opt-in, default off.** A write carries the connection's
principal, API key id and `Origin = DataConnection` to the driver. A Galaxy driver in `MxAccess.SecuredWrites =
ApiKeyIdentity` mode still refuses a SecuredWrite from a data connection (`BadUserAccessDenied`, before the wire, as
before) unless it also sets `MxAccess.SecuredWritesOverDataConnections = true`. Then it writes as the **connection key's**
Galaxy identity (the same `galaxy-ack-*` secrets as above; no fallback account). ⚠️ For a forwarding consumer cluster that
key is the link's service key, so every consumer-side client allowed to write the projected node would write secured
attributes as it. Unlike `AllowGalaxyServiceAck` there is no export-level switch; the driver option, the export's Write
grant and the origin ACL are the gates. A refused secured write reaches the caller as `OutcomeUnknown`, because the
Galaxy driver reports through the legacy write path. See
[Galaxy § Secured writes](drivers/Galaxy.md#secured-writes-under-the-callers-galaxy-identity-1017).
### Condition methods (`CallConditionMethod`)
An OPC UA client calls Acknowledge, AddComment or Confirm on an imported condition (the type method or the condition's
+37 -4
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; `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).
- **`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)), `SecuredWritesOverDataConnections` — `false` (default) | `true`: `ApiKeyIdentity` also applies to gRPC data-connection writes (#1074, same section), `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).
@@ -216,6 +216,38 @@ apiKeyId)` from the session identity → `IOpcUaNodeWriteGateway.WriteAsync(…,
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.
**…and over a gRPC data connection — a separate opt-in, default OFF (#1074): `MxAccess.SecuredWritesOverDataConnections`.**
A write from a gRPC data-connection client (`DataConnectionGrpcService` → `DataWriteExecutor` → `RouteRichWrite` →
`DriverInstanceActor.WriteAttributeWithOutcome`) carries the same `WriteCaller(principal, apiKeyId)` — the connection's
authenticated principal and the public id of the API key it authenticated with, bound into the `DataWriteAdmission`
from the transport's `DataAuthenticatedContext` (never from the request payload) and re-checked by the dispatch gate
at the commit point — plus `Origin = DataConnection`. The OPC UA node manager stamps `Origin = OpcUaSession`. The
runtime sets the origin from where it RECEIVED the write; nothing parses it out of the principal or key. No wire change.
The driver gives a caller an identity source only when `SecuredWrites = ApiKeyIdentity` **and** the origin is allowed:
| Origin | Identity source |
|---|---|
| `OpcUaSession` | yes (the #1017 opt-in alone) |
| `DataConnection` | only with `MxAccess.SecuredWritesOverDataConnections = true` (default `false`; AdminUI "Also for gRPC data-connection writes") |
| `Unspecified` (the `WriteCaller` default) | never — fail closed, so a future call site that forgets to say where a write came from gets nothing |
**Off (default):** a SecuredWrite arriving over a data connection is refused exactly as before #1074 — no identity
lookup, the writer's local `BadUserAccessDenied`, nothing on the wire — even when the same key writes it successfully
over OPC UA. **On:** it runs as the connection key's own `/api-keys` Galaxy identity, as an OPC UA session with that key
would; no identity (or a broken one) ⇒ refused. The option is ignored in `Refuse` mode. Read before turning it on:
- ⚠️ **Forwarded-write delegation: a federated write runs as the LINK's key.** When a consumer OtOpcUa cluster forwards
an OPC UA write on a projected node (mapping write-through), this origin sees the data connection's service key, not
the consumer's end user. With the option on and a Galaxy identity mapped to that service key (e.g. for
`DataExport.AllowGalaxyServiceAck` acks — the same `galaxy-ack-*` secrets), **every consumer-side client allowed to
write the projected node writes SecuredWrite attributes as that one Galaxy identity**, and the Galaxy/Historian audit
names the link's account, not the person. The remaining gates are the export's Write grant, the origin ACL for the
service principal and the consumer's own write grants. A direct client (e.g. ScadaBridge with its own key) is the case
the option is meant for; do not map an identity to a link's service key you do not want to delegate.
- **A refusal is not reported as one over gRPC.** The Galaxy driver is a plain `IWritable` (no
`IWriteOutcomeCapability`), so the rich write path reports any non-Good result, `BadUserAccessDenied` included, as
`OutcomeUnknown` — the same as every legacy driver's Bad (pre-existing; #1074 follow-up).
**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
@@ -233,8 +265,7 @@ carries one caller and no verifier, and storing a verifier credential per key wo
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.
Not live-gated (neither data plane).
**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
@@ -243,7 +274,9 @@ the same write anonymously / through a key with no identity ⇒ `BadUserAccessDe
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.
a gateway reconnect re-adds + re-advises the secured handle; the same write over a gRPC data connection with that
key ⇒ `BadUserAccessDenied`-refused (reported `OutcomeUnknown`, nothing in the gateway log) until
`SecuredWritesOverDataConnections = true`, then it commits as the mapped user (#1074).
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).
+1 -1
View File
@@ -1399,7 +1399,7 @@ public enum NodePermissions : int
}
```
The three Write tiers map to Galaxy's v1 `SecurityClassification` — `FreeAccess`/`Operate` → `WriteOperate`, `Tune` → `WriteTune`, `Configure` → `WriteConfigure`. `SecuredWrite` / `VerifiedWrite` / `ViewOnly` classifications remain read-only from OPC UA regardless of grant.
The three Write tiers map to Galaxy's v1 `SecurityClassification` — `FreeAccess`/`Operate` → `WriteOperate`, `Tune` → `WriteTune`, `Configure` → `WriteConfigure`. `VerifiedWrite` / `ViewOnly` classifications remain read-only from OPC UA regardless of grant; `SecuredWrite` is too unless the Galaxy driver opts in to `MxAccess.SecuredWrites = ApiKeyIdentity`, which writes it as the calling OPC UA session's key's own Galaxy identity (#1017). A secured write arriving over a **gRPC data connection** needs a second, default-off opt-in, `MxAccess.SecuredWritesOverDataConnections` (#1074); without it such a write is refused `BadUserAccessDenied` before the wire, as before. ⚠️ With it on, the identity is the **connection's** key — and a consumer OtOpcUa cluster forwarding its OPC UA clients' writes (projected-node write-through) presents its link's service key, so every consumer-side client allowed to write the projected node writes secured attributes as that key's Galaxy identity (the audit names the link's account, not the person). The driver tells the planes apart by `WriteCaller.Origin`, stamped by the runtime at the receiving seam (an unstated origin gets no identity). See [Galaxy § Secured writes](drivers/Galaxy.md#secured-writes-under-the-callers-galaxy-identity-1017).
`HistoryUpdate` (bit 12) is a **separate** permission from `HistoryRead` so a read-only grant cannot also authorize OPC UA HistoryUpdate operations. `TriePermissionEvaluator` maps `OpcUaOperation.HistoryUpdate` to this bit. It is **not** included in any composite bundle (`ReadOnly` / `Operator` / `Engineer` / `Admin`) — it must be granted explicitly, and it is offered as its own checkbox in the AdminUI ACL editor (`AclEdit.razor`). The HistoryUpdate service itself is now implemented (SQL Server historian backend only) — see the next section.
@@ -7,13 +7,40 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions;
/// </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);
/// <param name="Origin">
/// #1074 — which data plane the write arrived on. Set by the runtime from where the write was RECEIVED (the OPC UA
/// node manager or the gRPC data-connection admission), never parsed out of the principal or key id. The default,
/// <see cref="WriteCallerOrigin.Unspecified" />, must be treated as untrusted by a driver that grants anything on the
/// caller's identity (fail closed): a call site that forgets to say where a write came from gets nothing.
/// </param>
public sealed record WriteCaller(string? Principal, string? ApiKeyId,
WriteCallerOrigin Origin = WriteCallerOrigin.Unspecified);
/// <summary>#1074 — the data plane a <see cref="WriteCaller" />'s write arrived on.</summary>
public enum WriteCallerOrigin
{
/// <summary>Not stated. A driver acting on the caller's identity treats it as no identity (fail closed).</summary>
Unspecified = 0,
/// <summary>An OPC UA client session on this server (the session's API key, or anonymous).</summary>
OpcUaSession = 1,
/// <summary>
/// A gRPC data-connection client: the key the CONNECTION authenticated with. That can be a direct client
/// (e.g. ScadaBridge) or another OtOpcUa cluster forwarding its own OPC UA clients' writes (a projected node's
/// write-through) — in which case the key is the link's service key, not the end user.
/// </summary>
DataConnection = 2,
}
/// <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
/// of <see cref="IWritable.WriteAsync" /> whenever the write carries a <see cref="WriteCaller" />. Both data planes
/// supply one: an OPC UA write from its session, a gRPC data-connection write from the connection's authenticated
/// key (#1074) — except through <c>IWriteOutcomeCapability</c>, which takes precedence on the gRPC path and carries
/// no caller. 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>
@@ -184,6 +184,17 @@ public sealed record GalaxyMxAccessOptions(
/// <c>VerifiedWrite</c> attribute is refused in every mode.
/// </summary>
public GalaxySecuredWriteMode SecuredWrites { get; init; } = GalaxySecuredWriteMode.Refuse;
/// <summary>
/// #1074 — whether <see cref="GalaxySecuredWriteMode.ApiKeyIdentity"/> also applies to writes arriving over a
/// gRPC data connection. Default <c>false</c>: such a SecuredWrite is refused <c>BadUserAccessDenied</c> locally,
/// exactly as in <see cref="GalaxySecuredWriteMode.Refuse"/>, and only OPC UA sessions get the caller's identity.
/// ⚠️ When on, the identity is the CONNECTION's key: a consumer OtOpcUa cluster forwarding its OPC UA clients'
/// writes (projected-node write-through) presents its link's service key, so every client allowed to write the
/// projected node writes secured attributes as that key's Galaxy identity. Ignored unless
/// <see cref="SecuredWrites"/> is <see cref="GalaxySecuredWriteMode.ApiKeyIdentity"/>.
/// </summary>
public bool SecuredWritesOverDataConnections { get; init; }
}
/// <summary>How the Galaxy driver handles a write to a <c>SecuredWrite</c> attribute (#1017).</summary>
@@ -2385,8 +2385,9 @@ public sealed class GalaxyDriver
/// <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
/// written as the caller's API key's own Galaxy identity (no fallback account) — for an OPC UA session, and for a
/// gRPC data connection only with <c>MxAccess.SecuredWritesOverDataConnections</c> (#1074); 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>
@@ -2424,8 +2425,10 @@ public sealed class GalaxyDriver
// #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.
// No source ⇒ the writer refuses a SecuredWrite BadUserAccessDenied locally (the #991 behaviour).
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential = null;
if (caller is not null && _options.MxAccess.SecuredWrites == GalaxySecuredWriteMode.ApiKeyIdentity)
if (caller is not null && _options.MxAccess.SecuredWrites == GalaxySecuredWriteMode.ApiKeyIdentity
&& IsSecuredWriteOriginAllowed(caller.Origin))
{
var apiKeyId = caller.ApiKeyId;
securedCredential = ct => _ackCredentialResolver.ResolveKeyIdentityAsync(apiKeyId, ct);
@@ -2435,6 +2438,18 @@ public sealed class GalaxyDriver
dialledWrites, attributeRef => ResolveSecurity(ToRawPath(attributeRef)), securedCredential, cancellationToken);
}
/// <summary>
/// #1074 — which data planes a SecuredWrite may run under the caller's identity on. An OPC UA session always
/// (the #1017 opt-in alone); a gRPC data connection only with <c>MxAccess.SecuredWritesOverDataConnections</c>
/// (its key may be a link forwarding other clients' writes); an unstated origin never (fail closed).
/// </summary>
private bool IsSecuredWriteOriginAllowed(WriteCallerOrigin origin) => origin switch
{
WriteCallerOrigin.OpcUaSession => true,
WriteCallerOrigin.DataConnection => _options.MxAccess.SecuredWritesOverDataConnections,
_ => false,
};
// ===== ISubscribable (PR 4.4) =====
/// <inheritdoc />
@@ -118,6 +118,7 @@ public static class GalaxyDriverFactoryExtensions
EventPumpChannelCapacity: dto.MxAccess.EventPumpChannelCapacity ?? 50_000)
{
SecuredWrites = ParseSecuredWrites(dto.MxAccess.SecuredWrites, driverInstanceId),
SecuredWritesOverDataConnections = dto.MxAccess.SecuredWritesOverDataConnections ?? false,
},
Repository: new GalaxyRepositoryOptions(
DiscoverPageSize: dto.Repository?.DiscoverPageSize ?? 5000,
@@ -241,6 +242,8 @@ public static class GalaxyDriverFactoryExtensions
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>#1074: whether <c>ApiKeyIdentity</c> also applies to gRPC data-connection writes (default false).</summary>
public bool? SecuredWritesOverDataConnections { get; init; }
}
/// <summary>Repository configuration section.</summary>
@@ -112,6 +112,18 @@
<code>VerifiedWrite</code> attributes are always refused.
</div>
</div>
<div class="col-md-6">
<div class="form-check form-switch mt-4">
<InputCheckbox aria-describedby="@FieldIds("field-11b-hint")" @bind-Value="_form.Galaxy.MxSecuredWritesOverDataConnections" @bind-Value:after="EmitAsync" class="form-check-input" id="@FieldId("field-11b")" disabled="@(_form.Galaxy.MxSecuredWrites != GalaxySecuredWriteMode.ApiKeyIdentity)" />
<label class="form-check-label" for="@FieldId("field-11b")">Also for gRPC data-connection writes</label>
</div>
<div id="@FieldId("field-11b-hint")" class="form-text">
Off (default): a secured write arriving over a data connection is refused, and only OPC UA sessions write
as their key's identity (#1074). On: it runs as the <em>connection's</em> key. A consumer cluster forwarding
its own clients' writes presents its link's service key, so every client allowed to write the projected
node would write secured attributes as that key's Galaxy identity.
</div>
</div>
</div>
</div>
</section>
@@ -254,6 +266,7 @@
"gateway.keepAlivePingDelaySeconds", "gateway.keepAlivePingTimeoutSeconds",
"mxAccess.clientName", "mxAccess.publishingIntervalMs", "mxAccess.writeUserId", "mxAccess.eventPumpChannelCapacity",
"mxAccess.securedWrites",
"mxAccess.securedWritesOverDataConnections",
"repository.discoverPageSize", "repository.watchDeployEvents",
"reconnect.initialBackoffMs", "reconnect.maxBackoffMs", "reconnect.replayOnSessionLost",
"probeTimeoutSeconds",
@@ -334,6 +347,7 @@
public int MxWriteUserId { get; set; } = 0;
public int MxEventPumpChannelCapacity { get; set; } = 50_000;
public GalaxySecuredWriteMode MxSecuredWrites { get; set; } = GalaxySecuredWriteMode.Refuse;
public bool MxSecuredWritesOverDataConnections { get; set; }
// GalaxyRepositoryOptions
public int RepositoryDiscoverPageSize { get; set; } = 5000;
@@ -376,6 +390,7 @@
MxWriteUserId = mx.WriteUserId,
MxEventPumpChannelCapacity = mx.EventPumpChannelCapacity,
MxSecuredWrites = mx.SecuredWrites,
MxSecuredWritesOverDataConnections = mx.SecuredWritesOverDataConnections,
RepositoryDiscoverPageSize = repo.DiscoverPageSize,
RepositoryWatchDeployEvents = repo.WatchDeployEvents,
ReconnectInitialBackoffMs = rc.InitialBackoffMs,
@@ -407,6 +422,7 @@
EventPumpChannelCapacity: MxEventPumpChannelCapacity)
{
SecuredWrites = MxSecuredWrites,
SecuredWritesOverDataConnections = MxSecuredWritesOverDataConnections,
},
Repository: new GalaxyRepositoryOptions(
DiscoverPageSize: RepositoryDiscoverPageSize,
@@ -3559,7 +3559,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
return DispatchDeviceWrite(gateway, nodeKey, nodeBareId, nodeRealm, optimisticValue, priorValue, priorStatus, clientUserId,
(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));
identity is null ? null : new WriteCaller(identity.Principal.Length > 0 ? identity.Principal : null, identity.ApiKeyId,
WriteCallerOrigin.OpcUaSession));
}
/// <summary>
@@ -1508,8 +1508,16 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
// between that commit and the invocation below; preemption after commit is post-dispatch.
try
{
// #1074: a gRPC data-connection write carries its caller like an OPC UA write does (#1017) —
// the admission's principal + API key id, bound from the authenticated transport context
// (never from the request payload) and re-checked by the dispatch gate's commit above. A
// caller-aware driver (Galaxy SecuredWrite under the key's Galaxy identity) gets it; every
// other driver is unchanged. No driver is both IWriteOutcomeCapability and
// ICallerAwareWritable today; one that were would need a caller-aware outcome overload.
if (driver is IWriteOutcomeCapability rich)
_ = ObserveRichDriver(rich.WriteWithOutcomesAsync(request, ct), physical);
else if (driver is ICallerAwareWritable callerAware)
_ = ObserveLegacyDriver(callerAware.WriteAsync(request, RichCaller(msg.Ticket.Proof.Admission), ct), physical);
else
_ = ObserveLegacyDriver(((IWritable)driver).WriteAsync(request, ct), physical);
}
@@ -1569,6 +1577,18 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
return RichUnknown;
}
/// <summary>
/// #1074 — who issued a gRPC data-connection write, in the same shape the OPC UA node manager builds for a
/// session (#1017): the admitted principal and the public id of the API key the connection authenticated with.
/// Both are mandatory on an admission (<see cref="DataWriteAdmission.Validate"/>) and carry no secret. Marked
/// <see cref="WriteCallerOrigin.DataConnection"/> so a driver can hold this plane to its own opt-in (Galaxy
/// <c>MxAccess.SecuredWritesOverDataConnections</c>, default off).
/// </summary>
internal static WriteCaller RichCaller(DataWriteAdmission admission) =>
new(string.IsNullOrWhiteSpace(admission.PrincipalId) ? null : admission.PrincipalId,
string.IsNullOrWhiteSpace(admission.ApiKeyId) ? null : admission.ApiKeyId,
WriteCallerOrigin.DataConnection);
private static async Task ObserveRichDriver(Task<IReadOnlyList<DataWriteOutcome>> task,
TaskCompletionSource<DataWriteOutcome> physical)
{
@@ -82,6 +82,24 @@ public sealed class GalaxyDriverFactoryTests
ack.FallbackPasswordSecretRef.ShouldBe("secret:otopcua/galaxy/ack");
}
/// <summary>#1074: <c>MxAccess.SecuredWritesOverDataConnections</c> binds; absent means off.</summary>
[Fact]
public void CreateInstance_BindsSecuredWritesOverDataConnections_defaulting_off()
{
GalaxyDriverFactoryExtensions.CreateInstance("g", MinimalConfig).Options.MxAccess.SecuredWritesOverDataConnections
.ShouldBeFalse();
const string json = """
{
"Gateway": { "Endpoint": "https://mxgw.test:5001", "ApiKeySecretRef": "galaxy:apiKey" },
"mxAccess": { "clientName": "OtOpcUa-A", "securedWrites": "ApiKeyIdentity", "securedWritesOverDataConnections": true }
}
""";
var mx = GalaxyDriverFactoryExtensions.CreateInstance("g", json).Options.MxAccess;
mx.SecuredWrites.ShouldBe(GalaxySecuredWriteMode.ApiKeyIdentity);
mx.SecuredWritesOverDataConnections.ShouldBeTrue();
}
/// <summary>Verifies that defaults are overridden from full config.</summary>
[Fact]
public void CreateInstance_OverridesDefaults_FromFullConfig()
@@ -13,9 +13,9 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime;
/// </summary>
public sealed class GalaxyDriverSecuredWriteIdentityTests
{
private static GalaxyDriverOptions Opts(GalaxySecuredWriteMode mode) => new(
private static GalaxyDriverOptions Opts(GalaxySecuredWriteMode mode, bool overDataConnections = false) => new(
new GalaxyGatewayOptions("https://mxgw.test:5001", "key"),
new GalaxyMxAccessOptions("OtOpcUa-A") { SecuredWrites = mode },
new GalaxyMxAccessOptions("OtOpcUa-A") { SecuredWrites = mode, SecuredWritesOverDataConnections = overDataConnections },
new GalaxyRepositoryOptions(WatchDeployEvents: false),
new GalaxyReconnectOptions())
{
@@ -46,11 +46,12 @@ public sealed class GalaxyDriverSecuredWriteIdentityTests
}
private static (GalaxyDriver Driver, IdentityRecordingWriter Writer, FixedAckCredentialResolver Resolver) Build(
GalaxySecuredWriteMode mode)
GalaxySecuredWriteMode mode, bool overDataConnections = false)
{
var writer = new IdentityRecordingWriter();
var resolver = FixedAckCredentialResolver.Fallback();
var driver = new GalaxyDriver("g", Opts(mode), hierarchySource: null, dataWriter: writer, ackCredentialResolver: resolver);
var driver = new GalaxyDriver("g", Opts(mode, overDataConnections), hierarchySource: null, dataWriter: writer,
ackCredentialResolver: resolver);
return (driver, writer, resolver);
}
@@ -60,7 +61,7 @@ public sealed class GalaxyDriverSecuredWriteIdentityTests
var (driver, writer, resolver) = Build(GalaxySecuredWriteMode.ApiKeyIdentity);
await ((ICallerAwareWritable)driver).WriteAsync(
[new WriteRequest("Plant/Tank1/SP", 1.0)], new WriteCaller("svc-mes", "0a1b2c3d4e5f6071"),
[new WriteRequest("Plant/Tank1/SP", 1.0)], new WriteCaller("svc-mes", "0a1b2c3d4e5f6071", WriteCallerOrigin.OpcUaSession),
TestContext.Current.CancellationToken);
var source = writer.Sources.ShouldHaveSingleItem().ShouldNotBeNull();
@@ -75,7 +76,7 @@ public sealed class GalaxyDriverSecuredWriteIdentityTests
{
var (driver, writer, resolver) = Build(GalaxySecuredWriteMode.ApiKeyIdentity);
await driver.WriteAsync([new WriteRequest("Plant/Tank1/SP", 1.0)], new WriteCaller("anonymous", null),
await driver.WriteAsync([new WriteRequest("Plant/Tank1/SP", 1.0)], new WriteCaller("anonymous", null, WriteCallerOrigin.OpcUaSession),
TestContext.Current.CancellationToken);
var resolution = await writer.Sources.ShouldHaveSingleItem().ShouldNotBeNull()(TestContext.Current.CancellationToken);
@@ -83,12 +84,72 @@ public sealed class GalaxyDriverSecuredWriteIdentityTests
resolver.SecuredWriteKeyIds.ShouldBe([null]);
}
/// <summary>
/// #1074: a data-connection caller gets NO identity source unless
/// <c>MxAccess.SecuredWritesOverDataConnections</c> is on — the writer then refuses the SecuredWrite locally,
/// exactly as before #1074 — while an OPC UA session with the same key on the same driver still does.
/// </summary>
[Fact]
public async Task ApiKeyIdentity_mode_refuses_a_data_connection_caller_unless_opted_in()
{
var (driver, writer, resolver) = Build(GalaxySecuredWriteMode.ApiKeyIdentity);
await driver.WriteAsync([new WriteRequest("Plant/Tank1/SP", 1.0)],
new WriteCaller("svc-mes", "0a1b2c3d4e5f6071", WriteCallerOrigin.DataConnection),
TestContext.Current.CancellationToken);
await driver.WriteAsync([new WriteRequest("Plant/Tank1/SP", 1.0)],
new WriteCaller("svc-mes", "0a1b2c3d4e5f6071", WriteCallerOrigin.OpcUaSession),
TestContext.Current.CancellationToken);
writer.Sources.Count.ShouldBe(2);
writer.Sources[0].ShouldBeNull("a data-connection write is refused while the opt-in is off");
writer.Sources[1].ShouldNotBeNull("positive control: the OPC UA plane is unaffected by the data-connection opt-in");
resolver.SecuredWriteKeyIds.ShouldBeEmpty();
}
[Fact]
public async Task ApiKeyIdentity_mode_with_the_data_connection_opt_in_resolves_the_connection_keys_identity()
{
var (driver, writer, resolver) = Build(GalaxySecuredWriteMode.ApiKeyIdentity, overDataConnections: true);
await driver.WriteAsync([new WriteRequest("Plant/Tank1/SP", 1.0)],
new WriteCaller("svc-mes", "0a1b2c3d4e5f6071", WriteCallerOrigin.DataConnection),
TestContext.Current.CancellationToken);
var resolution = await writer.Sources.ShouldHaveSingleItem().ShouldNotBeNull()(TestContext.Current.CancellationToken);
resolution.Credential.ShouldNotBeNull();
resolver.SecuredWriteKeyIds.ShouldBe(["0a1b2c3d4e5f6071"]);
}
[Fact]
public async Task The_data_connection_opt_in_does_nothing_in_Refuse_mode()
{
var (driver, writer, _) = Build(GalaxySecuredWriteMode.Refuse, overDataConnections: true);
await driver.WriteAsync([new WriteRequest("Plant/Tank1/SP", 1.0)],
new WriteCaller("svc", "0a1b2c3d4e5f6071", WriteCallerOrigin.DataConnection), TestContext.Current.CancellationToken);
writer.Sources.ShouldHaveSingleItem().ShouldBeNull();
}
/// <summary>#1074 fail-closed default: a caller whose origin was never stated gets no identity, opt-ins or not.</summary>
[Fact]
public async Task A_caller_with_an_unspecified_origin_passes_no_identity_source()
{
var (driver, writer, _) = Build(GalaxySecuredWriteMode.ApiKeyIdentity, overDataConnections: true);
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 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"),
await driver.WriteAsync([new WriteRequest("Plant/Tank1/SP", 1.0)], new WriteCaller("svc", "0a1b2c3d4e5f6071", WriteCallerOrigin.OpcUaSession),
TestContext.Current.CancellationToken);
writer.Sources.ShouldHaveSingleItem().ShouldBeNull();
@@ -373,6 +373,30 @@ public sealed class GalaxyDriverPageFormSerializationTests
.MxAccess.SecuredWrites.ShouldBe(GalaxySecuredWriteMode.ApiKeyIdentity);
}
/// <summary>
/// #1074: <c>MxAccess.SecuredWritesOverDataConnections</c> defaults off and round-trips through the form under
/// the camelCase key the driver factory reads.
/// </summary>
[Fact]
public void FormModel_RoundTrips_SecuredWritesOverDataConnections()
{
new GalaxyDriverForm.GalaxyFormModel().MxSecuredWritesOverDataConnections.ShouldBeFalse();
var original = new GalaxyDriverOptions(
new GalaxyGatewayOptions("https://gw:5001", "env:K"),
new GalaxyMxAccessOptions("OtOpcUa")
{ SecuredWrites = GalaxySecuredWriteMode.ApiKeyIdentity, SecuredWritesOverDataConnections = true },
new GalaxyRepositoryOptions(),
new GalaxyReconnectOptions());
var form = GalaxyDriverForm.GalaxyFormModel.FromRecord(original);
form.MxSecuredWritesOverDataConnections.ShouldBeTrue();
var json = GalaxyDriverForm.Serialize(form.ToRecord(), originalJson: null);
json.ShouldContain("\"securedWritesOverDataConnections\":true");
JsonSerializer.Deserialize<GalaxyDriverOptions>(json, new JsonSerializerOptions(_pageOpts) { Converters = { new JsonStringEnumConverter() } })!
.MxAccess.SecuredWritesOverDataConnections.ShouldBeTrue();
}
/// <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).
@@ -256,8 +256,8 @@ public sealed class NodeManagerKeyUsabilityGateTests : IDisposable
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));
gateway.Callers[0].ShouldBe(new WriteCaller(Principal, KeyId, WriteCallerOrigin.OpcUaSession));
gateway.Callers[1].ShouldBe(new WriteCaller(OpcUaPrincipals.Anonymous, null, WriteCallerOrigin.OpcUaSession));
}
finally { await host.DisposeAsync(); }
}
@@ -313,6 +313,124 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase
driver.Calls.ShouldBe(1);
}
/// <summary>
/// #1074: a gRPC data-connection write reaches a caller-aware driver through
/// <see cref="ICallerAwareWritable"/> carrying the ADMITTED principal + API key id (bound from the authenticated
/// transport context), exactly as an OPC UA write carries its session's (#1017). Before the fix the rich path
/// always called the caller-less <see cref="IWritable.WriteAsync"/>, so a Galaxy SecuredWrite was refused.
/// </summary>
[Fact]
public async Task Rich_write_hands_a_caller_aware_driver_the_admitted_principal_and_key()
{
var driver = new CallerRecordingDriver();
var actor = Connect(driver, new RecordingGate(), new LateWriteObserver(1, TimeSpan.FromMinutes(1)));
var (ticket, claim) = NewWrite("caller", 1);
var result = await actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim),
Timeout, TestContext.Current.CancellationToken);
result.State.ShouldBe(DataWriteState.AcceptedUnconfirmed);
driver.Callers.ShouldBe([new WriteCaller("peer", "key", WriteCallerOrigin.DataConnection)]);
driver.Calls.ShouldBe(0, "the caller-less overload must not be used when the driver can act on the caller");
}
/// <summary>
/// #1074 — both data planes hand the driver the same caller shape: an OPC UA write's
/// <see cref="DriverInstanceActor.WriteAttribute"/> (caller from the session, #1017) and a gRPC data-connection
/// write's admission (caller from the authenticated connection) for the same key reach
/// <see cref="ICallerAwareWritable"/> with the same principal + key, each marked with the plane it came in on —
/// the origin is set by the runtime from where the write was received, not by the request.
/// </summary>
[Fact]
public async Task OpcUa_and_grpc_data_writes_reach_the_driver_with_the_same_key_and_their_own_origin()
{
var driver = new CallerRecordingDriver();
var actor = Connect(driver, new RecordingGate(), new LateWriteObserver(1, TimeSpan.FromMinutes(1)));
var opcUa = await actor.Ask<DriverInstanceActor.WriteAttributeResult>(
new DriverInstanceActor.WriteAttribute("plant/tag", 1,
Caller: new WriteCaller("peer", "key", WriteCallerOrigin.OpcUaSession)),
Timeout, TestContext.Current.CancellationToken);
opcUa.Success.ShouldBeTrue(opcUa.Reason);
var (ticket, claim) = NewWrite("parity", 2);
var grpc = await actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim),
Timeout, TestContext.Current.CancellationToken);
grpc.State.ShouldBe(DataWriteState.AcceptedUnconfirmed);
driver.Callers.Count.ShouldBe(2);
driver.Callers[0].Origin.ShouldBe(WriteCallerOrigin.OpcUaSession);
driver.Callers[1].ShouldBe(driver.Callers[0] with { Origin = WriteCallerOrigin.DataConnection });
driver.Calls.ShouldBe(0);
}
/// <summary>
/// #1074 end to end into the real Galaxy driver, opted in: with <c>MxAccess.SecuredWrites = ApiKeyIdentity</c>
/// and <c>SecuredWritesOverDataConnections = true</c>, a gRPC data-connection write resolves the CONNECTION's
/// API key's own Galaxy identity (never a fallback account) and hands the writer that identity source.
/// </summary>
[Fact]
public async Task Rich_write_to_an_opted_in_Galaxy_driver_runs_a_secured_write_as_the_connection_keys_identity()
{
var writer = new GalaxyIdentityRecordingWriter();
var resolver = new KeyIdentityResolver();
var galaxy = new ZB.MOM.WW.OtOpcUa.Driver.Galaxy.GalaxyDriver("driver", GalaxyOptions(overDataConnections: true),
hierarchySource: null, dataWriter: writer, ackCredentialResolver: resolver);
var actor = Connect(new GalaxyWriteHost(galaxy), new RecordingGate(), new LateWriteObserver(1, TimeSpan.FromMinutes(1)));
var (ticket, claim) = NewWrite("galaxy", 5, driverReference: "Plant/Tank1/SP");
var result = await actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim),
Timeout, TestContext.Current.CancellationToken);
result.State.ShouldBe(DataWriteState.AcceptedUnconfirmed);
writer.ResolvedUsers.ShouldBe(["mes-writer"], "the secured write ran as the key's own Galaxy identity");
resolver.SecuredWriteKeyIds.ShouldBe(["key"]);
}
/// <summary>
/// #1074 default: the same write to a Galaxy driver in <c>ApiKeyIdentity</c> mode WITHOUT
/// <c>SecuredWritesOverDataConnections</c> is refused exactly as before #1074 — no identity is resolved, the
/// writer refuses the SecuredWrite <c>BadUserAccessDenied</c> locally, and the gRPC caller sees the same outcome as
/// before (the legacy path's <c>OutcomeUnknown</c>). The OPC UA plane on the same driver still writes (control).
/// </summary>
[Fact]
public async Task Rich_write_to_a_Galaxy_driver_without_the_data_connection_opt_in_is_refused_as_before()
{
var writer = new GalaxyIdentityRecordingWriter();
var resolver = new KeyIdentityResolver();
var galaxy = new ZB.MOM.WW.OtOpcUa.Driver.Galaxy.GalaxyDriver("driver", GalaxyOptions(overDataConnections: false),
hierarchySource: null, dataWriter: writer, ackCredentialResolver: resolver);
var actor = Connect(new GalaxyWriteHost(galaxy), new RecordingGate(), new LateWriteObserver(1, TimeSpan.FromMinutes(1)));
var (ticket, claim) = NewWrite("galaxy-off", 5, driverReference: "Plant/Tank1/SP");
var result = await actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim),
Timeout, TestContext.Current.CancellationToken);
result.State.ShouldBe(DataWriteState.OutcomeUnknown, "the pre-#1074 report of a refused legacy write");
writer.Refusals.ShouldBe(1);
writer.ResolvedUsers.ShouldBeEmpty();
resolver.SecuredWriteKeyIds.ShouldBeEmpty("no identity is looked up for a data-connection write while opted out");
var opcUa = await actor.Ask<DriverInstanceActor.WriteAttributeResult>(
new DriverInstanceActor.WriteAttribute("Plant/Tank1/SP", 6,
Caller: new WriteCaller("peer", "key", WriteCallerOrigin.OpcUaSession)),
Timeout, TestContext.Current.CancellationToken);
opcUa.Success.ShouldBeTrue(opcUa.Reason);
writer.ResolvedUsers.ShouldBe(["mes-writer"], "positive control: the OPC UA session still writes as its key");
}
private static ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config.GalaxyDriverOptions GalaxyOptions(bool overDataConnections) => new(
new ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config.GalaxyGatewayOptions("https://mxgw.test:5001", "key"),
new ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config.GalaxyMxAccessOptions("OtOpcUa-A")
{
SecuredWrites = ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config.GalaxySecuredWriteMode.ApiKeyIdentity,
SecuredWritesOverDataConnections = overDataConnections,
},
new ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config.GalaxyRepositoryOptions(WatchDeployEvents: false),
new ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config.GalaxyReconnectOptions())
{
RawTags = [new RawTagEntry("Plant/Tank1/SP", """{"attributeRef":"Tank1.SP"}""", false)],
};
[Fact]
public async Task Token_ignoring_driver_stays_charged_and_its_actual_late_success_refines_unknown()
{
@@ -607,6 +725,81 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase
}
}
private sealed class CallerRecordingDriver : LegacyDriver, ICallerAwareWritable
{
private readonly Lock _gate = new();
private readonly List<WriteCaller> _callers = [];
public IReadOnlyList<WriteCaller> Callers { get { lock (_gate) return [.. _callers]; } }
public Task<IReadOnlyList<WriteResult>> WriteAsync(IReadOnlyList<WriteRequest> writes, WriteCaller caller,
CancellationToken cancellationToken)
{
lock (_gate) _callers.Add(caller);
return Task.FromResult<IReadOnlyList<WriteResult>>([new(0)]);
}
}
/// <summary>Hosts a real <see cref="ZB.MOM.WW.OtOpcUa.Driver.Galaxy.GalaxyDriver"/>'s write surface without its
/// gateway lifecycle (initialize would dial mxaccessgw).</summary>
private sealed class GalaxyWriteHost(ZB.MOM.WW.OtOpcUa.Driver.Galaxy.GalaxyDriver galaxy) : IDriver, ICallerAwareWritable
{
public string DriverInstanceId => "driver";
public string DriverType => "Galaxy";
public Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken) => Task.CompletedTask;
public Task ReinitializeAsync(string driverConfigJson, CancellationToken cancellationToken) => Task.CompletedTask;
public Task ShutdownAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public DriverHealth GetHealth() => new(DriverState.Healthy, DateTime.UtcNow, null);
#pragma warning disable OTOPCUA0001 // a pass-through host: the actor under test wraps THIS call in its invoker
public Task<IReadOnlyList<WriteResult>> WriteAsync(IReadOnlyList<WriteRequest> writes, CancellationToken cancellationToken)
=> galaxy.WriteAsync(writes, cancellationToken);
public Task<IReadOnlyList<WriteResult>> WriteAsync(IReadOnlyList<WriteRequest> writes, WriteCaller caller,
CancellationToken cancellationToken) => ((ICallerAwareWritable)galaxy).WriteAsync(writes, caller, cancellationToken);
#pragma warning restore OTOPCUA0001
}
/// <summary>A Galaxy data writer that, like the real one, writes a SecuredWrite only under a resolved identity and
/// refuses (<c>BadUserAccessDenied</c>) without one; records whose identity each write ran as.</summary>
private sealed class GalaxyIdentityRecordingWriter : ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime.IGalaxyDataWriter
{
private int _refusals;
public List<string?> ResolvedUsers { get; } = [];
public int Refusals => Volatile.Read(ref _refusals);
public Task<IReadOnlyList<WriteResult>> WriteAsync(IReadOnlyList<WriteRequest> writes,
Func<string, SecurityClassification> securityResolver, CancellationToken cancellationToken)
{
Interlocked.Increment(ref _refusals);
return Task.FromResult<IReadOnlyList<WriteResult>>([.. writes.Select(_ => new WriteResult(0x801F0000u))]);
}
async Task<IReadOnlyList<WriteResult>> ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime.IGalaxyDataWriter.WriteAsync(
IReadOnlyList<WriteRequest> writes, Func<string, SecurityClassification> securityResolver,
Func<CancellationToken, Task<ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime.GalaxyAckCredentialResolution>>? securedCredential,
CancellationToken cancellationToken)
{
if (securedCredential is null) return await WriteAsync(writes, securityResolver, cancellationToken);
var resolution = await securedCredential(cancellationToken);
ResolvedUsers.Add(resolution.Credential?.User);
return [.. writes.Select(_ => new WriteResult(resolution.Credential is null ? 0x801F0000u : 0u))];
}
public void InvalidateHandleCaches() { }
}
private sealed class KeyIdentityResolver : ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime.IGalaxyAckCredentialResolver
{
public List<string?> SecuredWriteKeyIds { get; } = [];
public Task<ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime.GalaxyAckCredentialResolution> ResolveAsync(string? apiKeyId,
CancellationToken cancellationToken) => throw new InvalidOperationException("a secured write never uses the ack fallback");
public Task<ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime.GalaxyAckCredentialResolution> ResolveKeyIdentityAsync(
string? apiKeyId, CancellationToken cancellationToken)
{
SecuredWriteKeyIds.Add(apiKeyId);
return Task.FromResult(apiKeyId == "key"
? ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime.GalaxyAckCredentialResolution.Resolved(
new("mes-writer", "PLANT", "pw", ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime.GalaxyAckCredentialSource.ApiKey))
: ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime.GalaxyAckCredentialResolution.Refused("no key identity"));
}
}
private sealed class SingleDriverFactory(IDriver driver) : IDriverFactory
{
public IReadOnlyCollection<string> SupportedTypes => ["Modbus"];