Merge Galaxy/AdminUI/Client follow-ups: opt-in SecuredWrite under the caller's API-key Galaxy identity, VerifiedWrite still refused (#1017), Galaxy form keeps KeepAlive keys (#1045), explicit empty ack password (#1050), Client.UI batched recursive subscribe + CLI --reconnect-timeout exit 3 (#1048)
This commit is contained in:
@@ -216,6 +216,12 @@ host logger factory (wired in `DriverFactoryBootstrap`; the FOCAS and TwinCAT fa
|
||||
Secondary's claim takes the Primary's over instead of coexisting (never make it random again). The claim
|
||||
subscribes to its own STATE topic and re-asserts over an OFFLINE it did not publish (older/equal ts ⇒ republish;
|
||||
newer ⇒ fresh claim with a newer ts; ≤ 1 per 2 s).
|
||||
- **Galaxy secured writes (#1017):** `MxAccess.SecuredWrites` = `Refuse` (default, #991 local `BadUserAccessDenied`) |
|
||||
`ApiKeyIdentity` — a SecuredWrite runs as the CALLING key's own `/api-keys` Galaxy identity (no fallback account;
|
||||
anonymous/no identity ⇒ refused): own plain-advised handle → `AuthenticateUser` every write → `WriteSecured(id, 0)`;
|
||||
gateway key needs `invoke:secure`. VerifiedWrite is refused in every mode (no verifier in an OPC UA Write — by
|
||||
design). The caller rides `WriteCaller` → `RouteNodeWrite`/`WriteAttribute.Caller` → `ICallerAwareWritable`; the gRPC
|
||||
data-connection write path carries no caller yet. Not live-gated. `docs/drivers/Galaxy.md` §Secured writes.
|
||||
- **No driver-side history (#655):** `IHistoryProvider`, `DriverCapability.HistoryRead`, `HistoryReadStatusException` and
|
||||
the OpcUaClient history passthrough are deleted — nothing ever dispatched HistoryRead to a driver; it is served only by the
|
||||
server-wide `IHistorianDataSource`. `isHistorized` on an OpcUaClient tag means OtOpcUa records it, not that upstream
|
||||
|
||||
@@ -71,6 +71,10 @@ When `-F` is provided, the shared service tries the primary URL first, then each
|
||||
|
||||
If every endpoint is down when a failover starts (a restarting server, a redundant partner mid-switchover) the service stays in `Reconnecting` and cycles the endpoint list again with a capped backoff (1 s doubling to 15 s) until one connects or the user disconnects; it never gives up on its own (#1000). Both commands print `CONNECTION <old> -> <new> (<endpoint>)` lines for every transition, so a run across a restart shows the drop and the recovery. On recovery all recorded subscriptions are re-created in one batched request per sampling interval, and `subscribe` itself creates its monitored items for the whole target set (including `-r`) in one request instead of one round trip per node.
|
||||
|
||||
The commands themselves do not wait forever, though (#1048): if the connection stays out of `Connected` for
|
||||
`--reconnect-timeout` seconds (default 300) they print a `WARNING`, the summary and exit with code **3**, so a
|
||||
scripted live gate across an outage that never ends fails instead of hanging and reporting pre-outage values as final.
|
||||
|
||||
```bash
|
||||
otopcua-cli connect -u opc.tcp://localhost:4840/OtOpcUa -F opc.tcp://localhost:4841/OtOpcUa
|
||||
```
|
||||
@@ -193,6 +197,7 @@ otopcua-cli subscribe -u opc.tcp://localhost:4840 -n "ns=3;s=ZB" -r --max-depth
|
||||
| `-q` / `--quiet` | Suppress per-update output; only print the final summary |
|
||||
| `--duration` | Auto-exit after N seconds and print the summary (0 = run until Ctrl+C, default: 0) |
|
||||
| `--summary-file` | Also write the summary to this file path on exit |
|
||||
| `--reconnect-timeout` | Seconds a lost connection may stay unrecovered before the command prints `WARNING: … did not recover …`, its summary (with a `Connection: LOST` line — the last values predate the loss) and exits with code **3** (default: 300; `0` = wait indefinitely). The service giving up (`Disconnected`) always ends the run with code 3 (#1048). |
|
||||
|
||||
#### Summary buckets
|
||||
|
||||
@@ -384,6 +389,7 @@ otopcua-cli alarms -u opc.tcp://localhost:4840/OtOpcUa \
|
||||
| `-n` / `--node` | Node ID to monitor for events (default: Server node) |
|
||||
| `-i` / `--interval` | Publishing interval in milliseconds (default: 1000) |
|
||||
| `--refresh` | Request a `ConditionRefresh` after subscribing to get current retained alarm states |
|
||||
| `--reconnect-timeout` | Same as `subscribe`: exit with code 3 and a `WARNING` line when a lost connection has not recovered after N seconds (default: 300; `0` = wait indefinitely), or at once if the service gives up (#1048) |
|
||||
|
||||
The active/acknowledged columns come from the standard `ActiveState/Id`, `AckedState/Id` and
|
||||
`EnabledState/Id` event fields. Before the 2026-10 fix the client's filter selected them with a single
|
||||
|
||||
+1
-1
@@ -85,7 +85,7 @@ Right-click on tree nodes to access:
|
||||
|
||||
| Action | Description |
|
||||
|--------|-------------|
|
||||
| **Subscribe** | Subscribe to data changes on the selected node(s). For Object nodes, recursively subscribes all Variable descendants (up to 10 levels deep). Switches to the Subscriptions tab. |
|
||||
| **Subscribe** | Subscribe to data changes on the selected node(s). For Object nodes, recursively subscribes all Variable descendants (up to 10 levels deep) — the subtree is browsed first and every monitored item is then created in one batched request (#1048), with per-node failures named in the status bar. Restoring saved subscriptions at connect is batched the same way. Switches to the Subscriptions tab. |
|
||||
| **View History** | Set the selected Variable node as the target in the History tab and switch to it. Only enabled for Variable nodes. |
|
||||
| **Monitor Alarms** | Stop any active alarm subscription and subscribe to alarm events on the selected node. Switches to the Alarms tab with automatic condition refresh. |
|
||||
|
||||
|
||||
@@ -459,7 +459,7 @@ The Galaxy/MxAccess connection settings are **not an `appsettings` section.** Th
|
||||
| Record | Key fields (default) | Meaning |
|
||||
|---|---|---|
|
||||
| `GalaxyGatewayOptions` (`Gateway`) | `Endpoint`; `ApiKeySecretRef`; `UseTls` (`true`); `CaCertificatePath` (`null`); `ConnectTimeoutSeconds` (`10`); `DefaultCallTimeoutSeconds` (`30`); `StreamTimeoutSeconds` (`0` = unlimited); `KeepAlivePingDelaySeconds` (`15`, `0` = no pings); `KeepAlivePingTimeoutSeconds` (`10`) — HTTP/2 keep-alive on the driver's gateway channels, so a silently dead connection faults the event stream (#991 G-19) | mxaccessgw gateway connection. `ApiKeySecretRef` supports `secret:galaxy/<name>` (or `secret:otopcua/galaxy/<name>`) / `env:OTOPCUA_GALAXY_<NAME>` (or legacy `env:GALAXY_MXGW_<NAME>`) / `dev:KEY` / literal forms (resolved at `InitializeAsync`); prefer `secret:` in production. Any other `secret:`/`env:` reference and every `file:` reference is refused at save, deploy (`CredentialReferenceOutOfScope`), Test Connect, browse and resolve — #815, see `docs/security.md` §"Credential references are namespaced per driver". Never store a cleartext key. |
|
||||
| `GalaxyMxAccessOptions` (`MxAccess`) | `ClientName`; `PublishingIntervalMs` (`1000`); `WriteUserId` (`0` = anonymous; the user a raw `Write` carries; SecuredWrite/VerifiedWrite attributes are refused `BadUserAccessDenied`); `EventPumpChannelCapacity` (`50000`) | MXAccess client identity + tuning. `ClientName` **must be unique per OtOpcUa instance** (redundancy pairs enforce this). |
|
||||
| `GalaxyMxAccessOptions` (`MxAccess`) | `ClientName`; `PublishingIntervalMs` (`1000`); `WriteUserId` (`0` = anonymous; the user a raw `Write` carries); `SecuredWrites` (`Refuse` = SecuredWrite attributes refused `BadUserAccessDenied`; `ApiKeyIdentity` = written as the calling API key's Galaxy identity via `AuthenticateUser` + `WriteSecured`, gateway key needs `invoke:secure` — #1017; VerifiedWrite always refused); `EventPumpChannelCapacity` (`50000`) | MXAccess client identity + tuning. `ClientName` **must be unique per OtOpcUa instance** (redundancy pairs enforce this). |
|
||||
| `GalaxyRepositoryOptions` (`Repository`) | `DiscoverPageSize` (`5000`); `WatchDeployEvents` (`true`) | Galaxy Repository browse paging + deploy-event watching. |
|
||||
| `GalaxyReconnectOptions` (`Reconnect`) | `InitialBackoffMs` (`500`); `MaxBackoffMs` (`30000`); `ReplayOnSessionLost` (`true`) | In-driver reconnect-supervisor backoff. |
|
||||
| (top-level) | `ProbeTimeoutSeconds` (`30`, range 1–60) | AdminUI Test-Connect probe timeout. |
|
||||
|
||||
+68
-9
@@ -81,8 +81,8 @@ 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.
|
||||
- **`MxAccess`** — `ClientName` (must be unique per OtOpcUa instance — redundancy pairs enforce uniqueness at install time), `PublishingIntervalMs` (forwarded as `buffered_update_interval_ms` on subscribe), `WriteUserId` — the user id a raw `Write` carries (secured/verified writes are refused, see below), `EventPumpChannelCapacity` (default 50_000 — one second of headroom at 50k tags / 1Hz; tune via the `galaxy.events.dropped` metric).
|
||||
- **`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).
|
||||
- **`Repository`** — `DiscoverPageSize`, `WatchDeployEvents`.
|
||||
- **`Reconnect`** — `InitialBackoffMs`, `MaxBackoffMs`, `ReplayOnSessionLost` (default `true`: after a gateway session is recreated, re-issue `SubscribeBulk` for every tracked subscription; `false` leaves them stranded — Bad + Degraded, see [Reconnect + Replay](#reconnect--replay)).
|
||||
- **`AlarmAck`** (optional, lmxopcua#749) — `FallbackUser`, `FallbackDomain`, `FallbackPasswordSecretRef`. See [Alarm acknowledge credential](#alarm-acknowledge-credential). `ConfirmTimeoutMs` (default `10000`, max `120000`, `0` = do not wait, negative = default; #869) — see [Ack confirmation](#ack-confirmation-869).
|
||||
@@ -187,6 +187,64 @@ the fallback secret must exist on the node that serves the OPC UA session and ho
|
||||
driver; on a split admin/driver topology create them on the driver nodes too (`/admin/secrets` or
|
||||
the `secret` CLI) under exactly those names.
|
||||
|
||||
### Secured writes under the caller's Galaxy identity (#1017)
|
||||
|
||||
ArchestrA classifies some attributes **SecuredWrite** (the writer must authenticate) or **VerifiedWrite** (a second,
|
||||
verifying user must authenticate too). MXAccess writes them with `AuthenticateUser(user, password)` → user id →
|
||||
`WriteSecured(current user, verifier user)`. mxaccessgw exposes both commands unchanged (scope **`invoke:secure`**),
|
||||
and its 2026-11-13 capture shows the sequence committing: an item **plain**-advised by the writing registration,
|
||||
`AuthenticateUser`, then `WriteSecured(userId, 0)` (`docs/LiveCaptures-2026-11-13.md` §4 in mxaccessgw — on
|
||||
`MxSecurityOperate` UDAs; 36 more secured writes in §5). No gateway change is needed for SecuredWrite.
|
||||
|
||||
**Opt-in, per driver: `MxAccess.SecuredWrites`** — `Refuse` (default; the #991 local `BadUserAccessDenied`) or
|
||||
`ApiKeyIdentity` (AdminUI driver form, MXAccess panel, "Secured writes"). The factory refuses any other value.
|
||||
|
||||
**Whose identity.** The OPC UA data plane is machine-to-machine: a session is an API key or anonymous, and carries
|
||||
no Galaxy password. A SecuredWrite therefore runs as **the calling key's own Galaxy identity** — the account mapped
|
||||
to the key on AdminUI `/api-keys` (the same `otopcua/apikeys/<keyId>/galaxy-ack-{user,password}` secrets an
|
||||
alarm acknowledge from that key uses; `IGalaxyAckCredentialResolver.ResolveKeyIdentityAsync`). Unlike the ack there
|
||||
is **no fallback account**: an anonymous session, a key with no identity, or a key whose identity is broken (user
|
||||
without a password secret, unreadable store) is refused `BadUserAccessDenied` and nothing reaches the gateway — a
|
||||
secured write is never attributed to a shared account. OtOpcUa's own `WriteOperate` gate / ACL runs first, as for
|
||||
every write; the Galaxy then enforces the account's own permission on the attribute (MXAccess 1016
|
||||
`UserNotHavingAccessRights` ⇒ `BadUserAccessDenied`).
|
||||
|
||||
**How the write reaches the driver.** `OtOpcUaNodeManager.OnEquipmentTagWrite` builds a `WriteCaller(principal,
|
||||
apiKeyId)` from the session identity → `IOpcUaNodeWriteGateway.WriteAsync(…, caller, …)` → `RouteNodeWrite.Caller` →
|
||||
`DriverInstanceActor.WriteAttribute.Caller` → `ICallerAwareWritable.WriteAsync(writes, caller, ct)` (a new optional
|
||||
`Core.Abstractions` capability; every other driver keeps `IWritable`). `GalaxyDriver` hands its writer a lazily
|
||||
resolved identity source only in `ApiKeyIdentity` mode with a caller present; the writer resolves it at most once
|
||||
per batch and only when a SecuredWrite tag is in the batch.
|
||||
|
||||
**The wire sequence** (`GatewayGalaxyDataWriter.WriteSecuredOneAsync`): the writer's own item handle for the secured
|
||||
path (separate from the raw path's supervisory-advised handle — MXAccess allows one advise mode per handle), plain
|
||||
`Advise` once per handle per session (a failed advise fails the write closed, `BadCommunicationError`, like the raw
|
||||
path) → `AuthenticateUser(DOMAIN\user, password)` on **every** write (no cached user id: MXAccess's user-id lifetime
|
||||
is unverified, and a rotated or revoked identity must take effect on the next write) → `WriteSecured(current = that
|
||||
id, verifier = 0)`, its correlated `OnWriteComplete` translated exactly like a raw write. A non-OK `AuthenticateUser`
|
||||
or user id 0 ⇒ `BadUserAccessDenied` with no `WriteSecured`. The password goes only into the `AuthenticateUser`
|
||||
command: every log line names the user, never the password, and gateway text is scrubbed of it. A gRPC
|
||||
`PermissionDenied` (the driver's gateway key lacks `invoke:secure`) ⇒ `BadUserAccessDenied` with a Warning naming the
|
||||
scope.
|
||||
|
||||
**VerifiedWrite stays refused, in every mode — by design, not a gap.** It needs a second, *verifying* user; MXAccess
|
||||
refuses one with no verifier (1008) and one whose verifier is the writer (8018), both live-captured. An OPC UA Write
|
||||
carries one caller and no verifier, and storing a verifier credential per key would let one client satisfy the
|
||||
two-person rule alone. Supporting it would need a verifier carried in the request (e.g. a Method with both
|
||||
identities) — a product decision, not plumbing.
|
||||
|
||||
**Not covered (yet):** writes over the gRPC data connection (`DataConnectionGrpcService` → `RouteRichWrite`) carry no
|
||||
caller, so a SecuredWrite there is refused as before even in `ApiKeyIdentity` mode. Not live-gated.
|
||||
|
||||
**Live-gate checklist (mxaccessgw + a Galaxy with a SecuredWrite UDA):** the driver's gateway key holds
|
||||
`invoke:secure`; map a Galaxy account to an API key on `/api-keys`; set `SecuredWrites = ApiKeyIdentity`; write the
|
||||
attribute through that key ⇒ value commits, Good, and the Galaxy/Historian attributes the write to the mapped user;
|
||||
the same write anonymously / through a key with no identity ⇒ `BadUserAccessDenied`, nothing in the gateway log; a
|
||||
wrong password ⇒ `BadUserAccessDenied` naming the user, password absent from every log; an account without the
|
||||
attribute's permission ⇒ `BadUserAccessDenied` (1016); a VerifiedWrite attribute ⇒ `BadUserAccessDenied` with no
|
||||
gateway traffic; a raw (FreeAccess) write on the same attribute's object still commits (the two handles coexist);
|
||||
a gateway reconnect re-adds + re-advises the secured handle.
|
||||
|
||||
Full per-field descriptions live in `Config/GalaxyDriverOptions.cs`. The full JSON skeleton is reproduced in [docs/v2/driver-specs.md §1](../v2/driver-specs.md).
|
||||
|
||||
## Reconnect + Replay
|
||||
@@ -238,13 +296,14 @@ Every (re)open of `StreamAlarms` replays the gateway's active-alarm snapshot. `G
|
||||
- **A dropped change is re-read (#991 G-4).** MXAccess sends a value only when it changes, so a data change the full channel drops (newest-dropped) used to leave its tag at the previous value, Good, until the attribute next changed. The pump records the item handles of dropped data changes and, once its channel has drained (so the resync is not lost to the same congestion), the driver re-advises exactly those tags — an advise is answered with the current value — rebinds them, and releases the superseded handles. One coalescing background worker; serialised with the replay-gap re-snapshot. The `galaxy.events.dropped` counter is unchanged; each burst logs one Warning ("re-reading them") and one Information line with the re-advised count. **Rate-limited (#991 review):** passes are at least 5 s apart and drops reported meanwhile coalesce into the next pass — repeated overflow bursts used to start a pass as soon as the previous one ended, re-advising (and pushing initial values into) the very channel that was overflowing. **A pass whose gateway session is gone no longer dials:** a reconnect completing between two subscriptions of a re-advise pass (resync, replay-gap re-snapshot, reconnect replay) used to send the next SubscribeBulk to the NEW session under the OLD session number; the rebind refused it and those live advises were never bound or released (then duplicated by the new session's replay). They cannot simply be released afterwards — once the session has moved, which session issued a reply's handles is ambiguous and old numbers are reused (#861) — so the pass stops before dialling.
|
||||
- **OPC DA limit bits do not warn (#991 G-2).** `StatusCodeMap.FromQualityByte` masks the two limit bits (`QQSSSSLL`) before its table lookup, so `Good | LowLimited` (0xC1) and friends map like the unlimited quality. A byte still unlisted after the mask logs one Warning per distinct value per process — it used to log one per event on the pump's dispatch thread, enough to back the channel up into drops.
|
||||
- **The deploy watcher paces every stream end (#991 G-3).** A `WatchDeployEvents` stream the gateway completes cleanly is re-subscribed after the same capped exponential backoff as a faulted one (1 s doubling to 30 s), and the backoff resets only after a stream stayed open 60 s — an event alone (the bootstrap every stream delivers) no longer resets it. It used to re-open immediately, hammering a gateway that ends its streams after the bootstrap.
|
||||
- **Secured / verified writes are REFUSED `BadUserAccessDenied`, locally (#991 G-1 + review).** The driver has no
|
||||
ArchestrA user identity: no `AuthenticateUser` flow, no supervisory advise for a secured item, and a gateway key would
|
||||
additionally need `invoke:secure`. G-1 briefly routed SecuredWrite / VerifiedWrite attributes to `WriteSecured`, which
|
||||
therefore could never succeed, and the gateway's refusal surfaced as `BadCommunicationError` (a comms fault). Until a
|
||||
real per-caller identity flow exists (follow-up — like the #749 ack credential) a write to such an attribute returns
|
||||
`BadUserAccessDenied` before anything reaches the wire (no AddItem / advise / Write; one Warning per attribute; no
|
||||
health impact). The per-tag classification map that makes the refusal local is still **seeded for the authored tags**
|
||||
- **Secured / verified writes are REFUSED `BadUserAccessDenied` by default, locally (#991 G-1 + review); a SecuredWrite
|
||||
can opt in to the caller's identity (#1017, [below](#secured-writes-under-the-callers-galaxy-identity-1017)).** By
|
||||
default the driver has no ArchestrA user identity to write under. G-1 briefly routed SecuredWrite / VerifiedWrite
|
||||
attributes to `WriteSecured` with no `AuthenticateUser`, which therefore could never succeed, and the gateway's refusal
|
||||
surfaced as `BadCommunicationError` (a comms fault). With `MxAccess.SecuredWrites = Refuse` (the default) a write to
|
||||
such an attribute returns `BadUserAccessDenied` before anything reaches the wire (no AddItem / advise / Write; one
|
||||
Warning per attribute; no health impact); a VerifiedWrite is refused in every mode. The per-tag classification map that
|
||||
makes the refusal local (and routes an opted-in SecuredWrite) is still **seeded for the authored tags**
|
||||
at `InitializeAsync` and on every deploy-watcher rediscovery, in the background, by one rooted depth-0
|
||||
`DiscoverHierarchy` per authored object (`Browse/GatewayGalaxyAttributeSecuritySource`, 4 concurrent; cost tracks the
|
||||
authored objects, not the Galaxy) — only `DiscoverAsync` filled it before, and the runtime never calls that on a served
|
||||
|
||||
+4
-1
@@ -591,7 +591,10 @@ without one and anonymous sessions use the Galaxy driver's `AlarmAck` fallback a
|
||||
neither the ack is refused before it reaches the gateway. Deleting a key on `/apikeys` removes its
|
||||
identity (if the Secrets store is down at that moment the list still refreshes and the error names the two
|
||||
leftover secrets to remove by hand). Re-saving an existing identity with the password box **blank keeps the
|
||||
stored password** (the editor never renders it back); a first-time save needs a password (#997 A-4/A-9). See [docs/drivers/Galaxy.md § Alarm acknowledge credential](drivers/Galaxy.md#alarm-acknowledge-credential).
|
||||
stored password** (the editor never renders it back); a first-time save needs a password (#997 A-4/A-9). A Galaxy
|
||||
account whose password is genuinely empty is stored with the editor's explicit **Empty password** checkbox
|
||||
(`IApiKeyGalaxyAckIdentityService.SetWithEmptyPasswordAsync`, #1050) — it writes an empty password secret
|
||||
(the driver sends an empty `operator_password`; an *absent* password secret is still a refusal). See [docs/drivers/Galaxy.md § Alarm acknowledge credential](drivers/Galaxy.md#alarm-acknowledge-credential).
|
||||
|
||||
### Anonymous is a normal principal
|
||||
|
||||
|
||||
@@ -38,12 +38,22 @@ public class AlarmsCommand : CommandBase
|
||||
[CommandOption("refresh", Description = "Request a ConditionRefresh after subscribing")]
|
||||
public bool Refresh { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets how long, in seconds, a lost connection may stay unrecovered before the command warns and exits with
|
||||
/// <see cref="SubscribeCommand.ConnectionLostExitCode" /> (#1048). <c>0</c> waits indefinitely; the service giving
|
||||
/// up (<c>Disconnected</c>) always ends the run.
|
||||
/// </summary>
|
||||
[CommandOption("reconnect-timeout", Description = "Exit non-zero (code 3) if a lost connection has not recovered after N seconds (0 = wait indefinitely)")]
|
||||
public int ReconnectTimeoutSeconds { get; init; } = SubscribeCommand.DefaultReconnectTimeoutSeconds;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override async ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
ConfigureLogging();
|
||||
if (Interval <= 0)
|
||||
throw new CommandException($"--interval must be greater than 0 (was {Interval}).");
|
||||
if (ReconnectTimeoutSeconds < 0)
|
||||
throw new CommandException($"--reconnect-timeout must be 0 or a positive number (was {ReconnectTimeoutSeconds}).");
|
||||
|
||||
NodeId? sourceNodeId;
|
||||
try
|
||||
@@ -96,10 +106,15 @@ public class AlarmsCommand : CommandBase
|
||||
}
|
||||
|
||||
// #1000 S-4: surface connection transitions (Reconnecting / Connected after a failover) so a run across a
|
||||
// restart is distinguishable from a server that simply stopped publishing.
|
||||
void ConnectionHandler(object? sender, ConnectionStateChangedEventArgs e) =>
|
||||
// restart is distinguishable from a server that simply stopped publishing. #1048: and end the run when
|
||||
// the connection is lost for good.
|
||||
using var lossWatch = new ConnectionLossWatch(TimeSpan.FromSeconds(ReconnectTimeoutSeconds));
|
||||
void ConnectionHandler(object? sender, ConnectionStateChangedEventArgs e)
|
||||
{
|
||||
outputChannel.Writer.TryWrite(
|
||||
$"[{DateTime.UtcNow:O}] CONNECTION {e.OldState} -> {e.NewState} ({e.EndpointUrl})");
|
||||
lossWatch.Observe(e);
|
||||
}
|
||||
|
||||
service.ConnectionStateChanged += ConnectionHandler;
|
||||
|
||||
@@ -128,15 +143,10 @@ public class AlarmsCommand : CommandBase
|
||||
await console.Output.WriteLineAsync(line);
|
||||
}, CancellationToken.None);
|
||||
|
||||
// Wait until cancellation
|
||||
try
|
||||
{
|
||||
await Task.Delay(Timeout.Infinite, ct);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// Expected on Ctrl+C
|
||||
}
|
||||
// Wait until cancellation (Ctrl+C) or a connection lost for good (#1048).
|
||||
var lostReason = await ConnectionLossWatch.WaitAsync(lossWatch, Timeout.InfiniteTimeSpan, ct);
|
||||
if (lostReason is not null)
|
||||
outputChannel.Writer.TryWrite($"[{DateTime.UtcNow:O}] WARNING: {lostReason}; stopping.");
|
||||
|
||||
// Stop accepting new notifications before writing final output.
|
||||
service.AlarmEvent -= AlarmEventHandler;
|
||||
@@ -145,6 +155,12 @@ public class AlarmsCommand : CommandBase
|
||||
await drainCts.CancelAsync();
|
||||
try { await drainTask; } catch (OperationCanceledException) { }
|
||||
|
||||
if (lostReason is not null)
|
||||
{
|
||||
// No unsubscribe over a dead connection; the finally block disconnects.
|
||||
throw new CommandException($"Connection lost: {lostReason}.", SubscribeCommand.ConnectionLostExitCode);
|
||||
}
|
||||
|
||||
await service.UnsubscribeAlarmsAsync();
|
||||
await console.Output.WriteLineAsync("Unsubscribed.");
|
||||
}
|
||||
|
||||
@@ -68,6 +68,20 @@ public class SubscribeCommand : CommandBase
|
||||
[CommandOption("summary-file", Description = "Write summary to this file path on exit (in addition to stdout)")]
|
||||
public string? SummaryFile { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets how long, in seconds, a lost connection may stay unrecovered before the command prints a warning, its
|
||||
/// summary, and exits with <see cref="ConnectionLostExitCode" /> (#1048). <c>0</c> waits indefinitely for the
|
||||
/// failover to reconnect; the service giving up (<c>Disconnected</c>) always ends the run.
|
||||
/// </summary>
|
||||
[CommandOption("reconnect-timeout", Description = "Exit non-zero (code 3) if a lost connection has not recovered after N seconds (0 = wait indefinitely)")]
|
||||
public int ReconnectTimeoutSeconds { get; init; } = DefaultReconnectTimeoutSeconds;
|
||||
|
||||
/// <summary>Default for <see cref="ReconnectTimeoutSeconds" />: comfortably longer than a server restart.</summary>
|
||||
public const int DefaultReconnectTimeoutSeconds = 300;
|
||||
|
||||
/// <summary>Process exit code when the run ends because its connection was lost for good (#1048).</summary>
|
||||
public const int ConnectionLostExitCode = 3;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override async ValueTask ExecuteAsync(IConsole console)
|
||||
{
|
||||
@@ -79,6 +93,8 @@ public class SubscribeCommand : CommandBase
|
||||
throw new CommandException($"--max-depth must be greater than 0 (was {MaxDepth}).");
|
||||
if (DurationSeconds < 0)
|
||||
throw new CommandException($"--duration must be 0 or a positive number (was {DurationSeconds}).");
|
||||
if (ReconnectTimeoutSeconds < 0)
|
||||
throw new CommandException($"--reconnect-timeout must be 0 or a positive number (was {ReconnectTimeoutSeconds}).");
|
||||
|
||||
NodeId rootNodeId;
|
||||
try
|
||||
@@ -142,10 +158,15 @@ public class SubscribeCommand : CommandBase
|
||||
}
|
||||
|
||||
// #1000 S-4: surface connection transitions (Reconnecting / Connected after a failover) so a run across a
|
||||
// restart is distinguishable from a server that simply stopped publishing.
|
||||
void ConnectionHandler(object? sender, ConnectionStateChangedEventArgs e) =>
|
||||
// restart is distinguishable from a server that simply stopped publishing. #1048: and end the run when
|
||||
// the connection is lost for good.
|
||||
using var lossWatch = new ConnectionLossWatch(TimeSpan.FromSeconds(ReconnectTimeoutSeconds));
|
||||
void ConnectionHandler(object? sender, ConnectionStateChangedEventArgs e)
|
||||
{
|
||||
outputChannel.Writer.TryWrite(
|
||||
$"[{DateTime.UtcNow:O}] CONNECTION {e.OldState} -> {e.NewState} ({e.EndpointUrl})");
|
||||
lossWatch.Observe(e);
|
||||
}
|
||||
|
||||
service.ConnectionStateChanged += ConnectionHandler;
|
||||
|
||||
@@ -180,16 +201,10 @@ public class SubscribeCommand : CommandBase
|
||||
await console.Output.WriteLineAsync(line);
|
||||
}, CancellationToken.None);
|
||||
|
||||
try
|
||||
{
|
||||
if (DurationSeconds > 0)
|
||||
await Task.Delay(TimeSpan.FromSeconds(DurationSeconds), ct);
|
||||
else
|
||||
await Task.Delay(Timeout.Infinite, ct);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
var lostReason = await ConnectionLossWatch.WaitAsync(
|
||||
lossWatch, DurationSeconds > 0 ? TimeSpan.FromSeconds(DurationSeconds) : Timeout.InfiniteTimeSpan, ct);
|
||||
if (lostReason is not null)
|
||||
outputChannel.Writer.TryWrite($"[{DateTime.UtcNow:O}] WARNING: {lostReason}; stopping.");
|
||||
|
||||
// Stop accepting new notifications before writing the summary.
|
||||
service.DataChanged -= DataChangedHandler;
|
||||
@@ -231,6 +246,8 @@ public class SubscribeCommand : CommandBase
|
||||
summary.Add($" Last status GOOD: {good.Count}");
|
||||
summary.Add($" Last status NOT-GOOD: {bad.Count}");
|
||||
summary.Add($" No update received at all: {never.Count}");
|
||||
if (lostReason is not null)
|
||||
summary.Add($"Connection: LOST — {lostReason}. Last values above predate the loss.");
|
||||
|
||||
if (neverWentBad.Count > 0 && neverWentBad.Count < targets.Count)
|
||||
{
|
||||
@@ -252,6 +269,12 @@ public class SubscribeCommand : CommandBase
|
||||
catch (Exception ex) { await console.Output.WriteLineAsync($"Failed to write summary file: {ex.Message}"); }
|
||||
}
|
||||
|
||||
if (lostReason is not null)
|
||||
{
|
||||
// No per-node unsubscribe over a dead connection; the finally block disconnects.
|
||||
throw new CommandException($"Connection lost: {lostReason}.", ConnectionLostExitCode);
|
||||
}
|
||||
|
||||
foreach (var (nodeId, _) in targets)
|
||||
{
|
||||
try { await service.UnsubscribeAsync(nodeId); } catch { /* ignore */ }
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Helpers;
|
||||
|
||||
/// <summary>
|
||||
/// Watches a long-running command's connection for a loss that never recovers (#1048). The shared service keeps
|
||||
/// a failover in <see cref="ConnectionState.Reconnecting" />, cycling the endpoints with a capped backoff, until it
|
||||
/// connects or is disconnected (#1000) — so without this a <c>subscribe</c>/<c>alarms</c> run across an outage
|
||||
/// that never ends just sits there, and its summary reports the last values seen before the drop as final.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para><see cref="Lost" /> completes, with the reason, when either:</para>
|
||||
/// <list type="bullet">
|
||||
/// <item>the service lands <see cref="ConnectionState.Disconnected" /> on its own — it will not retry; or</item>
|
||||
/// <item>the connection stays out of <see cref="ConnectionState.Connected" /> for longer than the timeout
|
||||
/// (<c>--reconnect-timeout</c>; <see cref="TimeSpan.Zero" /> = wait indefinitely for a reconnect).</item>
|
||||
/// </list>
|
||||
/// <para>A return to <see cref="ConnectionState.Connected" /> before the timeout re-arms the watch.</para>
|
||||
/// </remarks>
|
||||
internal sealed class ConnectionLossWatch : IDisposable
|
||||
{
|
||||
private readonly TimeSpan _timeout;
|
||||
private readonly TimeProvider _clock;
|
||||
private readonly object _gate = new();
|
||||
private readonly TaskCompletionSource<string> _lost = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private CancellationTokenSource? _pending;
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>Creates the watch.</summary>
|
||||
/// <param name="timeout">How long a loss may last before it counts as unrecovered; zero or less = no limit.</param>
|
||||
/// <param name="clock">Clock for the timeout (tests); null = the system clock.</param>
|
||||
public ConnectionLossWatch(TimeSpan timeout, TimeProvider? clock = null)
|
||||
{
|
||||
_timeout = timeout;
|
||||
_clock = clock ?? TimeProvider.System;
|
||||
}
|
||||
|
||||
/// <summary>Completes with a human-readable reason once the connection is lost for good; never faults.</summary>
|
||||
public Task<string> Lost => _lost.Task;
|
||||
|
||||
/// <summary>
|
||||
/// A long-running command's main wait: returns when <paramref name="ct" /> fires (Ctrl+C), when
|
||||
/// <paramref name="duration" /> elapses, or when the connection is lost for good.
|
||||
/// </summary>
|
||||
/// <param name="watch">The command's watch.</param>
|
||||
/// <param name="duration">How long to run; <see cref="Timeout.InfiniteTimeSpan" /> = until cancelled.</param>
|
||||
/// <param name="ct">The command's cancellation token.</param>
|
||||
/// <returns>The loss reason when the connection was lost for good, otherwise <see langword="null" />.</returns>
|
||||
public static async Task<string?> WaitAsync(ConnectionLossWatch watch, TimeSpan duration, CancellationToken ct)
|
||||
{
|
||||
using var waitCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
var wait = Task.Delay(duration, waitCts.Token);
|
||||
var first = await Task.WhenAny(wait, watch.Lost).ConfigureAwait(false);
|
||||
if (first == watch.Lost && !ct.IsCancellationRequested)
|
||||
{
|
||||
await waitCts.CancelAsync().ConfigureAwait(false);
|
||||
try { await wait.ConfigureAwait(false); } catch (OperationCanceledException) { }
|
||||
return await watch.Lost.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
try { await wait.ConfigureAwait(false); } catch (OperationCanceledException) { }
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Feeds one connection transition. Safe to call from the SDK's notification threads.</summary>
|
||||
/// <param name="e">The transition.</param>
|
||||
public void Observe(ConnectionStateChangedEventArgs e)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed || _lost.Task.IsCompleted) return;
|
||||
switch (e.NewState)
|
||||
{
|
||||
case ConnectionState.Connected:
|
||||
CancelPending();
|
||||
return;
|
||||
case ConnectionState.Disconnected:
|
||||
CancelPending();
|
||||
_lost.TrySetResult($"the client gave up and disconnected from {e.EndpointUrl}");
|
||||
return;
|
||||
default: // Reconnecting / Connecting: start the clock once per outage.
|
||||
if (_pending is not null || _timeout <= TimeSpan.Zero) return;
|
||||
var cts = new CancellationTokenSource();
|
||||
_pending = cts;
|
||||
var endpoint = e.EndpointUrl;
|
||||
_ = ExpireAsync(cts, endpoint);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ExpireAsync(CancellationTokenSource cts, string endpoint)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(_timeout, _clock, cts.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
lock (_gate)
|
||||
{
|
||||
if (!ReferenceEquals(_pending, cts) || _disposed) return;
|
||||
_lost.TrySetResult(
|
||||
$"the connection was lost (last endpoint {endpoint}) and did not recover within {_timeout.TotalSeconds:0} s");
|
||||
}
|
||||
}
|
||||
|
||||
private void CancelPending()
|
||||
{
|
||||
var pending = _pending;
|
||||
_pending = null;
|
||||
if (pending is null) return;
|
||||
pending.Cancel();
|
||||
pending.Dispose();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
CancelPending();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -215,19 +215,27 @@ public partial class SubscriptionsViewModel : ObservableObject
|
||||
/// <param name="nodeClass">The node class of the starting node so variables can be subscribed immediately.</param>
|
||||
/// <param name="intervalMs">The monitored-item interval, in milliseconds, used for created subscriptions.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public Task AddSubscriptionRecursiveAsync(string nodeIdStr, string nodeClass, int intervalMs = 1000)
|
||||
{
|
||||
return AddSubscriptionRecursiveAsync(nodeIdStr, nodeClass, intervalMs, maxDepth: 10, currentDepth: 0);
|
||||
}
|
||||
|
||||
private async Task AddSubscriptionRecursiveAsync(string nodeIdStr, string nodeClass, int intervalMs, int maxDepth, int currentDepth)
|
||||
public async Task AddSubscriptionRecursiveAsync(string nodeIdStr, string nodeClass, int intervalMs = 1000)
|
||||
{
|
||||
if (!IsConnected || string.IsNullOrWhiteSpace(nodeIdStr)) return;
|
||||
if (currentDepth >= maxDepth) return;
|
||||
|
||||
// #1048 (#1000 S-12): collect the whole subtree's variables first, then create every monitored item in ONE
|
||||
// batched SubscribeManyAsync — a recursive subscribe over thousands of variables used to be one server round
|
||||
// trip per node.
|
||||
var targets = new List<string>();
|
||||
await CollectVariablesAsync(nodeIdStr, nodeClass, maxDepth: 10, currentDepth: 0, targets,
|
||||
new HashSet<string>(StringComparer.Ordinal));
|
||||
await SubscribeManyNodesAsync(targets, intervalMs);
|
||||
}
|
||||
|
||||
private async Task CollectVariablesAsync(
|
||||
string nodeIdStr, string nodeClass, int maxDepth, int currentDepth, List<string> targets, HashSet<string> seen)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(nodeIdStr) || currentDepth >= maxDepth) return;
|
||||
|
||||
if (nodeClass == "Variable")
|
||||
{
|
||||
await AddSubscriptionForNodeAsync(nodeIdStr, intervalMs);
|
||||
if (seen.Add(nodeIdStr)) targets.Add(nodeIdStr);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -238,7 +246,7 @@ public partial class SubscriptionsViewModel : ObservableObject
|
||||
var children = await _service.BrowseAsync(nodeId);
|
||||
|
||||
foreach (var child in children)
|
||||
await AddSubscriptionRecursiveAsync(child.NodeId, child.NodeClass, intervalMs, maxDepth, currentDepth + 1);
|
||||
await CollectVariablesAsync(child.NodeId, child.NodeClass, maxDepth, currentDepth + 1, targets, seen);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -247,6 +255,61 @@ public partial class SubscriptionsViewModel : ObservableObject
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Subscribes <paramref name="nodeIdStrs" /> in one batched <see cref="IOpcUaClientService.SubscribeManyAsync" />
|
||||
/// (#1048), skipping nodes already subscribed. Nodes that subscribed are added as rows; per-node failures and a
|
||||
/// whole-batch failure are surfaced through <see cref="StatusMessage" />.
|
||||
/// </summary>
|
||||
private async Task SubscribeManyNodesAsync(IReadOnlyList<string> nodeIdStrs, int intervalMs)
|
||||
{
|
||||
var pending = new List<(string Text, NodeId Id)>();
|
||||
var failures = new List<string>();
|
||||
foreach (var text in nodeIdStrs.Distinct(StringComparer.Ordinal))
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text) || _rowsByNodeId.ContainsKey(text)) continue;
|
||||
try { pending.Add((text, NodeId.Parse(text))); }
|
||||
catch (Exception ex) { failures.Add($"{text}: {ex.Message}"); }
|
||||
}
|
||||
|
||||
var subscribed = new List<string>();
|
||||
if (pending.Count > 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
var outcomes = await _service.SubscribeManyAsync(pending.Select(p => p.Id).ToList(), intervalMs);
|
||||
for (var i = 0; i < pending.Count; i++)
|
||||
{
|
||||
var error = i < outcomes.Count ? outcomes[i] : null;
|
||||
if (error is null) subscribed.Add(pending[i].Text);
|
||||
else
|
||||
{
|
||||
Logger.Warning(error, "Subscribe failed for {NodeId}", pending[i].Text);
|
||||
failures.Add($"{pending[i].Text}: {error.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Warning(ex, "Batched subscribe of {Count} node(s) failed", pending.Count);
|
||||
_dispatcher.Post(() => StatusMessage = $"Subscribe failed for {pending.Count} node(s): {ex.Message}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
var failedCount = failures.Count;
|
||||
var total = subscribed.Count + failedCount;
|
||||
_dispatcher.Post(() =>
|
||||
{
|
||||
foreach (var text in subscribed)
|
||||
ActiveSubscriptions.Add(new SubscriptionItemViewModel(text, intervalMs));
|
||||
SubscriptionCount = ActiveSubscriptions.Count;
|
||||
StatusMessage = failedCount == 0
|
||||
? null
|
||||
: $"Subscribe failed for {failedCount} of {total} node(s): {string.Join("; ", failures.Take(5))}"
|
||||
+ (failedCount > 5 ? $"; … and {failedCount - 5} more" : string.Empty);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the node IDs of all active subscriptions for persistence.
|
||||
/// </summary>
|
||||
@@ -263,8 +326,9 @@ public partial class SubscriptionsViewModel : ObservableObject
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public async Task RestoreSubscriptionsAsync(IEnumerable<string> nodeIds)
|
||||
{
|
||||
foreach (var nodeId in nodeIds)
|
||||
await AddSubscriptionForNodeAsync(nodeId);
|
||||
if (!IsConnected) return;
|
||||
// #1048: one batched round trip for the whole saved set (it can be a recursive subscribe's thousands of nodes).
|
||||
await SubscribeManyNodesAsync(nodeIds.ToList(), intervalMs: 1000);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -22,6 +22,23 @@ public interface IOpcUaNodeWriteGateway
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>A task resolving to the device-write outcome.</returns>
|
||||
Task<NodeWriteOutcome> WriteAsync(string nodeId, object? value, AddressSpaceRealm realm, CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// #1017 — <see cref="WriteAsync(string, object?, AddressSpaceRealm, CancellationToken)"/> carrying WHO wrote
|
||||
/// (the session's principal + API key id), so a driver whose device enforces per-user write permission
|
||||
/// (<see cref="ZB.MOM.WW.OtOpcUa.Core.Abstractions.ICallerAwareWritable"/>) can act on it. The default
|
||||
/// implementation drops the caller — a gateway that cannot carry it behaves exactly as before.
|
||||
/// </summary>
|
||||
/// <param name="nodeId">The full ns-qualified node id being written.</param>
|
||||
/// <param name="value">The value the client wrote.</param>
|
||||
/// <param name="realm">The namespace realm of <paramref name="nodeId"/>.</param>
|
||||
/// <param name="caller">Who issued the write; null when unknown.</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>A task resolving to the device-write outcome.</returns>
|
||||
Task<NodeWriteOutcome> WriteAsync(
|
||||
string nodeId, object? value, AddressSpaceRealm realm,
|
||||
ZB.MOM.WW.OtOpcUa.Core.Abstractions.WriteCaller? caller, CancellationToken ct)
|
||||
=> WriteAsync(nodeId, value, realm, ct);
|
||||
}
|
||||
|
||||
/// <summary>Outcome of routing an inbound node write to the backing driver.</summary>
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Who issued a write (#1017): the authenticated data-plane principal and, for a key-bearing session, the
|
||||
/// public id of the API key it authenticated with. Carries no secret. <see cref="ApiKeyId" /> null = an
|
||||
/// anonymous session (or a write with no client session behind it).
|
||||
/// </summary>
|
||||
/// <param name="Principal">The ACL principal (e.g. the key's principal, or <c>anonymous</c>); null when unknown.</param>
|
||||
/// <param name="ApiKeyId">The authenticating API key's public id; null for anonymous.</param>
|
||||
public sealed record WriteCaller(string? Principal, string? ApiKeyId);
|
||||
|
||||
/// <summary>
|
||||
/// Optional companion to <see cref="IWritable" /> for a driver whose device enforces a per-USER write
|
||||
/// permission and can therefore act on the caller's identity (#1017 — the Galaxy driver's SecuredWrite
|
||||
/// attributes, written under the calling API key's Galaxy account). The runtime calls this overload instead
|
||||
/// of <see cref="IWritable.WriteAsync" /> whenever the write carries a <see cref="WriteCaller" />. It must keep
|
||||
/// every other behaviour of <see cref="IWritable.WriteAsync" />; a caller the driver cannot map is refused
|
||||
/// per write (e.g. <c>BadUserAccessDenied</c>), never silently written under another identity.
|
||||
/// </summary>
|
||||
public interface ICallerAwareWritable : IWritable
|
||||
{
|
||||
/// <summary>Write a batch on behalf of <paramref name="caller" />; one result per request, in order.</summary>
|
||||
/// <param name="writes">Pairs of full reference + value to write.</param>
|
||||
/// <param name="caller">Who issued the write.</param>
|
||||
/// <param name="cancellationToken">Cancellation token; the driver should abort the batch if cancelled.</param>
|
||||
/// <returns>One <see cref="WriteResult" /> per requested write, in the same order.</returns>
|
||||
Task<IReadOnlyList<WriteResult>> WriteAsync(
|
||||
IReadOnlyList<WriteRequest> writes,
|
||||
WriteCaller caller,
|
||||
CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -176,7 +176,34 @@ public sealed record GalaxyMxAccessOptions(
|
||||
string ClientName,
|
||||
int PublishingIntervalMs = 1000,
|
||||
int WriteUserId = 0,
|
||||
[Range(1, int.MaxValue)] int EventPumpChannelCapacity = 50_000);
|
||||
[Range(1, int.MaxValue)] int EventPumpChannelCapacity = 50_000)
|
||||
{
|
||||
/// <summary>
|
||||
/// How a write to a <c>SecuredWrite</c> attribute is handled (#1017). Default
|
||||
/// <see cref="GalaxySecuredWriteMode.Refuse"/> — refused <c>BadUserAccessDenied</c> locally (#991). A
|
||||
/// <c>VerifiedWrite</c> attribute is refused in every mode.
|
||||
/// </summary>
|
||||
public GalaxySecuredWriteMode SecuredWrites { get; init; } = GalaxySecuredWriteMode.Refuse;
|
||||
}
|
||||
|
||||
/// <summary>How the Galaxy driver handles a write to a <c>SecuredWrite</c> attribute (#1017).</summary>
|
||||
/// <remarks>Always (de)serialised as its NAME, whatever the caller's serializer options: the driver factory parses
|
||||
/// the string, and the browser/probe deserialise the options with options that may lack an enum converter.</remarks>
|
||||
[System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter<GalaxySecuredWriteMode>))]
|
||||
public enum GalaxySecuredWriteMode
|
||||
{
|
||||
/// <summary>Refuse it <c>BadUserAccessDenied</c> before anything reaches the gateway (the #991 behaviour).</summary>
|
||||
Refuse,
|
||||
|
||||
/// <summary>
|
||||
/// Write it as the CALLING session's API key's Galaxy identity — the account mapped to the key on AdminUI
|
||||
/// <c>/api-keys</c> (the same identity a native alarm acknowledge from that key uses,
|
||||
/// <see cref="GalaxyAckIdentitySecrets"/>): <c>AuthenticateUser</c> then <c>WriteSecured</c>. Anonymous
|
||||
/// sessions and keys with no (or a broken) identity are refused; there is NO driver fallback account for
|
||||
/// writes. Needs the driver's gateway API key to hold the <c>invoke:secure</c> scope.
|
||||
/// </summary>
|
||||
ApiKeyIdentity,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Galaxy Repository browse-side knobs consumed by PR 4.1's <c>GalaxyDiscoverer</c>.
|
||||
|
||||
@@ -38,7 +38,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy;
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class GalaxyDriver
|
||||
: IDriver, ITagDiscovery, IReadable, IWritable, ISubscribable, IRediscoverable, IHostConnectivityProbe, IAlarmSource, IAlarmInitialStateSignal, IAlarmAcknowledgePreflight, IAlarmAcknowledgeConfirmation, ISkippedTagReporter, IDisposable, IAsyncDisposable
|
||||
: IDriver, ITagDiscovery, IReadable, IWritable, ICallerAwareWritable, ISubscribable, IRediscoverable, IHostConnectivityProbe, IAlarmSource, IAlarmInitialStateSignal, IAlarmAcknowledgePreflight, IAlarmAcknowledgeConfirmation, ISkippedTagReporter, IDisposable, IAsyncDisposable
|
||||
{
|
||||
/// <summary>Authored tags this driver could not dial — a TagConfig with no usable
|
||||
/// <c>attributeRef</c> has no MXAccess address to bind.</summary>
|
||||
@@ -396,7 +396,7 @@ public sealed class GalaxyDriver
|
||||
|
||||
/// <summary>
|
||||
/// Test-visible ctor — inject custom seams so <see cref="DiscoverAsync"/>,
|
||||
/// <see cref="ReadAsync"/>, <see cref="WriteAsync"/>, and
|
||||
/// <see cref="ReadAsync"/>, <see cref="WriteAsync(IReadOnlyList{WriteRequest}, CancellationToken)"/>, and
|
||||
/// <see cref="SubscribeAsync"/> can be exercised against canned data without
|
||||
/// building real gRPC channels.
|
||||
/// </summary>
|
||||
@@ -908,7 +908,7 @@ public sealed class GalaxyDriver
|
||||
|
||||
/// <summary>
|
||||
/// #991 G-1 — one security seed pass: fetch the authored objects' attributes and record each authored tag's
|
||||
/// <see cref="SecurityClassification"/> under its RawPath, the key <see cref="WriteAsync"/> resolves against.
|
||||
/// <see cref="SecurityClassification"/> under its RawPath, the key <see cref="WriteAsync(IReadOnlyList{WriteRequest}, CancellationToken)"/> resolves against.
|
||||
/// Before this the map was filled only by <see cref="DiscoverAsync"/>, which the runtime never calls on a
|
||||
/// served driver. Never throws; a failed or late pass leaves the map as it was (FreeAccess for anything
|
||||
/// unseen, i.e. the raw path).
|
||||
@@ -2380,6 +2380,25 @@ public sealed class GalaxyDriver
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<WriteResult>> WriteAsync(
|
||||
IReadOnlyList<WriteRequest> writes, CancellationToken cancellationToken)
|
||||
=> WriteCoreAsync(writes, caller: null, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// #1017 — <see cref="WriteAsync(IReadOnlyList{WriteRequest}, CancellationToken)"/> on behalf of
|
||||
/// <paramref name="caller"/>. With <c>MxAccess.SecuredWrites = ApiKeyIdentity</c> a SecuredWrite attribute is
|
||||
/// written as the caller's API key's own Galaxy identity (no fallback account); otherwise — and for every
|
||||
/// VerifiedWrite attribute — it is refused <c>BadUserAccessDenied</c> as before. Non-secured tags are
|
||||
/// unaffected by the caller.
|
||||
/// </summary>
|
||||
/// <param name="writes">Pairs of full reference (RawPath) + value.</param>
|
||||
/// <param name="caller">Who issued the write.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>One result per request, in order.</returns>
|
||||
public Task<IReadOnlyList<WriteResult>> WriteAsync(
|
||||
IReadOnlyList<WriteRequest> writes, WriteCaller caller, CancellationToken cancellationToken)
|
||||
=> WriteCoreAsync(writes, caller ?? throw new ArgumentNullException(nameof(caller)), cancellationToken);
|
||||
|
||||
private Task<IReadOnlyList<WriteResult>> WriteCoreAsync(
|
||||
IReadOnlyList<WriteRequest> writes, WriteCaller? caller, CancellationToken cancellationToken)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
ArgumentNullException.ThrowIfNull(writes);
|
||||
@@ -2403,8 +2422,17 @@ public sealed class GalaxyDriver
|
||||
var dialledWrites = new List<WriteRequest>(writes.Count);
|
||||
foreach (var w in writes) dialledWrites.Add(w with { FullReference = ToAttributeRef(w.FullReference) });
|
||||
|
||||
// #1017: only an opted-in driver with a known caller carries an identity source; the writer resolves it
|
||||
// lazily (at most once per batch, only for a SecuredWrite tag). Key-only — never the ack fallback account.
|
||||
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential = null;
|
||||
if (caller is not null && _options.MxAccess.SecuredWrites == GalaxySecuredWriteMode.ApiKeyIdentity)
|
||||
{
|
||||
var apiKeyId = caller.ApiKeyId;
|
||||
securedCredential = ct => _ackCredentialResolver.ResolveKeyIdentityAsync(apiKeyId, ct);
|
||||
}
|
||||
|
||||
return _dataWriter.WriteAsync(
|
||||
dialledWrites, attributeRef => ResolveSecurity(ToRawPath(attributeRef)), cancellationToken);
|
||||
dialledWrites, attributeRef => ResolveSecurity(ToRawPath(attributeRef)), securedCredential, cancellationToken);
|
||||
}
|
||||
|
||||
// ===== ISubscribable (PR 4.4) =====
|
||||
|
||||
@@ -115,7 +115,10 @@ public static class GalaxyDriverFactoryExtensions
|
||||
$"Galaxy driver '{driverInstanceId}' missing required MxAccess.ClientName"),
|
||||
PublishingIntervalMs: dto.MxAccess.PublishingIntervalMs ?? 1000,
|
||||
WriteUserId: dto.MxAccess.WriteUserId ?? 0,
|
||||
EventPumpChannelCapacity: dto.MxAccess.EventPumpChannelCapacity ?? 50_000),
|
||||
EventPumpChannelCapacity: dto.MxAccess.EventPumpChannelCapacity ?? 50_000)
|
||||
{
|
||||
SecuredWrites = ParseSecuredWrites(dto.MxAccess.SecuredWrites, driverInstanceId),
|
||||
},
|
||||
Repository: new GalaxyRepositoryOptions(
|
||||
DiscoverPageSize: dto.Repository?.DiscoverPageSize ?? 5000,
|
||||
WatchDeployEvents: dto.Repository?.WatchDeployEvents ?? true),
|
||||
@@ -143,6 +146,24 @@ public static class GalaxyDriverFactoryExtensions
|
||||
|
||||
private static string? NullIfBlank(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
|
||||
/// <summary>
|
||||
/// #1017: <c>MxAccess.SecuredWrites</c> — absent/blank = <see cref="GalaxySecuredWriteMode.Refuse"/>. An
|
||||
/// unknown value fails the driver config loudly rather than silently refusing (a misspelt opt-in would
|
||||
/// otherwise look like a Galaxy permission problem).
|
||||
/// </summary>
|
||||
internal static GalaxySecuredWriteMode ParseSecuredWrites(string? value, string driverInstanceId)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value)) return GalaxySecuredWriteMode.Refuse;
|
||||
var text = value.Trim();
|
||||
if (!int.TryParse(text, out _)
|
||||
&& Enum.TryParse<GalaxySecuredWriteMode>(text, ignoreCase: true, out var mode)
|
||||
&& Enum.IsDefined(mode))
|
||||
return mode;
|
||||
throw new InvalidOperationException(
|
||||
$"Galaxy driver '{driverInstanceId}' has an unknown MxAccess.SecuredWrites value '{text}' " +
|
||||
$"(expected {string.Join(" | ", Enum.GetNames<GalaxySecuredWriteMode>())}).");
|
||||
}
|
||||
|
||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
@@ -218,6 +239,8 @@ public static class GalaxyDriverFactoryExtensions
|
||||
public int? WriteUserId { get; init; }
|
||||
/// <summary>Gets or sets the event pump channel capacity.</summary>
|
||||
public int? EventPumpChannelCapacity { get; init; }
|
||||
/// <summary>Gets or sets the SecuredWrite handling (#1017): <c>Refuse</c> (default) or <c>ApiKeyIdentity</c>.</summary>
|
||||
public string? SecuredWrites { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Repository configuration section.</summary>
|
||||
|
||||
@@ -46,7 +46,7 @@ internal sealed class GalaxyAckCredentialResolver : IGalaxyAckCredentialResolver
|
||||
string? keyNote = null;
|
||||
if (!string.IsNullOrWhiteSpace(apiKeyId))
|
||||
{
|
||||
var keyResult = await ResolveKeyIdentityAsync(apiKeyId, cancellationToken).ConfigureAwait(false);
|
||||
var keyResult = await ResolveMappedKeyIdentityAsync(apiKeyId, cancellationToken).ConfigureAwait(false);
|
||||
if (keyResult.Credential is not null) return keyResult;
|
||||
// A key whose identity is half-configured (user without password, unreadable secret) is
|
||||
// refused outright — silently acknowledging as the fallback account would record the wrong
|
||||
@@ -66,8 +66,30 @@ internal sealed class GalaxyAckCredentialResolver : IGalaxyAckCredentialResolver
|
||||
"in AdminUI /api-keys or configure the driver's fallback ack account.");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<GalaxyAckCredentialResolution> ResolveKeyIdentityAsync(string? apiKeyId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(apiKeyId))
|
||||
{
|
||||
return GalaxyAckCredentialResolution.Refused(
|
||||
"the session is anonymous (no API key), and a secured write runs only as the calling key's own Galaxy identity");
|
||||
}
|
||||
|
||||
var keyResult = await ResolveMappedKeyIdentityAsync(apiKeyId, cancellationToken).ConfigureAwait(false);
|
||||
if (keyResult.Credential is not null || keyResult.RefusalReason is not null)
|
||||
{
|
||||
return keyResult.RefusalReason is null
|
||||
? keyResult
|
||||
: GalaxyAckCredentialResolution.Refused(keyResult.RefusalReason.Replace(
|
||||
"the acknowledge was not sent", "the write was not sent", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
return GalaxyAckCredentialResolution.Refused(
|
||||
$"API key '{apiKeyId}' has no Galaxy identity (AdminUI /api-keys); a secured write has no fallback account.");
|
||||
}
|
||||
|
||||
// Returns Resolved, Refused (mapped but broken), or (null, null) = "no identity mapped".
|
||||
private async Task<GalaxyAckCredentialResolution> ResolveKeyIdentityAsync(string apiKeyId, CancellationToken ct)
|
||||
private async Task<GalaxyAckCredentialResolution> ResolveMappedKeyIdentityAsync(string apiKeyId, CancellationToken ct)
|
||||
{
|
||||
string userName, passwordName;
|
||||
try
|
||||
|
||||
@@ -13,10 +13,11 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
|
||||
/// Production <see cref="IGalaxyDataWriter"/> over <see cref="GalaxyMxSession"/>.
|
||||
/// For each batch entry: lazy-AddItem to obtain the MXAccess item handle, encode
|
||||
/// the value via <see cref="MxValueEncoder"/>, supervisory-advise + Write, and translate the
|
||||
/// reply's <c>MxStatusProxy</c> into an OPC UA <see cref="WriteResult"/>. A SecuredWrite /
|
||||
/// VerifiedWrite attribute (per-tag <see cref="SecurityClassification"/>) is refused
|
||||
/// <c>BadUserAccessDenied</c> without a round trip — the driver has no ArchestrA identity to
|
||||
/// write it under (#991 review G-1).
|
||||
/// reply's <c>MxStatusProxy</c> into an OPC UA <see cref="WriteResult"/>. A SecuredWrite attribute
|
||||
/// (per-tag <see cref="SecurityClassification"/>) is written as the caller's Galaxy identity when the
|
||||
/// driver supplies one (#1017: own plain-advised handle → <c>AuthenticateUser</c> → <c>WriteSecured</c>),
|
||||
/// and refused <c>BadUserAccessDenied</c> without a round trip otherwise (#991 review G-1); a
|
||||
/// VerifiedWrite attribute is always refused that way (no verifying user).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Item handle cache survives across writes — repeated writes to the same tag avoid
|
||||
@@ -41,6 +42,11 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
|
||||
private readonly ConcurrentDictionary<int, byte> _supervisedHandles = new();
|
||||
// Attributes whose secured/verified-write refusal has been logged (once per attribute, #991 review G-1).
|
||||
private readonly ConcurrentDictionary<string, byte> _securedRefusalWarned = new(StringComparer.OrdinalIgnoreCase);
|
||||
// #1017: the secured path's OWN item handles, PLAIN-advised (AuthenticateUser + WriteSecured commits through a
|
||||
// plain advise — live-captured, mxaccessgw docs/LiveCaptures-2026-11-13.md §4). Kept apart from _itemHandles,
|
||||
// whose handles are supervisory-advised for the raw path: MXAccess allows one advise mode per handle.
|
||||
private readonly ConcurrentDictionary<string, int> _securedItemHandles = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly ConcurrentDictionary<int, byte> _securedAdvisedHandles = new();
|
||||
private int _addItemCallCount;
|
||||
|
||||
// Write failure-visibility meters (archreview 06/S-1). Reuse the pump's meter name so the single host
|
||||
@@ -73,6 +79,8 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
|
||||
{
|
||||
_itemHandles.Clear();
|
||||
_supervisedHandles.Clear();
|
||||
_securedItemHandles.Clear();
|
||||
_securedAdvisedHandles.Clear();
|
||||
}
|
||||
|
||||
// ===== Test seams (internal — not part of the public contract) =====
|
||||
@@ -109,10 +117,25 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<WriteResult>> WriteAsync(
|
||||
public Task<IReadOnlyList<WriteResult>> WriteAsync(
|
||||
IReadOnlyList<WriteRequest> writes,
|
||||
Func<string, SecurityClassification> securityResolver,
|
||||
CancellationToken cancellationToken)
|
||||
=> WriteCoreAsync(writes, securityResolver, securedCredential: null, cancellationToken);
|
||||
|
||||
/// <inheritdoc />
|
||||
Task<IReadOnlyList<WriteResult>> IGalaxyDataWriter.WriteAsync(
|
||||
IReadOnlyList<WriteRequest> writes,
|
||||
Func<string, SecurityClassification> securityResolver,
|
||||
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential,
|
||||
CancellationToken cancellationToken)
|
||||
=> WriteCoreAsync(writes, securityResolver, securedCredential, cancellationToken);
|
||||
|
||||
private async Task<IReadOnlyList<WriteResult>> WriteCoreAsync(
|
||||
IReadOnlyList<WriteRequest> writes,
|
||||
Func<string, SecurityClassification> securityResolver,
|
||||
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(writes);
|
||||
ArgumentNullException.ThrowIfNull(securityResolver);
|
||||
@@ -125,7 +148,7 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
|
||||
// Bind the per-batch MX write operations behind the internal IMxWriteOps seam (see below) so the
|
||||
// whole write pipeline is unit-testable without the sealed SDK session (archreview 06/S-1).
|
||||
var ops = new SessionMxWriteOps(session, serverHandle);
|
||||
return await WriteBatchAsync(ops, writes, securityResolver, cancellationToken).ConfigureAwait(false);
|
||||
return await WriteBatchAsync(ops, writes, securityResolver, cancellationToken, securedCredential).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -142,10 +165,12 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
|
||||
/// <param name="securityResolver">Per-tag classification resolver.</param>
|
||||
/// <param name="ct">The cancellation token.</param>
|
||||
/// <returns>One result per request, in input order.</returns>
|
||||
/// <param name="securedCredential">The caller's Galaxy identity source for secured writes (#1017); null = none.</param>
|
||||
internal Task<IReadOnlyList<WriteResult>> WriteBatchForTestAsync(
|
||||
IMxWriteOps ops, IReadOnlyList<WriteRequest> writes,
|
||||
Func<string, SecurityClassification> securityResolver, CancellationToken ct)
|
||||
=> WriteBatchAsync(ops, writes, securityResolver, ct);
|
||||
Func<string, SecurityClassification> securityResolver, CancellationToken ct,
|
||||
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential = null)
|
||||
=> WriteBatchAsync(ops, writes, securityResolver, ct, securedCredential);
|
||||
|
||||
/// <summary>
|
||||
/// Run a batch as one lane per distinct tag (OrdinalIgnoreCase): writes to the SAME tag
|
||||
@@ -155,11 +180,21 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
|
||||
/// </summary>
|
||||
private async Task<IReadOnlyList<WriteResult>> WriteBatchAsync(
|
||||
IMxWriteOps ops, IReadOnlyList<WriteRequest> writes,
|
||||
Func<string, SecurityClassification> securityResolver, CancellationToken ct)
|
||||
Func<string, SecurityClassification> securityResolver, CancellationToken ct,
|
||||
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential = null)
|
||||
{
|
||||
var results = new WriteResult[writes.Count];
|
||||
if (writes.Count == 0) return results;
|
||||
|
||||
// #1017: the caller's identity is resolved at most ONCE per batch, and only when a secured tag needs it.
|
||||
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? batchCredential = null;
|
||||
if (securedCredential is not null)
|
||||
{
|
||||
var once = new Lazy<Task<GalaxyAckCredentialResolution>>(
|
||||
() => securedCredential(ct), LazyThreadSafetyMode.ExecutionAndPublication);
|
||||
batchCredential = _ => once.Value;
|
||||
}
|
||||
|
||||
// Group request indices by tag, first-seen order preserved so the lane start order is
|
||||
// deterministic and a same-tag sequence keeps its authored order.
|
||||
var lanes = new Dictionary<string, List<int>>(StringComparer.OrdinalIgnoreCase);
|
||||
@@ -203,7 +238,7 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
|
||||
foreach (var i in lane)
|
||||
{
|
||||
results[i] = await WriteOneAsync(ops, writes[i],
|
||||
securityResolver(writes[i].FullReference), ct).ConfigureAwait(false);
|
||||
securityResolver(writes[i].FullReference), ct, batchCredential).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -216,29 +251,38 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
|
||||
/// <param name="classification">The tag's security classification.</param>
|
||||
/// <param name="ct">The cancellation token.</param>
|
||||
/// <returns>The translated write result.</returns>
|
||||
/// <param name="securedCredential">The caller's Galaxy identity source for a SecuredWrite (#1017); null = none.</param>
|
||||
internal Task<WriteResult> WriteOneForTestAsync(
|
||||
IMxWriteOps ops, WriteRequest request, SecurityClassification classification, CancellationToken ct)
|
||||
=> WriteOneAsync(ops, request, classification, ct);
|
||||
IMxWriteOps ops, WriteRequest request, SecurityClassification classification, CancellationToken ct,
|
||||
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential = null)
|
||||
=> WriteOneAsync(ops, request, classification, ct, securedCredential);
|
||||
|
||||
private async Task<WriteResult> WriteOneAsync(
|
||||
IMxWriteOps ops, WriteRequest request,
|
||||
SecurityClassification classification, CancellationToken ct)
|
||||
SecurityClassification classification, CancellationToken ct,
|
||||
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential = null)
|
||||
{
|
||||
if (NeedsSecuredWrite(classification))
|
||||
if (classification is SecurityClassification.VerifiedWrite)
|
||||
{
|
||||
// #991 review (G-1): REFUSED, before anything reaches the wire. A SecuredWrite/VerifiedWrite attribute
|
||||
// needs a real ArchestrA identity — AuthenticateUser (+ a verifier for VerifiedWrite), the item advised
|
||||
// for that user, and a gateway key holding invoke:secure — none of which this driver has. Routing it to
|
||||
// WriteSecured could only fail, and the gateway's refusal surfaced as BadCommunicationError (a comms
|
||||
// fault). Until a per-caller identity flow exists this is an access refusal: no health impact.
|
||||
if (_securedRefusalWarned.TryAdd(request.FullReference, 0))
|
||||
// #991 review (G-1) / #1017: ALWAYS refused, before anything reaches the wire. A VerifiedWrite needs a
|
||||
// SECOND, verifying user (MXAccess refuses one with no verifier — 1008 — and one whose verifier is the
|
||||
// writer — 8018, both live-captured). An OPC UA Write carries one caller, never a verifier; a stored
|
||||
// verifier credential would let one client satisfy the two-person rule alone.
|
||||
return RefuseSecured(request.FullReference, classification,
|
||||
"a VerifiedWrite needs a second, verifying user, which an OPC UA write cannot carry");
|
||||
}
|
||||
|
||||
if (classification is SecurityClassification.SecuredWrite)
|
||||
{
|
||||
if (securedCredential is null)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"GalaxyDriver write to {FullRef} refused BadUserAccessDenied — the attribute is {Classification} and the " +
|
||||
"driver has no ArchestrA user identity to write it under (logged once per attribute).",
|
||||
request.FullReference, classification);
|
||||
// #991 review (G-1): no caller identity is in play (the driver's MxAccess.SecuredWrites is Refuse,
|
||||
// or the write carries no caller) — an access refusal, no health impact.
|
||||
return RefuseSecured(request.FullReference, classification,
|
||||
"the driver has no ArchestrA user identity to write it under (MxAccess.SecuredWrites = Refuse, or no caller)");
|
||||
}
|
||||
return new WriteResult(StatusCodeMap.BadUserAccessDenied);
|
||||
|
||||
return await WriteSecuredOneAsync(ops, request, securedCredential, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
try
|
||||
@@ -289,8 +333,183 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
|
||||
}
|
||||
}
|
||||
|
||||
private static bool NeedsSecuredWrite(SecurityClassification classification) =>
|
||||
classification is SecurityClassification.SecuredWrite or SecurityClassification.VerifiedWrite;
|
||||
private WriteResult RefuseSecured(string fullRef, SecurityClassification classification, string why)
|
||||
{
|
||||
if (_securedRefusalWarned.TryAdd(fullRef, 0))
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"GalaxyDriver write to {FullRef} refused BadUserAccessDenied — the attribute is {Classification} and {Why} " +
|
||||
"(logged once per attribute).",
|
||||
fullRef, classification, why);
|
||||
}
|
||||
return new WriteResult(StatusCodeMap.BadUserAccessDenied);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #1017 — a SecuredWrite under the CALLER's Galaxy identity: the writer's own plain-advised handle →
|
||||
/// <c>AuthenticateUser(DOMAIN\user, password)</c> → <c>WriteSecured(current = that user, verifier = 0)</c>, the
|
||||
/// sequence mxaccessgw live-captured committing (docs/LiveCaptures-2026-11-13.md §4). The password goes only
|
||||
/// into the <c>AuthenticateUser</c> command; nothing here logs it, and gateway text is scrubbed of it.
|
||||
/// Authenticates on EVERY write (no cached user id): MXAccess's user-id lifetime is unverified, and a rotated
|
||||
/// or revoked identity must take effect on the next write.
|
||||
/// </summary>
|
||||
private async Task<WriteResult> WriteSecuredOneAsync(
|
||||
IMxWriteOps ops, WriteRequest request,
|
||||
Func<CancellationToken, Task<GalaxyAckCredentialResolution>> securedCredential, CancellationToken ct)
|
||||
{
|
||||
GalaxyAckCredentialResolution resolution;
|
||||
try
|
||||
{
|
||||
resolution = await securedCredential(ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"GalaxyDriver secured write to {FullRef} refused BadUserAccessDenied — resolving the caller's Galaxy identity failed ({ExceptionType}).",
|
||||
request.FullReference, ex.GetType().Name);
|
||||
return new WriteResult(StatusCodeMap.BadUserAccessDenied);
|
||||
}
|
||||
|
||||
if (resolution.Credential is not { } credential)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"GalaxyDriver secured write to {FullRef} refused BadUserAccessDenied — {Reason}",
|
||||
request.FullReference, resolution.RefusalReason ?? "no Galaxy identity for the caller");
|
||||
return new WriteResult(StatusCodeMap.BadUserAccessDenied);
|
||||
}
|
||||
|
||||
var password = credential.Password;
|
||||
try
|
||||
{
|
||||
var mxValue = MxValueEncoder.Encode(request.Value);
|
||||
var itemHandle = await EnsureSecuredItemHandleAsync(ops, request.FullReference, ct).ConfigureAwait(false);
|
||||
if (!await EnsurePlainAdvisedAsync(ops, itemHandle, ct).ConfigureAwait(false))
|
||||
{
|
||||
WriteAdviseFailed.Add(1);
|
||||
return new WriteResult(StatusCodeMap.BadCommunicationError);
|
||||
}
|
||||
|
||||
var authReply = await ops.InvokeAsync(new MxCommandRequest
|
||||
{
|
||||
SessionId = ops.SessionId,
|
||||
ClientCorrelationId = Guid.NewGuid().ToString("N"),
|
||||
Command = new MxCommand
|
||||
{
|
||||
Kind = MxCommandKind.AuthenticateUser,
|
||||
AuthenticateUser = new AuthenticateUserCommand
|
||||
{
|
||||
ServerHandle = ops.ServerHandle,
|
||||
VerifyUser = credential.DisplayName,
|
||||
VerifyUserPassword = password,
|
||||
},
|
||||
},
|
||||
}, ct).ConfigureAwait(false);
|
||||
|
||||
var userId = authReply.AuthenticateUser?.UserId ?? 0;
|
||||
if (authReply.ProtocolStatus is { } authProto && authProto.Code != ProtocolStatusCode.Ok || userId == 0)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"GalaxyDriver secured write to {FullRef} refused BadUserAccessDenied — MXAccess did not authenticate " +
|
||||
"Galaxy user {GalaxyUser} ({Code}, native 0x{Hresult:X8}: {Message})",
|
||||
request.FullReference, credential.DisplayName, authReply.ProtocolStatus?.Code, authReply.Hresult,
|
||||
GatewayGalaxyAlarmAcknowledger.Scrub(authReply.ProtocolStatus?.Message ?? authReply.DiagnosticMessage, password));
|
||||
return new WriteResult(StatusCodeMap.BadUserAccessDenied);
|
||||
}
|
||||
|
||||
var writeReply = await ops.InvokeAsync(new MxCommandRequest
|
||||
{
|
||||
SessionId = ops.SessionId,
|
||||
ClientCorrelationId = Guid.NewGuid().ToString("N"),
|
||||
Command = new MxCommand
|
||||
{
|
||||
Kind = MxCommandKind.WriteSecured,
|
||||
WriteSecured = new WriteSecuredCommand
|
||||
{
|
||||
ServerHandle = ops.ServerHandle,
|
||||
ItemHandle = itemHandle,
|
||||
CurrentUserId = userId,
|
||||
VerifierUserId = 0,
|
||||
Value = mxValue,
|
||||
},
|
||||
},
|
||||
}, ct).ConfigureAwait(false);
|
||||
|
||||
return TranslateReply(writeReply, request.FullReference);
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"GalaxyDriver secured write rejected — unsupported value type for {FullRef} ({ExceptionType})",
|
||||
request.FullReference, ex.GetType().Name);
|
||||
return new WriteResult(StatusCodeMap.BadInternalError);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
|
||||
catch (Exception ex) when (IsCallerRefused(ex))
|
||||
{
|
||||
// The gateway refused the CALLER — typically the driver's API key lacks invoke:secure.
|
||||
_logger.LogWarning(
|
||||
"GalaxyDriver secured write to {FullRef} refused by the gateway ({Reason}) — BadUserAccessDenied. " +
|
||||
"Secured writes need the gateway key to hold the invoke:secure scope.",
|
||||
request.FullReference, ((RpcException)UnwrapRpc(ex)!).StatusCode);
|
||||
return new WriteResult(StatusCodeMap.BadUserAccessDenied);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Type + scrubbed message only: an exception on this path could carry the AuthenticateUser request.
|
||||
_logger.LogWarning(
|
||||
"GalaxyDriver secured write failed for {FullRef} ({ExceptionType}: {Message})",
|
||||
request.FullReference, ex.GetType().Name, GatewayGalaxyAlarmAcknowledger.Scrub(ex.Message, password));
|
||||
return new WriteResult(StatusCodeMap.BadCommunicationError);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<int> EnsureSecuredItemHandleAsync(IMxWriteOps ops, string fullRef, CancellationToken ct)
|
||||
{
|
||||
if (_securedItemHandles.TryGetValue(fullRef, out var existing)) return existing;
|
||||
var handle = await ops.AddItemAsync(fullRef, ct).ConfigureAwait(false);
|
||||
Interlocked.Increment(ref _addItemCallCount);
|
||||
_securedItemHandles[fullRef] = handle;
|
||||
return handle;
|
||||
}
|
||||
|
||||
/// <summary>Plain-advise the secured path's handle once per session (MXAccess refuses writes to an unadvised
|
||||
/// item). <c>false</c> = the advise failed and the write must fail closed.</summary>
|
||||
private async Task<bool> EnsurePlainAdvisedAsync(IMxWriteOps ops, int itemHandle, CancellationToken ct)
|
||||
{
|
||||
if (!_securedAdvisedHandles.TryAdd(itemHandle, 0)) return true;
|
||||
|
||||
MxCommandReply reply;
|
||||
try
|
||||
{
|
||||
reply = await ops.InvokeAsync(new MxCommandRequest
|
||||
{
|
||||
SessionId = ops.SessionId,
|
||||
ClientCorrelationId = Guid.NewGuid().ToString("N"),
|
||||
Command = new MxCommand
|
||||
{
|
||||
Kind = MxCommandKind.Advise,
|
||||
Advise = new AdviseCommand { ServerHandle = ops.ServerHandle, ItemHandle = itemHandle },
|
||||
},
|
||||
}, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_securedAdvisedHandles.TryRemove(itemHandle, out _);
|
||||
throw;
|
||||
}
|
||||
|
||||
if (reply.ProtocolStatus is { } proto && proto.Code != ProtocolStatusCode.Ok)
|
||||
{
|
||||
_securedAdvisedHandles.TryRemove(itemHandle, out _);
|
||||
_logger.LogWarning(
|
||||
"GalaxyDriver advise for a secured write failed for item {ItemHandle}: {Code} {Message}",
|
||||
itemHandle, proto.Code, proto.Message);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Whether <paramref name="ex"/> (or an inner exception) is the gateway refusing the caller.</summary>
|
||||
internal static bool IsCallerRefused(Exception ex) =>
|
||||
|
||||
@@ -15,4 +15,15 @@ internal interface IGalaxyAckCredentialResolver
|
||||
/// <param name="cancellationToken">Cancels secret resolution.</param>
|
||||
/// <returns>The resolved credential or the refusal reason.</returns>
|
||||
Task<GalaxyAckCredentialResolution> ResolveAsync(string? apiKeyId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// #1017 — the identity a SECURED WRITE from <paramref name="apiKeyId"/> runs as: the key's own Galaxy
|
||||
/// identity only. Unlike <see cref="ResolveAsync"/> there is NO fallback account — an anonymous session or a
|
||||
/// key without (or with a broken) identity is refused, so a secured write is never attributed to a shared
|
||||
/// account. Never throws for a missing or unreadable credential.
|
||||
/// </summary>
|
||||
/// <param name="apiKeyId">The authenticating API key id, or null (anonymous).</param>
|
||||
/// <param name="cancellationToken">Cancels secret resolution.</param>
|
||||
/// <returns>The resolved credential or the refusal reason.</returns>
|
||||
Task<GalaxyAckCredentialResolution> ResolveKeyIdentityAsync(string? apiKeyId, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
@@ -4,9 +4,9 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
|
||||
|
||||
/// <summary>
|
||||
/// Driver-side seam for batched writes. Production implementation decides by
|
||||
/// <see cref="SecurityClassification"/>: SecuredWrite / VerifiedWrite are refused
|
||||
/// <c>BadUserAccessDenied</c> (no ArchestrA identity to write them under — #991 review G-1),
|
||||
/// everything else goes supervisory-advise + raw <c>Write</c>. Tests substitute a fake to record routing
|
||||
/// <see cref="SecurityClassification"/>: SecuredWrite goes <c>AuthenticateUser</c> + <c>WriteSecured</c> under the
|
||||
/// caller's Galaxy identity when one is supplied (#1017) and is otherwise refused <c>BadUserAccessDenied</c>
|
||||
/// (#991 review G-1); VerifiedWrite is always refused; everything else goes supervisory-advise + raw <c>Write</c>. Tests substitute a fake to record routing
|
||||
/// decisions without touching real gw infrastructure.
|
||||
/// </summary>
|
||||
public interface IGalaxyDataWriter
|
||||
@@ -31,6 +31,24 @@ public interface IGalaxyDataWriter
|
||||
Func<string, SecurityClassification> securityResolver,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// #1017 — <see cref="WriteAsync(IReadOnlyList{WriteRequest}, Func{string, SecurityClassification}, CancellationToken)"/>
|
||||
/// with the CALLER's Galaxy identity for SecuredWrite tags: <paramref name="securedCredential"/> resolves it
|
||||
/// (at most once per batch, only when a SecuredWrite tag is present); null = no identity (secured writes refused).
|
||||
/// VerifiedWrite is refused either way. The default implementation ignores the identity (refuses).
|
||||
/// </summary>
|
||||
/// <param name="writes">Pairs of full reference + value to write.</param>
|
||||
/// <param name="securityResolver">Per-tag classification resolver.</param>
|
||||
/// <param name="securedCredential">The caller's Galaxy identity source, or null.</param>
|
||||
/// <param name="cancellationToken">Aborts the in-flight batch.</param>
|
||||
/// <returns>One <see cref="WriteResult"/> per request entry, in input order.</returns>
|
||||
internal Task<IReadOnlyList<WriteResult>> WriteAsync(
|
||||
IReadOnlyList<WriteRequest> writes,
|
||||
Func<string, SecurityClassification> securityResolver,
|
||||
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential,
|
||||
CancellationToken cancellationToken)
|
||||
=> WriteAsync(writes, securityResolver, cancellationToken);
|
||||
|
||||
/// <summary>Drop cached gateway item handles + supervisory-advise state. Call after a session
|
||||
/// reconnect — the prior handles are dead, so the next write must re-AddItem + re-AdviseSupervisory.</summary>
|
||||
void InvalidateHandleCaches();
|
||||
|
||||
@@ -14,10 +14,25 @@ internal sealed class TracedGalaxyDataWriter(IGalaxyDataWriter inner, string cli
|
||||
public void InvalidateHandleCaches() => inner.InvalidateHandleCaches();
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<WriteResult>> WriteAsync(
|
||||
public Task<IReadOnlyList<WriteResult>> WriteAsync(
|
||||
IReadOnlyList<WriteRequest> writes,
|
||||
Func<string, SecurityClassification> securityResolver,
|
||||
CancellationToken cancellationToken)
|
||||
=> TraceAsync(writes, securityResolver, () => inner.WriteAsync(writes, securityResolver, cancellationToken));
|
||||
|
||||
/// <inheritdoc />
|
||||
Task<IReadOnlyList<WriteResult>> IGalaxyDataWriter.WriteAsync(
|
||||
IReadOnlyList<WriteRequest> writes,
|
||||
Func<string, SecurityClassification> securityResolver,
|
||||
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential,
|
||||
CancellationToken cancellationToken)
|
||||
=> TraceAsync(writes, securityResolver,
|
||||
() => inner.WriteAsync(writes, securityResolver, securedCredential, cancellationToken));
|
||||
|
||||
private async Task<IReadOnlyList<WriteResult>> TraceAsync(
|
||||
IReadOnlyList<WriteRequest> writes,
|
||||
Func<string, SecurityClassification> securityResolver,
|
||||
Func<Task<IReadOnlyList<WriteResult>>> write)
|
||||
{
|
||||
using var activity = GalaxyTelemetry.ActivitySource.StartActivity("galaxy.write");
|
||||
activity?.SetTag("galaxy.client", clientName);
|
||||
@@ -44,8 +59,7 @@ internal sealed class TracedGalaxyDataWriter(IGalaxyDataWriter inner, string cli
|
||||
|
||||
try
|
||||
{
|
||||
var results = await inner.WriteAsync(writes, securityResolver, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
var results = await write().ConfigureAwait(false);
|
||||
activity?.SetTag("galaxy.success_count", results.Count(r => r.StatusCode < 0x80000000u));
|
||||
return results;
|
||||
}
|
||||
|
||||
@@ -35,6 +35,19 @@ public interface IApiKeyGalaxyAckIdentityService
|
||||
/// <returns>A task representing the operation.</returns>
|
||||
Task SetAsync(string apiKeyId, string user, string? domain, string? password, string actor, CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// Sets (or replaces) a key's Galaxy ack identity with an EMPTY password (#1050). Galaxy accounts can have
|
||||
/// empty passwords, but <see cref="SetAsync"/> reads a blank password as "keep the stored one" (and refuses it
|
||||
/// first time), so storing an empty password needs this explicit call.
|
||||
/// </summary>
|
||||
/// <param name="apiKeyId">The public key id.</param>
|
||||
/// <param name="user">Galaxy user; required.</param>
|
||||
/// <param name="domain">Optional domain.</param>
|
||||
/// <param name="actor">The admin performing the change, for audit.</param>
|
||||
/// <param name="ct">The cancellation token.</param>
|
||||
/// <returns>A task representing the operation.</returns>
|
||||
Task SetWithEmptyPasswordAsync(string apiKeyId, string user, string? domain, string actor, CancellationToken ct);
|
||||
|
||||
/// <summary>Removes a key's Galaxy ack identity (no-op when none).</summary>
|
||||
/// <param name="apiKeyId">The public key id.</param>
|
||||
/// <param name="actor">The admin performing the change, for audit.</param>
|
||||
@@ -97,8 +110,16 @@ public sealed class ApiKeyGalaxyAckIdentityService : IApiKeyGalaxyAckIdentitySer
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task SetAsync(
|
||||
public Task SetAsync(
|
||||
string apiKeyId, string user, string? domain, string? password, string actor, CancellationToken ct)
|
||||
=> SetCoreAsync(apiKeyId, user, domain, password, emptyPassword: false, actor, ct);
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task SetWithEmptyPasswordAsync(string apiKeyId, string user, string? domain, string actor, CancellationToken ct)
|
||||
=> SetCoreAsync(apiKeyId, user, domain, password: null, emptyPassword: true, actor, ct);
|
||||
|
||||
private async Task SetCoreAsync(
|
||||
string apiKeyId, string user, string? domain, string? password, bool emptyPassword, string actor, CancellationToken ct)
|
||||
{
|
||||
user = (user ?? string.Empty).Trim();
|
||||
if (user.Length == 0) throw new ArgumentException("A Galaxy user is required.", nameof(user));
|
||||
@@ -108,14 +129,23 @@ public sealed class ApiKeyGalaxyAckIdentityService : IApiKeyGalaxyAckIdentitySer
|
||||
var userName = new SecretName(GalaxyAckIdentitySecrets.UserSecretName(apiKeyId));
|
||||
var passwordName = new SecretName(GalaxyAckIdentitySecrets.PasswordSecretName(apiKeyId));
|
||||
|
||||
if (string.IsNullOrEmpty(password))
|
||||
if (emptyPassword)
|
||||
{
|
||||
// #1050: the explicit "this account has an empty password" option. Written like any new password —
|
||||
// password FIRST, so a concurrent ack never pairs the new user with a missing password.
|
||||
await UpsertAsync(passwordName, string.Empty, $"Galaxy ack password (empty) for API key {apiKeyId}", actor, ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
else if (string.IsNullOrEmpty(password))
|
||||
{
|
||||
// The editor never renders a stored password back, so a blank box means "keep the current one" -
|
||||
// overwriting it with an empty value would silently break every ack on this key (#997 A-4). With no
|
||||
// existing identity there is nothing to keep, so a blank password is refused instead (as is a half-configured identity whose password secret is gone).
|
||||
var existing = await _store.GetAsync(passwordName, ct).ConfigureAwait(false);
|
||||
if (existing is null || existing.IsDeleted)
|
||||
throw new ArgumentException("A password is required when setting a Galaxy ack identity.", nameof(password));
|
||||
throw new ArgumentException(
|
||||
"A password is required when setting a Galaxy ack identity (for an account whose password is empty, " +
|
||||
"tick \"Empty password\").", nameof(password));
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
@@ -64,6 +64,8 @@
|
||||
the Historian records it as the operator. Stored encrypted in the Secrets store
|
||||
(<span class="mono">otopcua/apikeys/@(_ackEditKeyId)/galaxy-ack-*</span>), never in the database. Keys
|
||||
without an identity use the Galaxy driver's fallback account; with neither, acknowledges are refused.
|
||||
A Galaxy driver set to <em>Secured writes = API key identity</em> also writes <code>SecuredWrite</code>
|
||||
attributes as this account (#1017) — with no fallback: a key without an identity cannot make secured writes.
|
||||
On a split admin/driver topology the two secrets must also exist on the driver nodes.
|
||||
</div>
|
||||
<div class="row g-2">
|
||||
@@ -78,8 +80,13 @@
|
||||
<div class="col-md-3">
|
||||
<label class="form-label" for="ack-password">Password</label>
|
||||
<input id="ack-password" type="password" class="form-control form-control-sm" @bind="_ackPassword"
|
||||
placeholder="@(_ackIdentities.ContainsKey(_ackEditKeyId) ? "leave blank to keep the current password" : null)"
|
||||
autocomplete="new-password" />
|
||||
placeholder="@(_ackEmptyPassword ? "(empty password)" : _ackIdentities.ContainsKey(_ackEditKeyId) ? "leave blank to keep the current password" : null)"
|
||||
disabled="@_ackEmptyPassword" autocomplete="new-password" />
|
||||
<div class="form-check mt-1">
|
||||
<input id="ack-empty-password" type="checkbox" class="form-check-input" @bind="_ackEmptyPassword" @bind:after="OnAckEmptyPasswordChanged" />
|
||||
<label class="form-check-label" for="ack-empty-password">Empty password</label>
|
||||
</div>
|
||||
<div class="form-text">The account's password is genuinely empty (a blank box keeps the stored password).</div>
|
||||
</div>
|
||||
<div class="col-md-3 d-flex align-items-end gap-2">
|
||||
<button class="btn btn-sm btn-primary" @onclick="SaveAckIdentityAsync" disabled="@_busy">Save</button>
|
||||
@@ -191,6 +198,8 @@
|
||||
private string _ackUser = "";
|
||||
private string _ackDomain = "";
|
||||
private string _ackPassword = "";
|
||||
// #1050: explicit "the account's password is empty" — a blank box alone means "keep the stored password".
|
||||
private bool _ackEmptyPassword;
|
||||
private string _newName = "";
|
||||
private string _newPrincipal = "";
|
||||
private DateTime? _newExpires;
|
||||
@@ -320,6 +329,7 @@
|
||||
{
|
||||
_ackEditKeyId = apiKeyId;
|
||||
_ackPassword = "";
|
||||
_ackEmptyPassword = false;
|
||||
if (_ackIdentities.TryGetValue(apiKeyId, out var current))
|
||||
{
|
||||
var slash = current.IndexOf('\\');
|
||||
@@ -339,6 +349,13 @@
|
||||
_ackUser = "";
|
||||
_ackDomain = "";
|
||||
_ackPassword = "";
|
||||
_ackEmptyPassword = false;
|
||||
}
|
||||
|
||||
// A typed password and "Empty password" are mutually exclusive: ticking the box discards what was typed.
|
||||
private void OnAckEmptyPasswordChanged()
|
||||
{
|
||||
if (_ackEmptyPassword) _ackPassword = "";
|
||||
}
|
||||
|
||||
private async Task SaveAckIdentityAsync()
|
||||
@@ -348,7 +365,10 @@
|
||||
_error = null;
|
||||
try
|
||||
{
|
||||
await AckIdentities.SetAsync(id, _ackUser, _ackDomain, _ackPassword, await ActorAsync(), default);
|
||||
if (_ackEmptyPassword)
|
||||
await AckIdentities.SetWithEmptyPasswordAsync(id, _ackUser, _ackDomain, await ActorAsync(), default);
|
||||
else
|
||||
await AckIdentities.SetAsync(id, _ackUser, _ackDomain, _ackPassword, await ActorAsync(), default);
|
||||
CloseAckEditor();
|
||||
await ReloadAsync();
|
||||
}
|
||||
|
||||
+71
-3
@@ -53,6 +53,18 @@
|
||||
<div id="@FieldId("field-07-error")" class="field-error">@if (_fieldEditContext is not null) { <ValidationMessage For="@(() => _form.Galaxy.GatewayStreamTimeoutSeconds)" /> }</div>
|
||||
<div id="@FieldId("field-07-hint")" class="form-text">Default 0 (lifetime of driver).</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label for="@FieldId("field-07a")" class="form-label">Keep-alive ping delay (s)</label>
|
||||
<InputNumber DisplayName="Keep-alive ping delay (s)" aria-describedby="@FieldIds("field-07a-error", "field-07a-hint")" id="@FieldId("field-07a")" @bind-Value="_form.Galaxy.GatewayKeepAlivePingDelaySeconds" @bind-Value:after="EmitAsync" min="0" class="form-control form-control-sm" />
|
||||
<div id="@FieldId("field-07a-error")" class="field-error">@if (_fieldEditContext is not null) { <ValidationMessage For="@(() => _form.Galaxy.GatewayKeepAlivePingDelaySeconds)" /> }</div>
|
||||
<div id="@FieldId("field-07a-hint")" class="form-text">HTTP/2 PING interval on every gateway channel, so a silently dead connection faults the event stream (#991). Default 15; 0 = no pings.</div>
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label for="@FieldId("field-07b")" class="form-label">Keep-alive ping timeout (s)</label>
|
||||
<InputNumber DisplayName="Keep-alive ping timeout (s)" aria-describedby="@FieldIds("field-07b-error", "field-07b-hint")" id="@FieldId("field-07b")" @bind-Value="_form.Galaxy.GatewayKeepAlivePingTimeoutSeconds" @bind-Value:after="EmitAsync" min="0" class="form-control form-control-sm" />
|
||||
<div id="@FieldId("field-07b-error")" class="field-error">@if (_fieldEditContext is not null) { <ValidationMessage For="@(() => _form.Galaxy.GatewayKeepAlivePingTimeoutSeconds)" /> }</div>
|
||||
<div id="@FieldId("field-07b-hint")" class="form-text">How long an unanswered PING may wait before the connection is failed. Default 10.</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -86,6 +98,20 @@
|
||||
<div id="@FieldId("field-11-error")" class="field-error">@if (_fieldEditContext is not null) { <ValidationMessage For="@(() => _form.Galaxy.MxEventPumpChannelCapacity)" /> }</div>
|
||||
<div id="@FieldId("field-11-hint")" class="form-text">Default 50000. Raise if events.dropped appears.</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label for="@FieldId("field-11a")" class="form-label">Secured writes</label>
|
||||
<InputSelect aria-describedby="@FieldIds("field-11a-hint")" id="@FieldId("field-11a")" @bind-Value="_form.Galaxy.MxSecuredWrites" @bind-Value:after="EmitAsync" class="form-select form-select-sm">
|
||||
<option value="@GalaxySecuredWriteMode.Refuse">Refuse (default)</option>
|
||||
<option value="@GalaxySecuredWriteMode.ApiKeyIdentity">Write as the calling API key's Galaxy identity</option>
|
||||
</InputSelect>
|
||||
<div id="@FieldId("field-11a-hint")" class="form-text">
|
||||
How a write to a <code>SecuredWrite</code> attribute is handled (#1017). <em>Refuse</em> answers
|
||||
<code>BadUserAccessDenied</code>. <em>API key identity</em> authenticates as the Galaxy account mapped to the
|
||||
session's key on <a href="/apikeys">API keys</a> and issues <code>WriteSecured</code>; anonymous sessions and keys
|
||||
without an identity are refused (no fallback account). The gateway key needs <code>invoke:secure</code>.
|
||||
<code>VerifiedWrite</code> attributes are always refused.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -213,6 +239,26 @@
|
||||
|
||||
private FormModel _form = new();
|
||||
private string? _lastParsed;
|
||||
// The stored config as loaded (then as last emitted), so keys the form does not model survive a save (#1045).
|
||||
private string? _originalJson;
|
||||
|
||||
/// <summary>
|
||||
/// The DriverConfig paths this form edits (#1045). Everything else in the stored JSON — a newer option, a
|
||||
/// hand-edited key, <c>rawTags</c> — is carried through a save untouched by <see cref="DriverConfigJsonOverlay"/>.
|
||||
/// A new form field MUST add its path here, or its edits are discarded on save.
|
||||
/// </summary>
|
||||
internal static readonly string[] OwnedPaths =
|
||||
[
|
||||
"gateway.endpoint", "gateway.apiKeySecretRef", "gateway.useTls", "gateway.caCertificatePath",
|
||||
"gateway.connectTimeoutSeconds", "gateway.defaultCallTimeoutSeconds", "gateway.streamTimeoutSeconds",
|
||||
"gateway.keepAlivePingDelaySeconds", "gateway.keepAlivePingTimeoutSeconds",
|
||||
"mxAccess.clientName", "mxAccess.publishingIntervalMs", "mxAccess.writeUserId", "mxAccess.eventPumpChannelCapacity",
|
||||
"mxAccess.securedWrites",
|
||||
"repository.discoverPageSize", "repository.watchDeployEvents",
|
||||
"reconnect.initialBackoffMs", "reconnect.maxBackoffMs", "reconnect.replayOnSessionLost",
|
||||
"probeTimeoutSeconds",
|
||||
"alarmAck.fallbackUser", "alarmAck.fallbackDomain", "alarmAck.fallbackPasswordSecretRef", "alarmAck.confirmTimeoutMs",
|
||||
];
|
||||
|
||||
protected override void OnParametersSet()
|
||||
{
|
||||
@@ -220,17 +266,26 @@
|
||||
{
|
||||
var opts = TryDeserialize(DriverConfigJson) ?? CreateDefaultOptions();
|
||||
_form = new FormModel { Galaxy = GalaxyFormModel.FromRecord(opts) };
|
||||
_originalJson = DriverConfigJson;
|
||||
_lastParsed = DriverConfigJson;
|
||||
}
|
||||
}
|
||||
|
||||
public string GetConfigJson()
|
||||
=> JsonSerializer.Serialize(_form.Galaxy.ToRecord(), _jsonOpts);
|
||||
=> Serialize(_form.Galaxy.ToRecord(), _originalJson);
|
||||
|
||||
/// <summary>Serializes <paramref name="options"/> and overlays the form-owned paths onto <paramref name="originalJson"/>.</summary>
|
||||
/// <param name="options">The form's options.</param>
|
||||
/// <param name="originalJson">The stored config, so unmodelled keys survive (#1045); null/blank = the typed JSON alone.</param>
|
||||
/// <returns>The DriverConfig JSON to save.</returns>
|
||||
internal static string Serialize(GalaxyDriverOptions options, string? originalJson)
|
||||
=> DriverConfigJsonOverlay.Apply(originalJson, JsonSerializer.Serialize(options, _jsonOpts), OwnedPaths);
|
||||
|
||||
private async Task EmitAsync()
|
||||
{
|
||||
var json = GetConfigJson();
|
||||
_lastParsed = json;
|
||||
_originalJson = json;
|
||||
await DriverConfigJsonChanged.InvokeAsync(json);
|
||||
}
|
||||
|
||||
@@ -268,12 +323,17 @@
|
||||
public int GatewayConnectTimeoutSeconds { get; set; } = 10;
|
||||
public int GatewayDefaultCallTimeoutSeconds { get; set; } = 30;
|
||||
public int GatewayStreamTimeoutSeconds { get; set; } = 0;
|
||||
[System.ComponentModel.DataAnnotations.Range(0, int.MaxValue, ErrorMessage = "Must be 0 (no pings) or more.")]
|
||||
public int GatewayKeepAlivePingDelaySeconds { get; set; } = 15;
|
||||
[System.ComponentModel.DataAnnotations.Range(0, int.MaxValue, ErrorMessage = "Must be 0 or more.")]
|
||||
public int GatewayKeepAlivePingTimeoutSeconds { get; set; } = 10;
|
||||
|
||||
// GalaxyMxAccessOptions
|
||||
public string MxClientName { get; set; } = "OtOpcUa";
|
||||
public int MxPublishingIntervalMs { get; set; } = 1000;
|
||||
public int MxWriteUserId { get; set; } = 0;
|
||||
public int MxEventPumpChannelCapacity { get; set; } = 50_000;
|
||||
public GalaxySecuredWriteMode MxSecuredWrites { get; set; } = GalaxySecuredWriteMode.Refuse;
|
||||
|
||||
// GalaxyRepositoryOptions
|
||||
public int RepositoryDiscoverPageSize { get; set; } = 5000;
|
||||
@@ -309,10 +369,13 @@
|
||||
GatewayConnectTimeoutSeconds = gw.ConnectTimeoutSeconds,
|
||||
GatewayDefaultCallTimeoutSeconds = gw.DefaultCallTimeoutSeconds,
|
||||
GatewayStreamTimeoutSeconds = gw.StreamTimeoutSeconds,
|
||||
GatewayKeepAlivePingDelaySeconds = gw.KeepAlivePingDelaySeconds,
|
||||
GatewayKeepAlivePingTimeoutSeconds = gw.KeepAlivePingTimeoutSeconds,
|
||||
MxClientName = mx.ClientName,
|
||||
MxPublishingIntervalMs = mx.PublishingIntervalMs,
|
||||
MxWriteUserId = mx.WriteUserId,
|
||||
MxEventPumpChannelCapacity = mx.EventPumpChannelCapacity,
|
||||
MxSecuredWrites = mx.SecuredWrites,
|
||||
RepositoryDiscoverPageSize = repo.DiscoverPageSize,
|
||||
RepositoryWatchDeployEvents = repo.WatchDeployEvents,
|
||||
ReconnectInitialBackoffMs = rc.InitialBackoffMs,
|
||||
@@ -334,12 +397,17 @@
|
||||
CaCertificatePath: string.IsNullOrWhiteSpace(GatewayCaCertificatePath) ? null : GatewayCaCertificatePath,
|
||||
ConnectTimeoutSeconds: GatewayConnectTimeoutSeconds,
|
||||
DefaultCallTimeoutSeconds: GatewayDefaultCallTimeoutSeconds,
|
||||
StreamTimeoutSeconds: GatewayStreamTimeoutSeconds),
|
||||
StreamTimeoutSeconds: GatewayStreamTimeoutSeconds,
|
||||
KeepAlivePingDelaySeconds: GatewayKeepAlivePingDelaySeconds,
|
||||
KeepAlivePingTimeoutSeconds: GatewayKeepAlivePingTimeoutSeconds),
|
||||
MxAccess: new GalaxyMxAccessOptions(
|
||||
ClientName: MxClientName,
|
||||
PublishingIntervalMs: MxPublishingIntervalMs,
|
||||
WriteUserId: MxWriteUserId,
|
||||
EventPumpChannelCapacity: MxEventPumpChannelCapacity),
|
||||
EventPumpChannelCapacity: MxEventPumpChannelCapacity)
|
||||
{
|
||||
SecuredWrites = MxSecuredWrites,
|
||||
},
|
||||
Repository: new GalaxyRepositoryOptions(
|
||||
DiscoverPageSize: RepositoryDiscoverPageSize,
|
||||
WatchDeployEvents: RepositoryWatchDeployEvents),
|
||||
|
||||
@@ -3557,7 +3557,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
var clientUserId = identity is { Principal.Length: > 0 } ? identity.Principal : identity?.DisplayName;
|
||||
|
||||
return DispatchDeviceWrite(gateway, nodeKey, nodeBareId, nodeRealm, optimisticValue, priorValue, priorStatus, clientUserId,
|
||||
(node as EquipmentVariableState)?.ActiveWriteStamp);
|
||||
(node as EquipmentVariableState)?.ActiveWriteStamp,
|
||||
// #1017: WHO wrote rides to the driver, so a per-user device permission (Galaxy SecuredWrite) can act on it.
|
||||
identity is null ? null : new WriteCaller(identity.Principal.Length > 0 ? identity.Principal : null, identity.ApiKeyId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -3578,12 +3580,14 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
internal ServiceResult DispatchDeviceWrite(
|
||||
IOpcUaNodeWriteGateway gateway, string nodeKey, string nodeBareId, AddressSpaceRealm nodeRealm,
|
||||
object? optimisticValue, object? priorValue, StatusCode priorStatus, string? clientUserId,
|
||||
EquipmentVariableState.WriteStamp? writeStamp = null)
|
||||
EquipmentVariableState.WriteStamp? writeStamp = null, WriteCaller? caller = null)
|
||||
{
|
||||
Task<NodeWriteOutcome> dispatch;
|
||||
try
|
||||
{
|
||||
dispatch = gateway.WriteAsync(nodeKey, optimisticValue, nodeRealm, CancellationToken.None);
|
||||
dispatch = caller is null
|
||||
? gateway.WriteAsync(nodeKey, optimisticValue, nodeRealm, CancellationToken.None)
|
||||
: gateway.WriteAsync(nodeKey, optimisticValue, nodeRealm, caller, CancellationToken.None);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using Akka.Actor;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
||||
|
||||
@@ -44,7 +45,12 @@ public sealed class ActorNodeWriteGateway : IOpcUaNodeWriteGateway
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<NodeWriteOutcome> WriteAsync(string nodeId, object? value, AddressSpaceRealm realm, CancellationToken ct)
|
||||
public Task<NodeWriteOutcome> WriteAsync(string nodeId, object? value, AddressSpaceRealm realm, CancellationToken ct)
|
||||
=> WriteAsync(nodeId, value, realm, caller: null, ct);
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<NodeWriteOutcome> WriteAsync(
|
||||
string nodeId, object? value, AddressSpaceRealm realm, WriteCaller? caller, CancellationToken ct)
|
||||
{
|
||||
var driverHost = _resolveDriverHost();
|
||||
if (driverHost is null)
|
||||
@@ -56,7 +62,7 @@ public sealed class ActorNodeWriteGateway : IOpcUaNodeWriteGateway
|
||||
try
|
||||
{
|
||||
var result = await driverHost.Ask<DriverHostActor.NodeWriteResult>(
|
||||
new DriverHostActor.RouteNodeWrite(nodeId, value, realm), _askTimeout, ct).ConfigureAwait(false);
|
||||
new DriverHostActor.RouteNodeWrite(nodeId, value, realm, caller), _askTimeout, ct).ConfigureAwait(false);
|
||||
if (!result.Success)
|
||||
_logger.LogWarning("Operator write to {NodeId} rejected: {Reason}", nodeId, result.Reason);
|
||||
return new NodeWriteOutcome(result.Success, result.Reason);
|
||||
|
||||
@@ -695,7 +695,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
/// </summary>
|
||||
/// <param name="NodeId">The folder-scoped equipment-variable NodeId the operator wrote to.</param>
|
||||
/// <param name="Value">The value to write (the driver coerces it to the attribute's data type).</param>
|
||||
public sealed record RouteNodeWrite(string NodeId, object? Value, AddressSpaceRealm Realm);
|
||||
public sealed record RouteNodeWrite(string NodeId, object? Value, AddressSpaceRealm Realm, WriteCaller? Caller = null);
|
||||
|
||||
/// <summary>Reply to <see cref="RouteNodeWrite"/>: the outcome of forwarding the write to the driver
|
||||
/// (or a gate/lookup failure that never reached the driver).</summary>
|
||||
@@ -2613,7 +2613,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
|
||||
var replyTo = Sender;
|
||||
var askDeadline = new CancellationTokenSource(_writeBounds.HostAsk, _writeClock);
|
||||
entry.Actor.Ask<DriverInstanceActor.WriteAttributeResult>(
|
||||
new DriverInstanceActor.WriteAttribute(target.RawPath, msg.Value!, _writeClock.GetTimestamp()),
|
||||
new DriverInstanceActor.WriteAttribute(target.RawPath, msg.Value!, _writeClock.GetTimestamp(), msg.Caller),
|
||||
System.Threading.Timeout.InfiniteTimeSpan,
|
||||
askDeadline.Token)
|
||||
.ContinueWith(
|
||||
|
||||
@@ -136,7 +136,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
/// stamps it so the time the write spends in this actor's MAILBOX counts against the queue budget too: a write
|
||||
/// delayed there (behind a hanging alarm subscribe, say) and then started could otherwise still be running
|
||||
/// when the host's Ask fires (lmxopcua#777).</param>
|
||||
public sealed record WriteAttribute(string TagId, object Value, long? IssuedAt = null);
|
||||
public sealed record WriteAttribute(string TagId, object Value, long? IssuedAt = null, WriteCaller? Caller = null);
|
||||
public sealed record WriteAttributeResult(bool Success, string? Reason);
|
||||
internal sealed record WriteAttributeWithOutcome(WriteAdmissionTicket Ticket, WriteClaim Claim);
|
||||
/// <summary>
|
||||
@@ -1669,7 +1669,11 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
|
||||
var attempt = invoker.ExecuteWriteAsync(
|
||||
hostKey,
|
||||
isIdempotent: false,
|
||||
async ct => await writable.WriteAsync(request, ct),
|
||||
// #1017: a write that carries its caller reaches a driver that can act on it (the Galaxy driver's
|
||||
// SecuredWrite attributes) through ICallerAwareWritable; every other driver/write is unchanged.
|
||||
async ct => msg.Caller is { } caller && writable is ICallerAwareWritable callerAware
|
||||
? await callerAware.WriteAsync(request, caller, ct)
|
||||
: await writable.WriteAsync(request, ct),
|
||||
cts.Token).AsTask();
|
||||
IReadOnlyList<WriteResult> results;
|
||||
try
|
||||
|
||||
@@ -202,4 +202,28 @@ public class AlarmsCommandTests
|
||||
fakeService.DisconnectCalled.ShouldBeTrue();
|
||||
fakeService.DisposeCalled.ShouldBeTrue();
|
||||
}
|
||||
|
||||
/// <summary>#1048: an outage that outlasts --reconnect-timeout ends the alarm watch non-zero, with a WARNING.</summary>
|
||||
[Fact]
|
||||
public async Task Execute_ExitsNonZero_WhenTheConnectionNeverRecovers()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService();
|
||||
var command = new AlarmsCommand(new FakeOpcUaClientServiceFactory(fakeService))
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
ReconnectTimeoutSeconds = 1,
|
||||
};
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
var task = Task.Run(async () => { await command.ExecuteAsync(console); }, TestContext.Current.CancellationToken);
|
||||
await fakeService.SubscribeAlarmsInvoked.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
|
||||
|
||||
fakeService.RaiseConnectionStateChanged(Shared.Models.ConnectionState.Connected,
|
||||
Shared.Models.ConnectionState.Reconnecting, "opc.tcp://localhost:4840");
|
||||
|
||||
var ex = await Should.ThrowAsync<CliFx.Exceptions.CommandException>(
|
||||
() => task.WaitAsync(TimeSpan.FromSeconds(15), TestContext.Current.CancellationToken));
|
||||
ex.ExitCode.ShouldNotBe(0);
|
||||
TestConsoleHelper.GetOutput(console).ShouldContain("WARNING");
|
||||
fakeService.DisconnectCalled.ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using CliFx.Exceptions;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Client.CLI.Commands;
|
||||
@@ -139,4 +140,98 @@ public class SubscribeCommandTests
|
||||
output.ShouldContain("CONNECTION Connected -> Reconnecting (opc.tcp://localhost:4840)");
|
||||
output.ShouldContain("CONNECTION Reconnecting -> Connected (opc.tcp://backup:4840)");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #1048: a connection that stays out of Connected past --reconnect-timeout ends the run with a WARNING, the
|
||||
/// summary, and a non-zero exit — instead of waiting forever and reporting pre-outage values as final.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Execute_ExitsNonZero_WhenTheConnectionNeverRecovers()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService();
|
||||
var command = new SubscribeCommand(new FakeOpcUaClientServiceFactory(fakeService))
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
NodeId = "ns=2;s=TestVar",
|
||||
ReconnectTimeoutSeconds = 1,
|
||||
};
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
var task = Task.Run(async () => { await command.ExecuteAsync(console); }, TestContext.Current.CancellationToken);
|
||||
await fakeService.SubscribeInvoked.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
|
||||
|
||||
fakeService.RaiseConnectionStateChanged(Shared.Models.ConnectionState.Connected,
|
||||
Shared.Models.ConnectionState.Reconnecting, "opc.tcp://localhost:4840");
|
||||
|
||||
var ex = await Should.ThrowAsync<CommandException>(() => task.WaitAsync(TimeSpan.FromSeconds(15), TestContext.Current.CancellationToken));
|
||||
ex.ExitCode.ShouldNotBe(0);
|
||||
ex.Message.ShouldContain("did not recover within 1 s");
|
||||
var output = TestConsoleHelper.GetOutput(console);
|
||||
output.ShouldContain("WARNING");
|
||||
output.ShouldContain("==================== SUMMARY ====================");
|
||||
output.ShouldContain("Connection:");
|
||||
fakeService.DisconnectCalled.ShouldBeTrue();
|
||||
}
|
||||
|
||||
/// <summary>#1048 positive control: a recovery inside the window re-arms the watch and the run continues.</summary>
|
||||
[Fact]
|
||||
public async Task Execute_KeepsRunning_WhenTheConnectionRecoversInsideTheTimeout()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService();
|
||||
var command = new SubscribeCommand(new FakeOpcUaClientServiceFactory(fakeService))
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
NodeId = "ns=2;s=TestVar",
|
||||
ReconnectTimeoutSeconds = 2,
|
||||
};
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
var task = Task.Run(async () => { await command.ExecuteAsync(console); }, TestContext.Current.CancellationToken);
|
||||
await fakeService.SubscribeInvoked.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
|
||||
|
||||
fakeService.RaiseConnectionStateChanged(Shared.Models.ConnectionState.Connected,
|
||||
Shared.Models.ConnectionState.Reconnecting, "opc.tcp://localhost:4840");
|
||||
fakeService.RaiseConnectionStateChanged(Shared.Models.ConnectionState.Reconnecting,
|
||||
Shared.Models.ConnectionState.Connected, "opc.tcp://backup:4840");
|
||||
await Task.Delay(TimeSpan.FromSeconds(3), TestContext.Current.CancellationToken);
|
||||
|
||||
task.IsCompleted.ShouldBeFalse();
|
||||
console.RequestCancellation();
|
||||
await task; // a clean Ctrl+C exit: no exception
|
||||
TestConsoleHelper.GetOutput(console).ShouldNotContain("WARNING");
|
||||
}
|
||||
|
||||
/// <summary>#1048: the service landing Disconnected on its own is final — it will not retry — so exit at once.</summary>
|
||||
[Fact]
|
||||
public async Task Execute_ExitsNonZero_WhenTheServiceDisconnectsOnItsOwn()
|
||||
{
|
||||
var fakeService = new FakeOpcUaClientService();
|
||||
var command = new SubscribeCommand(new FakeOpcUaClientServiceFactory(fakeService))
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
NodeId = "ns=2;s=TestVar",
|
||||
ReconnectTimeoutSeconds = 0, // no time limit — Disconnected still ends the run
|
||||
};
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
var task = Task.Run(async () => { await command.ExecuteAsync(console); }, TestContext.Current.CancellationToken);
|
||||
await fakeService.SubscribeInvoked.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
|
||||
|
||||
fakeService.RaiseConnectionStateChanged(Shared.Models.ConnectionState.Reconnecting,
|
||||
Shared.Models.ConnectionState.Disconnected, "opc.tcp://localhost:4840");
|
||||
|
||||
var ex = await Should.ThrowAsync<CommandException>(() => task.WaitAsync(TimeSpan.FromSeconds(15), TestContext.Current.CancellationToken));
|
||||
ex.Message.ShouldContain("gave up");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Execute_RejectsNegativeReconnectTimeout()
|
||||
{
|
||||
var command = new SubscribeCommand(new FakeOpcUaClientServiceFactory(new FakeOpcUaClientService()))
|
||||
{
|
||||
Url = "opc.tcp://localhost:4840",
|
||||
NodeId = "ns=2;s=TestVar",
|
||||
ReconnectTimeoutSeconds = -1,
|
||||
};
|
||||
using var console = TestConsoleHelper.CreateConsole();
|
||||
var ex = await Should.ThrowAsync<CommandException>(async () => await command.ExecuteAsync(console));
|
||||
ex.Message.ShouldContain("--reconnect-timeout");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -217,6 +217,32 @@ public sealed class FakeOpcUaClientService : IOpcUaClientService
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>Number of batched <see cref="SubscribeManyAsync" /> calls (#1048).</summary>
|
||||
public int SubscribeManyCallCount { get; private set; }
|
||||
|
||||
/// <summary>The node lists each <see cref="SubscribeManyAsync" /> call carried, in call order.</summary>
|
||||
public List<List<string>> SubscribeManyBatches { get; } = [];
|
||||
|
||||
/// <summary>Nodes whose entry in a batch should come back as a per-node failure.</summary>
|
||||
public Dictionary<string, Exception> SubscribeManyNodeFailures { get; } = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>
|
||||
/// Batched subscribe (#1000 S-12 / #1048): one call for the whole set, a per-node failure for the nodes in
|
||||
/// <see cref="SubscribeManyNodeFailures" />, or <see cref="SubscribeException" /> for the whole batch.
|
||||
/// </summary>
|
||||
public Task<IReadOnlyList<Exception?>> SubscribeManyAsync(IReadOnlyList<NodeId> nodeIds, int intervalMs = 1000,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
SubscribeManyCallCount++;
|
||||
SubscribeManyBatches.Add(nodeIds.Select(n => n.ToString()).ToList());
|
||||
LastSubscribeIntervalMs = intervalMs;
|
||||
if (SubscribeException != null) throw SubscribeException;
|
||||
IReadOnlyList<Exception?> results = nodeIds
|
||||
.Select(n => SubscribeManyNodeFailures.TryGetValue(n.ToString(), out var ex) ? ex : null)
|
||||
.ToList();
|
||||
return Task.FromResult(results);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task UnsubscribeAsync(NodeId nodeId, CancellationToken ct = default)
|
||||
{
|
||||
|
||||
@@ -272,7 +272,10 @@ public class SubscriptionsViewModelTests
|
||||
await _vm.RestoreSubscriptionsAsync(["ns=2;s=A", "ns=2;s=B"]);
|
||||
|
||||
_vm.ActiveSubscriptions.Count.ShouldBe(2);
|
||||
_service.SubscribeCallCount.ShouldBe(2);
|
||||
// #1048: one batched round trip for the whole saved set.
|
||||
_service.SubscribeManyCallCount.ShouldBe(1);
|
||||
_service.SubscribeManyBatches[0].ShouldBe(["ns=2;s=A", "ns=2;s=B"]);
|
||||
_service.SubscribeCallCount.ShouldBe(0);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that ValidateAndWriteAsync returns true on successful write.</summary>
|
||||
@@ -359,7 +362,54 @@ public class SubscriptionsViewModelTests
|
||||
await _vm.AddSubscriptionRecursiveAsync("ns=2;s=Folder", "Object");
|
||||
|
||||
_vm.ActiveSubscriptions.Count.ShouldBe(2);
|
||||
_service.SubscribeCallCount.ShouldBe(2);
|
||||
// #1048: the whole collected set is one batched SubscribeManyAsync, not a round trip per node.
|
||||
_service.SubscribeManyCallCount.ShouldBe(1);
|
||||
_service.SubscribeManyBatches[0].ShouldBe(["ns=2;s=Child1", "ns=2;s=Child2"]);
|
||||
_service.SubscribeCallCount.ShouldBe(0);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #1048: a per-node rejection inside the batch adds only the nodes that subscribed and names the failure;
|
||||
/// nodes already subscribed and duplicates reached twice in the walk are not sent again.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task AddSubscriptionRecursiveAsync_BatchReportsPerNodeFailuresAndSkipsAlreadySubscribed()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
await _vm.AddSubscriptionForNodeAsync("ns=2;s=Already");
|
||||
_service.BrowseResultsByParent["ns=2;s=Root"] =
|
||||
[
|
||||
new BrowseResult("ns=2;s=Already", "Already", "Variable", false),
|
||||
new BrowseResult("ns=2;s=Good", "Good", "Variable", false),
|
||||
new BrowseResult("ns=2;s=Bad", "Bad", "Variable", false),
|
||||
new BrowseResult("ns=2;s=Sub", "Sub", "Object", true),
|
||||
];
|
||||
_service.BrowseResultsByParent["ns=2;s=Sub"] = [new BrowseResult("ns=2;s=Good", "Good", "Variable", false)];
|
||||
_service.SubscribeManyNodeFailures["ns=2;s=Bad"] = new Exception("BadNodeIdUnknown");
|
||||
|
||||
await _vm.AddSubscriptionRecursiveAsync("ns=2;s=Root", "Object");
|
||||
|
||||
_service.SubscribeManyBatches.ShouldHaveSingleItem().ShouldBe(["ns=2;s=Good", "ns=2;s=Bad"]);
|
||||
_vm.ActiveSubscriptions.Select(s => s.NodeId).ShouldBe(["ns=2;s=Already", "ns=2;s=Good"]);
|
||||
_vm.SubscriptionCount.ShouldBe(2);
|
||||
_vm.StatusMessage.ShouldNotBeNull();
|
||||
_vm.StatusMessage.ShouldContain("1 of 2");
|
||||
_vm.StatusMessage.ShouldContain("ns=2;s=Bad");
|
||||
_vm.StatusMessage.ShouldContain("BadNodeIdUnknown");
|
||||
}
|
||||
|
||||
/// <summary>#1048: a batch that fails as a whole adds nothing and surfaces the error.</summary>
|
||||
[Fact]
|
||||
public async Task AddSubscriptionRecursiveAsync_WholeBatchFailure_SurfacesStatusMessage()
|
||||
{
|
||||
_vm.IsConnected = true;
|
||||
_service.BrowseResultsByParent["ns=2;s=Root"] = [new BrowseResult("ns=2;s=V", "V", "Variable", false)];
|
||||
_service.SubscribeException = new Exception("session closed");
|
||||
|
||||
await _vm.AddSubscriptionRecursiveAsync("ns=2;s=Root", "Object");
|
||||
|
||||
_vm.ActiveSubscriptions.ShouldBeEmpty();
|
||||
_vm.StatusMessage.ShouldNotBeNull().ShouldContain("session closed");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime;
|
||||
|
||||
/// <summary>
|
||||
/// #1017 — the driver hands its writer the CALLER's Galaxy identity source only when
|
||||
/// <c>MxAccess.SecuredWrites = ApiKeyIdentity</c> AND the write carries a caller; the source resolves the key's
|
||||
/// own identity (<see cref="IGalaxyAckCredentialResolver.ResolveKeyIdentityAsync"/> — never the ack fallback).
|
||||
/// </summary>
|
||||
public sealed class GalaxyDriverSecuredWriteIdentityTests
|
||||
{
|
||||
private static GalaxyDriverOptions Opts(GalaxySecuredWriteMode mode) => new(
|
||||
new GalaxyGatewayOptions("https://mxgw.test:5001", "key"),
|
||||
new GalaxyMxAccessOptions("OtOpcUa-A") { SecuredWrites = mode },
|
||||
new GalaxyRepositoryOptions(WatchDeployEvents: false),
|
||||
new GalaxyReconnectOptions())
|
||||
{
|
||||
RawTags = [new RawTagEntry("Plant/Tank1/SP", """{"attributeRef":"Tank1.SP"}""", false)],
|
||||
};
|
||||
|
||||
private sealed class IdentityRecordingWriter : IGalaxyDataWriter
|
||||
{
|
||||
public List<Func<CancellationToken, Task<GalaxyAckCredentialResolution>>?> Sources { get; } = [];
|
||||
|
||||
public Task<IReadOnlyList<WriteResult>> WriteAsync(
|
||||
IReadOnlyList<WriteRequest> writes, Func<string, SecurityClassification> securityResolver,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
Sources.Add(null);
|
||||
return Task.FromResult<IReadOnlyList<WriteResult>>([.. writes.Select(_ => new WriteResult(StatusCodeMap.Good))]);
|
||||
}
|
||||
|
||||
Task<IReadOnlyList<WriteResult>> IGalaxyDataWriter.WriteAsync(
|
||||
IReadOnlyList<WriteRequest> writes, Func<string, SecurityClassification> securityResolver,
|
||||
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential, CancellationToken cancellationToken)
|
||||
{
|
||||
Sources.Add(securedCredential);
|
||||
return Task.FromResult<IReadOnlyList<WriteResult>>([.. writes.Select(_ => new WriteResult(StatusCodeMap.Good))]);
|
||||
}
|
||||
|
||||
public void InvalidateHandleCaches() { }
|
||||
}
|
||||
|
||||
private static (GalaxyDriver Driver, IdentityRecordingWriter Writer, FixedAckCredentialResolver Resolver) Build(
|
||||
GalaxySecuredWriteMode mode)
|
||||
{
|
||||
var writer = new IdentityRecordingWriter();
|
||||
var resolver = FixedAckCredentialResolver.Fallback();
|
||||
var driver = new GalaxyDriver("g", Opts(mode), hierarchySource: null, dataWriter: writer, ackCredentialResolver: resolver);
|
||||
return (driver, writer, resolver);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApiKeyIdentity_mode_with_a_caller_passes_a_key_only_identity_source()
|
||||
{
|
||||
var (driver, writer, resolver) = Build(GalaxySecuredWriteMode.ApiKeyIdentity);
|
||||
|
||||
await ((ICallerAwareWritable)driver).WriteAsync(
|
||||
[new WriteRequest("Plant/Tank1/SP", 1.0)], new WriteCaller("svc-mes", "0a1b2c3d4e5f6071"),
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
var source = writer.Sources.ShouldHaveSingleItem().ShouldNotBeNull();
|
||||
var resolution = await source(TestContext.Current.CancellationToken);
|
||||
resolution.Credential.ShouldNotBeNull();
|
||||
resolver.SecuredWriteKeyIds.ShouldBe(["0a1b2c3d4e5f6071"]);
|
||||
resolver.RequestedKeyIds.ShouldBeEmpty("a secured write never uses the ack resolution (with its fallback)");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ApiKeyIdentity_mode_for_an_anonymous_caller_resolves_a_refusal()
|
||||
{
|
||||
var (driver, writer, resolver) = Build(GalaxySecuredWriteMode.ApiKeyIdentity);
|
||||
|
||||
await driver.WriteAsync([new WriteRequest("Plant/Tank1/SP", 1.0)], new WriteCaller("anonymous", null),
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
var resolution = await writer.Sources.ShouldHaveSingleItem().ShouldNotBeNull()(TestContext.Current.CancellationToken);
|
||||
resolution.Credential.ShouldBeNull();
|
||||
resolver.SecuredWriteKeyIds.ShouldBe([null]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Refuse_mode_passes_no_identity_source_even_with_a_caller()
|
||||
{
|
||||
var (driver, writer, _) = Build(GalaxySecuredWriteMode.Refuse);
|
||||
|
||||
await driver.WriteAsync([new WriteRequest("Plant/Tank1/SP", 1.0)], new WriteCaller("svc", "0a1b2c3d4e5f6071"),
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
writer.Sources.ShouldHaveSingleItem().ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_write_without_a_caller_passes_no_identity_source()
|
||||
{
|
||||
var (driver, writer, _) = Build(GalaxySecuredWriteMode.ApiKeyIdentity);
|
||||
|
||||
await driver.WriteAsync([new WriteRequest("Plant/Tank1/SP", 1.0)], TestContext.Current.CancellationToken);
|
||||
|
||||
writer.Sources.ShouldHaveSingleItem().ShouldBeNull();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null, GalaxySecuredWriteMode.Refuse)]
|
||||
[InlineData("", GalaxySecuredWriteMode.Refuse)]
|
||||
[InlineData("refuse", GalaxySecuredWriteMode.Refuse)]
|
||||
[InlineData("ApiKeyIdentity", GalaxySecuredWriteMode.ApiKeyIdentity)]
|
||||
[InlineData("apikeyidentity", GalaxySecuredWriteMode.ApiKeyIdentity)]
|
||||
public void The_factory_parses_SecuredWrites(string? value, GalaxySecuredWriteMode expected)
|
||||
=> GalaxyDriverFactoryExtensions.ParseSecuredWrites(value, "g").ShouldBe(expected);
|
||||
|
||||
[Theory]
|
||||
[InlineData("ApiKey")]
|
||||
[InlineData("1")]
|
||||
[InlineData("Fallback")]
|
||||
public void The_factory_refuses_an_unknown_SecuredWrites_value(string value)
|
||||
=> Should.Throw<InvalidOperationException>(() => GalaxyDriverFactoryExtensions.ParseSecuredWrites(value, "g"))
|
||||
.Message.ShouldContain("SecuredWrites");
|
||||
}
|
||||
+287
@@ -0,0 +1,287 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime;
|
||||
|
||||
/// <summary>
|
||||
/// #1017 — a SecuredWrite attribute is written under the CALLER's Galaxy identity (the session's API key identity,
|
||||
/// resolved by the driver and handed to the writer): the writer's own plain-advised handle →
|
||||
/// <c>AuthenticateUser(DOMAIN\user, password)</c> → <c>WriteSecured(current = that user, verifier = 0)</c>.
|
||||
/// No usable identity (no resolver, a refused resolution, an authentication MXAccess rejects) is still the #991
|
||||
/// local <c>BadUserAccessDenied</c> refusal, and a VerifiedWrite is ALWAYS refused (no second, verifying identity).
|
||||
/// </summary>
|
||||
[Collection(ProcessWideTelemetryCollection.Name)]
|
||||
public sealed class GatewayGalaxyDataWriterSecuredWriteTests
|
||||
{
|
||||
private const string Password = "S3cr3t-pw!";
|
||||
private const int AuthenticatedUserId = 4242;
|
||||
|
||||
private static GatewayGalaxyDataWriter NewWriter(CapturingLogger? logger = null)
|
||||
=> new(new GalaxyMxSession(new Config.GalaxyMxAccessOptions(ClientName: "OtOpcUa-Test")), writeUserId: 0, logger);
|
||||
|
||||
private static Func<CancellationToken, Task<GalaxyAckCredentialResolution>> Identity(
|
||||
string user = "op", string? domain = "PLANT", string password = Password) =>
|
||||
_ => Task.FromResult(GalaxyAckCredentialResolution.Resolved(
|
||||
new GalaxyAckCredential(user, domain, password, GalaxyAckCredentialSource.ApiKey)));
|
||||
|
||||
private static MxCommandReply Ok() => new() { ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok } };
|
||||
|
||||
private static SecuredFakeOps HappyOps() => new()
|
||||
{
|
||||
InvokeResponder = r => r.Command.Kind switch
|
||||
{
|
||||
MxCommandKind.AuthenticateUser => new MxCommandReply
|
||||
{
|
||||
ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok },
|
||||
AuthenticateUser = new AuthenticateUserReply { UserId = AuthenticatedUserId },
|
||||
},
|
||||
MxCommandKind.WriteSecured => new MxCommandReply
|
||||
{
|
||||
ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok },
|
||||
Statuses = { new MxStatusProxy { Success = 1, Category = MxStatusCategory.Ok } },
|
||||
},
|
||||
_ => Ok(),
|
||||
},
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public async Task SecuredWrite_with_a_caller_identity_authenticates_then_writes_secured_on_a_plain_advised_handle()
|
||||
{
|
||||
var ops = HappyOps();
|
||||
var logger = new CapturingLogger();
|
||||
var writer = NewWriter(logger);
|
||||
|
||||
var result = await writer.WriteOneForTestAsync(
|
||||
ops, new WriteRequest("Tank.SetPoint", 12.5), SecurityClassification.SecuredWrite, CancellationToken.None,
|
||||
Identity());
|
||||
|
||||
result.StatusCode.ShouldBe(StatusCodeMap.Good);
|
||||
ops.AddItemRefs.ShouldBe(["Tank.SetPoint"]);
|
||||
ops.RawWriteHandles.ShouldBeEmpty(); // never the supervisory raw path
|
||||
ops.Invokes.Select(i => i.Command.Kind).ShouldBe(
|
||||
[MxCommandKind.Advise, MxCommandKind.AuthenticateUser, MxCommandKind.WriteSecured]);
|
||||
|
||||
var advise = ops.Invokes[0].Command.Advise;
|
||||
advise.ServerHandle.ShouldBe(ops.ServerHandle);
|
||||
advise.ItemHandle.ShouldBe(ops.NextHandle);
|
||||
|
||||
var auth = ops.Invokes[1].Command.AuthenticateUser;
|
||||
auth.ServerHandle.ShouldBe(ops.ServerHandle);
|
||||
auth.VerifyUser.ShouldBe("PLANT\\op");
|
||||
auth.VerifyUserPassword.ShouldBe(Password);
|
||||
|
||||
var write = ops.Invokes[2].Command.WriteSecured;
|
||||
write.ItemHandle.ShouldBe(ops.NextHandle);
|
||||
write.CurrentUserId.ShouldBe(AuthenticatedUserId);
|
||||
write.VerifierUserId.ShouldBe(0);
|
||||
write.Value.ShouldNotBeNull();
|
||||
|
||||
logger.AllText.ShouldNotContain(Password);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SecuredWrite_reuses_the_advised_handle_but_authenticates_every_write()
|
||||
{
|
||||
var ops = HappyOps();
|
||||
var writer = NewWriter();
|
||||
|
||||
await writer.WriteOneForTestAsync(ops, new WriteRequest("T.A", 1), SecurityClassification.SecuredWrite, CancellationToken.None, Identity());
|
||||
await writer.WriteOneForTestAsync(ops, new WriteRequest("T.A", 2), SecurityClassification.SecuredWrite, CancellationToken.None, Identity());
|
||||
|
||||
ops.AddItemRefs.Count.ShouldBe(1);
|
||||
ops.Invokes.Count(i => i.Command.Kind == MxCommandKind.Advise).ShouldBe(1);
|
||||
ops.Invokes.Count(i => i.Command.Kind == MxCommandKind.AuthenticateUser).ShouldBe(2);
|
||||
ops.Invokes.Count(i => i.Command.Kind == MxCommandKind.WriteSecured).ShouldBe(2);
|
||||
}
|
||||
|
||||
/// <summary>The secured handle is NOT the raw path's supervisory handle (one advise mode per handle).</summary>
|
||||
[Fact]
|
||||
public async Task SecuredWrite_uses_its_own_handle_apart_from_the_supervisory_raw_handle()
|
||||
{
|
||||
var ops = HappyOps();
|
||||
var writer = NewWriter();
|
||||
writer.SeedHandleCachesForTest("T.A", itemHandle: 99, supervised: true);
|
||||
|
||||
await writer.WriteOneForTestAsync(ops, new WriteRequest("T.A", 1), SecurityClassification.SecuredWrite, CancellationToken.None, Identity());
|
||||
|
||||
ops.AddItemRefs.ShouldBe(["T.A"]); // a fresh handle for the secured path
|
||||
ops.Invokes.Single(i => i.Command.Kind == MxCommandKind.WriteSecured).Command.WriteSecured.ItemHandle.ShouldBe(ops.NextHandle);
|
||||
ops.Invokes.ShouldNotContain(i => i.Command.Kind == MxCommandKind.AdviseSupervisory);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SecuredWrite_without_an_identity_source_is_refused_without_touching_the_wire()
|
||||
{
|
||||
var ops = HappyOps();
|
||||
|
||||
var result = await NewWriter().WriteOneForTestAsync(
|
||||
ops, new WriteRequest("T.A", 1), SecurityClassification.SecuredWrite, CancellationToken.None, securedCredential: null);
|
||||
|
||||
result.StatusCode.ShouldBe(StatusCodeMap.BadUserAccessDenied);
|
||||
ops.AddItemRefs.ShouldBeEmpty();
|
||||
ops.Invokes.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SecuredWrite_with_a_refused_identity_is_refused_without_touching_the_wire_and_logs_the_reason()
|
||||
{
|
||||
var ops = HappyOps();
|
||||
var logger = new CapturingLogger();
|
||||
|
||||
var result = await NewWriter(logger).WriteOneForTestAsync(
|
||||
ops, new WriteRequest("T.A", 1), SecurityClassification.SecuredWrite, CancellationToken.None,
|
||||
_ => Task.FromResult(GalaxyAckCredentialResolution.Refused("API key 'k1' has no Galaxy identity")));
|
||||
|
||||
result.StatusCode.ShouldBe(StatusCodeMap.BadUserAccessDenied);
|
||||
ops.AddItemRefs.ShouldBeEmpty();
|
||||
ops.Invokes.ShouldBeEmpty();
|
||||
logger.AllText.ShouldContain("has no Galaxy identity");
|
||||
}
|
||||
|
||||
/// <summary>A VerifiedWrite needs a second, verifying user — never supplied, so it stays refused even WITH an identity.</summary>
|
||||
[Fact]
|
||||
public async Task VerifiedWrite_is_refused_even_with_an_identity()
|
||||
{
|
||||
var ops = HappyOps();
|
||||
var resolved = 0;
|
||||
|
||||
var result = await NewWriter().WriteOneForTestAsync(
|
||||
ops, new WriteRequest("T.A", 1), SecurityClassification.VerifiedWrite, CancellationToken.None,
|
||||
ct => { resolved++; return Identity()(ct); });
|
||||
|
||||
result.StatusCode.ShouldBe(StatusCodeMap.BadUserAccessDenied);
|
||||
ops.Invokes.ShouldBeEmpty();
|
||||
ops.AddItemRefs.ShouldBeEmpty();
|
||||
resolved.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)] // MXAccess rejected the credential: no user id
|
||||
[InlineData(false)] // protocol-level failure
|
||||
public async Task An_authentication_MXAccess_rejects_is_BadUserAccessDenied_and_nothing_is_written(bool zeroUserId)
|
||||
{
|
||||
var ops = new SecuredFakeOps
|
||||
{
|
||||
InvokeResponder = r => r.Command.Kind == MxCommandKind.AuthenticateUser
|
||||
? zeroUserId
|
||||
? new MxCommandReply { ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok }, AuthenticateUser = new AuthenticateUserReply { UserId = 0 } }
|
||||
: new MxCommandReply { ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.MxaccessFailure, Message = $"bad credential {Password}" }, Hresult = unchecked((int)0x80070005) }
|
||||
: Ok(),
|
||||
};
|
||||
var logger = new CapturingLogger();
|
||||
|
||||
var result = await NewWriter(logger).WriteOneForTestAsync(
|
||||
ops, new WriteRequest("T.A", 1), SecurityClassification.SecuredWrite, CancellationToken.None, Identity());
|
||||
|
||||
result.StatusCode.ShouldBe(StatusCodeMap.BadUserAccessDenied);
|
||||
ops.Invokes.ShouldNotContain(i => i.Command.Kind == MxCommandKind.WriteSecured);
|
||||
logger.AllText.ShouldContain("PLANT\\op");
|
||||
logger.AllText.ShouldNotContain(Password);
|
||||
}
|
||||
|
||||
/// <summary>A failed plain advise fails the write CLOSED (no AuthenticateUser, no WriteSecured), like the raw path.</summary>
|
||||
[Fact]
|
||||
public async Task A_failed_advise_fails_closed_before_authenticating()
|
||||
{
|
||||
var ops = new SecuredFakeOps
|
||||
{
|
||||
InvokeResponder = r => r.Command.Kind == MxCommandKind.Advise
|
||||
? new MxCommandReply { ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.MxaccessFailure, Message = "E_INVALIDARG" } }
|
||||
: Ok(),
|
||||
};
|
||||
|
||||
var result = await NewWriter().WriteOneForTestAsync(
|
||||
ops, new WriteRequest("T.A", 1), SecurityClassification.SecuredWrite, CancellationToken.None, Identity());
|
||||
|
||||
result.StatusCode.ShouldBe(StatusCodeMap.BadCommunicationError);
|
||||
ops.Invokes.Select(i => i.Command.Kind).ShouldBe([MxCommandKind.Advise]);
|
||||
}
|
||||
|
||||
/// <summary>MXAccess refusing the user's rights on the secured write (1016) is an access refusal.</summary>
|
||||
[Fact]
|
||||
public async Task A_secured_write_MXAccess_refuses_for_rights_is_BadUserAccessDenied()
|
||||
{
|
||||
var ops = new SecuredFakeOps
|
||||
{
|
||||
InvokeResponder = r => r.Command.Kind switch
|
||||
{
|
||||
MxCommandKind.AuthenticateUser => new MxCommandReply { ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok }, AuthenticateUser = new AuthenticateUserReply { UserId = 7 } },
|
||||
MxCommandKind.WriteSecured => new MxCommandReply
|
||||
{
|
||||
ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok },
|
||||
Statuses = { new MxStatusProxy { Success = 0, Category = MxStatusCategory.SecurityError, Detail = 1016 } },
|
||||
},
|
||||
_ => Ok(),
|
||||
},
|
||||
};
|
||||
|
||||
var result = await NewWriter().WriteOneForTestAsync(
|
||||
ops, new WriteRequest("T.A", 1), SecurityClassification.SecuredWrite, CancellationToken.None, Identity());
|
||||
|
||||
result.StatusCode.ShouldBe(StatusCodeMap.BadUserAccessDenied);
|
||||
}
|
||||
|
||||
/// <summary>A whole batch resolves the caller's identity ONCE, however many secured tags it carries.</summary>
|
||||
[Fact]
|
||||
public async Task A_batch_resolves_the_identity_once()
|
||||
{
|
||||
var ops = HappyOps();
|
||||
var resolved = 0;
|
||||
var writer = NewWriter();
|
||||
|
||||
var results = await writer.WriteBatchForTestAsync(ops,
|
||||
[new WriteRequest("T.A", 1), new WriteRequest("T.B", 2), new WriteRequest("T.C", 3)],
|
||||
_ => SecurityClassification.SecuredWrite, CancellationToken.None,
|
||||
ct => { Interlocked.Increment(ref resolved); return Identity()(ct); });
|
||||
|
||||
results.ShouldAllBe(r => r.StatusCode == StatusCodeMap.Good);
|
||||
resolved.ShouldBe(1);
|
||||
}
|
||||
|
||||
/// <summary>Invalidation (a reconnect) forgets the secured handles too, so a fresh session re-adds + re-advises.</summary>
|
||||
[Fact]
|
||||
public async Task InvalidateHandleCaches_forgets_secured_handles()
|
||||
{
|
||||
var ops = HappyOps();
|
||||
var writer = NewWriter();
|
||||
await writer.WriteOneForTestAsync(ops, new WriteRequest("T.A", 1), SecurityClassification.SecuredWrite, CancellationToken.None, Identity());
|
||||
|
||||
writer.InvalidateHandleCaches();
|
||||
await writer.WriteOneForTestAsync(ops, new WriteRequest("T.A", 2), SecurityClassification.SecuredWrite, CancellationToken.None, Identity());
|
||||
|
||||
ops.AddItemRefs.Count.ShouldBe(2);
|
||||
ops.Invokes.Count(i => i.Command.Kind == MxCommandKind.Advise).ShouldBe(2);
|
||||
}
|
||||
|
||||
private sealed class SecuredFakeOps : IMxWriteOps
|
||||
{
|
||||
public string SessionId => "sess-1";
|
||||
public int ServerHandle => 100;
|
||||
public int NextHandle { get; init; } = 7;
|
||||
public List<string> AddItemRefs { get; } = new();
|
||||
public List<MxCommandRequest> Invokes { get; } = new();
|
||||
public List<int> RawWriteHandles { get; } = new();
|
||||
public Func<MxCommandRequest, MxCommandReply>? InvokeResponder { get; init; }
|
||||
|
||||
public Task<int> AddItemAsync(string fullRef, CancellationToken ct)
|
||||
{
|
||||
AddItemRefs.Add(fullRef);
|
||||
return Task.FromResult(NextHandle);
|
||||
}
|
||||
|
||||
public Task<MxCommandReply> InvokeAsync(MxCommandRequest request, CancellationToken ct)
|
||||
{
|
||||
lock (Invokes) Invokes.Add(request);
|
||||
return Task.FromResult(InvokeResponder?.Invoke(request) ?? new MxCommandReply());
|
||||
}
|
||||
|
||||
public Task<MxCommandReply> WriteRawAsync(int itemHandle, MxValue value, int userId, CancellationToken ct)
|
||||
{
|
||||
RawWriteHandles.Add(itemHandle);
|
||||
return Task.FromResult(new MxCommandReply());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,4 +30,16 @@ internal sealed class FixedAckCredentialResolver : IGalaxyAckCredentialResolver
|
||||
? GalaxyAckCredentialResolution.Refused("test refusal")
|
||||
: GalaxyAckCredentialResolution.Resolved(_credential));
|
||||
}
|
||||
|
||||
/// <summary>Gets the key ids a secured write resolved for (#1017), in order.</summary>
|
||||
public List<string?> SecuredWriteKeyIds { get; } = [];
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<GalaxyAckCredentialResolution> ResolveKeyIdentityAsync(string? apiKeyId, CancellationToken cancellationToken)
|
||||
{
|
||||
SecuredWriteKeyIds.Add(apiKeyId);
|
||||
return Task.FromResult(_credential is null || apiKeyId is null
|
||||
? GalaxyAckCredentialResolution.Refused("test refusal (no key identity)")
|
||||
: GalaxyAckCredentialResolution.Resolved(_credential));
|
||||
}
|
||||
}
|
||||
|
||||
+43
@@ -124,6 +124,49 @@ public sealed class ApiKeyGalaxyAckIdentityServiceTests
|
||||
_store.Rows.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #1050: Galaxy accounts can have empty passwords, and a blank box means "keep", so storing an EMPTY password
|
||||
/// needs its own explicit option — first-time (where blank is refused) and over an existing password.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task SetWithEmptyPassword_stores_an_empty_password_first_time()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
|
||||
await Service().SetWithEmptyPasswordAsync(KeyId, "alice", "CORP", "admin", ct);
|
||||
|
||||
_cipher.Decrypt(_store.Rows[GalaxyAckIdentitySecrets.PasswordSecretName(KeyId)]).ShouldBe(string.Empty);
|
||||
_cipher.Decrypt(_store.Rows[GalaxyAckIdentitySecrets.UserSecretName(KeyId)]).ShouldBe("CORP\\alice");
|
||||
_store.UpsertOrder.ShouldBe([GalaxyAckIdentitySecrets.PasswordSecretName(KeyId), GalaxyAckIdentitySecrets.UserSecretName(KeyId)]);
|
||||
_invalidator.Invalidated.ShouldContain(GalaxyAckIdentitySecrets.PasswordSecretName(KeyId));
|
||||
_audit.Events.ShouldHaveSingleItem().Action.ShouldBe("apikey.galaxy-ack-identity.set");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetWithEmptyPassword_replaces_a_stored_password_and_a_later_blank_keeps_it_empty()
|
||||
{
|
||||
var svc = Service();
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
await svc.SetAsync(KeyId, "alice", "CORP", Password, "admin", ct);
|
||||
|
||||
await svc.SetWithEmptyPasswordAsync(KeyId, "alice", "CORP", "admin", ct);
|
||||
_cipher.Decrypt(_store.Rows[GalaxyAckIdentitySecrets.PasswordSecretName(KeyId)]).ShouldBe(string.Empty);
|
||||
|
||||
// A later edit with a blank box keeps the (empty) password rather than refusing — it exists.
|
||||
await svc.SetAsync(KeyId, "alice", "NEWDOM", null, "admin", ct);
|
||||
_cipher.Decrypt(_store.Rows[GalaxyAckIdentitySecrets.PasswordSecretName(KeyId)]).ShouldBe(string.Empty);
|
||||
_cipher.Decrypt(_store.Rows[GalaxyAckIdentitySecrets.UserSecretName(KeyId)]).ShouldBe("NEWDOM\\alice");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData("CORP\\alice")]
|
||||
public async Task SetWithEmptyPassword_validates_the_user_like_SetAsync(string user)
|
||||
{
|
||||
await Should.ThrowAsync<ArgumentException>(() => Service().SetWithEmptyPasswordAsync(KeyId, user, null, "admin", default));
|
||||
_store.Rows.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Set_rejects_a_malformed_key_id()
|
||||
{
|
||||
|
||||
+113
@@ -285,4 +285,117 @@ public sealed class GalaxyDriverPageFormSerializationTests
|
||||
JsonSerializer.Deserialize<GalaxyDriverOptions>(json, _pageOpts)!.AlarmAck.ConfirmTimeoutMs.ShouldBe(0);
|
||||
new GalaxyDriverForm.GalaxyFormModel().AckConfirmTimeoutMs.ShouldBe(GalaxyAlarmAckOptions.DefaultConfirmTimeoutMs);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#1045: the HTTP/2 keep-alive knobs (#991 G-19) must survive FromRecord/ToRecord, or saving the
|
||||
/// Galaxy driver page silently resets an operator's setting (e.g. the 0 = no-pings opt-out) to the default.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void FormModel_RoundTrips_KeepAlivePings()
|
||||
{
|
||||
var original = new GalaxyDriverOptions(
|
||||
new GalaxyGatewayOptions("https://gw:5001", "env:K", KeepAlivePingDelaySeconds: 0, KeepAlivePingTimeoutSeconds: 7),
|
||||
new GalaxyMxAccessOptions("OtOpcUa"),
|
||||
new GalaxyRepositoryOptions(),
|
||||
new GalaxyReconnectOptions());
|
||||
|
||||
var form = GalaxyDriverForm.GalaxyFormModel.FromRecord(original);
|
||||
form.GatewayKeepAlivePingDelaySeconds.ShouldBe(0);
|
||||
form.GatewayKeepAlivePingTimeoutSeconds.ShouldBe(7);
|
||||
|
||||
var back = form.ToRecord();
|
||||
back.Gateway.KeepAlivePingDelaySeconds.ShouldBe(0);
|
||||
back.Gateway.KeepAlivePingTimeoutSeconds.ShouldBe(7);
|
||||
|
||||
var defaults = new GalaxyGatewayOptions("e", "k");
|
||||
var fresh = new GalaxyDriverForm.GalaxyFormModel();
|
||||
fresh.GatewayKeepAlivePingDelaySeconds.ShouldBe(defaults.KeepAlivePingDelaySeconds);
|
||||
fresh.GatewayKeepAlivePingTimeoutSeconds.ShouldBe(defaults.KeepAlivePingTimeoutSeconds);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#1045: a key the form does not model (a newer option, a hand-edited key) must survive a save —
|
||||
/// the form overlays only the paths it owns onto the stored JSON instead of re-serialising the typed record.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Serialize_preserves_unmodelled_keys_and_overwrites_owned_ones()
|
||||
{
|
||||
var stored = """
|
||||
{
|
||||
"Gateway": { "Endpoint": "http://old:5120", "ApiKeySecretRef": "env:GALAXY_MXGW_API_KEY", "FutureGatewayKnob": 42 },
|
||||
"MxAccess": { "ClientName": "OtOpcUa-A" },
|
||||
"Repository": {},
|
||||
"Reconnect": {},
|
||||
"futureTopLevel": "keep-me"
|
||||
}
|
||||
""";
|
||||
var opts = JsonSerializer.Deserialize<GalaxyDriverOptions>(stored, _pageOpts)!;
|
||||
var form = GalaxyDriverForm.GalaxyFormModel.FromRecord(opts);
|
||||
form.GatewayEndpoint = "http://new:5120";
|
||||
form.GatewayKeepAlivePingDelaySeconds = 0;
|
||||
|
||||
var json = GalaxyDriverForm.Serialize(form.ToRecord(), stored);
|
||||
|
||||
var root = System.Text.Json.Nodes.JsonNode.Parse(json)!.AsObject();
|
||||
root["futureTopLevel"]!.GetValue<string>().ShouldBe("keep-me");
|
||||
var gw = root["Gateway"]!.AsObject();
|
||||
gw["FutureGatewayKnob"]!.GetValue<int>().ShouldBe(42);
|
||||
gw["endpoint"]!.GetValue<string>().ShouldBe("http://new:5120");
|
||||
gw.ContainsKey("Endpoint").ShouldBeFalse();
|
||||
gw["keepAlivePingDelaySeconds"]!.GetValue<int>().ShouldBe(0);
|
||||
|
||||
var back = JsonSerializer.Deserialize<GalaxyDriverOptions>(json, _pageOpts)!;
|
||||
back.Gateway.Endpoint.ShouldBe("http://new:5120");
|
||||
back.Gateway.KeepAlivePingDelaySeconds.ShouldBe(0);
|
||||
back.MxAccess.ClientName.ShouldBe("OtOpcUa-A");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #1017: <c>MxAccess.SecuredWrites</c> round-trips through the form and is saved as a STRING the driver
|
||||
/// factory parses (it refuses an unknown value, and a numeric enum would be unknown).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void FormModel_RoundTrips_SecuredWrites_as_a_string()
|
||||
{
|
||||
var original = new GalaxyDriverOptions(
|
||||
new GalaxyGatewayOptions("https://gw:5001", "env:K"),
|
||||
new GalaxyMxAccessOptions("OtOpcUa") { SecuredWrites = GalaxySecuredWriteMode.ApiKeyIdentity },
|
||||
new GalaxyRepositoryOptions(),
|
||||
new GalaxyReconnectOptions());
|
||||
|
||||
var form = GalaxyDriverForm.GalaxyFormModel.FromRecord(original);
|
||||
form.MxSecuredWrites.ShouldBe(GalaxySecuredWriteMode.ApiKeyIdentity);
|
||||
new GalaxyDriverForm.GalaxyFormModel().MxSecuredWrites.ShouldBe(GalaxySecuredWriteMode.Refuse);
|
||||
|
||||
var json = GalaxyDriverForm.Serialize(form.ToRecord(), originalJson: null);
|
||||
json.ShouldContain("\"securedWrites\":\"ApiKeyIdentity\"");
|
||||
JsonSerializer.Deserialize<GalaxyDriverOptions>(json, new JsonSerializerOptions(_pageOpts) { Converters = { new JsonStringEnumConverter() } })!
|
||||
.MxAccess.SecuredWrites.ShouldBe(GalaxySecuredWriteMode.ApiKeyIdentity);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#1045 guard: every leaf the form's record serialises must be an owned path, or an edit to it is
|
||||
/// silently discarded by the overlay on save (<c>rawTags</c> is authored elsewhere and deliberately not owned).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Every_serialised_leaf_is_an_owned_path()
|
||||
{
|
||||
var json = GalaxyDriverForm.Serialize(new GalaxyDriverForm.GalaxyFormModel().ToRecord(), originalJson: null);
|
||||
var leaves = new List<string>();
|
||||
void Walk(System.Text.Json.Nodes.JsonObject o, string prefix)
|
||||
{
|
||||
foreach (var (k, v) in o)
|
||||
{
|
||||
var path = prefix.Length == 0 ? k : $"{prefix}.{k}";
|
||||
if (v is System.Text.Json.Nodes.JsonObject child) Walk(child, path);
|
||||
else leaves.Add(path);
|
||||
}
|
||||
}
|
||||
Walk(System.Text.Json.Nodes.JsonNode.Parse(json)!.AsObject(), "");
|
||||
|
||||
leaves.ShouldContain("gateway.keepAlivePingDelaySeconds");
|
||||
leaves.Where(l => l != "rawTags")
|
||||
.Except(GalaxyDriverForm.OwnedPaths, StringComparer.OrdinalIgnoreCase)
|
||||
.ShouldBeEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,6 +108,9 @@ public sealed class ApiKeysDeleteTests : BunitContext
|
||||
public Task SetAsync(string apiKeyId, string user, string? domain, string? password, string actor, CancellationToken ct) =>
|
||||
throw new NotSupportedException();
|
||||
|
||||
public Task SetWithEmptyPasswordAsync(string apiKeyId, string user, string? domain, string actor, CancellationToken ct) =>
|
||||
throw new NotSupportedException();
|
||||
|
||||
public Task ClearAsync(string apiKeyId, string actor, CancellationToken ct)
|
||||
{
|
||||
ClearCalls++;
|
||||
|
||||
+40
-1
@@ -5,6 +5,7 @@ using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
|
||||
@@ -232,15 +233,53 @@ public sealed class NodeManagerKeyUsabilityGateTests : IDisposable
|
||||
return errors;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #1017: the dispatched write carries WHO wrote — the session's principal and API key id — so a driver whose
|
||||
/// device enforces per-user write permission (Galaxy SecuredWrite) can act as that caller. Anonymous carries
|
||||
/// the anonymous principal and no key.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task The_dispatched_write_carries_the_sessions_principal_and_key()
|
||||
{
|
||||
var (host, server) = await BootAsync();
|
||||
try
|
||||
{
|
||||
var nm = server.NodeManager!;
|
||||
var gateway = new RecordingWriteGateway();
|
||||
nm.NodeWriteGateway = gateway;
|
||||
Wire(nm, new FakeClock(Start), Key(expiresUtc: null));
|
||||
var nodeId = Writable(nm, "Plant/Modbus/dev1/Setpoint");
|
||||
|
||||
Write(nm, KeyIdentity(OpcUaDataPlaneRoles.WriteOperate), nodeId, 1f)[0].StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
|
||||
var anonymous = new RoleCarryingUserIdentity(
|
||||
new AnonymousIdentityToken(), [OpcUaDataPlaneRoles.WriteOperate], OpcUaPrincipals.Anonymous, apiKeyId: null);
|
||||
Write(nm, anonymous, nodeId, 2f)[0].StatusCode.Code.ShouldBe(StatusCodes.Good.Code);
|
||||
|
||||
gateway.Callers.Count.ShouldBe(2);
|
||||
gateway.Callers[0].ShouldBe(new WriteCaller(Principal, KeyId));
|
||||
gateway.Callers[1].ShouldBe(new WriteCaller(OpcUaPrincipals.Anonymous, null));
|
||||
}
|
||||
finally { await host.DisposeAsync(); }
|
||||
}
|
||||
|
||||
/// <summary>Records what actually reached the device.</summary>
|
||||
private sealed class RecordingWriteGateway : IOpcUaNodeWriteGateway
|
||||
{
|
||||
public List<string> Writes { get; } = [];
|
||||
public List<WriteCaller?> Callers { get; } = [];
|
||||
|
||||
public Task<NodeWriteOutcome> WriteAsync(
|
||||
string nodeId, object? value, AddressSpaceRealm realm, CancellationToken ct)
|
||||
=> WriteAsync(nodeId, value, realm, caller: null, ct);
|
||||
|
||||
public Task<NodeWriteOutcome> WriteAsync(
|
||||
string nodeId, object? value, AddressSpaceRealm realm, WriteCaller? caller, CancellationToken ct)
|
||||
{
|
||||
lock (Writes) Writes.Add(nodeId);
|
||||
lock (Writes)
|
||||
{
|
||||
Writes.Add(nodeId);
|
||||
Callers.Add(caller);
|
||||
}
|
||||
return Task.FromResult(new NodeWriteOutcome(true, null));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,6 +37,27 @@ public sealed class ActorNodeWriteGatewayTests : RuntimeActorTestBase
|
||||
outcome.Reason.ShouldBeNull();
|
||||
}
|
||||
|
||||
/// <summary>#1017: the caller-carrying overload puts the caller on the RouteNodeWrite; the plain one carries none.</summary>
|
||||
[Fact]
|
||||
public async Task The_caller_rides_the_route_message()
|
||||
{
|
||||
var probe = CreateTestProbe();
|
||||
IOpcUaNodeWriteGateway gateway = new ActorNodeWriteGateway(resolveDriverHost: () => probe.Ref, NullLogger.Instance);
|
||||
var caller = new ZB.MOM.WW.OtOpcUa.Core.Abstractions.WriteCaller("scadabridge", "0a1b2c3d4e5f6071");
|
||||
|
||||
var withCaller = gateway.WriteAsync("eq-1/speed", 1.0, AddressSpaceRealm.Uns, caller, CancellationToken.None);
|
||||
probe.ExpectMsg<DriverHostActor.RouteNodeWrite>(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken)
|
||||
.Caller.ShouldBe(caller);
|
||||
probe.Reply(new DriverHostActor.NodeWriteResult(true, null));
|
||||
(await withCaller).Success.ShouldBeTrue();
|
||||
|
||||
var without = gateway.WriteAsync("eq-1/speed", 2.0, AddressSpaceRealm.Uns, CancellationToken.None);
|
||||
probe.ExpectMsg<DriverHostActor.RouteNodeWrite>(TimeSpan.FromSeconds(5), cancellationToken: TestContext.Current.CancellationToken)
|
||||
.Caller.ShouldBeNull();
|
||||
probe.Reply(new DriverHostActor.NodeWriteResult(true, null));
|
||||
(await without).Success.ShouldBeTrue();
|
||||
}
|
||||
|
||||
/// <summary>Probe replies failure → the outcome carries the same (false, reason) verbatim.</summary>
|
||||
[Fact]
|
||||
public async Task Failure_reply_maps_to_failure_outcome_with_reason()
|
||||
|
||||
+43
-4
@@ -87,6 +87,31 @@ public sealed class DriverHostActorWriteRoutingTests : RuntimeActorTestBase
|
||||
}, duration: Timeout, cancellationToken: TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #1017: a RouteNodeWrite that carries its caller reaches a caller-aware driver through
|
||||
/// <see cref="ICallerAwareWritable"/> with that caller; one without a caller keeps the plain
|
||||
/// <see cref="IWritable"/> path (positive control).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void The_writes_caller_reaches_a_caller_aware_driver()
|
||||
{
|
||||
var db = NewInMemoryDbFactory();
|
||||
var recorder = new RecordingDriverFactory("Modbus");
|
||||
var deploymentId = SeedV3Deployment(db, RevA);
|
||||
var actor = SpawnHostAndApply(db, deploymentId, recorder);
|
||||
var caller = new WriteCaller("scadabridge", "0a1b2c3d4e5f6071");
|
||||
|
||||
RouteWriteUntilAccepted(actor, $"ns=2;s={RawPath}", 1.0, AddressSpaceRealm.Raw, caller);
|
||||
RouteWriteUntilAccepted(actor, $"ns=2;s={RawPath}", 2.0, AddressSpaceRealm.Raw);
|
||||
|
||||
AwaitAssert(() =>
|
||||
{
|
||||
recorder.Callers.Count.ShouldBe(2);
|
||||
recorder.Callers[0].ShouldBe(caller);
|
||||
recorder.Callers[1].ShouldBeNull();
|
||||
}, duration: Timeout, cancellationToken: TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Routes a write, retrying until the host accepts it, and fails with the host's own rejection
|
||||
/// <c>Reason</c> if it never does.
|
||||
@@ -113,14 +138,14 @@ public sealed class DriverHostActorWriteRoutingTests : RuntimeActorTestBase
|
||||
/// <param name="value">The value to write.</param>
|
||||
/// <param name="realm">The address-space realm the NodeId belongs to.</param>
|
||||
private void RouteWriteUntilAccepted(
|
||||
IActorRef actor, string nodeId, object value, AddressSpaceRealm realm)
|
||||
IActorRef actor, string nodeId, object value, AddressSpaceRealm realm, WriteCaller? caller = null)
|
||||
{
|
||||
var lastReason = "(no reply)";
|
||||
AwaitAssert(
|
||||
() =>
|
||||
{
|
||||
var asker = CreateTestProbe();
|
||||
actor.Tell(new DriverHostActor.RouteNodeWrite(nodeId, value, realm), asker.Ref);
|
||||
actor.Tell(new DriverHostActor.RouteNodeWrite(nodeId, value, realm, caller), asker.Ref);
|
||||
var result = asker.ExpectMsg<DriverHostActor.NodeWriteResult>(TimeSpan.FromSeconds(1));
|
||||
lastReason = result.Reason ?? "(none)";
|
||||
result.Success.ShouldBeTrue($"host kept rejecting the write; last reason: {lastReason}");
|
||||
@@ -393,6 +418,9 @@ public sealed class DriverHostActorWriteRoutingTests : RuntimeActorTestBase
|
||||
/// <summary>The writes the spawned driver received.</summary>
|
||||
public IReadOnlyList<WriteRequest> Writes => _driver.Writes;
|
||||
|
||||
/// <summary>The caller each write carried (#1017).</summary>
|
||||
public IReadOnlyList<WriteCaller?> Callers => _driver.Callers;
|
||||
|
||||
/// <inheritdoc />
|
||||
public IDriver? TryCreate(string driverType, string driverInstanceId, string driverConfigJson)
|
||||
{
|
||||
@@ -406,9 +434,12 @@ public sealed class DriverHostActorWriteRoutingTests : RuntimeActorTestBase
|
||||
}
|
||||
|
||||
/// <summary>An <see cref="IDriver"/> + <see cref="IWritable"/> that records every write and returns Good.</summary>
|
||||
private sealed class RecordingDriver : IDriver, IWritable
|
||||
private sealed class RecordingDriver : IDriver, ICallerAwareWritable
|
||||
{
|
||||
private readonly ConcurrentQueue<WriteRequest> _writes = new();
|
||||
private readonly ConcurrentQueue<WriteCaller?> _callers = new();
|
||||
/// <summary>The caller each write carried (null = the plain IWritable overload), in order (#1017).</summary>
|
||||
public IReadOnlyList<WriteCaller?> Callers => _callers.ToArray();
|
||||
/// <inheritdoc />
|
||||
public string DriverInstanceId { get; private set; } = string.Empty;
|
||||
/// <inheritdoc />
|
||||
@@ -429,7 +460,15 @@ public sealed class DriverHostActorWriteRoutingTests : RuntimeActorTestBase
|
||||
public Task<IReadOnlyList<WriteResult>> WriteAsync(
|
||||
IReadOnlyList<WriteRequest> writes, CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var w in writes) _writes.Enqueue(w);
|
||||
foreach (var w in writes) { _writes.Enqueue(w); _callers.Enqueue(null); }
|
||||
return Task.FromResult<IReadOnlyList<WriteResult>>(
|
||||
writes.Select(_ => new WriteResult(0u)).ToArray());
|
||||
}
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<WriteResult>> WriteAsync(
|
||||
IReadOnlyList<WriteRequest> writes, WriteCaller caller, CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var w in writes) { _writes.Enqueue(w); _callers.Enqueue(caller); }
|
||||
return Task.FromResult<IReadOnlyList<WriteResult>>(
|
||||
writes.Select(_ => new WriteResult(0u)).ToArray());
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user