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
@@ -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)