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

- MxAccess.SecuredWrites = Refuse (default, unchanged #991 local BadUserAccessDenied) |
  ApiKeyIdentity. Opted in, a SecuredWrite runs as the calling key's own /api-keys Galaxy
  identity (ResolveKeyIdentityAsync: no fallback account; anonymous / no identity / broken
  identity refused before the wire): own plain-advised handle (apart from the raw path's
  supervisory handle) -> AuthenticateUser every write -> WriteSecured(userId, 0), the sequence
  mxaccessgw live-captured committing. Auth failure / user id 0 -> BadUserAccessDenied; password
  only in the AuthenticateUser command, scrubbed from every log. Identity resolved once per batch.
- VerifiedWrite is refused in every mode: an OPC UA Write carries no verifier (MXAccess refuses
  no verifier 1008 / self-verifier 8018), and a stored verifier would defeat the two-person rule.
- Caller plumbing: WriteCaller + optional ICallerAwareWritable (Core.Abstractions); node manager
  passes principal + key id -> IOpcUaNodeWriteGateway caller overload (default drops it) ->
  RouteNodeWrite.Caller -> WriteAttribute.Caller -> ICallerAwareWritable. The gRPC data-connection
  write path carries no caller yet (secured writes refused there).
- AdminUI Galaxy form 'Secured writes' select (owned path); enum serialises as its name; factory
  refuses an unknown value. Docs: Galaxy.md design + live-gate checklist. Not live-gated.
This commit is contained in:
Joseph Doherty
2026-12-03 15:29:02 -05:00
parent 9496db9357
commit 13521354cc
26 changed files with 1120 additions and 65 deletions
+67 -8
View File
@@ -82,7 +82,7 @@ Project root files:
`DriverConfig` JSON binds to `Config/GalaxyDriverOptions.cs`. The four sections are:
- **`Gateway`** — endpoint, API key secret ref (`secret:galaxy/<name>` · `secret:otopcua/galaxy/<name>` · `env:OTOPCUA_GALAXY_<NAME>` · legacy `env:GALAXY_MXGW_<NAME>` · `dev:KEY` · literal; anything else, incl. `file:`, is refused — #815 (an already-deployed driver keeps resolving a pre-#815 ref on init and every gateway reconnect in deprecated warn-only mode until its next deploy), [`docs/security.md`](../security.md) §"Credential references are namespaced per driver"), TLS knobs, connect/call/stream timeouts. `StreamTimeoutSeconds = 0` keeps the long-lived `StreamEvents` RPC open for the driver's lifetime. `KeepAlivePingDelaySeconds` (`15`) / `KeepAlivePingTimeoutSeconds` (`10`) — HTTP/2 keep-alive pings on every gateway channel (#991 G-19, below); `0` disables them. Both have AdminUI fields in the driver form's connection panel (#1045 — the form used to drop them on save, resetting a `0` opt-out to the default). The form now overlays only the keys it edits onto the stored JSON (`GalaxyDriverForm.OwnedPaths` + `DriverConfigJsonOverlay`), so a key it does not model survives a save; a new form field must add its path there.
- **`MxAccess`** — `ClientName` (must be unique per OtOpcUa instance — redundancy pairs enforce uniqueness at install time), `PublishingIntervalMs` (forwarded as `buffered_update_interval_ms` on subscribe), `WriteUserId` — the user id a raw `Write` carries (secured/verified writes are refused, see below), `EventPumpChannelCapacity` (default 50_000 — one second of headroom at 50k tags / 1Hz; tune via the `galaxy.events.dropped` metric).
- **`MxAccess`** — `ClientName` (must be unique per OtOpcUa instance — redundancy pairs enforce uniqueness at install time), `PublishingIntervalMs` (forwarded as `buffered_update_interval_ms` on subscribe), `WriteUserId` — the user id a raw `Write` carries; `SecuredWrites` — `Refuse` (default) | `ApiKeyIdentity` (#1017, [Secured writes under the caller's Galaxy identity](#secured-writes-under-the-callers-galaxy-identity-1017)), `EventPumpChannelCapacity` (default 50_000 — one second of headroom at 50k tags / 1Hz; tune via the `galaxy.events.dropped` metric).
- **`Repository`** — `DiscoverPageSize`, `WatchDeployEvents`.
- **`Reconnect`** — `InitialBackoffMs`, `MaxBackoffMs`, `ReplayOnSessionLost` (default `true`: after a gateway session is recreated, re-issue `SubscribeBulk` for every tracked subscription; `false` leaves them stranded — Bad + Degraded, see [Reconnect + Replay](#reconnect--replay)).
- **`AlarmAck`** (optional, lmxopcua#749) — `FallbackUser`, `FallbackDomain`, `FallbackPasswordSecretRef`. See [Alarm acknowledge credential](#alarm-acknowledge-credential). `ConfirmTimeoutMs` (default `10000`, max `120000`, `0` = do not wait, negative = default; #869) — see [Ack confirmation](#ack-confirmation-869).
@@ -187,6 +187,64 @@ the fallback secret must exist on the node that serves the OPC UA session and ho
driver; on a split admin/driver topology create them on the driver nodes too (`/admin/secrets` or
the `secret` CLI) under exactly those names.
### Secured writes under the caller's Galaxy identity (#1017)
ArchestrA classifies some attributes **SecuredWrite** (the writer must authenticate) or **VerifiedWrite** (a second,
verifying user must authenticate too). MXAccess writes them with `AuthenticateUser(user, password)` → user id →
`WriteSecured(current user, verifier user)`. mxaccessgw exposes both commands unchanged (scope **`invoke:secure`**),
and its 2026-11-13 capture shows the sequence committing: an item **plain**-advised by the writing registration,
`AuthenticateUser`, then `WriteSecured(userId, 0)` (`docs/LiveCaptures-2026-11-13.md` §4 in mxaccessgw — on
`MxSecurityOperate` UDAs; 36 more secured writes in §5). No gateway change is needed for SecuredWrite.
**Opt-in, per driver: `MxAccess.SecuredWrites`** — `Refuse` (default; the #991 local `BadUserAccessDenied`) or
`ApiKeyIdentity` (AdminUI driver form, MXAccess panel, "Secured writes"). The factory refuses any other value.
**Whose identity.** The OPC UA data plane is machine-to-machine: a session is an API key or anonymous, and carries
no Galaxy password. A SecuredWrite therefore runs as **the calling key's own Galaxy identity** — the account mapped
to the key on AdminUI `/api-keys` (the same `otopcua/apikeys/<keyId>/galaxy-ack-{user,password}` secrets an
alarm acknowledge from that key uses; `IGalaxyAckCredentialResolver.ResolveKeyIdentityAsync`). Unlike the ack there
is **no fallback account**: an anonymous session, a key with no identity, or a key whose identity is broken (user
without a password secret, unreadable store) is refused `BadUserAccessDenied` and nothing reaches the gateway — a
secured write is never attributed to a shared account. OtOpcUa's own `WriteOperate` gate / ACL runs first, as for
every write; the Galaxy then enforces the account's own permission on the attribute (MXAccess 1016
`UserNotHavingAccessRights` ⇒ `BadUserAccessDenied`).
**How the write reaches the driver.** `OtOpcUaNodeManager.OnEquipmentTagWrite` builds a `WriteCaller(principal,
apiKeyId)` from the session identity → `IOpcUaNodeWriteGateway.WriteAsync(…, caller, …)` → `RouteNodeWrite.Caller` →
`DriverInstanceActor.WriteAttribute.Caller` → `ICallerAwareWritable.WriteAsync(writes, caller, ct)` (a new optional
`Core.Abstractions` capability; every other driver keeps `IWritable`). `GalaxyDriver` hands its writer a lazily
resolved identity source only in `ApiKeyIdentity` mode with a caller present; the writer resolves it at most once
per batch and only when a SecuredWrite tag is in the batch.
**The wire sequence** (`GatewayGalaxyDataWriter.WriteSecuredOneAsync`): the writer's own item handle for the secured
path (separate from the raw path's supervisory-advised handle — MXAccess allows one advise mode per handle), plain
`Advise` once per handle per session (a failed advise fails the write closed, `BadCommunicationError`, like the raw
path) → `AuthenticateUser(DOMAIN\user, password)` on **every** write (no cached user id: MXAccess's user-id lifetime
is unverified, and a rotated or revoked identity must take effect on the next write) → `WriteSecured(current = that
id, verifier = 0)`, its correlated `OnWriteComplete` translated exactly like a raw write. A non-OK `AuthenticateUser`
or user id 0 ⇒ `BadUserAccessDenied` with no `WriteSecured`. The password goes only into the `AuthenticateUser`
command: every log line names the user, never the password, and gateway text is scrubbed of it. A gRPC
`PermissionDenied` (the driver's gateway key lacks `invoke:secure`) ⇒ `BadUserAccessDenied` with a Warning naming the
scope.
**VerifiedWrite stays refused, in every mode — by design, not a gap.** It needs a second, *verifying* user; MXAccess
refuses one with no verifier (1008) and one whose verifier is the writer (8018), both live-captured. An OPC UA Write
carries one caller and no verifier, and storing a verifier credential per key would let one client satisfy the
two-person rule alone. Supporting it would need a verifier carried in the request (e.g. a Method with both
identities) — a product decision, not plumbing.
**Not covered (yet):** writes over the gRPC data connection (`DataConnectionGrpcService` → `RouteRichWrite`) carry no
caller, so a SecuredWrite there is refused as before even in `ApiKeyIdentity` mode. Not live-gated.
**Live-gate checklist (mxaccessgw + a Galaxy with a SecuredWrite UDA):** the driver's gateway key holds
`invoke:secure`; map a Galaxy account to an API key on `/api-keys`; set `SecuredWrites = ApiKeyIdentity`; write the
attribute through that key ⇒ value commits, Good, and the Galaxy/Historian attributes the write to the mapped user;
the same write anonymously / through a key with no identity ⇒ `BadUserAccessDenied`, nothing in the gateway log; a
wrong password ⇒ `BadUserAccessDenied` naming the user, password absent from every log; an account without the
attribute's permission ⇒ `BadUserAccessDenied` (1016); a VerifiedWrite attribute ⇒ `BadUserAccessDenied` with no
gateway traffic; a raw (FreeAccess) write on the same attribute's object still commits (the two handles coexist);
a gateway reconnect re-adds + re-advises the secured handle.
Full per-field descriptions live in `Config/GalaxyDriverOptions.cs`. The full JSON skeleton is reproduced in [docs/v2/driver-specs.md §1](../v2/driver-specs.md).
## Reconnect + Replay
@@ -238,13 +296,14 @@ Every (re)open of `StreamAlarms` replays the gateway's active-alarm snapshot. `G
- **A dropped change is re-read (#991 G-4).** MXAccess sends a value only when it changes, so a data change the full channel drops (newest-dropped) used to leave its tag at the previous value, Good, until the attribute next changed. The pump records the item handles of dropped data changes and, once its channel has drained (so the resync is not lost to the same congestion), the driver re-advises exactly those tags — an advise is answered with the current value — rebinds them, and releases the superseded handles. One coalescing background worker; serialised with the replay-gap re-snapshot. The `galaxy.events.dropped` counter is unchanged; each burst logs one Warning ("re-reading them") and one Information line with the re-advised count. **Rate-limited (#991 review):** passes are at least 5 s apart and drops reported meanwhile coalesce into the next pass — repeated overflow bursts used to start a pass as soon as the previous one ended, re-advising (and pushing initial values into) the very channel that was overflowing. **A pass whose gateway session is gone no longer dials:** a reconnect completing between two subscriptions of a re-advise pass (resync, replay-gap re-snapshot, reconnect replay) used to send the next SubscribeBulk to the NEW session under the OLD session number; the rebind refused it and those live advises were never bound or released (then duplicated by the new session's replay). They cannot simply be released afterwards — once the session has moved, which session issued a reply's handles is ambiguous and old numbers are reused (#861) — so the pass stops before dialling.
- **OPC DA limit bits do not warn (#991 G-2).** `StatusCodeMap.FromQualityByte` masks the two limit bits (`QQSSSSLL`) before its table lookup, so `Good | LowLimited` (0xC1) and friends map like the unlimited quality. A byte still unlisted after the mask logs one Warning per distinct value per process — it used to log one per event on the pump's dispatch thread, enough to back the channel up into drops.
- **The deploy watcher paces every stream end (#991 G-3).** A `WatchDeployEvents` stream the gateway completes cleanly is re-subscribed after the same capped exponential backoff as a faulted one (1 s doubling to 30 s), and the backoff resets only after a stream stayed open 60 s — an event alone (the bootstrap every stream delivers) no longer resets it. It used to re-open immediately, hammering a gateway that ends its streams after the bootstrap.
- **Secured / verified writes are REFUSED `BadUserAccessDenied`, locally (#991 G-1 + review).** The driver has no
ArchestrA user identity: no `AuthenticateUser` flow, no supervisory advise for a secured item, and a gateway key would
additionally need `invoke:secure`. G-1 briefly routed SecuredWrite / VerifiedWrite attributes to `WriteSecured`, which
therefore could never succeed, and the gateway's refusal surfaced as `BadCommunicationError` (a comms fault). Until a
real per-caller identity flow exists (follow-up — like the #749 ack credential) a write to such an attribute returns
`BadUserAccessDenied` before anything reaches the wire (no AddItem / advise / Write; one Warning per attribute; no
health impact). The per-tag classification map that makes the refusal local is still **seeded for the authored tags**
- **Secured / verified writes are REFUSED `BadUserAccessDenied` by default, locally (#991 G-1 + review); a SecuredWrite
can opt in to the caller's identity (#1017, [below](#secured-writes-under-the-callers-galaxy-identity-1017)).** By
default the driver has no ArchestrA user identity to write under. G-1 briefly routed SecuredWrite / VerifiedWrite
attributes to `WriteSecured` with no `AuthenticateUser`, which therefore could never succeed, and the gateway's refusal
surfaced as `BadCommunicationError` (a comms fault). With `MxAccess.SecuredWrites = Refuse` (the default) a write to
such an attribute returns `BadUserAccessDenied` before anything reaches the wire (no AddItem / advise / Write; one
Warning per attribute; no health impact); a VerifiedWrite is refused in every mode. The per-tag classification map that
makes the refusal local (and routes an opted-in SecuredWrite) is still **seeded for the authored tags**
at `InitializeAsync` and on every deploy-watcher rediscovery, in the background, by one rooted depth-0
`DiscoverHierarchy` per authored object (`Browse/GatewayGalaxyAttributeSecuritySource`, 4 concurrent; cost tracks the
authored objects, not the Galaxy) — only `DiscoverAsync` filled it before, and the runtime never calls that on a served