Files
lmxopcua/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/ScriptForeignKeysAndExternalIdUniquenessMigrationTests.cs
T
Joseph Doherty 8e2a793000 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.
2026-12-04 14:58:16 -05:00

111 lines
6.1 KiB
C#

using Microsoft.Data.SqlClient;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests;
/// <summary>
/// lmxopcua#1040 / #1049: migration <c>ScriptForeignKeysAndExternalIdUniqueness</c> must refuse — loudly, naming the
/// rows, and changing NOTHING — a populated ConfigDb holding data its constraints cannot hold (dangling script
/// references, duplicated ZTag / SAPID, reservation history it would drop); and apply cleanly once they are fixed.
/// Each test migrates its own scratch database to the previous migration, seeds, then migrates up.
/// </summary>
[Trait("Category", "SchemaCompliance")]
[Collection(nameof(SchemaComplianceCollection))]
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)
{
var uuid = Guid.NewGuid();
return new Equipment
{
EquipmentId = "EQ-" + uuid.ToString("N")[..12], EquipmentUuid = uuid, UnsLineId = "line-" + uuid.ToString("N"),
Name = "eq", MachineCode = "mc-" + uuid.ToString("N"), ZTag = zTag, SAPID = sapId,
};
}
/// <summary>Every offending row class is named in ONE refusal and the schema is left exactly as it was.</summary>
[Fact]
public void Offending_rows_refuse_the_migration_and_nothing_changes()
{
using var scratch = new MigrationScratchDatabase();
scratch.MigrateTo(Previous);
using (var db = scratch.NewContext())
{
db.VirtualTags.Add(new VirtualTag
{
VirtualTagId = "VT-dangling", EquipmentId = "EQ-x", Name = "V", DataType = "Int32", ScriptId = "SC-gone",
});
db.ScriptedAlarms.Add(new ScriptedAlarm
{
ScriptedAlarmId = "SA-dangling", EquipmentId = "EQ-x", Name = "A", AlarmType = "AlarmCondition",
MessageTemplate = "m", PredicateScriptId = "SC-also-gone",
});
db.Equipment.AddRange(NewEquipment(zTag: "ZT-1"), NewEquipment(zTag: "zt-1"), NewEquipment(sapId: "SAP-1"), NewEquipment(sapId: "SAP-1"));
db.SaveChanges();
}
scratch.Execute(
"INSERT ExternalIdReservation (Kind, Value, EquipmentUuid, ClusterId, FirstPublishedBy) VALUES ('ZTag', 'ZT-9', NEWID(), 'c', 't')");
var ex = Should.Throw<SqlException>(() => scratch.MigrateTo(This));
ex.Number.ShouldBe(51049);
ex.Message.ShouldContain("VT-dangling->SC-gone");
ex.Message.ShouldContain("SA-dangling->SC-also-gone");
ex.Message.ShouldContain("ZTag value(s)");
ex.Message.ShouldContain("SAPID value(s)");
ex.Message.ShouldContain("1 ExternalIdReservation row(s)");
scratch.LastAppliedMigration().ShouldBe(Previous);
scratch.Scalar("SELECT COUNT(*) FROM sys.indexes WHERE name = 'IX_Equipment_ZTag'").ShouldBe(1);
scratch.Scalar("SELECT COUNT(*) FROM ExternalIdReservation").ShouldBe(1);
scratch.Scalar("SELECT COUNT(*) FROM sys.foreign_keys WHERE name = 'FK_VirtualTag_Script'").ShouldBe(0);
}
/// <summary>Positive control: once the operator fixes the rows the same database migrates and the constraints exist.</summary>
[Fact]
public void A_clean_populated_database_migrates_and_gains_the_constraints()
{
using var scratch = new MigrationScratchDatabase();
scratch.MigrateTo(Previous);
using (var db = scratch.NewContext())
{
db.Scripts.Add(new Script { ScriptId = "SC-1", Name = "s", SourceCode = "return 1;", SourceHash = new string('a', 64) });
db.VirtualTags.Add(new VirtualTag
{
VirtualTagId = "VT-ok", EquipmentId = "EQ-x", Name = "V", DataType = "Int32", ScriptId = "SC-1",
});
db.ScriptedAlarms.Add(new ScriptedAlarm
{
ScriptedAlarmId = "SA-ok", EquipmentId = "EQ-x", Name = "A", AlarmType = "AlarmCondition",
MessageTemplate = "m", PredicateScriptId = "SC-1",
});
// Blank and NULL identifiers are "none" and may repeat; distinct values are fine.
db.Equipment.AddRange(NewEquipment(), NewEquipment(), NewEquipment(zTag: "", sapId: ""), NewEquipment(zTag: "", sapId: ""),
NewEquipment(zTag: "ZT-1", sapId: "SAP-1"), NewEquipment(zTag: "ZT-2", sapId: "SAP-2"));
db.SaveChanges();
}
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);
scratch.Scalar("SELECT COUNT(*) FROM sys.indexes WHERE is_unique = 1 AND name IN ('UX_Equipment_ZTag', 'UX_Equipment_SAPID')").ShouldBe(2);
scratch.Scalar("SELECT OBJECT_ID(N'ExternalIdReservation')").ShouldBe(DBNull.Value);
scratch.Scalar("SELECT OBJECT_ID(N'dbo.sp_ReleaseExternalIdReservation')").ShouldBe(DBNull.Value);
scratch.Scalar("SELECT COUNT(*) FROM VirtualTag").ShouldBe(1);
// Down restores the previous shape (table, procedure, non-unique indexes) without touching the data.
Should.NotThrow(() => scratch.MigrateTo(Previous));
scratch.Scalar("SELECT COUNT(*) FROM sys.indexes WHERE is_unique = 0 AND name IN ('IX_Equipment_ZTag', 'IX_Equipment_SAPID')").ShouldBe(2);
scratch.Scalar("SELECT COUNT(*) FROM sys.foreign_keys WHERE name LIKE 'FK_%_Script'").ShouldBe(0);
scratch.Scalar("SELECT CASE WHEN OBJECT_ID(N'dbo.sp_ReleaseExternalIdReservation') IS NULL THEN 0 ELSE 1 END").ShouldBe(1);
scratch.Scalar("SELECT COUNT(*) FROM ExternalIdReservation").ShouldBe(0);
scratch.Scalar("SELECT COUNT(*) FROM Equipment").ShouldBe(6);
}
}