diff --git a/.claude/rules/drivers.md b/.claude/rules/drivers.md index 994973118..873b4955e 100644 --- a/.claude/rules/drivers.md +++ b/.claude/rules/drivers.md @@ -221,8 +221,9 @@ host logger factory (wired in `DriverFactoryBootstrap`; the FOCAS and TwinCAT fa 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`; a gRPC data-connection - write carries the connection's principal + key id from its `DataWriteAdmission` (#1074 — federated writes therefore run - as the LINK key's identity). Not live-gated. `docs/drivers/Galaxy.md` §Secured writes. + 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 diff --git a/docs/Configuration.md b/docs/Configuration.md index 4f4647e99..618fcd6c6 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -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/` (or `secret:otopcua/galaxy/`) / `env:OTOPCUA_GALAXY_` (or legacy `env:GALAXY_MXGW_`) / `dev:KEY` / literal forms (resolved at `InitializeAsync`); prefer `secret:` in production. Any other `secret:`/`env:` reference and every `file:` reference is refused at save, deploy (`CredentialReferenceOutOfScope`), Test Connect, browse and resolve — #815, see `docs/security.md` §"Credential references are namespaced per driver". Never store a cleartext key. | -| `GalaxyMxAccessOptions` (`MxAccess`) | `ClientName`; `PublishingIntervalMs` (`1000`); `WriteUserId` (`0` = anonymous; the user a raw `Write` carries); `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. | diff --git a/docs/DataConnections.md b/docs/DataConnections.md index 0720fab30..68d7860b1 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -799,13 +799,16 @@ not see these bits; see "Mixed versions" above. `otopcua/apikeys//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).** A write carries the connection's principal and API key id to -the driver, as an OPC UA session's write does (#1017). A Galaxy driver with `MxAccess.SecuredWrites = ApiKeyIdentity` -therefore writes a SecuredWrite attribute as the **connection key's** Galaxy identity (the same `galaxy-ack-*` secrets -as above; no fallback account). Without an identity it is refused. There is no export-level opt-in for this, unlike -`AllowGalaxyServiceAck`. The export's Write grant, the origin ACL and the driver's mode are the only 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). +**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`) diff --git a/docs/drivers/Galaxy.md b/docs/drivers/Galaxy.md index abcf0e09b..391a96fb2 100644 --- a/docs/drivers/Galaxy.md +++ b/docs/drivers/Galaxy.md @@ -82,7 +82,7 @@ Project root files: `DriverConfig` JSON binds to `Config/GalaxyDriverOptions.cs`. The four sections are: - **`Gateway`** — endpoint, API key secret ref (`secret:galaxy/` · `secret:otopcua/galaxy/` · `env:OTOPCUA_GALAXY_` · legacy `env:GALAXY_MXGW_` · `dev:KEY` · literal; anything else, incl. `file:`, is refused — #815 (an already-deployed driver keeps resolving a pre-#815 ref on init and every gateway reconnect in deprecated warn-only mode until its next deploy), [`docs/security.md`](../security.md) §"Credential references are namespaced per driver"), TLS knobs, connect/call/stream timeouts. `StreamTimeoutSeconds = 0` keeps the long-lived `StreamEvents` RPC open for the driver's lifetime. `KeepAlivePingDelaySeconds` (`15`) / `KeepAlivePingTimeoutSeconds` (`10`) — HTTP/2 keep-alive pings on every gateway channel (#991 G-19, below); `0` disables them. Both have AdminUI fields in the driver form's connection panel (#1045 — the form used to drop them on save, resetting a `0` opt-out to the default). The form now overlays only the keys it edits onto the stored JSON (`GalaxyDriverForm.OwnedPaths` + `DriverConfigJsonOverlay`), so a key it does not model survives a save; a new form field must add its path there. -- **`MxAccess`** — `ClientName` (must be unique per OtOpcUa instance — redundancy pairs enforce uniqueness at install time), `PublishingIntervalMs` (forwarded as `buffered_update_interval_ms` on subscribe), `WriteUserId` — the user id a raw `Write` carries; `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,20 +216,34 @@ 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 (#1074).** 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. So a SecuredWrite over gRPC runs as **the -connection key's own** `/api-keys` Galaxy identity, exactly like an OPC UA session with that key. No wire change — the -identity was already on the server side. Every admission carries a key, so "no caller" cannot reach the driver on this -path; a key with no (or a broken) identity is refused as above. Two consequences to know: -- **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), the origin sees the data connection's service key, not the consumer's end user. Mapping a - Galaxy identity to that service key (e.g. for `DataExport.AllowGalaxyServiceAck` acks) therefore also lets every - consumer-side client with write access to the projected node write SecuredWrite attributes as that identity, once the - origin driver is in `ApiKeyIdentity` mode and the export grants Write. Unlike the ack, there is no export-level opt-in - for this yet (#1074 follow-up). Do not map an identity to a service key you do not want to delegate. +**…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). @@ -260,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). diff --git a/docs/security.md b/docs/security.md index 2780b36d3..8419d0be9 100644 --- a/docs/security.md +++ b/docs/security.md @@ -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`. `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 key's own Galaxy identity over both the OPC UA and the gRPC data-connection planes (#1017, #1074; [Galaxy § Secured writes](drivers/Galaxy.md#secured-writes-under-the-callers-galaxy-identity-1017)). +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. diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/ICallerAwareWritable.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/ICallerAwareWritable.cs index 68e2ebfe5..bd2c4cefb 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/ICallerAwareWritable.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/ICallerAwareWritable.cs @@ -7,7 +7,31 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions; /// /// The ACL principal (e.g. the key's principal, or anonymous); null when unknown. /// The authenticating API key's public id; null for anonymous. -public sealed record WriteCaller(string? Principal, string? ApiKeyId); +/// +/// #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, +/// , 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. +/// +public sealed record WriteCaller(string? Principal, string? ApiKeyId, + WriteCallerOrigin Origin = WriteCallerOrigin.Unspecified); + +/// #1074 — the data plane a 's write arrived on. +public enum WriteCallerOrigin +{ + /// Not stated. A driver acting on the caller's identity treats it as no identity (fail closed). + Unspecified = 0, + + /// An OPC UA client session on this server (the session's API key, or anonymous). + OpcUaSession = 1, + + /// + /// 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. + /// + DataConnection = 2, +} /// /// Optional companion to for a driver whose device enforces a per-USER write diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Contracts/GalaxyDriverOptions.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Contracts/GalaxyDriverOptions.cs index a19fb2b7c..e742615e7 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Contracts/GalaxyDriverOptions.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Contracts/GalaxyDriverOptions.cs @@ -184,6 +184,17 @@ public sealed record GalaxyMxAccessOptions( /// VerifiedWrite attribute is refused in every mode. /// public GalaxySecuredWriteMode SecuredWrites { get; init; } = GalaxySecuredWriteMode.Refuse; + + /// + /// #1074 — whether also applies to writes arriving over a + /// gRPC data connection. Default false: such a SecuredWrite is refused BadUserAccessDenied locally, + /// exactly as in , 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 + /// is . + /// + public bool SecuredWritesOverDataConnections { get; init; } } /// How the Galaxy driver handles a write to a SecuredWrite attribute (#1017). diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs index 74de232e0..49eec7271 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs @@ -2385,8 +2385,9 @@ public sealed class GalaxyDriver /// /// #1017 — on behalf of /// . With MxAccess.SecuredWrites = ApiKeyIdentity a SecuredWrite attribute is - /// written as the caller's API key's own Galaxy identity (no fallback account); otherwise — and for every - /// VerifiedWrite attribute — it is refused BadUserAccessDenied as before. Non-secured tags are + /// 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 MxAccess.SecuredWritesOverDataConnections (#1074); otherwise — and for + /// every VerifiedWrite attribute — it is refused BadUserAccessDenied as before. Non-secured tags are /// unaffected by the caller. /// /// Pairs of full reference (RawPath) + value. @@ -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>? 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); } + /// + /// #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 MxAccess.SecuredWritesOverDataConnections + /// (its key may be a link forwarding other clients' writes); an unstated origin never (fail closed). + /// + private bool IsSecuredWriteOriginAllowed(WriteCallerOrigin origin) => origin switch + { + WriteCallerOrigin.OpcUaSession => true, + WriteCallerOrigin.DataConnection => _options.MxAccess.SecuredWritesOverDataConnections, + _ => false, + }; + // ===== ISubscribable (PR 4.4) ===== /// diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriverFactoryExtensions.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriverFactoryExtensions.cs index e2c63b8fd..2cfc30975 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriverFactoryExtensions.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriverFactoryExtensions.cs @@ -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; } /// Gets or sets the SecuredWrite handling (#1017): Refuse (default) or ApiKeyIdentity. public string? SecuredWrites { get; init; } + /// #1074: whether ApiKeyIdentity also applies to gRPC data-connection writes (default false). + public bool? SecuredWritesOverDataConnections { get; init; } } /// Repository configuration section. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/Drivers/Forms/GalaxyDriverForm.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/Drivers/Forms/GalaxyDriverForm.razor index 1cdba33a3..ae8e2ede8 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/Drivers/Forms/GalaxyDriverForm.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/Drivers/Forms/GalaxyDriverForm.razor @@ -112,6 +112,18 @@ VerifiedWrite attributes are always refused. +
+
+ + +
+
+ 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 connection's 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. +
+
@@ -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, diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index a5379608e..8d28c4600 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -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)); } /// diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs index d9fb88a5f..810abcdbf 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs @@ -1580,11 +1580,14 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers /// /// #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 () and carry no secret. + /// Both are mandatory on an admission () and carry no secret. Marked + /// so a driver can hold this plane to its own opt-in (Galaxy + /// MxAccess.SecuredWritesOverDataConnections, default off). /// internal static WriteCaller RichCaller(DataWriteAdmission admission) => new(string.IsNullOrWhiteSpace(admission.PrincipalId) ? null : admission.PrincipalId, - string.IsNullOrWhiteSpace(admission.ApiKeyId) ? null : admission.ApiKeyId); + string.IsNullOrWhiteSpace(admission.ApiKeyId) ? null : admission.ApiKeyId, + WriteCallerOrigin.DataConnection); private static async Task ObserveRichDriver(Task> task, TaskCompletionSource physical) diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/GalaxyDriverFactoryTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/GalaxyDriverFactoryTests.cs index 77208e69d..f34f54b05 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/GalaxyDriverFactoryTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/GalaxyDriverFactoryTests.cs @@ -82,6 +82,24 @@ public sealed class GalaxyDriverFactoryTests ack.FallbackPasswordSecretRef.ShouldBe("secret:otopcua/galaxy/ack"); } + /// #1074: MxAccess.SecuredWritesOverDataConnections binds; absent means off. + [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(); + } + /// Verifies that defaults are overridden from full config. [Fact] public void CreateInstance_OverridesDefaults_FromFullConfig() diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GalaxyDriverSecuredWriteIdentityTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GalaxyDriverSecuredWriteIdentityTests.cs index a82439885..31b2d2dc9 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GalaxyDriverSecuredWriteIdentityTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GalaxyDriverSecuredWriteIdentityTests.cs @@ -13,9 +13,9 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime; /// 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]); } + /// + /// #1074: a data-connection caller gets NO identity source unless + /// MxAccess.SecuredWritesOverDataConnections 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. + /// + [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(); + } + + /// #1074 fail-closed default: a caller whose origin was never stated gets no identity, opt-ins or not. + [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(); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/GalaxyDriverPageFormSerializationTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/GalaxyDriverPageFormSerializationTests.cs index e3de7744b..3451ae6ac 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/GalaxyDriverPageFormSerializationTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/GalaxyDriverPageFormSerializationTests.cs @@ -373,6 +373,30 @@ public sealed class GalaxyDriverPageFormSerializationTests .MxAccess.SecuredWrites.ShouldBe(GalaxySecuredWriteMode.ApiKeyIdentity); } + /// + /// #1074: MxAccess.SecuredWritesOverDataConnections defaults off and round-trips through the form under + /// the camelCase key the driver factory reads. + /// + [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(json, new JsonSerializerOptions(_pageOpts) { Converters = { new JsonStringEnumConverter() } })! + .MxAccess.SecuredWritesOverDataConnections.ShouldBeTrue(); + } + /// /// lmxopcua#1045 guard: every leaf the form's record serialises must be an owned path, or an edit to it is /// silently discarded by the overlay on save (rawTags is authored elsewhere and deliberately not owned). diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerKeyUsabilityGateTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerKeyUsabilityGateTests.cs index c00f8b8b0..f387b7932 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerKeyUsabilityGateTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerKeyUsabilityGateTests.cs @@ -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(); } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDriverOutcomeTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDriverOutcomeTests.cs index 4ff33d584..055bf81a9 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDriverOutcomeTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDriverOutcomeTests.cs @@ -330,7 +330,7 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase Timeout, TestContext.Current.CancellationToken); result.State.ShouldBe(DataWriteState.AcceptedUnconfirmed); - driver.Callers.ShouldBe([new WriteCaller("peer", "key")]); + 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"); } @@ -338,16 +338,18 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase /// #1074 — both data planes hand the driver the same caller shape: an OPC UA write's /// (caller from the session, #1017) and a gRPC data-connection /// write's admission (caller from the authenticated connection) for the same key reach - /// with equal s. + /// 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. /// [Fact] - public async Task OpcUa_and_grpc_data_writes_reach_the_driver_with_the_same_caller() + 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( - new DriverInstanceActor.WriteAttribute("plant/tag", 1, Caller: new WriteCaller("peer", "key")), + 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); @@ -356,21 +358,22 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase grpc.State.ShouldBe(DataWriteState.AcceptedUnconfirmed); driver.Callers.Count.ShouldBe(2); - driver.Callers[1].ShouldBe(driver.Callers[0]); + driver.Callers[0].Origin.ShouldBe(WriteCallerOrigin.OpcUaSession); + driver.Callers[1].ShouldBe(driver.Callers[0] with { Origin = WriteCallerOrigin.DataConnection }); driver.Calls.ShouldBe(0); } /// - /// #1074 end to end into the real Galaxy driver: with MxAccess.SecuredWrites = ApiKeyIdentity, 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. Before the fix the writer got no source at all (secured write refused). + /// #1074 end to end into the real Galaxy driver, opted in: with MxAccess.SecuredWrites = ApiKeyIdentity + /// and SecuredWritesOverDataConnections = true, 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. /// [Fact] - public async Task Rich_write_to_a_Galaxy_driver_runs_a_secured_write_as_the_connection_keys_identity() + 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(), + 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"); @@ -383,10 +386,45 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase resolver.SecuredWriteKeyIds.ShouldBe(["key"]); } - private static ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config.GalaxyDriverOptions GalaxyOptions() => new( + /// + /// #1074 default: the same write to a Galaxy driver in ApiKeyIdentity mode WITHOUT + /// SecuredWritesOverDataConnections is refused exactly as before #1074 — no identity is resolved, the + /// writer refuses the SecuredWrite BadUserAccessDenied locally, and the gRPC caller sees the same outcome as + /// before (the legacy path's OutcomeUnknown). The OPC UA plane on the same driver still writes (control). + /// + [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(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( + 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 }, + { + 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()) { @@ -722,10 +760,15 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase /// refuses (BadUserAccessDenied) without one; records whose identity each write ran as. private sealed class GalaxyIdentityRecordingWriter : ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime.IGalaxyDataWriter { + private int _refusals; public List ResolvedUsers { get; } = []; + public int Refusals => Volatile.Read(ref _refusals); public Task> WriteAsync(IReadOnlyList writes, Func securityResolver, CancellationToken cancellationToken) - => Task.FromResult>([.. writes.Select(_ => new WriteResult(0x801F0000u))]); + { + Interlocked.Increment(ref _refusals); + return Task.FromResult>([.. writes.Select(_ => new WriteResult(0x801F0000u))]); + } async Task> ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime.IGalaxyDataWriter.WriteAsync( IReadOnlyList writes, Func securityResolver,