feat(grpc-data): #1084 secured writes over a data connection need an export-level opt-in; #1091 Galaxy reports gRPC write outcomes definitively

#1084 - DataExport.AllowSecuredWrites (default false; migration AddDataExportAllowSecuredWrites, a bit NOT NULL DEFAULT 0
column, no constraint => no MigrationPreChecks twin; the preflight's legacy-schema tolerance covers the missing column).
- Valid only with Write: validator code DataExportSecuredWriteInvalid at authoring, the deploy gate and on a deployed
  row (an artifact row breaking it fails closed), modelled on AllowGalaxyServiceAck.
- LocalExportCatalog keeps it per rule (counts only with Write) and answers AllowsSecuredWrite(principal, node): an
  export of the principal, in the node's realm, granting Write, opted in, whose root contains the node.
- DataWriteExecutor stamps DataWriteAdmission.AllowsSecuredWrite (new, default false) from the catalog generation that
  admitted the write (re-checked by the dispatch gate's commit), never from the request.
- DriverInstanceActor.RichCaller returns null without it, so the driver gets NO caller: the driver option
  MxAccess.SecuredWritesOverDataConnections alone no longer lets a forwarding consumer cluster's link key write
  SecuredWrite attributes. Fail closed by default.
- AdminUI export editor: "Allow secured writes under this peer's key identity" checkbox (enabled only with Write).

#1091 (a) - GalaxyDriver implements IWriteOutcomeCapability + ICallerAwareWriteOutcomeCapability. GalaxyWriteOutcomes
maps BadUserAccessDenied and the OnWriteComplete verdicts BadNotWritable/BadTypeMismatch/BadOutOfRange/
BadConfigurationError to DriverConfirmedFailure, Good to AcceptedUnconfirmed (a provisional Good is indistinguishable),
everything else to OutcomeUnknown. A refused secured write is now a definite BadUserAccessDenied, not OutcomeUnknown.
- RunRichWriteAsync precedence: caller-aware outcome overload (caller present) -> outcome overload -> ICallerAwareWritable
  (caller present) -> IWritable. Both earlier behaviours kept; the OPC UA path is unchanged.

Tests (each failed before its fix where applicable):
- End to end through the runtime path (artifact -> catalog -> DataWriteRuntime executor -> ActorDataWriteRoute ->
  DriverInstanceActor behind the real dispatch gate -> real GalaxyDriver): export opt-in x driver option matrix; only
  both commit as the key's identity, either alone refuses BadUserAccessDenied definitively with no identity lookup.
  Ignoring the flag in RichCaller fails 3 tests.
- Catalog scope (root containment, Write, principal), artifact round-trip + fail-closed row, validator, migration SQL +
  no pending model changes, AdminUI checkbox enable/save (bUnit), actor precedence, Galaxy outcome mapping.
- ScriptForeignKeysAndExternalIdUniquenessMigrationTests now migrate to THEIR migration, not the latest.

Docs: DataConnections.md (two-gate table), Galaxy.md, security.md, rules/drivers.md.
This commit is contained in:
Joseph Doherty
2026-12-04 14:58:16 -05:00
parent 2f22003061
commit 8e2a793000
23 changed files with 2704 additions and 53 deletions
+6 -1
View File
@@ -228,7 +228,12 @@ host logger factory (wired in `DriverFactoryBootstrap`; the FOCAS and TwinCAT fa
design). The caller rides `WriteCaller` → `RouteNodeWrite`/`WriteAttribute.Caller` → `ICallerAwareWritable`; a gRPC data-connection
write carries the connection's principal + key id from its `DataWriteAdmission` + `WriteCaller.Origin = DataConnection`
(#1074), honoured only with the default-OFF `MxAccess.SecuredWritesOverDataConnections` (a forwarded write runs as the
LINK key's identity); `Origin` is stamped at the receiving seam, `Unspecified` ⇒ no identity. Not live-gated. `docs/drivers/Galaxy.md` §Secured writes.
LINK key's identity) AND the origin export's default-OFF `DataExport.AllowSecuredWrites` (#1084 — without it
`DriverInstanceActor.RichCaller` returns null, no caller reaches the driver); `Origin` is stamped at the receiving seam,
`Unspecified` ⇒ no identity. gRPC outcomes (#1091): Galaxy is `ICallerAwareWriteOutcomeCapability` — a refusal is
`DriverConfirmedFailure` + `BadUserAccessDenied` (`GalaxyWriteOutcomes`), not `OutcomeUnknown`; rich-write precedence =
caller-aware outcome (caller present) → outcome → `ICallerAwareWritable` (caller present) → `IWritable`. Both caller-aware
interfaces are OTOPCUA0001-guarded. 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
+25 -11
View File
@@ -14,7 +14,7 @@ The deployed configuration uses three entities:
| Entity | Operator choices |
|---|---|
| `DataConnection` | Owning cluster, explicit consumer nodes, expected remote cluster/node, Node or Cluster target, endpoint set, consistency, secret reference, operation subset and finite call limits. |
| `DataExport` | Origin-owned Raw or UNS root, authenticated peer principal, operation grants and export limits. |
| `DataExport` | Origin-owned Raw or UNS root, authenticated peer principal, operation grants, export limits and the default-off identity opt-ins `AllowGalaxyServiceAck` and `AllowSecuredWrites` (#1084, migration `AddDataExportAllowSecuredWrites`). |
| `RemoteNamespaceMapping` | Connection, consumer subset, local parent and branch name, same-realm remote root/address, operations, optional write-through, projection limits and freshness settings. |
New connections, exports and mappings are disabled by default; write-through also defaults off.
@@ -799,16 +799,30 @@ not see these bits; see "Mixed versions" above.
`otopcua/apikeys/<serviceKeyId>/galaxy-ack-user` and `…/galaxy-ack-password` in the **origin's** secrets store; without
them the #765 preflight refuses `BadUserAccessDenied`.
**Galaxy secured writes over a data connection (#1074) — opt-in, default off.** A write carries the connection's
principal, API key id and `Origin = DataConnection` to the driver. A Galaxy driver in `MxAccess.SecuredWrites =
ApiKeyIdentity` mode still refuses a SecuredWrite from a data connection (`BadUserAccessDenied`, before the wire, as
before) unless it also sets `MxAccess.SecuredWritesOverDataConnections = true`. Then it writes as the **connection key's**
Galaxy identity (the same `galaxy-ack-*` secrets as above; no fallback account). ⚠️ For a forwarding consumer cluster that
key is the link's service key, so every consumer-side client allowed to write the projected node would write secured
attributes as it. Unlike `AllowGalaxyServiceAck` there is no export-level switch; the driver option, the export's Write
grant and the origin ACL are the gates. A refused secured write reaches the caller as `OutcomeUnknown`, because the
Galaxy driver reports through the legacy write path. See
[Galaxy § Secured writes](drivers/Galaxy.md#secured-writes-under-the-callers-galaxy-identity-1017).
**Galaxy secured writes over a data connection (#1074, #1084) — two opt-ins, both default off.** A SecuredWrite
attribute written through a data connection runs as the **connection key's** Galaxy identity (the same `galaxy-ack-*`
secrets as above; no fallback account) only when BOTH hold:
| Gate | Where | Default | Without it |
|---|---|---|---|
| **`DataExport.AllowSecuredWrites`** (#1084; AdminUI export editor "Allow secured writes under this peer's key identity") | origin ConfigDb, per export; valid only with `Write` (validator code `DataExportSecuredWriteInvalid`, authoring, deploy gate and deployed row) | `false` | the origin dispatches the write to the driver with **no caller** — it is still admitted on the Write grant, but a caller-aware driver refuses an identity-bearing write exactly as an anonymous one |
| **`MxAccess.SecuredWritesOverDataConnections`** (#1074) | Galaxy driver config (with `SecuredWrites = ApiKeyIdentity`) | `false` | the driver refuses a caller whose `Origin = DataConnection` |
- The export flag counts only on an export of the connection's principal that grants `Write` AND whose root contains the
node (`LocalExportCatalog.AllowsSecuredWrite`); any one such export suffices, as for every grant. The origin decides it
when it admits the write, from the same catalog generation (`DataWriteAdmission.AllowsSecuredWrite`) — never from the
request — and the dispatch gate's commit re-checks that generation, so a deploy that clears it reaches the next write.
- Why two switches: the driver option applies to every connection that can write the driver's nodes, including a
**forwarding consumer cluster**, whose link key stands for every consumer-side client allowed to write the projected
node. The export flag scopes the delegation to one peer principal and one root. Turn it on for a direct client (e.g.
ScadaBridge with its own key); leave it off on an export to another OtOpcUa cluster unless delegating to the link's
identity is intended.
- The remaining gates are unchanged: the export's Write grant, the origin ACL for the connection's principal and, on a
consumer, its own write grants.
- **A refusal is reported definitively (#1091):** the Galaxy driver reports gRPC writes through `IWriteOutcomeCapability`
(+ the caller-aware `ICallerAwareWriteOutcomeCapability`), so a refused secured write is `DriverConfirmedFailure` +
`BadUserAccessDenied` (it used to be `OutcomeUnknown`). See
[Galaxy § Secured writes](drivers/Galaxy.md#secured-writes-under-the-callers-galaxy-identity-1017).
### Condition methods (`CallConditionMethod`)
+21 -6
View File
@@ -224,6 +224,12 @@ from the transport's `DataAuthenticatedContext` (never from the request payload)
at the commit point — plus `Origin = DataConnection`. The OPC UA node manager stamps `Origin = OpcUaSession`. The
runtime sets the origin from where it RECEIVED the write; nothing parses it out of the principal or key. No wire change.
**…and the origin's export must opt in too (#1084): `DataExport.AllowSecuredWrites`** (default `false`, valid only with
`Write`; AdminUI export editor "Allow secured writes under this peer's key identity"). The origin decides at admission
whether an export of the connection's principal that grants Write on the node opts in; if none does, the runtime hands
the driver **no caller** (`DriverInstanceActor.RichCaller` returns null) and the write takes the caller-less path — so the
driver option alone is not enough. See [DataConnections § Galaxy secured writes](../DataConnections.md).
The driver gives a caller an identity source only when `SecuredWrites = ApiKeyIdentity` **and** the origin is allowed:
| Origin | Identity source |
@@ -232,7 +238,7 @@ The driver gives a caller an identity source only when `SecuredWrites = ApiKeyId
| `DataConnection` | only with `MxAccess.SecuredWritesOverDataConnections = true` (default `false`; AdminUI "Also for gRPC data-connection writes") |
| `Unspecified` (the `WriteCaller` default) | never — fail closed, so a future call site that forgets to say where a write came from gets nothing |
**Off (default):** a SecuredWrite arriving over a data connection is refused exactly as before #1074 — no identity
**Off (default — either switch):** a SecuredWrite arriving over a data connection is refused exactly as before #1074 — no identity
lookup, the writer's local `BadUserAccessDenied`, nothing on the wire — even when the same key writes it successfully
over OPC UA. **On:** it runs as the connection key's own `/api-keys` Galaxy identity, as an OPC UA session with that key
would; no identity (or a broken one) ⇒ refused. The option is ignored in `Refuse` mode. Read before turning it on:
@@ -244,9 +250,17 @@ would; no identity (or a broken one) ⇒ refused. The option is ignored in `Refu
names the link's account, not the person. The remaining gates are the export's Write grant, the origin ACL for the
service principal and the consumer's own write grants. A direct client (e.g. ScadaBridge with its own key) is the case
the option is meant for; do not map an identity to a link's service key you do not want to delegate.
- **A refusal is not reported as one over gRPC.** The Galaxy driver is a plain `IWritable` (no
`IWriteOutcomeCapability`), so the rich write path reports any non-Good result, `BadUserAccessDenied` included, as
`OutcomeUnknown` — the same as every legacy driver's Bad (pre-existing; #1074 follow-up).
- **The forwarded-write case is why the export flag exists (#1084):** set `AllowSecuredWrites` on the export for a direct
client's principal and leave it off on an export to another OtOpcUa cluster's link unless delegating to it is intended.
- **gRPC write outcomes are definite where they can be (#1091).** The driver implements `IWriteOutcomeCapability` and the
caller-aware `ICallerAwareWriteOutcomeCapability` (`DriverInstanceActor.RunRichWriteAsync` precedence: caller-aware
outcome overload when the write carries a caller → plain outcome overload → `ICallerAwareWritable` → `IWritable`; the OPC
UA path is unchanged). `GalaxyWriteOutcomes` maps each result: `BadUserAccessDenied` (every secured/verified refusal, a
failed `AuthenticateUser`, a gateway `PermissionDenied`, MXAccess's access verdicts) and the `OnWriteComplete` verdicts
`BadNotWritable` / `BadTypeMismatch` / `BadOutOfRange` / `BadConfigurationError` ⇒ `DriverConfirmedFailure` with that
status; Good ⇒ `AcceptedUnconfirmed` (the writer cannot tell a confirmed Good from the provisional one an empty statuses
array produces); everything else (`BadCommunicationError`, `BadTimeout`, Uncertain, …) ⇒ `OutcomeUnknown`. Before
#1091 every non-Good result was `OutcomeUnknown`.
**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
@@ -275,8 +289,9 @@ wrong password ⇒ `BadUserAccessDenied` naming the user, password absent from e
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; the same write over a gRPC data connection with that
key ⇒ `BadUserAccessDenied`-refused (reported `OutcomeUnknown`, nothing in the gateway log) until
`SecuredWritesOverDataConnections = true`, then it commits as the mapped user (#1074).
key ⇒ `BadUserAccessDenied`-refused (reported `DriverConfirmedFailure`, #1091; nothing in the gateway log) until BOTH
`SecuredWritesOverDataConnections = true` and the origin export's `AllowSecuredWrites = true` (#1084) — check each alone
still refuses — then it commits as the mapped user (#1074).
Full per-field descriptions live in `Config/GalaxyDriverOptions.cs`. The full JSON skeleton is reproduced in [docs/v2/driver-specs.md §1](../v2/driver-specs.md).
+1 -1
View File
@@ -1401,7 +1401,7 @@ public enum NodePermissions : int
}
```
The three Write tiers map to Galaxy's v1 `SecurityClassification` — `FreeAccess`/`Operate` → `WriteOperate`, `Tune` → `WriteTune`, `Configure` → `WriteConfigure`. `VerifiedWrite` / `ViewOnly` classifications remain read-only from OPC UA regardless of grant; `SecuredWrite` is too unless the Galaxy driver opts in to `MxAccess.SecuredWrites = ApiKeyIdentity`, which writes it as the calling OPC UA session's key's own Galaxy identity (#1017). A secured write arriving over a **gRPC data connection** needs a second, default-off opt-in, `MxAccess.SecuredWritesOverDataConnections` (#1074); without it such a write is refused `BadUserAccessDenied` before the wire, as before. ⚠️ With it on, the identity is the **connection's** key — and a consumer OtOpcUa cluster forwarding its OPC UA clients' writes (projected-node write-through) presents its link's service key, so every consumer-side client allowed to write the projected node writes secured attributes as that key's Galaxy identity (the audit names the link's account, not the person). The driver tells the planes apart by `WriteCaller.Origin`, stamped by the runtime at the receiving seam (an unstated origin gets no identity). See [Galaxy § Secured writes](drivers/Galaxy.md#secured-writes-under-the-callers-galaxy-identity-1017).
The three Write tiers map to Galaxy's v1 `SecurityClassification` — `FreeAccess`/`Operate` → `WriteOperate`, `Tune` → `WriteTune`, `Configure` → `WriteConfigure`. `VerifiedWrite` / `ViewOnly` classifications remain read-only from OPC UA regardless of grant; `SecuredWrite` is too unless the Galaxy driver opts in to `MxAccess.SecuredWrites = ApiKeyIdentity`, which writes it as the calling OPC UA session's key's own Galaxy identity (#1017). A secured write arriving over a **gRPC data connection** needs two more default-off opt-ins: the driver's `MxAccess.SecuredWritesOverDataConnections` (#1074) AND, on the origin, the `DataExport.AllowSecuredWrites` of an export that grants the connection's principal `Write` on the node (#1084). Without the export flag the origin hands the driver no caller at all; without the driver option the driver refuses a data-connection caller; either way the write is refused `BadUserAccessDenied` before the wire and reported to the gRPC caller as a definite failure (#1091). ⚠️ With both on, the identity is the **connection's** key — and a consumer OtOpcUa cluster forwarding its OPC UA clients' writes (projected-node write-through) presents its link's service key, so every consumer-side client allowed to write the projected node writes secured attributes as that key's Galaxy identity (the audit names the link's account, not the person). That is why the export flag exists: it scopes the delegation to one peer and one root, so leave it off on an export to another OtOpcUa cluster unless that delegation is intended. The driver tells the planes apart by `WriteCaller.Origin`, stamped by the runtime at the receiving seam (an unstated origin gets no identity). See [Galaxy § Secured writes](drivers/Galaxy.md#secured-writes-under-the-callers-galaxy-identity-1017).
`HistoryUpdate` (bit 12) is a **separate** permission from `HistoryRead` so a read-only grant cannot also authorize OPC UA HistoryUpdate operations. `TriePermissionEvaluator` maps `OpcUaOperation.HistoryUpdate` to this bit. It is **not** included in any composite bundle (`ReadOnly` / `Operator` / `Engineer` / `Admin`) — it must be granted explicitly, and it is offered as its own checkbox in the AdminUI ACL editor (`AclEdit.razor`). The HistoryUpdate service itself is now implemented (SQL Server historian backend only) — see the next section.
@@ -31,5 +31,13 @@ public sealed class DataExport
/// <summary>A2 (used by A2b): per-export opt-in for remote acknowledgement of Galaxy conditions, which execute as the
/// origin's service identity (plan §5.6, Q2). Valid only with <c>AlarmAcknowledge</c>.</summary>
public bool AllowGalaxyServiceAck { get; set; }
/// <summary>
/// #1084: per-export opt-in for writes that act under the connection key's own identity (Galaxy SecuredWrite attributes,
/// written as the key's <c>/api-keys</c> Galaxy account). Without it the origin hands the driver NO caller for a write
/// admitted through this export, so a caller-aware driver refuses an identity-bearing write exactly as it would an
/// anonymous one — even with the driver's own <c>MxAccess.SecuredWritesOverDataConnections</c> on. Both are needed.
/// Valid only with <c>Write</c>. Default false (fail closed).
/// </summary>
public bool AllowSecuredWrites { get; set; }
public byte[] RowVersion { get; set; } = [];
}
@@ -0,0 +1,32 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
{
/// <inheritdoc />
public partial class AddDataExportAllowSecuredWrites : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
// #1084: the export-level opt-in for secured (caller-identity) writes over a data connection. Non-null with a
// false default, so every existing export keeps refusing them and no row needs a backfill. No check constraint:
// "only with Write" is a validator rule (DataExportSecuredWriteInvalid), like AllowGalaxyServiceAck's.
migrationBuilder.AddColumn<bool>(
name: "AllowSecuredWrites",
table: "DataExport",
type: "bit",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "AllowSecuredWrites",
table: "DataExport");
}
}
}
@@ -500,6 +500,9 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations
b.Property<bool>("AllowGalaxyServiceAck")
.HasColumnType("bit");
b.Property<bool>("AllowSecuredWrites")
.HasColumnType("bit");
b.Property<int>("AllowedOperations")
.HasColumnType("int");
@@ -349,6 +349,10 @@ public static class DataConnectionValidator
// must stay false; a deployed row from a newer central that carries both is tolerated (the flag is inert here).
if (export.AllowGalaxyServiceAck && !export.AllowedOperations.HasFlag(DataOperations.AlarmAcknowledge))
Add("DataExportGalaxyAckInvalid", id, "Galaxy service acknowledgement can be allowed only on an export that grants AlarmAcknowledge.");
// #1084: the secured-write (caller-identity) opt-in qualifies the Write grant and means nothing without it. Checked
// at authoring, at the deploy gate and on a deployed row alike (a deployed row breaking it fails closed).
if (export.AllowSecuredWrites && !export.AllowedOperations.HasFlag(DataOperations.Write))
Add("DataExportSecuredWriteInvalid", id, "Secured writes can be allowed only on an export that grants Write.");
// #942: an alarm-bearing tag is never a value (#917: an unsupported value node, hidden from Browse; #896: no UNS
// variable), and its condition placements sit under the tag's folder / the referencing equipment, never under the
// tag. So an export rooted at the tag (RawTag) grants nothing at all, and one rooted at a reference to it
@@ -29,10 +29,16 @@ public sealed record WriteItem(string CorrelationId, string OperationId, DataVie
/// recheck the original key's current principal and credential version against authority and its
/// original expiry even when the epoch is unchanged. ApiKeyId and CredentialVersion are non-secret
/// identifiers, never the bearer credential.
/// <para>
/// <paramref name="AllowsSecuredWrite"/> (#1084): whether an export covering the node opts in to secured (caller-identity)
/// writes (<c>DataExport.AllowSecuredWrites</c>). Only then does the runtime hand the driver the connection's caller; false
/// (the default — fail closed) dispatches the write with no caller, so a caller-aware driver refuses an identity-bearing
/// write exactly as it would an anonymous one.
/// </para>
/// </summary>
public sealed record DataWriteAdmission(string PrincipalId, DataView View, long AuthorityEpoch, long CatalogRevision,
string ServingIncarnation, string DriverIncarnation, string OperationId, long MonotonicExpiry,
string ApiKeyId, DateTimeOffset? CredentialExpiresUtc, string CredentialVersion)
string ApiKeyId, DateTimeOffset? CredentialExpiresUtc, string CredentialVersion, bool AllowsSecuredWrite = false)
{
public void Validate()
{
@@ -39,8 +39,9 @@ public enum WriteCallerOrigin
/// 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" />. Both data planes
/// supply one: an OPC UA write from its session, a gRPC data-connection write from the connection's authenticated
/// key (#1074) — except through <c>IWriteOutcomeCapability</c>, which takes precedence on the gRPC path and carries
/// no caller. It must keep
/// key (#1074), and only when the origin export opts in (<c>DataExport.AllowSecuredWrites</c>, #1084). On the gRPC path
/// a driver that also implements <c>IWriteOutcomeCapability</c> is called through that instead — with a caller, through
/// <c>ICallerAwareWriteOutcomeCapability</c> (#1091). 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>
@@ -4,6 +4,7 @@ using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.MxGateway.Client;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Browse;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Health;
@@ -38,7 +39,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy;
/// </para>
/// </remarks>
public sealed class GalaxyDriver
: IDriver, ITagDiscovery, IReadable, IWritable, ICallerAwareWritable, ISubscribable, IRediscoverable, IHostConnectivityProbe, IAlarmSource, IAlarmInitialStateSignal, IAlarmAcknowledgePreflight, IAlarmAcknowledgeConfirmation, ISkippedTagReporter, IDisposable, IAsyncDisposable
: IDriver, ITagDiscovery, IReadable, IWritable, ICallerAwareWritable, ICallerAwareWriteOutcomeCapability, 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>
@@ -2438,6 +2439,42 @@ public sealed class GalaxyDriver
dialledWrites, attributeRef => ResolveSecurity(ToRawPath(attributeRef)), securedCredential, cancellationToken);
}
// ===== IWriteOutcomeCapability (#1091) — the gRPC data-connection write path =====
/// <summary>
/// #1091 — <see cref="WriteAsync(IReadOnlyList{WriteRequest}, CancellationToken)"/> reported as explicit outcomes for
/// the gRPC data-connection write path (<see cref="GalaxyWriteOutcomes.From"/>): a refusal is a definite
/// <see cref="DataWriteState.DriverConfirmedFailure"/> carrying its status (a refused secured write ⇒
/// <c>BadUserAccessDenied</c>), where the legacy path reported every non-Good result as <c>OutcomeUnknown</c>.
/// </summary>
/// <param name="writes">Pairs of full reference (RawPath) + value.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>One outcome per request, in order.</returns>
public Task<IReadOnlyList<DataWriteOutcome>> WriteWithOutcomesAsync(
IReadOnlyList<WriteRequest> writes, CancellationToken cancellationToken)
=> WithOutcomesAsync(writes, caller: null, cancellationToken);
/// <summary>
/// #1091 — <see cref="WriteAsync(IReadOnlyList{WriteRequest}, WriteCaller, CancellationToken)"/> (the caller's Galaxy
/// identity for SecuredWrite attributes, under the same origin rules) reported as explicit outcomes.
/// </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 outcome per request, in order.</returns>
public Task<IReadOnlyList<DataWriteOutcome>> WriteWithOutcomesAsync(
IReadOnlyList<WriteRequest> writes, WriteCaller caller, CancellationToken cancellationToken)
=> WithOutcomesAsync(writes, caller ?? throw new ArgumentNullException(nameof(caller)), cancellationToken);
private async Task<IReadOnlyList<DataWriteOutcome>> WithOutcomesAsync(
IReadOnlyList<WriteRequest> writes, WriteCaller? caller, CancellationToken cancellationToken)
{
var results = await WriteCoreAsync(writes, caller, cancellationToken).ConfigureAwait(false);
var outcomes = new DataWriteOutcome[results.Count];
for (var i = 0; i < results.Count; i++) outcomes[i] = GalaxyWriteOutcomes.From(results[i]);
return outcomes;
}
/// <summary>
/// #1074 — which data planes a SecuredWrite may run under the caller's identity on. An OPC UA session always
/// (the #1017 opt-in alone); a gRPC data connection only with <c>MxAccess.SecuredWritesOverDataConnections</c>
@@ -0,0 +1,47 @@
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
/// <summary>
/// #1091 — how a Galaxy <see cref="WriteResult"/> reads as a gRPC data-connection <see cref="DataWriteOutcome"/>. Only a
/// status that can arise solely from a definite verdict is reported as one; everything ambiguous stays
/// <see cref="DataWriteState.OutcomeUnknown"/>, because a caller treats a definite failure as "the value did not change".
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><b>Good</b> ⇒ <see cref="DataWriteState.AcceptedUnconfirmed"/> (as the legacy path reported it): the writer
/// reports a provisional Good off an EMPTY gateway statuses array (the completion wait timed out), which the result
/// cannot tell apart from a confirmed one.</item>
/// <item><b>Definite refusals</b> ⇒ <see cref="DataWriteState.DriverConfirmedFailure"/> with the status:
/// <c>BadUserAccessDenied</c> — a local secured/verified-write refusal (no identity, origin not allowed, identity
/// unresolvable), a failed <c>AuthenticateUser</c> (no <c>WriteSecured</c> sent), the gateway refusing the caller
/// (<c>PermissionDenied</c>/<c>Unauthenticated</c>, nothing executed) or MXAccess's own access verdict (1008/1012/
/// 1013/1016/1017); and the MXAccess <c>OnWriteComplete</c> verdicts <c>BadNotWritable</c>, <c>BadTypeMismatch</c>,
/// <c>BadOutOfRange</c> and <c>BadConfigurationError</c>, which no transport/exception path of the writer produces.</item>
/// <item><b>Everything else</b> ⇒ <see cref="DataWriteState.OutcomeUnknown"/> with the status:
/// <c>BadCommunicationError</c> (protocol failure, exception, failed advise), <c>BadTimeout</c>, Uncertain
/// (Pending/Warning), <c>BadInternalError</c>, generic Bad and any other code.</item>
/// </list>
/// </remarks>
internal static class GalaxyWriteOutcomes
{
/// <summary>Maps one write result.</summary>
/// <param name="result">The writer's result.</param>
/// <returns>The data-connection outcome.</returns>
public static DataWriteOutcome From(WriteResult result)
{
ArgumentNullException.ThrowIfNull(result);
var status = result.StatusCode;
if (status == StatusCodeMap.Good) return new(DataWriteState.AcceptedUnconfirmed, status, null);
return status switch
{
StatusCodeMap.BadUserAccessDenied => new(DataWriteState.DriverConfirmedFailure, status, "Write refused: access denied."),
StatusCodeMap.BadNotWritable => new(DataWriteState.DriverConfirmedFailure, status, "Write refused: not writable."),
StatusCodeMap.BadTypeMismatch => new(DataWriteState.DriverConfirmedFailure, status, "Write refused: type mismatch."),
StatusCodeMap.BadOutOfRange => new(DataWriteState.DriverConfirmedFailure, status, "Write refused: out of range."),
StatusCodeMap.BadConfigurationError => new(DataWriteState.DriverConfirmedFailure, status, "Write refused: configuration error."),
_ => new(DataWriteState.OutcomeUnknown, status, "Write outcome unknown."),
};
}
}
@@ -123,6 +123,7 @@ else
<label class="form-label" for="export-history-bytes">History response bytes</label><input id="export-history-bytes" type="number" min="@DataConnectionValidator.MinHistoryResponseBytesLimit" max="@DataConnectionValidator.MaxHistoryResponseBytesLimit" class="form-control mb-2" @bind="e.MaxHistoryResponseBytes" /><div class="form-text">Larger answers are sent in bounded chunks.</div>
<label class="form-label" for="export-max-conditions">Conditions per alarm subscription</label><input id="export-max-conditions" type="number" min="1" max="@DataConnectionValidator.MaxConditionsLimit" class="form-control mb-2" @bind="e.MaxConditions" /><div class="form-text">A remote AlarmSubscribe scope with more conditions than this is refused (ConditionCapacity) before anything is imported.</div>
<label class="d-block"><input id="export-galaxy-ack" type="checkbox" @bind="e.AllowGalaxyServiceAck" disabled="@(!e.AllowedOperations.HasFlag(DataOperations.AlarmAcknowledge) && !e.AllowGalaxyServiceAck)" /> Allow remote acknowledge of Galaxy alarms</label><div class="form-text">Galaxy-sourced alarms are acknowledged under this peer's API-key Galaxy ack identity (provision <code>otopcua/apikeys/&lt;keyId&gt;/galaxy-ack-user</code> and <code>…/galaxy-ack-password</code> on this cluster). Requires AlarmAcknowledge.</div>
<label class="d-block"><input id="export-secured-writes" type="checkbox" @bind="e.AllowSecuredWrites" disabled="@(!e.AllowedOperations.HasFlag(DataOperations.Write) && !e.AllowSecuredWrites)" /> Allow secured writes under this peer's key identity</label><div class="form-text">Galaxy SecuredWrite attributes written through this export run as this peer's API-key Galaxy identity (the same <code>otopcua/apikeys/&lt;keyId&gt;/galaxy-ack-*</code> secrets). Also needs the Galaxy driver's "Also for gRPC data-connection writes". If the peer is another OtOpcUa cluster, every client it forwards writes for writes as that one identity. Requires Write.</div>
<label><input type="checkbox" @bind="e.Enabled" /> Enabled in next deployment</label>@Actions(e, e.DataExportRowId != Guid.Empty)
</div></section>
}
@@ -144,7 +144,10 @@ internal sealed class DataWriteExecutor(DataAuthenticatedContext context, Func<L
var issued = clock.GetTimestamp();
var admission = new DataWriteAdmission(context.PrincipalId, node.Metadata.View, current.AuthorityEpoch,
current.Serving.CatalogEpoch, current.Serving.Incarnation, target.DriverIncarnation, item.OperationId,
expiration, context.ApiKeyId, context.CredentialExpiresUtc, context.CredentialVersion);
expiration, context.ApiKeyId, context.CredentialExpiresUtc, context.CredentialVersion,
// #1084: decided here, from the same catalog generation that admitted the write (the dispatch gate's commit
// re-checks that generation), never from the request.
AllowsSecuredWrite: current.AllowsSecuredWrite(context.PrincipalId, node));
var scope = new FrozenWriteScope(node.Scope.ClusterId, node.Scope.Kind, node.Scope.Segments.ToImmutableArray());
var proof = new WriteRouteProof(admission, scope, node.EntityKind, node.EntityId, node.Source,
target.DriverInstanceId, target.DriverReference, target.RouteGeneration, target.PrimaryGeneration, current.Serving);
@@ -22,7 +22,7 @@ public sealed partial class LocalExportCatalog
private sealed record ExportRule(string Identity, string Principal, DataRealm Realm, DataView? Root, bool WholeRealm,
DataOperations Operations, int Batch, int Page, int Items, int Streams,
int HistoryReads = 4, int HistoryValuesPerPage = 10_000, int HistoryResponseBytes = 4 * 1024 * 1024,
int Conditions = 1000, bool GalaxyServiceAck = false);
int Conditions = 1000, bool GalaxyServiceAck = false, bool SecuredWrites = false);
public LocalExportCatalog(string clusterId, ServingIdentity serving, IDataMappedCatalogAuthority activation,
IEnumerable<LocalDataNode> nodes, IEnumerable<DataExport> exports, int maximumNodes = 100_000,
@@ -100,7 +100,9 @@ public sealed partial class LocalExportCatalog
export.AllowedOperations & DataOperationSets.Understood, export.MaxBatchItems, export.MaxPageItems, export.MaxMonitoredItems, export.MaxStreams,
export.MaxConcurrentHistoryReads, export.MaxHistoryValuesPerPage, export.MaxHistoryResponseBytes, export.MaxConditions,
// A2b (§6, Q2): the Galaxy service-ack opt-in counts only with the AlarmAcknowledge grant it qualifies.
export.AllowGalaxyServiceAck && (export.AllowedOperations & DataOperations.AlarmAcknowledge) != 0));
export.AllowGalaxyServiceAck && (export.AllowedOperations & DataOperations.AlarmAcknowledge) != 0,
// #1084: the secured-write (caller-identity) opt-in counts only with the Write grant it qualifies.
export.AllowSecuredWrites && (export.AllowedOperations & DataOperations.Write) != 0));
if (UnknownOperationDrops.Unknown(export.AllowedOperations) is var unknown && unknown != DataOperations.None)
dropped[export.DataExportId] = unknown;
}
@@ -201,6 +203,25 @@ public sealed partial class LocalExportCatalog
return false;
}
/// <summary>
/// #1084: whether <paramref name="principal"/> holds an export of the node's realm that grants Write on it AND opts in to
/// secured writes (<c>DataExport.AllowSecuredWrites</c>) — i.e. a write admitted for this node may carry the connection's
/// caller to a caller-aware driver (Galaxy SecuredWrite under the key's Galaxy identity). Any one such export suffices,
/// exactly as for <see cref="AllowsExport"/>; with none the write is still admitted (on the Write grant) but goes to the
/// driver without a caller, so an identity-bearing write is refused there.
/// </summary>
internal bool AllowsSecuredWrite(string principal, LocalDataNode node)
{
ArgumentNullException.ThrowIfNull(node);
foreach (var rule in _exports)
{
if (!rule.SecuredWrites || !string.Equals(principal, rule.Principal, StringComparison.OrdinalIgnoreCase)
|| rule.Realm != node.Metadata.View.Realm || (rule.Operations & DataOperations.Write) == 0) continue;
if (rule.WholeRealm || IsAncestor(rule.Root!, node.Metadata.View)) return true;
}
return false;
}
internal string SubscriptionExportScope(string principal, LocalDataNode node)
{
var ids = _exports.Where(rule => string.Equals(principal, rule.Principal, StringComparison.OrdinalIgnoreCase) &&
@@ -1510,14 +1510,18 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
{
// #1074: a gRPC data-connection write carries its caller like an OPC UA write does (#1017) —
// the admission's principal + API key id, bound from the authenticated transport context
// (never from the request payload) and re-checked by the dispatch gate's commit above. A
// caller-aware driver (Galaxy SecuredWrite under the key's Galaxy identity) gets it; every
// other driver is unchanged. No driver is both IWriteOutcomeCapability and
// ICallerAwareWritable today; one that were would need a caller-aware outcome overload.
if (driver is IWriteOutcomeCapability rich)
// (never from the request payload) and re-checked by the dispatch gate's commit above. #1084:
// only when an export covering the node opts in (AllowsSecuredWrite); otherwise there is no
// caller and a caller-aware driver gets the caller-less call (identity-bearing writes refused).
// Precedence (#1091): the explicit-outcome path wins over the legacy one, and within each the
// caller-aware overload is used whenever there is a caller.
var caller = RichCaller(msg.Ticket.Proof.Admission);
if (caller is not null && driver is ICallerAwareWriteOutcomeCapability richCaller)
_ = ObserveRichDriver(richCaller.WriteWithOutcomesAsync(request, caller, ct), physical);
else if (driver is IWriteOutcomeCapability rich)
_ = ObserveRichDriver(rich.WriteWithOutcomesAsync(request, ct), physical);
else if (driver is ICallerAwareWritable callerAware)
_ = ObserveLegacyDriver(callerAware.WriteAsync(request, RichCaller(msg.Ticket.Proof.Admission), ct), physical);
else if (caller is not null && driver is ICallerAwareWritable callerAware)
_ = ObserveLegacyDriver(callerAware.WriteAsync(request, caller, ct), physical);
else
_ = ObserveLegacyDriver(((IWritable)driver).WriteAsync(request, ct), physical);
}
@@ -1583,11 +1587,17 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// Both are mandatory on an admission (<see cref="DataWriteAdmission.Validate"/>) and carry no secret. Marked
/// <see cref="WriteCallerOrigin.DataConnection"/> so a driver can hold this plane to its own opt-in (Galaxy
/// <c>MxAccess.SecuredWritesOverDataConnections</c>, default off).
/// <para>
/// #1084: null unless the admission says an export covering the node opts in to secured writes
/// (<c>DataExport.AllowSecuredWrites</c>, default off). The driver option alone is therefore not enough: a
/// forwarding consumer cluster's link gets no caller identity unless the origin's export for it says so.
/// </para>
/// </summary>
internal static WriteCaller RichCaller(DataWriteAdmission admission) =>
new(string.IsNullOrWhiteSpace(admission.PrincipalId) ? null : admission.PrincipalId,
string.IsNullOrWhiteSpace(admission.ApiKeyId) ? null : admission.ApiKeyId,
WriteCallerOrigin.DataConnection);
internal static WriteCaller? RichCaller(DataWriteAdmission admission) =>
!admission.AllowsSecuredWrite ? null
: new(string.IsNullOrWhiteSpace(admission.PrincipalId) ? null : admission.PrincipalId,
string.IsNullOrWhiteSpace(admission.ApiKeyId) ? null : admission.ApiKeyId,
WriteCallerOrigin.DataConnection);
private static async Task ObserveRichDriver(Task<IReadOnlyList<DataWriteOutcome>> task,
TaskCompletionSource<DataWriteOutcome> physical)
@@ -0,0 +1,60 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests.DataConnections;
/// <summary>
/// #1084: <see cref="DataExport.AllowSecuredWrites"/> — the export-level opt-in a secured (caller-identity) write over a data
/// connection needs on top of the driver's own <c>MxAccess.SecuredWritesOverDataConnections</c>. Default off, valid only with
/// the Write grant it qualifies, added by a default-false column.
/// </summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData")]
public sealed class GrpcDataSecuredWriteExportConfigurationTests
{
[Fact]
public void A_new_export_does_not_allow_secured_writes()
{
new DataExport().AllowSecuredWrites.ShouldBeFalse("fail closed: the opt-in defaults off");
}
[Fact]
public void AllowSecuredWrites_is_valid_only_with_Write_at_authoring_and_on_a_deployed_row()
{
var draft = GrpcDataReservedOperationAuthoringTests.Snapshot(DataOperations.Browse | DataOperations.Read);
DataConnectionValidator.Validate(draft).ShouldNotContain(x => x.Code == "DataExportSecuredWriteInvalid");
draft.DataExports[0].AllowSecuredWrites = true;
DataConnectionValidator.Validate(draft).ShouldContain(x => x.Code == "DataExportSecuredWriteInvalid" && x.Context == "export");
DataConnectionValidator.ValidateDeployed(draft).ShouldContain(x => x.Code == "DataExportSecuredWriteInvalid" && x.Context == "export");
// With the Write grant the flag authors and deploys cleanly.
draft.DataExports[0].AllowedOperations = DataOperations.Browse | DataOperations.Read | DataOperations.Write;
DataConnectionValidator.Validate(draft).ShouldNotContain(x => x.Code == "DataExportSecuredWriteInvalid");
DataConnectionValidator.ValidateDeployed(draft).ShouldNotContain(x => x.Code == "DataExportSecuredWriteInvalid");
// A disabled export is not validated (it grants nothing either way).
draft.DataExports[0].AllowedOperations = DataOperations.Read;
draft.DataExports[0].Enabled = false;
DataConnectionValidator.Validate(draft).ShouldNotContain(x => x.Code == "DataExportSecuredWriteInvalid");
}
[Fact]
public void Migration_adds_a_default_false_column_reversibly_and_no_constraint()
{
using var db = new OtOpcUaConfigDbContext(new DbContextOptionsBuilder<OtOpcUaConfigDbContext>()
.UseSqlServer("Server=127.0.0.1,1;Database=design;Integrated Security=true;TrustServerCertificate=true").Options);
var migrations = db.Database.GetMigrations().ToArray();
var index = Array.FindIndex(migrations, x => x.EndsWith("_AddDataExportAllowSecuredWrites", StringComparison.Ordinal));
index.ShouldBeGreaterThan(0);
var migrator = db.GetService<IMigrator>();
var up = migrator.GenerateScript(migrations[index - 1], migrations[index]);
up.ShouldContain("ALTER TABLE [DataExport] ADD [AllowSecuredWrites] bit NOT NULL DEFAULT CAST(0 AS bit)");
up.ShouldNotContain("CHECK", Case.Sensitive, "no constraint, so the upgrade preflight needs no MigrationPreChecks twin");
var down = migrator.GenerateScript(migrations[index], migrations[index - 1]);
down.ShouldContain("DROP COLUMN [AllowSecuredWrites]");
db.Database.HasPendingModelChanges().ShouldBeFalse();
}
}
@@ -16,6 +16,8 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests;
public sealed class ScriptForeignKeysAndExternalIdUniquenessMigrationTests
{
private const string Previous = "20261203154217_ConfigurationGapsIndexesAndRowVersions";
// Migrate up to THIS migration, not the latest: a later migration must not change what these tests assert (#1084 added one).
private const string This = "20261203200204_ScriptForeignKeysAndExternalIdUniqueness";
private static Equipment NewEquipment(string? zTag = null, string? sapId = null)
{
@@ -50,7 +52,7 @@ public sealed class ScriptForeignKeysAndExternalIdUniquenessMigrationTests
scratch.Execute(
"INSERT ExternalIdReservation (Kind, Value, EquipmentUuid, ClusterId, FirstPublishedBy) VALUES ('ZTag', 'ZT-9', NEWID(), 'c', 't')");
var ex = Should.Throw<SqlException>(() => scratch.MigrateTo());
var ex = Should.Throw<SqlException>(() => scratch.MigrateTo(This));
ex.Number.ShouldBe(51049);
ex.Message.ShouldContain("VT-dangling->SC-gone");
@@ -88,7 +90,7 @@ public sealed class ScriptForeignKeysAndExternalIdUniquenessMigrationTests
db.SaveChanges();
}
Should.NotThrow(() => scratch.MigrateTo());
Should.NotThrow(() => scratch.MigrateTo(This));
scratch.LastAppliedMigration().ShouldEndWith("_ScriptForeignKeysAndExternalIdUniqueness");
scratch.Scalar("SELECT COUNT(*) FROM sys.foreign_keys WHERE name IN ('FK_VirtualTag_Script', 'FK_ScriptedAlarm_Script')").ShouldBe(2);
@@ -0,0 +1,124 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
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>
/// #1091 — the Galaxy driver reports gRPC data-connection writes through <see cref="IWriteOutcomeCapability"/> (and its
/// caller-aware overload), so a refused secured write is a definite <see cref="DataWriteState.DriverConfirmedFailure"/> +
/// <c>BadUserAccessDenied</c> instead of the legacy path's <c>OutcomeUnknown</c>; only verdict-only statuses are definite.
/// </summary>
public sealed class GalaxyDriverWriteOutcomeTests
{
[Theory]
[InlineData(StatusCodeMap.Good, DataWriteState.AcceptedUnconfirmed)]
[InlineData(StatusCodeMap.BadUserAccessDenied, DataWriteState.DriverConfirmedFailure)]
[InlineData(StatusCodeMap.BadNotWritable, DataWriteState.DriverConfirmedFailure)]
[InlineData(StatusCodeMap.BadTypeMismatch, DataWriteState.DriverConfirmedFailure)]
[InlineData(StatusCodeMap.BadOutOfRange, DataWriteState.DriverConfirmedFailure)]
[InlineData(StatusCodeMap.BadConfigurationError, DataWriteState.DriverConfirmedFailure)]
[InlineData(StatusCodeMap.BadCommunicationError, DataWriteState.OutcomeUnknown)]
[InlineData(StatusCodeMap.BadTimeout, DataWriteState.OutcomeUnknown)]
[InlineData(StatusCodeMap.BadInternalError, DataWriteState.OutcomeUnknown)]
[InlineData(StatusCodeMap.BadOutOfService, DataWriteState.OutcomeUnknown)]
[InlineData(StatusCodeMap.Uncertain, DataWriteState.OutcomeUnknown)]
[InlineData(StatusCodeMap.Bad, DataWriteState.OutcomeUnknown)]
public void A_write_result_maps_to_a_definite_outcome_only_for_a_verdict_status(uint status, DataWriteState expected)
{
var outcome = GalaxyWriteOutcomes.From(new WriteResult(status));
outcome.State.ShouldBe(expected);
outcome.StatusCode.ShouldBe(status, "the status rides the outcome unchanged");
}
[Fact]
public async Task A_secured_write_with_no_caller_is_reported_as_a_definite_access_refusal()
{
var (driver, writer) = Build(overDataConnections: true);
var outcomes = await driver.WriteWithOutcomesAsync([new WriteRequest("Plant/Tank1/SP", 1.0)],
TestContext.Current.CancellationToken);
var outcome = outcomes.ShouldHaveSingleItem();
outcome.State.ShouldBe(DataWriteState.DriverConfirmedFailure);
outcome.StatusCode.ShouldBe(StatusCodeMap.BadUserAccessDenied);
writer.Sources.ShouldHaveSingleItem().ShouldBeNull("no caller ⇒ no identity source");
}
[Fact]
public async Task The_caller_overload_follows_the_same_origin_rules_as_the_legacy_one()
{
var (driver, writer) = Build(overDataConnections: false);
var caller = new WriteCaller("svc-mes", "0a1b2c3d4e5f6071", WriteCallerOrigin.DataConnection);
var refused = await driver.WriteWithOutcomesAsync([new WriteRequest("Plant/Tank1/SP", 1.0)], caller,
TestContext.Current.CancellationToken);
refused.ShouldHaveSingleItem().State.ShouldBe(DataWriteState.DriverConfirmedFailure,
"a data-connection caller gets no identity without MxAccess.SecuredWritesOverDataConnections");
var (optedIn, optedInWriter) = Build(overDataConnections: true);
var written = await optedIn.WriteWithOutcomesAsync([new WriteRequest("Plant/Tank1/SP", 1.0)], caller,
TestContext.Current.CancellationToken);
written.ShouldHaveSingleItem().State.ShouldBe(DataWriteState.AcceptedUnconfirmed);
optedInWriter.Sources.ShouldHaveSingleItem().ShouldNotBeNull("positive control: the opted-in driver writes as the key");
writer.Sources.ShouldHaveSingleItem().ShouldBeNull();
}
[Fact]
public async Task Outcomes_keep_request_order_for_a_mixed_batch()
{
var (driver, _) = Build(overDataConnections: true, statuses: [StatusCodeMap.Good, StatusCodeMap.BadCommunicationError, StatusCodeMap.BadNotWritable]);
var outcomes = await driver.WriteWithOutcomesAsync(
[new WriteRequest("Plant/Tank1/SP", 1.0), new WriteRequest("Plant/Tank1/SP", 2.0), new WriteRequest("Plant/Tank1/SP", 3.0)],
TestContext.Current.CancellationToken);
outcomes.Select(o => o.State).ShouldBe(
[DataWriteState.AcceptedUnconfirmed, DataWriteState.OutcomeUnknown, DataWriteState.DriverConfirmedFailure]);
}
private static (GalaxyDriver Driver, SecuredWriter Writer) Build(bool overDataConnections, uint[]? statuses = null)
{
var writer = new SecuredWriter(statuses);
var options = new GalaxyDriverOptions(
new GalaxyGatewayOptions("https://mxgw.test:5001", "key"),
new GalaxyMxAccessOptions("OtOpcUa-A")
{
SecuredWrites = GalaxySecuredWriteMode.ApiKeyIdentity,
SecuredWritesOverDataConnections = overDataConnections,
},
new GalaxyRepositoryOptions(WatchDeployEvents: false),
new GalaxyReconnectOptions())
{
RawTags = [new RawTagEntry("Plant/Tank1/SP", """{"attributeRef":"Tank1.SP"}""", false)],
};
return (new GalaxyDriver("g", options, hierarchySource: null, dataWriter: writer,
ackCredentialResolver: FixedAckCredentialResolver.Fallback()), writer);
}
/// <summary>Like the real writer for a SecuredWrite tag: refuses <c>BadUserAccessDenied</c> without an identity source;
/// with one (or with canned <paramref name="statuses"/>) answers per request.</summary>
private sealed class SecuredWriter(uint[]? statuses) : IGalaxyDataWriter
{
public List<Func<CancellationToken, Task<GalaxyAckCredentialResolution>>?> Sources { get; } = [];
public Task<IReadOnlyList<WriteResult>> WriteAsync(IReadOnlyList<WriteRequest> writes,
Func<string, SecurityClassification> securityResolver, CancellationToken cancellationToken)
=> ((IGalaxyDataWriter)this).WriteAsync(writes, securityResolver, null, cancellationToken);
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>>(statuses is not null
? [.. statuses.Select(s => new WriteResult(s))]
: [.. writes.Select(_ => new WriteResult(securedCredential is null ? StatusCodeMap.BadUserAccessDenied : StatusCodeMap.Good))]);
}
public void InvalidateHandleCaches() { }
}
}
@@ -54,6 +54,8 @@ public sealed class DataConnectionRootPickerTests : BunitContext
protected override object? Invoke(System.Reflection.MethodInfo? method, object?[]? args) => throw new NotSupportedException("Node-pick mode must not call " + method?.Name);
}
private string? _dbName;
private IRenderedComponent<CascadingValue<Task<AuthenticationState>>> RenderPage()
{
Services.RemoveAll<IAuthorizationService>();
@@ -62,7 +64,7 @@ public sealed class DataConnectionRootPickerTests : BunitContext
Services.AddCascadingAuthenticationState();
Services.AddSingleton<AuthenticationStateProvider>(new PrincipalState());
Services.AddSingleton<IFleetDiagnosticsClient>(new NoDiagnostics());
var name = RawTreeTestDb.SeedFresh();
var name = _dbName = RawTreeTestDb.SeedFresh();
using (var db = RawTreeTestDb.CreateNamed(name))
{
db.UnsAreas.Add(new UnsArea { UnsAreaId = "AREA-1", ClusterId = Cluster, Name = "Packaging" });
@@ -138,6 +140,27 @@ public sealed class DataConnectionRootPickerTests : BunitContext
cut.WaitForAssertion(() => cut.Find("#remote-root").GetAttribute("value").ShouldBe("AREA-OTHER"));
}
/// <summary>#1084: the export editor's secured-write opt-in is offered only with the Write grant and is saved to the row.</summary>
[Fact]
public void Export_SecuredWritesCheckbox_RequiresWrite_AndIsSaved()
{
var cut = RenderPage();
cut.WaitForElement("button:contains('New export')").Click();
cut.WaitForElement("#export-secured-writes").HasAttribute("disabled").ShouldBeTrue("a new export has no Write grant");
cut.Find("#export-id").Change("EXP-SW");
cut.Find("#principal").Change("peer-principal");
cut.Find("#export-root-id").Change("RawDevice|" + RawTreeTestDb.FolderedDeviceId);
cut.FindAll("fieldset label").Single(l => l.TextContent.Trim() == "Write").QuerySelector("input")!.Change(true);
cut.WaitForAssertion(() => cut.Find("#export-secured-writes").HasAttribute("disabled").ShouldBeFalse());
cut.Find("#export-secured-writes").Change(true);
cut.Find("button:contains('Save draft')").Click();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Draft saved"));
using var db = RawTreeTestDb.CreateNamed(_dbName!);
var saved = db.DataExports.Single(x => x.DataExportId == "EXP-SW");
saved.AllowSecuredWrites.ShouldBeTrue();
saved.AllowedOperations.HasFlag(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataOperations.Write).ShouldBeTrue();
}
[Fact]
public void Cancel_LeavesTheFieldUnchanged()
{
@@ -22,7 +22,7 @@ using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P05")]
public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase
public sealed partial class GrpcDataDriverOutcomeTests : RuntimeActorTestBase
{
private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10);
@@ -318,13 +318,14 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase
/// <see cref="ICallerAwareWritable"/> carrying the ADMITTED principal + API key id (bound from the authenticated
/// transport context), exactly as an OPC UA write carries its session's (#1017). Before the fix the rich path
/// always called the caller-less <see cref="IWritable.WriteAsync"/>, so a Galaxy SecuredWrite was refused.
/// #1084: only for a write whose admitting export opts in to secured writes.
/// </summary>
[Fact]
public async Task Rich_write_hands_a_caller_aware_driver_the_admitted_principal_and_key()
{
var driver = new CallerRecordingDriver();
var actor = Connect(driver, new RecordingGate(), new LateWriteObserver(1, TimeSpan.FromMinutes(1)));
var (ticket, claim) = NewWrite("caller", 1);
var (ticket, claim) = NewWrite("caller", 1, securedWrites: true);
var result = await actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim),
Timeout, TestContext.Current.CancellationToken);
@@ -334,6 +335,51 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase
driver.Calls.ShouldBe(0, "the caller-less overload must not be used when the driver can act on the caller");
}
/// <summary>
/// #1084 fail closed: an admission whose export does NOT opt in to secured writes hands a caller-aware driver no
/// caller at all — the caller-less overload runs, so an identity-bearing write is refused exactly as an anonymous one.
/// </summary>
[Fact]
public async Task Rich_write_without_the_export_opt_in_reaches_a_caller_aware_driver_without_a_caller()
{
var driver = new CallerRecordingDriver();
var actor = Connect(driver, new RecordingGate(), new LateWriteObserver(1, TimeSpan.FromMinutes(1)));
var (ticket, claim) = NewWrite("no-export-opt-in", 1);
var result = await actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim),
Timeout, TestContext.Current.CancellationToken);
result.State.ShouldBe(DataWriteState.AcceptedUnconfirmed);
driver.Callers.ShouldBeEmpty("no caller identity without the export's opt-in");
driver.Calls.ShouldBe(1);
}
/// <summary>
/// #1091 precedence: a driver with the explicit-outcome capability AND a caller-aware outcome overload gets the
/// caller-aware overload when the write carries a caller, the plain outcome overload when it does not — never the
/// legacy <see cref="IWritable"/> path either way, and its outcome is reported as the driver gave it.
/// </summary>
[Fact]
public async Task Rich_write_to_a_caller_aware_outcome_driver_uses_the_caller_overload_only_with_a_caller()
{
var driver = new CallerRecordingRichDriver();
var actor = Connect(driver, new RecordingGate(), new LateWriteObserver(1, TimeSpan.FromMinutes(1)));
var (withTicket, withClaim) = NewWrite("rich-caller", 1, securedWrites: true);
var with = await actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(withTicket, withClaim),
Timeout, TestContext.Current.CancellationToken);
var (withoutTicket, withoutClaim) = NewWrite("rich-no-caller", 2);
var without = await actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(withoutTicket, withoutClaim),
Timeout, TestContext.Current.CancellationToken);
with.State.ShouldBe(DataWriteState.DriverConfirmedFailure);
with.StatusCode.ShouldBe(0x801F0000u);
without.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
driver.Callers.ShouldBe([new WriteCaller("peer", "key", WriteCallerOrigin.DataConnection)]);
driver.CallerlessOutcomeCalls.ShouldBe(1);
driver.Calls.ShouldBe(0, "the legacy IWritable path is never used by an outcome-capable driver");
}
/// <summary>
/// #1074 — both data planes hand the driver the same caller shape: an OPC UA write's
/// <see cref="DriverInstanceActor.WriteAttribute"/> (caller from the session, #1017) and a gRPC data-connection
@@ -352,7 +398,7 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase
Caller: new WriteCaller("peer", "key", WriteCallerOrigin.OpcUaSession)),
Timeout, TestContext.Current.CancellationToken);
opcUa.Success.ShouldBeTrue(opcUa.Reason);
var (ticket, claim) = NewWrite("parity", 2);
var (ticket, claim) = NewWrite("parity", 2, securedWrites: true);
var grpc = await actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim),
Timeout, TestContext.Current.CancellationToken);
grpc.State.ShouldBe(DataWriteState.AcceptedUnconfirmed);
@@ -376,7 +422,7 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase
var galaxy = new ZB.MOM.WW.OtOpcUa.Driver.Galaxy.GalaxyDriver("driver", GalaxyOptions(overDataConnections: true),
hierarchySource: null, dataWriter: writer, ackCredentialResolver: resolver);
var actor = Connect(new GalaxyWriteHost(galaxy), new RecordingGate(), new LateWriteObserver(1, TimeSpan.FromMinutes(1)));
var (ticket, claim) = NewWrite("galaxy", 5, driverReference: "Plant/Tank1/SP");
var (ticket, claim) = NewWrite("galaxy", 5, driverReference: "Plant/Tank1/SP", securedWrites: true);
var result = await actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim),
Timeout, TestContext.Current.CancellationToken);
@@ -388,9 +434,11 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase
/// <summary>
/// #1074 default: the same write to a Galaxy driver in <c>ApiKeyIdentity</c> mode WITHOUT
/// <c>SecuredWritesOverDataConnections</c> is refused exactly as before #1074 — no identity is resolved, the
/// writer refuses the SecuredWrite <c>BadUserAccessDenied</c> locally, and the gRPC caller sees the same outcome as
/// before (the legacy path's <c>OutcomeUnknown</c>). The OPC UA plane on the same driver still writes (control).
/// <c>SecuredWritesOverDataConnections</c> is refused exactly as before #1074 — no identity is resolved and the
/// writer refuses the SecuredWrite <c>BadUserAccessDenied</c> locally — even though the export opts in (#1084: both
/// are needed). #1091: the gRPC caller now hears that refusal definitively (<c>DriverConfirmedFailure</c> +
/// <c>BadUserAccessDenied</c>; it used to be <c>OutcomeUnknown</c>). The OPC UA plane on the same driver still writes
/// (control).
/// </summary>
[Fact]
public async Task Rich_write_to_a_Galaxy_driver_without_the_data_connection_opt_in_is_refused_as_before()
@@ -400,12 +448,13 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase
var galaxy = new ZB.MOM.WW.OtOpcUa.Driver.Galaxy.GalaxyDriver("driver", GalaxyOptions(overDataConnections: false),
hierarchySource: null, dataWriter: writer, ackCredentialResolver: resolver);
var actor = Connect(new GalaxyWriteHost(galaxy), new RecordingGate(), new LateWriteObserver(1, TimeSpan.FromMinutes(1)));
var (ticket, claim) = NewWrite("galaxy-off", 5, driverReference: "Plant/Tank1/SP");
var (ticket, claim) = NewWrite("galaxy-off", 5, driverReference: "Plant/Tank1/SP", securedWrites: true);
var result = await actor.Ask<DataWriteOutcome>(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim),
Timeout, TestContext.Current.CancellationToken);
result.State.ShouldBe(DataWriteState.OutcomeUnknown, "the pre-#1074 report of a refused legacy write");
result.State.ShouldBe(DataWriteState.DriverConfirmedFailure, "#1091: a refused secured write is a definite failure");
result.StatusCode.ShouldBe(0x801F0000u, "BadUserAccessDenied");
writer.Refusals.ShouldBe(1);
writer.ResolvedUsers.ShouldBeEmpty();
resolver.SecuredWriteKeyIds.ShouldBeEmpty("no identity is looked up for a data-connection write while opted out");
@@ -677,12 +726,13 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase
}
private static (WriteAdmissionTicket Ticket, WriteClaim Claim) NewWrite(string operation, int value,
string driverReference = "plant/tag", string driverInstanceId = "driver")
string driverReference = "plant/tag", string driverInstanceId = "driver", bool securedWrites = false)
{
var now = TimeProvider.System.GetTimestamp();
var view = new DataView(new("cluster", "urn:raw", "string", "plant/tag"), DataRealm.Raw, null, 0, "plant/tag");
var admission = new DataWriteAdmission("peer", view, 1, 1, "serving", "driver-incarnation", operation,
now + 60 * TimeProvider.System.TimestampFrequency, "key", DateTimeOffset.UtcNow.AddMinutes(1), "key-version");
now + 60 * TimeProvider.System.TimestampFrequency, "key", DateTimeOffset.UtcNow.AddMinutes(1), "key-version",
AllowsSecuredWrite: securedWrites);
var scope = new FrozenWriteScope("cluster", NodeHierarchyKind.Raw, ImmutableArray.Create("plant", "tag"));
var proof = new WriteRouteProof(admission, scope, "RawTag", "tag", null, driverInstanceId, driverReference, 1, 1);
var ticket = new WriteAdmissionTicket(proof, DataValue.FromScalar(DataValueKind.Int32, value), now);
@@ -738,9 +788,31 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase
}
}
private sealed class CallerRecordingRichDriver : LegacyDriver, ICallerAwareWriteOutcomeCapability
{
private readonly Lock _gate = new();
private readonly List<WriteCaller> _callers = [];
private int _callerless;
public IReadOnlyList<WriteCaller> Callers { get { lock (_gate) return [.. _callers]; } }
public int CallerlessOutcomeCalls => Volatile.Read(ref _callerless);
public Task<IReadOnlyList<DataWriteOutcome>> WriteWithOutcomesAsync(IReadOnlyList<WriteRequest> writes,
CancellationToken cancellationToken)
{
Interlocked.Increment(ref _callerless);
return Task.FromResult<IReadOnlyList<DataWriteOutcome>>([new(DataWriteState.DriverConfirmedSuccess, 0, null)]);
}
public Task<IReadOnlyList<DataWriteOutcome>> WriteWithOutcomesAsync(IReadOnlyList<WriteRequest> writes, WriteCaller caller,
CancellationToken cancellationToken)
{
lock (_gate) _callers.Add(caller);
return Task.FromResult<IReadOnlyList<DataWriteOutcome>>([new(DataWriteState.DriverConfirmedFailure, 0x801F0000u, "denied")]);
}
}
/// <summary>Hosts a real <see cref="ZB.MOM.WW.OtOpcUa.Driver.Galaxy.GalaxyDriver"/>'s write surface without its
/// gateway lifecycle (initialize would dial mxaccessgw).</summary>
private sealed class GalaxyWriteHost(ZB.MOM.WW.OtOpcUa.Driver.Galaxy.GalaxyDriver galaxy) : IDriver, ICallerAwareWritable
private sealed class GalaxyWriteHost(ZB.MOM.WW.OtOpcUa.Driver.Galaxy.GalaxyDriver galaxy)
: IDriver, ICallerAwareWritable, ICallerAwareWriteOutcomeCapability
{
public string DriverInstanceId => "driver";
public string DriverType => "Galaxy";
@@ -753,6 +825,10 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase
=> galaxy.WriteAsync(writes, cancellationToken);
public Task<IReadOnlyList<WriteResult>> WriteAsync(IReadOnlyList<WriteRequest> writes, WriteCaller caller,
CancellationToken cancellationToken) => ((ICallerAwareWritable)galaxy).WriteAsync(writes, caller, cancellationToken);
public Task<IReadOnlyList<DataWriteOutcome>> WriteWithOutcomesAsync(IReadOnlyList<WriteRequest> writes,
CancellationToken cancellationToken) => galaxy.WriteWithOutcomesAsync(writes, cancellationToken);
public Task<IReadOnlyList<DataWriteOutcome>> WriteWithOutcomesAsync(IReadOnlyList<WriteRequest> writes, WriteCaller caller,
CancellationToken cancellationToken) => galaxy.WriteWithOutcomesAsync(writes, caller, cancellationToken);
#pragma warning restore OTOPCUA0001
}
@@ -793,7 +869,7 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase
string? apiKeyId, CancellationToken cancellationToken)
{
SecuredWriteKeyIds.Add(apiKeyId);
return Task.FromResult(apiKeyId == "key"
return Task.FromResult(apiKeyId is "key" or "peer-key"
? ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime.GalaxyAckCredentialResolution.Resolved(
new("mes-writer", "PLANT", "pw", ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime.GalaxyAckCredentialSource.ApiKey))
: ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime.GalaxyAckCredentialResolution.Refused("no key identity"));
@@ -0,0 +1,175 @@
using System.Text;
using System.Text.Json.Nodes;
using Akka.Actor;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
/// <summary>
/// #1084 — a secured (caller-identity) write over a gRPC data connection needs BOTH the origin export's opt-in
/// (<c>DataExport.AllowSecuredWrites</c>) AND the Galaxy driver's <c>MxAccess.SecuredWritesOverDataConnections</c>.
/// Driven end to end through the runtime write path: a deployed artifact → the compiled export catalog → the real
/// <see cref="DataWriteRuntime"/> executor (admission) → the real <see cref="ActorDataWriteRoute"/> → the
/// <see cref="DriverInstanceActor"/> behind the real dispatch gate → a real <c>GalaxyDriver</c> (#1091 outcomes).
/// </summary>
public sealed partial class GrpcDataDriverOutcomeTests
{
[Theory]
[InlineData(true, true)]
[InlineData(false, true)]
[InlineData(true, false)]
public async Task A_secured_write_over_a_data_connection_needs_both_the_export_opt_in_and_the_driver_option(
bool exportOptIn, bool driverOption)
{
var ct = TestContext.Current.CancellationToken;
var clock = TimeProvider.System;
var fence = new DataWriteDispatchFence();
var authority = new DataPlaneAuthorityState(fence);
var activation = new CatalogActivation(fence);
var role = new RedundancyRoleView(fence);
role.PublishPrimaryRole(true);
var serving = new ServingIdentity("node-a", "serving", "Primary", 0, 0);
var coordinator = new LocalCatalogCoordinator(activation, authority, () => serving);
var bytes = SecuredWriteArtifact(exportOptIn);
var attempt = coordinator.BeginAttempt("catalog-revision");
coordinator.InstallAuthority(attempt, DeploymentArtifact.ParseDataPlaneAuthority(bytes, "node-a")).ShouldBeTrue();
using (var parsed = DeploymentArtifact.Open(bytes))
coordinator.Stage(attempt, parsed.ParseLocalCatalogSnapshot("node-a")!, "node-a").ShouldBeTrue();
coordinator.Complete(attempt, true).ShouldBeTrue();
var catalog = coordinator.Current.ShouldNotBeNull();
var node = catalog.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "tag");
var key = authority.Current.FindUsableKey("peer-key", clock.GetUtcNow().UtcDateTime).ShouldNotBeNull();
var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000,
TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1));
var capabilities = new DataCapabilitiesProvider("cluster", () => coordinator.Current!.Serving, () => true, limits);
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, clock), clock);
var bounds = new DriverWriteBounds(TimeSpan.FromSeconds(5));
var runtime = new DataWriteRuntime(coordinator, activation, authority, policy, capabilities, role, clock, bounds,
"serving", 16, 16_384, 16_384, 4, TimeSpan.FromMinutes(1));
var writer = new GalaxyIdentityRecordingWriter();
var resolver = new KeyIdentityResolver();
var galaxy = new ZB.MOM.WW.OtOpcUa.Driver.Galaxy.GalaxyDriver("driver", GalaxyOptions(driverOption),
hierarchySource: null, dataWriter: writer, ackCredentialResolver: resolver);
var actor = Connect(new GalaxyWriteHost(galaxy), runtime.Gate, runtime.Observer, writeClock: clock,
writeRouteState: runtime.Routes);
var incarnation = runtime.Routes.CurrentDriverIncarnation("driver").ShouldNotBeNull();
runtime.Routes.Publish(node.Metadata.View, "driver", "Plant/Tank1/SP", incarnation);
var host = Sys.ActorOf(Props.Create(() => new RichRouteForwarder(actor)));
var context = new DataAuthenticatedContext("peer", "peer-key", DataCallerIdentity.CredentialVersionFor(key),
null, catalog.AuthorityEpoch);
var results = await runtime.ForCaller(context, () => host).WriteAsync(new WriteBatch(
[new WriteItem("c1", "secured-op", node.Metadata.View, DataValue.FromScalar(DataValueKind.Int32, 7),
catalog.Serving.CatalogEpoch, "serving", TimeSpan.FromSeconds(30))],
new DataBudget(TimeSpan.FromSeconds(30), 8, 64_000)), ct);
var outcome = results.ShouldHaveSingleItem().Outcome;
if (exportOptIn && driverOption)
{
outcome.State.ShouldBe(DataWriteState.AcceptedUnconfirmed, outcome.Diagnostic);
writer.ResolvedUsers.ShouldBe(["mes-writer"], "the secured write ran as the connection key's own Galaxy identity");
resolver.SecuredWriteKeyIds.ShouldBe(["peer-key"]);
}
else
{
outcome.State.ShouldBe(DataWriteState.DriverConfirmedFailure, outcome.Diagnostic);
outcome.StatusCode.ShouldBe(0x801F0000u, "BadUserAccessDenied, reported definitively (#1091)");
writer.Refusals.ShouldBe(1);
writer.ResolvedUsers.ShouldBeEmpty();
resolver.SecuredWriteKeyIds.ShouldBeEmpty("no identity is looked up unless both opt-ins are set");
}
}
/// <summary>#1084: the opt-in is per export and per root — only an export of the principal that grants Write AND opts in,
/// and whose root contains the node, lets a write carry the caller; another principal's export never does.</summary>
[Fact]
public void Only_an_opted_in_Write_export_whose_root_contains_the_node_allows_a_secured_write()
{
var root = JsonNode.Parse(SecuredWriteArtifact(exportOptIn: false))!.AsObject();
root["Devices"]!.AsArray().Add(JsonNode.Parse("""{"DeviceId":"device2","DriverInstanceId":"driver","Name":"Other","DeviceConfig":"{}","Enabled":true}"""));
root["Tags"]!.AsArray().Add(JsonNode.Parse("""{"TagId":"tag2","DeviceId":"device2","Name":"Level","DataType":"Int32","AccessLevel":1,"TagConfig":"{}"}"""));
root["DataExports"]!.AsArray().Add(JsonNode.Parse("""
{"DataExportId":"device-only","ClusterId":"cluster","Enabled":true,"Realm":1,"RootKind":"RawDevice","RootEntityId":"device",
"PrincipalId":"peer","AllowedOperations":8,"AllowSecuredWrites":true}
"""));
root["DataExports"]!.AsArray().Add(JsonNode.Parse("""
{"DataExportId":"other-principal","ClusterId":"cluster","Enabled":true,"Realm":1,"RootKind":"Cluster","RootEntityId":"cluster",
"PrincipalId":"other","AllowedOperations":12,"AllowSecuredWrites":true}
"""));
var catalog = Compile(Encoding.UTF8.GetBytes(root.ToJsonString()));
var inside = catalog.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "tag");
var outside = catalog.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "tag2");
catalog.AllowsSecuredWrite("peer", inside).ShouldBeTrue("the device-rooted export opts in and contains the tag");
catalog.AllowsSecuredWrite("peer", outside).ShouldBeFalse("only the whole-realm export without the opt-in covers it");
catalog.AllowsExport("peer", outside, DataOperations.Write).ShouldBeTrue("the write itself is still admitted");
catalog.AllowsSecuredWrite("PEER", inside).ShouldBeTrue("principals compare case-insensitively, as for every grant");
catalog.AllowsSecuredWrite("stranger", inside).ShouldBeFalse();
}
/// <summary>#1084: the flag rides the artifact; on a deployed row without the Write grant it fails closed.</summary>
[Fact]
public void AllowSecuredWrites_rides_the_artifact_and_without_Write_fails_the_row_closed()
{
using (var parsed = DeploymentArtifact.Open(SecuredWriteArtifact(exportOptIn: true)))
parsed.ParseDataExports("node-a").ShouldHaveSingleItem().AllowSecuredWrites.ShouldBeTrue();
var root = JsonNode.Parse(SecuredWriteArtifact(exportOptIn: true))!.AsObject();
root["DataExports"]![0]!["AllowedOperations"] = (int)(DataOperations.Browse | DataOperations.Read);
using var bad = DeploymentArtifact.Open(Encoding.UTF8.GetBytes(root.ToJsonString()));
Should.Throw<InvalidDataException>(() => bad.ParseDataExports("node-a"));
using var old = DeploymentArtifact.Open(SecuredWriteArtifact(exportOptIn: null));
old.ParseDataExports("node-a").ShouldHaveSingleItem().AllowSecuredWrites.ShouldBeFalse("a pre-#1084 artifact grants none");
}
private static LocalExportCatalog Compile(byte[] bytes)
{
var fence = new DataWriteDispatchFence();
var authority = new DataPlaneAuthorityState(fence);
var coordinator = new LocalCatalogCoordinator(new CatalogActivation(fence), authority,
() => new ServingIdentity("node-a", "serving", "Primary", 0, 0));
var attempt = coordinator.BeginAttempt("catalog-revision");
coordinator.InstallAuthority(attempt, DeploymentArtifact.ParseDataPlaneAuthority(bytes, "node-a")).ShouldBeTrue();
using (var parsed = DeploymentArtifact.Open(bytes))
coordinator.Stage(attempt, parsed.ParseLocalCatalogSnapshot("node-a")!, "node-a").ShouldBeTrue();
coordinator.Complete(attempt, true).ShouldBeTrue();
return coordinator.Current.ShouldNotBeNull();
}
/// <param name="exportOptIn">The export's AllowSecuredWrites; null omits the field (a pre-#1084 artifact).</param>
private static byte[] SecuredWriteArtifact(bool? exportOptIn)
{
var root = JsonNode.Parse("""
{
"Clusters":[{"ClusterId":"cluster","Name":"Cluster","Enterprise":"ent","Site":"site","CreatedBy":"test","RedundancyMode":0,"Enabled":true}],
"Nodes":[{"NodeId":"node-a","ClusterId":"cluster","Host":"node-a","ApplicationUri":"urn:node-a","CreatedBy":"test","Enabled":true,"MaintenanceMode":false}],
"ApiKeys":[{"ApiKeyId":"peer-key","Name":"peer-key","SecretHash":"hash","Principal":"peer","Enabled":true}],
"NodeAcls":[{"NodeAclId":"acl","ClusterId":"cluster","Principal":"peer","ScopeKind":0,"PermissionFlags":16}],
"RawFolders":[{"RawFolderId":"folder","ClusterId":"cluster","Name":"Plant"}],
"DriverInstances":[{"DriverInstanceId":"driver","ClusterId":"cluster","RawFolderId":"folder","Name":"Driver","DriverType":"Modbus","DriverConfig":"{}","Enabled":true}],
"Devices":[{"DeviceId":"device","DriverInstanceId":"driver","Name":"Device","DeviceConfig":"{}","Enabled":true}],
"Tags":[{"TagId":"tag","DeviceId":"device","Name":"Speed","DataType":"Int32","AccessLevel":1,"TagConfig":"{}"}],
"TagGroups":[],"UnsAreas":[],"UnsLines":[],"Equipment":[],"UnsTagReferences":[],"VirtualTags":[],
"DataConnections":[],"RemoteNamespaceMappings":[],
"DataExports":[{"DataExportId":"raw","ClusterId":"cluster","Enabled":true,"Realm":1,"RootKind":"Cluster","RootEntityId":"cluster","PrincipalId":"peer","AllowedOperations":8}]
}
""")!.AsObject();
if (exportOptIn is { } optIn) root["DataExports"]![0]!["AllowSecuredWrites"] = optIn;
return Encoding.UTF8.GetBytes(root.ToJsonString());
}
/// <summary>Stands in for <see cref="DriverHostActor"/>'s rich-write routing: hands the routed write to the one child.</summary>
private sealed class RichRouteForwarder : ReceiveActor
{
public RichRouteForwarder(IActorRef child) =>
Receive<DriverHostActor.RouteRichWrite>(msg =>
child.Forward(new DriverInstanceActor.WriteAttributeWithOutcome(msg.Ticket, msg.Claim)));
}
}