fix(grpc-data): stop sending stable_source_id (#916); export alarm-bearing raw tags as UnsupportedVariable (#917)

#916: Metadata.stable_source_id carried the internal acquisition key
(<len>:<driverInstanceId><RawPath>) on every export, so a UNS-only peer learned
driver ids and RawPaths. No consumer uses the field beyond byte accounting; it is
optional on the wire and absent decodes as null. It is now never sent; the
internal BackingSourceKey is unchanged.

#917: alarm-bearing raw tags never get a value but were exported as Variables.
They are now the existing explicit UnsupportedVariable kind (browsable,
Unsupported on every value op). The node is kept so exports rooted at it still
compile and A1 condition placements are unaffected.

The real-origin v1 goldens are not re-recorded: GrpcDataV1RealOriginCorrections
applies exactly these two edits to the parsed goldens, pinned by a test.
Evidence: docs/plans/evidence/grpc-data-ext/V1-916-917.md
This commit is contained in:
Joseph Doherty
2026-11-28 09:23:34 -05:00
parent 05f431f5d8
commit b7ca71f188
10 changed files with 325 additions and 12 deletions
@@ -69,7 +69,7 @@ public sealed class GrpcDataHistoryWireTests
byId["Plant/Modbus/dev1/Speed"].History.Historizing.ShouldBeFalse();
(byId["Plant/Modbus/dev1/Speed"].AllowedOperations & 32u).ShouldBe(0u);
// Header-less: the golden (no Metadata.history, no bit 32).
(await origin.DriveAsync("GetMetadata", new Metadata())).ShouldBe(GrpcDataV1RealOriginGoldens.Responses["GetMetadata"]);
(await origin.DriveAsync("GetMetadata", new Metadata())).ShouldBe(GrpcDataV1RealOriginCorrections.Expected("GetMetadata"));
// A caller whose ACL lacks HistoryRead sees historizing=false on Flow: the same as an unhistorized node.
await using var denied = new RealOrigin(permissions: NodePermissions.Operator & ~NodePermissions.HistoryRead);
var deniedMeta = W.MetadataResponse.Parser.ParseFrom(Convert.FromHexString(await denied.DriveAsync("GetMetadata", History)));
@@ -66,13 +66,47 @@ public sealed class GrpcDataV1RealOriginCompatibilityTests
Hex(RealOriginRequests.Bytes(scenario)).ShouldBe(GrpcDataV1RealOriginGoldens.Requests[scenario], $"recorded {scenario} request");
}
/// <summary>
/// #916/#917: the corrections are exact and not vacuous — an unedited golden re-serialises byte-identically, the
/// uncorrected scenarios are the raw goldens, the recorded UNS browse really leaked the driver id + RawPath, and the
/// corrected bytes carry neither the leak nor a value-bearing HighTemp.
/// </summary>
[Fact]
public void V1_corrections_916_917_are_exact_and_the_recorded_leak_was_real()
{
foreach (var scenario in RealOriginRequests.Scenarios.Where(s => s != "Subscribe"))
{
var golden = GrpcDataV1RealOriginGoldens.Responses[scenario];
IMessage parsed = scenario.Split('/')[0] switch
{
"GetCapabilities" => W.CapabilitiesResponse.Parser.ParseFrom(Convert.FromHexString(golden)),
"Browse" => W.BrowseResponse.Parser.ParseFrom(Convert.FromHexString(golden)),
"GetMetadata" => W.MetadataResponse.Parser.ParseFrom(Convert.FromHexString(golden)),
"Read" => W.ReadResponse.Parser.ParseFrom(Convert.FromHexString(golden)),
_ => W.WriteResponse.Parser.ParseFrom(Convert.FromHexString(golden)),
};
Hex(parsed.ToByteArray()).ShouldBe(golden, $"{scenario}: re-serialising a golden is byte-identical");
if (GrpcDataV1RealOriginCorrections.Corrected.Contains(scenario))
GrpcDataV1RealOriginCorrections.Expected(scenario).ShouldNotBe(golden, $"{scenario} carries a corrected field");
else
GrpcDataV1RealOriginCorrections.Expected(scenario).ShouldBe(golden);
}
var leak = Hex(System.Text.Encoding.UTF8.GetBytes("driver-1Plant/Modbus/dev1/"));
GrpcDataV1RealOriginGoldens.Responses["Browse/uns"].ShouldContain(leak, Case.Sensitive, "the recorded v1 UNS browse leaked it (#916)");
foreach (var scenario in GrpcDataV1RealOriginCorrections.Corrected)
GrpcDataV1RealOriginCorrections.Expected(scenario).ShouldNotContain(leak, Case.Sensitive);
var metadata = W.MetadataResponse.Parser.ParseFrom(Convert.FromHexString(GrpcDataV1RealOriginCorrections.Expected("GetMetadata")));
metadata.Items.Count(x => x.Status == (int)DataItemStatus.Unsupported).ShouldBe(1);
metadata.Items.ShouldNotContain(x => x.Value != null && x.Value.View.Address.Identifier == RealOriginRequests.HighTemp.Address.Identifier);
}
[Theory]
[MemberData(nameof(Scenarios))]
public async Task V1_client_without_feature_header_gets_the_recorded_v1_response_bytes(string scenario)
{
await using var origin = new RealOrigin();
var actual = await origin.DriveAsync(scenario, new Metadata());
actual.ShouldBe(GrpcDataV1RealOriginGoldens.Responses[scenario], $"{scenario} response diverged from the recorded v1 bytes");
actual.ShouldBe(GrpcDataV1RealOriginCorrections.Expected(scenario), $"{scenario} response diverged from the recorded v1 bytes");
}
[Theory]
@@ -83,10 +117,10 @@ public sealed class GrpcDataV1RealOriginCompatibilityTests
// effective set is empty and the bytes are v1.
await using var origin = new RealOrigin(historian: false, conditions: false);
var actual = await origin.DriveAsync(scenario, new Metadata { { "x-otopcua-data-features", "history,conditions" } });
actual.ShouldBe(GrpcDataV1RealOriginGoldens.Responses[scenario], $"{scenario} response must not change when nothing requested is servable");
actual.ShouldBe(GrpcDataV1RealOriginCorrections.Expected(scenario), $"{scenario} response must not change when nothing requested is servable");
await using var conditionsOnly = new RealOrigin(conditions: false);
(await conditionsOnly.DriveAsync(scenario, new Metadata { { "x-otopcua-data-features", "conditions" } }))
.ShouldBe(GrpcDataV1RealOriginGoldens.Responses[scenario], $"{scenario}: conditions on an origin that cannot serve them change nothing");
.ShouldBe(GrpcDataV1RealOriginCorrections.Expected(scenario), $"{scenario}: conditions on an origin that cannot serve them change nothing");
}
[Fact]
@@ -219,6 +253,59 @@ public sealed class GrpcDataV1RealOriginCompatibilityTests
internal static IMessage Normalise(IMessage message) => message;
}
/// <summary>
/// The deliberate pre-deploy v1 corrections (#916, #917; v1 was merged but never deployed, #915). The goldens in
/// <see cref="GrpcDataV1RealOriginGoldens"/> are NOT re-recorded: the expected bytes are the recorded golden with exactly
/// these edits applied to its parsed message, and every other byte must still match. Re-serialising an unedited golden is
/// byte-identical (asserted), so the edit is the only difference. Nothing here changes the wire SHAPE — both corrections
/// use fields and values a v1 client already handles (an absent optional field; the existing UnsupportedVariable kind and
/// Unsupported status, which the consumer already treats as "not a value node").
/// <list type="bullet">
/// <item><b>#916</b> — <c>Metadata.stable_source_id</c> is never sent (it was <c>&lt;len&gt;:&lt;driverInstanceId&gt;&lt;RawPath&gt;</c>, even on
/// UNS exports). Cleared on every Metadata of every Browse/GetMetadata response.</item>
/// <item><b>#917</b> — the alarm-bearing raw tag (HighTemp) is exported as <c>UnsupportedVariable</c>: in a Browse page it is
/// <c>node_kind = "UnsupportedVariable"</c>, <c>value_kind = NULL</c>, <c>allowed_operations = Browse</c> (the existing
/// unsupported-node masking); a GetMetadata item for it is <c>status = Unsupported</c> with no value and no lease.</item>
/// </list>
/// </summary>
internal static class GrpcDataV1RealOriginCorrections
{
internal static readonly string[] Corrected = ["Browse", "Browse/uns", "GetMetadata"];
internal static string Expected(string scenario)
{
var golden = GrpcDataV1RealOriginGoldens.Responses[scenario];
if (!Corrected.Contains(scenario)) return golden;
var bytes = Convert.FromHexString(golden);
var alarm = RealOriginRequests.HighTemp.Address.Identifier;
IMessage corrected;
if (scenario == "GetMetadata")
{
var response = W.MetadataResponse.Parser.ParseFrom(bytes);
foreach (var item in response.Items)
{
if (item.Value is null) continue;
if (item.Value.View.Address.Identifier == alarm && item.Value.View.Realm == (int)DataRealm.Raw)
{ item.Status = (int)DataItemStatus.Unsupported; item.Value = null; item.Lease = null; continue; }
item.Value.ClearStableSourceId();
}
corrected = response;
}
else
{
var response = W.BrowseResponse.Parser.ParseFrom(bytes);
foreach (var item in response.Items)
{
item.ClearStableSourceId();
if (item.View.Address.Identifier == alarm && item.View.Realm == (int)DataRealm.Raw)
{ item.NodeKind = "UnsupportedVariable"; item.ValueKind = W.ValueKind.Null; item.AllowedOperations = (uint)DataOperations.Browse; }
}
corrected = response;
}
return GrpcDataV1RealOriginCompatibilityTests.Hex(corrected.ToByteArray());
}
}
/// <summary>The recorded v1 client requests against <see cref="RealOrigin"/>'s catalog. Changing any value invalidates the goldens.</summary>
internal static class RealOriginRequests
{
@@ -6,6 +6,8 @@ namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections;
/// NEVER re-record these to make a later phase (H2, A2, A3, ...) pass: a difference is a v1 wire regression of the
/// real origin, not a stale golden. A later phase extends <see cref="RealOrigin"/>'s snapshot with its new-shape data
/// and must still produce these exact bytes for a headerless (and, while unsupported, a feature-requesting) v1 call.
/// The only sanctioned differences are the pre-deploy corrections #916/#917, applied to these bytes (not re-recorded) by
/// <see cref="GrpcDataV1RealOriginCorrections"/>.
/// </summary>
internal static class GrpcDataV1RealOriginGoldens
{
@@ -2,6 +2,7 @@ using System.Security.Cryptography;
using System.Text.Json;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
@@ -306,6 +307,81 @@ public sealed class GrpcDataConditionPlacementTests
listedNative.ShouldBeGreaterThan(20); // the generator really exercised native UNS placements
}
/// <summary>
/// #916: no exported metadata carries <c>stable_source_id</c> — a driver source's internal key is
/// <c>&lt;len&gt;:&lt;driverInstanceId&gt;&lt;RawPath&gt;</c>, so sending it told a UNS-only peer the origin's driver ids and
/// RawPaths. The internal <see cref="BackingSourceKey"/> is unchanged (positive control: it still holds both, so the
/// search below would see a leak). Checked on the encoded wire bytes of every node, every realm, 60 seeds.
/// </summary>
[Fact]
public void No_exported_metadata_carries_the_internal_source_key_916()
{
var checkedSources = 0;
for (var seed = 1; seed <= 60; seed++)
{
var (snapshot, rawPaths, driverIds, _) = Generate(seed);
using var fixture = new LocalDataFixture();
var catalog = LocalExportCatalog.Compile(snapshot, fixture.Serving, fixture.Activation.CaptureAuthority());
foreach (var node in catalog.Nodes)
{
node.Metadata.StableSourceId.ShouldBeNull($"seed {seed} {node.EntityKind} {node.EntityId}");
var wire = DataProtoMapper.EncodeMetadata(node.Metadata);
wire.HasStableSourceId.ShouldBeFalse();
if (node.Metadata.View.Realm != DataRealm.Uns) continue;
var text = wire.ToString();
foreach (var rawPath in rawPaths) text.ShouldNotContain(rawPath, Case.Sensitive, $"seed {seed}");
foreach (var driverId in driverIds) text.ShouldNotContain(driverId, Case.Sensitive, $"seed {seed}");
// Positive control: the internal key of a driver-backed UNS reference still names its driver and RawPath.
if (node.Source is { SourceKind: "driver" } source)
{
driverIds.ShouldContain(d => source.StableSourceId.Contains(d, StringComparison.Ordinal));
rawPaths.ShouldContain(r => source.StableSourceId.EndsWith(r, StringComparison.Ordinal));
checkedSources++;
}
}
}
checkedSources.ShouldBeGreaterThan(20); // the generator really produced driver-backed UNS references
}
/// <summary>
/// #917: an alarm-bearing raw tag gets no value (DriverHostActor keeps it out of the value fan-out, and #896 gives it
/// no UNS variable), so v1 exports it as the pre-existing explicit <c>UnsupportedVariable</c> kind: browsable, with
/// no Read/Subscribe/Write/HistoryRead bit, and Unsupported on every value operation — never a Variable that waits
/// forever. Its condition placements (A1) are untouched, and an export rooted at it still compiles.
/// </summary>
[Fact]
public void An_alarm_bearing_raw_tag_is_an_UnsupportedVariable_and_keeps_its_condition_placements_917()
{
using var fixture = new LocalDataFixture();
var catalog = LocalExportCatalog.Compile(Fixed(), fixture.Serving, fixture.Activation.CaptureAuthority());
var alarm = catalog.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "alarm-tag");
alarm.Supported.ShouldBeFalse();
alarm.Metadata.NodeKind.ShouldBe("UnsupportedVariable");
alarm.Metadata.ValueKind.ShouldBe(DataValueKind.Null);
alarm.Metadata.Writable.ShouldBeFalse();
// (Every value gate keys on Supported; the operations a caller sees are masked to Browse by LocalDataServices —
// pinned on the wire by GrpcDataV1RealOriginCompatibilityTests.)
// Positive controls: a plain tag is still a Variable, and the same tag without its alarm config is one too.
var speed = catalog.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "tag");
speed.Supported.ShouldBeTrue();
speed.Metadata.NodeKind.ShouldBe("Variable");
var plain = LocalExportCatalog.Compile(Fixed(withAlarms: false), fixture.Serving, fixture.Activation.CaptureAuthority())
.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "alarm-tag");
plain.Supported.ShouldBeTrue();
plain.Metadata.NodeKind.ShouldBe("Variable");
plain.Metadata.ValueKind.ShouldBe(DataValueKind.Boolean);
// Condition forwarding is unaffected: the Raw placement at its RawPath and both UNS placements remain.
catalog.PlacementsOf(new(AddressSpaceRealm.Raw, "Plant/Driver/Device/Group/OverTemp")).Count.ShouldBe(3);
catalog.ListConditions("raw-peer", LocalExportCatalog.RealmRoot("cluster", DataRealm.Raw), DataOperations.Subscribe,
ConditionKeys.FromSecret(Secret)).ShouldHaveSingleItem();
// A deployable export rooted at the alarm-bearing tag still compiles (the node is kept, not removed).
var b = Fixed();
Should.NotThrow(() => LocalExportCatalog.Compile(With(b, exports: [.. b.DataExports,
Export("tag-root", DataRealm.Raw, "tag-peer", rootKind: "RawTag", rootId: "alarm-tag")]), fixture.Serving, fixture.Activation.CaptureAuthority()));
}
private static (DraftSnapshot Snapshot, string[] RawPaths, string[] DriverIds, int ExpectedUnsNative) Generate(int seed)
{
var random = new Random(seed);