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:
+24
-1
@@ -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()
|
||||
{
|
||||
|
||||
+89
-13
@@ -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"));
|
||||
|
||||
+175
@@ -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)));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user