590 lines
42 KiB
C#
590 lines
42 KiB
C#
using System.Net;
|
|
using System.Net.Security;
|
|
using System.Net.Sockets;
|
|
using System.Security.Authentication;
|
|
using System.Security.Cryptography;
|
|
using System.Security.Cryptography.X509Certificates;
|
|
using System.Text.Json;
|
|
using Google.Protobuf;
|
|
using Grpc.Core;
|
|
using Grpc.Net.Client;
|
|
using GrpcDataProbe;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
|
|
|
|
var failurePhase = ProbeFailurePhase.WireSetup;
|
|
string? failureTarget = null;
|
|
string? failureOutput = null;
|
|
var results = new List<ProbeResult>();
|
|
try
|
|
{
|
|
var arguments = args.Chunk(2).ToDictionary(pair => pair[0], pair => pair.Length == 2 ? pair[1] : throw new ArgumentException());
|
|
failureOutput = arguments.GetValueOrDefault("--output");
|
|
var manifestPath = Path.GetFullPath(arguments["--manifest"]);
|
|
Restricted(manifestPath);
|
|
using var manifest = JsonDocument.Parse(await File.ReadAllTextAsync(manifestPath));
|
|
var root = manifest.RootElement;
|
|
var scenario = arguments.GetValueOrDefault("--scenario", "all");
|
|
if (scenario is not ("all" or "D13" or "wire" or "history" or "conditions" or "condition-records")) throw new ArgumentException("Unsupported wire scenario.");
|
|
var nodes = root.GetProperty("nodes");
|
|
var endpoints = root.GetProperty("endpoints");
|
|
var keyPath = root.GetProperty("credentials").GetProperty("data_key_files").GetProperty("source").GetString()!;
|
|
Restricted(keyPath);
|
|
var key = (await File.ReadAllTextAsync(keyPath)).Trim();
|
|
var caPath = root.GetProperty("tls").GetProperty("ca_file").GetString()!;
|
|
using var ca = X509Certificate2.CreateFromPem(File.ReadAllText(caPath));
|
|
var sourceNodes = nodes.EnumerateObject().Where(item => item.Value.GetProperty("cluster_id").GetString() == "SOURCE").ToArray();
|
|
if (sourceNodes.Length != 2) throw new InvalidOperationException();
|
|
var routes = sourceNodes.ToDictionary(item => item.Name, item => endpoints.GetProperty(item.Name + ".data").GetProperty("host_port").GetInt32());
|
|
foreach (var port in routes.Values) if (port is < 1 or > 65535) throw new InvalidOperationException();
|
|
using var security = new ProbeSecurity(routes, ca, key);
|
|
if (scenario is "all" or "D13")
|
|
{
|
|
foreach (var node in sourceNodes)
|
|
{
|
|
var name = node.Name;
|
|
failureTarget = name is "source-1" or "source-2" ? name : null;
|
|
var nodeId = node.Value.GetProperty("node_id").GetString()!;
|
|
async Task Reject(string id, string credential, bool correctCa, bool correctName, bool useUi = false, bool plainData = false)
|
|
{
|
|
failurePhase = id switch
|
|
{
|
|
"bad-key" => ProbeFailurePhase.WireBadKey, "wrong-ca" => ProbeFailurePhase.WireWrongCa,
|
|
"wrong-san" => ProbeFailurePhase.WireWrongSan, "wrong-listener" => ProbeFailurePhase.WireWrongListener,
|
|
"h2c-data-listener" => ProbeFailurePhase.WireH2c, _ => ProbeFailurePhase.Other
|
|
};
|
|
using var handler = security.Handler(name, correctCa, correctName, useUi
|
|
? endpoints.GetProperty(name + ".admin").GetProperty("host_port").GetInt32() : null);
|
|
using var channel = GrpcChannel.ForAddress($"{(useUi || plainData ? "http" : "https")}://{name}:{(useUi ? 9000 : 4057)}", new() { HttpHandler = handler });
|
|
var client = new W.DataConnectionService.DataConnectionServiceClient(channel);
|
|
var headers = Headers(credential, "Node", nodeId);
|
|
var denied = false;
|
|
try { await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, headers, DateTime.UtcNow.AddSeconds(5)); }
|
|
catch (RpcException error) when (error.StatusCode is StatusCode.Unauthenticated or StatusCode.PermissionDenied or StatusCode.Unavailable or StatusCode.Unimplemented or StatusCode.Internal) { denied = true; }
|
|
results.Add(new(id + "-" + name, "wire-rejection", denied, 1, new() { ["target"] = nodeId, ["rejected"] = denied }));
|
|
}
|
|
// Each negative changes only one admission input after a positive TLS call.
|
|
using (var handler = security.Handler(name))
|
|
using (var channel = GrpcChannel.ForAddress($"https://{name}:4057", new() { HttpHandler = handler }))
|
|
{
|
|
failurePhase = ProbeFailurePhase.WirePositiveCapabilities;
|
|
var client = new W.DataConnectionService.DataConnectionServiceClient(channel);
|
|
var caps = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, Headers(key, "Node", nodeId), DateTime.UtcNow.AddSeconds(5));
|
|
var valid = caps.ProtocolMajor == 1 && caps.ClusterId == "SOURCE" && caps.Serving.NodeId == nodeId;
|
|
results.Add(new("positive-" + name, "wire-capabilities", valid, 3, new() { ["serving"] = caps.Serving.ToString() }));
|
|
var incompatible = false;
|
|
failurePhase = ProbeFailurePhase.WireProtocolMajor;
|
|
try { await client.GetCapabilitiesAsync(new() { ProtocolMajor = 99 }, Headers(key, "Node", nodeId), DateTime.UtcNow.AddSeconds(5)); }
|
|
catch (RpcException error) when (error.StatusCode == StatusCode.Unimplemented) { incompatible = true; }
|
|
results.Add(new("protocol-major-" + name, "wire-negotiation", incompatible, 1, new() { ["rejectedIncompatibleMajor"] = incompatible }));
|
|
if (arguments.TryGetValue("--previous-key-state", out var previousState))
|
|
{
|
|
failurePhase = ProbeFailurePhase.WirePreviousKey;
|
|
if (previousState is not ("enabled" or "revoked")) throw new ArgumentException();
|
|
var previousPath = Path.Combine(Path.GetDirectoryName(keyPath)!, "source-previous.key");
|
|
Restricted(previousPath);
|
|
var previousKey = (await File.ReadAllTextAsync(previousPath)).Trim();
|
|
var accepted = false;
|
|
var explicitlyDenied = false;
|
|
try
|
|
{
|
|
var oldCaps = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, Headers(previousKey, "Node", nodeId), DateTime.UtcNow.AddSeconds(5));
|
|
accepted = oldCaps.Serving.NodeId == nodeId;
|
|
}
|
|
catch (RpcException error) when (error.StatusCode is StatusCode.Unauthenticated or StatusCode.PermissionDenied) { explicitlyDenied = true; }
|
|
results.Add(new("previous-key-" + name, "wire-credential-rotation", previousState == "enabled" ? accepted : explicitlyDenied, 1,
|
|
new() { ["expectedState"] = previousState, ["accepted"] = accepted, ["explicitlyDenied"] = explicitlyDenied }));
|
|
}
|
|
}
|
|
await Reject("bad-key", "invalid-presented-key", true, true);
|
|
await Reject("wrong-ca", key, false, true);
|
|
await Reject("wrong-san", key, true, false);
|
|
await Reject("wrong-listener", key, true, true, useUi: true);
|
|
await Reject("h2c-data-listener", key, true, true, plainData: true);
|
|
if (root.GetProperty("tls").TryGetProperty("rotation", out var rotation) && rotation.GetString() == "retired")
|
|
{
|
|
failurePhase = ProbeFailurePhase.WireRetiredCa;
|
|
using var oldCa = X509Certificate2.CreateFromPem(File.ReadAllText(Path.Combine(Path.GetDirectoryName(caPath)!, "ca-original.pem")));
|
|
using var oldSecurity = new ProbeSecurity(routes, oldCa, key);
|
|
using var handler = oldSecurity.Handler(name);
|
|
using var channel = GrpcChannel.ForAddress($"https://{name}:4057", new() { HttpHandler = handler });
|
|
var rejected = false;
|
|
ProbeFailureEvidence? tlsRejection = null;
|
|
try { await new W.DataConnectionService.DataConnectionServiceClient(channel).GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, Headers(key, "Node", nodeId), DateTime.UtcNow.AddSeconds(5)); }
|
|
catch (RpcException error) when (ProbeFailureClassifier.IsRetiredCaTlsRejection(
|
|
ProbeFailureClassifier.Capture(error, ProbeFailurePhase.WireRetiredCa)))
|
|
{
|
|
rejected = true;
|
|
tlsRejection = ProbeFailureClassifier.Capture(error, ProbeFailurePhase.WireRetiredCa);
|
|
}
|
|
results.Add(new("retired-ca-" + name, "wire-trust-retirement", rejected, 1,
|
|
new() { ["oldCaRejected"] = rejected, ["failureEvidence"] = tlsRejection }));
|
|
}
|
|
}
|
|
}
|
|
if (scenario == "history")
|
|
{
|
|
// H2 smoke (opt-in history fixture): raw origin RPCs on each SOURCE data listener.
|
|
failurePhase = ProbeFailurePhase.WireOperation;
|
|
var fixture = root.GetProperty("fixture");
|
|
var rawUri = fixture.GetProperty("namespace_uris").GetProperty("raw").GetString()!;
|
|
var paths = fixture.GetProperty("history");
|
|
var historized = paths.GetProperty("historized").GetProperty("raw").GetString()!;
|
|
var unhistorized = paths.GetProperty("unhistorized").GetProperty("raw").GetString()!;
|
|
var otherKeyPath = root.GetProperty("credentials").GetProperty("data_key_files").GetProperty("source_nohistory").GetString()!;
|
|
Restricted(otherKeyPath);
|
|
var otherKey = (await File.ReadAllTextAsync(otherKeyPath)).Trim();
|
|
W.View View(string path) => new() { Address = new() { OriginClusterId = "SOURCE", NamespaceUri = rawUri, IdentifierKind = "string", Identifier = path },
|
|
Realm = (int)DataRealm.Raw, Subject = path };
|
|
W.Budget HistoryBudget() => new() { TimeoutTicks = TimeSpan.FromSeconds(20).Ticks, MaxItems = 8, MaxBytes = 4 * 1024 * 1024 };
|
|
static string Hex(uint status) => "0x" + status.ToString("X8");
|
|
static object Samples(W.HistoryReadResult item) => item.Samples.Select(sample => new
|
|
{
|
|
value = sample.Value?.ToString(), statusCode = Hex(sample.StatusCode),
|
|
sourceTimestampUtc = sample.SourceTimestamp?.Value?.ToDateTimeOffset().ToString("O"),
|
|
serverTimestampUtc = sample.ServerTimestamp?.Value?.ToDateTimeOffset().ToString("O"),
|
|
}).ToArray();
|
|
static byte[] Shape(W.HistoryReadResult item) { var copy = item.Clone(); copy.CorrelationId = ""; return copy.ToByteArray(); }
|
|
var windowStart = arguments.TryGetValue("--history-start", out var startText) ? DateTimeOffset.Parse(startText, System.Globalization.CultureInfo.InvariantCulture) : (DateTimeOffset?)null;
|
|
var windowEnd = arguments.TryGetValue("--history-end", out var endText) ? DateTimeOffset.Parse(endText, System.Globalization.CultureInfo.InvariantCulture) : (DateTimeOffset?)null;
|
|
foreach (var node in sourceNodes)
|
|
{
|
|
var name = node.Name;
|
|
failureTarget = name;
|
|
var nodeId = node.Value.GetProperty("node_id").GetString()!;
|
|
Metadata With(string credential, bool feature)
|
|
{
|
|
var headers = Headers(credential, "Node", nodeId);
|
|
if (feature) headers.Add("x-otopcua-data-features", "history");
|
|
return headers;
|
|
}
|
|
using var handler = security.Handler(name);
|
|
using var channel = GrpcChannel.ForAddress($"https://{name}:4057", new() { HttpHandler = handler });
|
|
var client = new W.DataConnectionService.DataConnectionServiceClient(channel);
|
|
var deadline = () => DateTime.UtcNow.AddSeconds(20);
|
|
// 1. Capabilities with and without the feature header.
|
|
var plain = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, With(key, false), deadline());
|
|
var featured = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, With(key, true), deadline());
|
|
var plainV1Shape = plain.History is null && (plain.Operations & 32) == 0;
|
|
var featuredShape = featured.History is not null && (featured.Operations & 32) == 32;
|
|
var sameOtherwise = plain.Operations == (featured.Operations & ~32u) && plain.ClusterId == featured.ClusterId;
|
|
results.Add(new("history-capabilities-" + name, "history-capabilities", plainV1Shape && featuredShape && sameOtherwise, 3, new()
|
|
{
|
|
["withoutHeader"] = new { operations = plain.Operations, historyPresent = plain.History is not null, bytes = plain.CalculateSize() },
|
|
["withHeader"] = new { operations = featured.Operations, history = featured.History?.ToString(), bytes = featured.CalculateSize() },
|
|
["serving"] = featured.Serving.ToString(),
|
|
}));
|
|
// 2. Raw end=now, 5 values, newest first + continuation; resume once; resume the same token again.
|
|
var now = DateTimeOffset.UtcNow;
|
|
W.HistoryReadRequest Raw(W.View view, ByteString? continuation, DateTimeOffset? start = null, DateTimeOffset? end = null, uint count = 5)
|
|
{
|
|
var request = new W.HistoryReadRequest { Budget = HistoryBudget(), Raw = new() { NumValuesPerNode = count, ReturnBounds = false } };
|
|
if (start is { } s) request.Raw.Start = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTimeOffset(s);
|
|
request.Raw.End = Google.Protobuf.WellKnownTypes.Timestamp.FromDateTimeOffset(end ?? now);
|
|
var item = new W.HistoryReadItem { CorrelationId = "one", View = view };
|
|
if (continuation is not null) item.Continuation = continuation;
|
|
request.Items.Add(item);
|
|
return request;
|
|
}
|
|
var page1 = (await client.HistoryReadAsync(Raw(View(historized), null), With(key, true), deadline())).Items.Single();
|
|
var times1 = page1.Samples.Select(x => x.SourceTimestamp.Value.ToDateTimeOffset()).ToArray();
|
|
var page1Ok = page1.StatusCode >> 30 == 0 && page1.Samples.Count is > 0 and <= 5 && page1.HasContinuation
|
|
&& times1.Zip(times1.Skip(1)).All(pair => pair.First > pair.Second);
|
|
var page2 = page1.HasContinuation ? (await client.HistoryReadAsync(Raw(View(historized), page1.Continuation), With(key, true), deadline())).Items.Single() : null;
|
|
var times2 = page2?.Samples.Select(x => x.SourceTimestamp.Value.ToDateTimeOffset()).ToArray() ?? [];
|
|
var page2Ok = page2 is not null && page2.StatusCode >> 30 == 0 && page2.Samples.Count is > 0 and <= 5
|
|
&& times2.Zip(times2.Skip(1)).All(pair => pair.First > pair.Second) && times2[0] < times1[^1];
|
|
var replay = page1.HasContinuation ? (await client.HistoryReadAsync(Raw(View(historized), page1.Continuation), With(key, true), deadline())).Items.Single() : null;
|
|
var replayOk = replay is not null && replay.StatusCode == 0x804A0000u && replay.Samples.Count == 0;
|
|
if (page2 is not null && page2.HasContinuation)
|
|
await client.HistoryReadAsync(new W.HistoryReadRequest { Budget = HistoryBudget(), Raw = new() { NumValuesPerNode = 5 }, ReleaseContinuations = true,
|
|
Items = { new W.HistoryReadItem { CorrelationId = "one", View = View(historized), Continuation = page2.Continuation } } }, With(key, true), deadline());
|
|
results.Add(new("history-raw-paging-" + name, "history-raw", page1Ok && page2Ok && replayOk, 3, new()
|
|
{
|
|
["end"] = now.ToString("O"),
|
|
["page1"] = new { statusCode = Hex(page1.StatusCode), hasContinuation = page1.HasContinuation, samples = Samples(page1) },
|
|
["page2"] = page2 is null ? null : new { statusCode = Hex(page2.StatusCode), hasContinuation = page2.HasContinuation, samples = Samples(page2) },
|
|
["replaySameToken"] = replay is null ? null : new { statusCode = Hex(replay.StatusCode), samples = replay.Samples.Count, hasContinuation = replay.HasContinuation },
|
|
["serving"] = featured.Serving.ToString(),
|
|
}));
|
|
// 3. Unhistorized tag and the no-HistoryRead principal answer the same bytes; no header ⇒ FAILED_PRECONDITION.
|
|
// --denied-expect: `permission-denied` (the second principal's export lacks HistoryRead ⇒ RPC refused) or
|
|
// `unsupported` (export granted, origin ACL denies ⇒ per-item, byte-identical to the unhistorized answer).
|
|
var deniedExpect = arguments.GetValueOrDefault("--denied-expect", "unsupported");
|
|
var unhist = (await client.HistoryReadAsync(Raw(View(unhistorized), null), With(key, true), deadline())).Items.Single();
|
|
W.HistoryReadResult? denied = null;
|
|
string? deniedRpc = null;
|
|
try { denied = (await client.HistoryReadAsync(Raw(View(historized), null), With(otherKey, true), deadline())).Items.Single(); }
|
|
catch (RpcException error) { deniedRpc = error.StatusCode.ToString(); }
|
|
var otherCaps = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, With(otherKey, true), deadline());
|
|
var identical = denied is not null && Shape(unhist).AsSpan().SequenceEqual(Shape(denied));
|
|
// Review fix 7a: a peer without a HistoryRead grant sees `history` (the origin has a historian) but no aggregates,
|
|
// resolution 0 and no bit 32.
|
|
var noGrantShape = otherCaps.History is not null && otherCaps.History.Aggregates.Count == 0
|
|
&& otherCaps.History.TimestampResolutionTicks == 0 && (otherCaps.Operations & 32) == 0;
|
|
var deniedOk = deniedExpect == "permission-denied"
|
|
? deniedRpc == "PermissionDenied" && noGrantShape
|
|
: denied is not null && denied.StatusCode == 0x80720000u && identical;
|
|
string? precondition = null;
|
|
try { await client.HistoryReadAsync(Raw(View(historized), null), With(key, false), deadline()); precondition = "OK"; }
|
|
catch (RpcException error) { precondition = error.StatusCode.ToString(); }
|
|
results.Add(new("history-refusals-" + name, "history-refusals",
|
|
unhist.StatusCode == 0x80720000u && deniedOk && precondition == "FailedPrecondition", 3, new()
|
|
{
|
|
["unhistorized"] = new { statusCode = Hex(unhist.StatusCode), unhist.Samples.Count, unhist.HasContinuation, unhist.HasDiagnostic, bytes = Convert.ToHexString(Shape(unhist)) },
|
|
["deniedExpect"] = deniedExpect,
|
|
["deniedPrincipal"] = denied is null ? new { rpcStatus = deniedRpc } : (object)new { statusCode = Hex(denied.StatusCode), denied.Samples.Count, denied.HasContinuation, denied.HasDiagnostic, bytes = Convert.ToHexString(Shape(denied)) },
|
|
["deniedPrincipalCapabilities"] = new { operations = otherCaps.Operations, historyPresent = otherCaps.History is not null,
|
|
history = otherCaps.History?.ToString(), noGrantShape },
|
|
["byteIdentical"] = identical,
|
|
["withoutFeatureHeader"] = precondition,
|
|
}));
|
|
// 4. Optional fixed window (forward, all values) for comparison with an OPC UA historyread.
|
|
if (windowStart is { } ws && windowEnd is { } we)
|
|
{
|
|
var window = (await client.HistoryReadAsync(Raw(View(historized), null, ws, we, 0), With(key, true), deadline())).Items.Single();
|
|
results.Add(new("history-window-" + name, "history-window", window.StatusCode >> 30 == 0 && window.Samples.Count > 0 && !window.HasContinuation, 1, new()
|
|
{
|
|
["start"] = ws.ToString("O"), ["end"] = we.ToString("O"), ["statusCode"] = Hex(window.StatusCode), ["samples"] = Samples(window),
|
|
}));
|
|
}
|
|
}
|
|
}
|
|
if (scenario == "conditions")
|
|
{
|
|
// A2a smoke (opt-in conditions fixture): a root-scoped condition item on each SOURCE listener's UNS equipment root.
|
|
failurePhase = ProbeFailurePhase.WireOperation;
|
|
var unsUri = root.GetProperty("fixture").GetProperty("namespace_uris").GetProperty("uns").GetString()!;
|
|
// The UNS export root: the equipment's catalog identifier (EquipmentId) and its subject (the area/line/equipment path).
|
|
var equipmentPath = arguments.GetValueOrDefault("--equipment", "area/line/plc");
|
|
var equipmentSubject = arguments.GetValueOrDefault("--subject", equipmentPath);
|
|
var deviceUrl = endpoints.GetProperty("device.control").GetProperty("url").GetString()!;
|
|
using var http = new HttpClient();
|
|
async Task SetScalar(int value)
|
|
{
|
|
using var response = await http.PostAsync(deviceUrl + "/control", new StringContent(
|
|
JsonSerializer.Serialize(new { action = "set", address = 20, value }), System.Text.Encoding.UTF8, "application/json"));
|
|
response.EnsureSuccessStatusCode();
|
|
}
|
|
var equipmentView = new W.View { Address = new() { OriginClusterId = "SOURCE", NamespaceUri = unsUri, IdentifierKind = "string",
|
|
Identifier = equipmentPath }, Realm = (int)DataRealm.Uns, Subject = equipmentSubject };
|
|
static object Record(W.ConditionState r) => new
|
|
{
|
|
key = r.ConditionKey, r.Version, r.Removed, r.StateKnown, r.Active, r.Acknowledged, r.Severity, r.Message,
|
|
comment = r.HasComment ? r.Comment : null, clientUserId = r.HasClientUserId ? r.ClientUserId : null,
|
|
activation = r.Activation is null ? null : r.Activation.Incarnation[..Math.Min(8, r.Activation.Incarnation.Length)] + ":" + r.Activation.Sequence,
|
|
info = r.Info is null ? null : new { r.Info.ConditionType, r.Info.ConditionName, r.Info.SourceKind,
|
|
placements = r.Info.Placements.Select(p => p.Address.NamespaceUri + "|" + p.Address.Identifier).ToArray() },
|
|
};
|
|
foreach (var node in sourceNodes)
|
|
{
|
|
var name = node.Name;
|
|
failureTarget = name;
|
|
var nodeId = node.Value.GetProperty("node_id").GetString()!;
|
|
Metadata With(bool feature)
|
|
{
|
|
var headers = Headers(key, "Node", nodeId);
|
|
if (feature) headers.Add("x-otopcua-data-features", "conditions");
|
|
return headers;
|
|
}
|
|
using var handler = security.Handler(name);
|
|
using var channel = GrpcChannel.ForAddress($"https://{name}:4057", new() { HttpHandler = handler });
|
|
var client = new W.DataConnectionService.DataConnectionServiceClient(channel);
|
|
var plain = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, With(false), DateTime.UtcNow.AddSeconds(20));
|
|
var featured = await client.GetCapabilitiesAsync(new() { ProtocolMajor = 1, ProtocolMinor = 3 }, With(true), DateTime.UtcNow.AddSeconds(20));
|
|
var capsOk = plain.Conditions is null && (plain.Operations & 64) == 0 && featured.Conditions is not null && (featured.Operations & 64) == 64;
|
|
var primary = featured.Serving.Role == "Primary";
|
|
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(90));
|
|
using var call = client.Subscribe(With(true), cancellationToken: cts.Token);
|
|
var open = new W.SubscriptionCommand { SubscriptionId = "conditions-" + name, StreamEpoch = 1, CommandId = "open-1",
|
|
AcknowledgementTimeoutTicks = TimeSpan.FromSeconds(10).Ticks, Open = new() { SessionLifetimeTicks = TimeSpan.FromMinutes(5).Ticks,
|
|
SnapshotBudget = new() { TimeoutTicks = TimeSpan.FromSeconds(20).Ticks, MaxItems = 8, MaxBytes = 4 * 1024 * 1024 } } };
|
|
open.Open.Items.Add(new W.SubscriptionItem { ClientItemId = "conditions", View = equipmentView,
|
|
Settings = new() { Trigger = 2 }, ConditionScope = new() { IncludeInfo = true } });
|
|
await call.RequestStream.WriteAsync(open);
|
|
int? ackStatus = null, total = null;
|
|
var snapshot = new List<W.ConditionState>();
|
|
var deltas = new List<W.ConditionState>();
|
|
var complete = false;
|
|
var frames = new List<string>();
|
|
var flipped = false;
|
|
// A2b: on the Primary, a remote Acknowledge of the active alarm (once the snapshot is complete), a duplicate of the
|
|
// same operation id (joins), and the same call without the header (FAILED_PRECONDITION); on the Secondary the
|
|
// call is RejectedBeforeDispatch (Primary-only).
|
|
object? ackEvidence = null;
|
|
var acked = false;
|
|
var ackSent = false;
|
|
async Task<object> RemoteAck(W.View placement, W.ActivationMarker marker)
|
|
{
|
|
var request = new W.ConditionMethodRequest
|
|
{
|
|
OperationId = "a2b-ack-" + name + "-" + Guid.NewGuid().ToString("N")[..8], Placement = placement, Method = 1,
|
|
ExpectedActivation = marker, Comment = "A2b remote ack",
|
|
ExpectedServingIncarnation = featured.Serving.Incarnation, RemainingBudgetTicks = TimeSpan.FromSeconds(10).Ticks,
|
|
OnBehalfOf = "probe\u0007operator",
|
|
};
|
|
var first = await client.CallConditionMethodAsync(request, With(true), DateTime.UtcNow.AddSeconds(15));
|
|
var again = await client.CallConditionMethodAsync(request, With(true), DateTime.UtcNow.AddSeconds(15));
|
|
string? headerless;
|
|
try { await client.CallConditionMethodAsync(request, With(false), DateTime.UtcNow.AddSeconds(15)); headerless = "OK"; }
|
|
catch (RpcException ex) { headerless = ex.StatusCode.ToString(); }
|
|
return new { first = new { first.State, first.StatusCode, first.Diagnostic }, duplicate = new { again.State, again.StatusCode },
|
|
duplicateEqual = first.Equals(again), headerless, firstState = first.State };
|
|
}
|
|
while (await call.ResponseStream.MoveNext(cts.Token))
|
|
{
|
|
var frame = call.ResponseStream.Current;
|
|
frames.Add(frame.FrameCase.ToString());
|
|
if (frame.Ack is { } ack) { ackStatus = ack.Items.Single().Status; if (ackStatus != 1) break; continue; }
|
|
if (frame.ConditionStates is not { } states) continue;
|
|
if (states.IsSnapshot)
|
|
{
|
|
if (states.HasTotal) { total = states.Total; snapshot.Clear(); }
|
|
snapshot.AddRange(states.Items);
|
|
complete = states.SnapshotComplete;
|
|
if (complete && !ackSent && snapshot.FirstOrDefault(r => r.Active && r.Info is not null) is { } target)
|
|
{
|
|
ackSent = true;
|
|
ackEvidence = await RemoteAck(target.Info.Placements[0], target.Activation);
|
|
}
|
|
continue;
|
|
}
|
|
deltas.AddRange(states.Items);
|
|
if (!acked && deltas.Any(r => r.Active && r.Acknowledged && r.StateKnown))
|
|
{
|
|
// The stream carried the acked delta; now clear the alarm (scalar := 0) and wait for the inactive delta.
|
|
acked = true;
|
|
flipped = true;
|
|
await SetScalar(0);
|
|
continue;
|
|
}
|
|
if (acked && deltas.Any(r => !r.Active && r.StateKnown)) break;
|
|
}
|
|
await cts.CancelAsync();
|
|
// The Secondary never streams (ack Unavailable): its call is refused at the Primary check, before placement lookup.
|
|
if (!primary && ackEvidence is null)
|
|
ackEvidence = await RemoteAck(equipmentView, new W.ActivationMarker { Incarnation = "none", Sequence = 0 });
|
|
var leaked = snapshot.Concat(deltas).Any(r => Record(r).ToString()!.Contains("modbus/plc", StringComparison.Ordinal));
|
|
var ackJson = JsonSerializer.SerializeToElement(ackEvidence);
|
|
var methodState = ackEvidence is null ? -1 : ackJson.GetProperty("firstState").GetInt32();
|
|
// Method bits: with the header on the Primary only (stripped off-Primary), never without the header.
|
|
// State: scripted ⇒ 2 (applied), native ⇒ 4 (AcceptedUnconfirmed); Secondary ⇒ 1 (RejectedBeforeDispatch).
|
|
// The stream may carry more than one acked record (a state-only re-projection after the method's own record);
|
|
// "exactly one ack" is the ORIGIN's event count, asserted by conditions_smoke.py.
|
|
var scripted = snapshot.FirstOrDefault(r => r.Active && r.Info is not null)?.Info.SourceKind == 2;
|
|
var methodsOk = (featured.Operations & 384) == (primary ? 384u : 0u) && (plain.Operations & 384) == 0 && ackEvidence is not null
|
|
&& ackJson.GetProperty("headerless").GetString() == "FailedPrecondition"
|
|
&& ackJson.GetProperty("duplicateEqual").GetBoolean()
|
|
&& (primary
|
|
? methodState == (scripted ? 2 : 4) && deltas.Any(r => r.Active && r.Acknowledged && r.StateKnown)
|
|
: methodState == 1);
|
|
var passed = capsOk && methodsOk && (primary
|
|
? ackStatus == 1 && total >= 1 && complete && snapshot.Count == total && snapshot.Any(r => r.Active && r.StateKnown)
|
|
&& acked && deltas.Any(r => !r.Active && r.StateKnown) && !leaked
|
|
: ackStatus == 6);
|
|
results.Add(new("conditions-" + name, "conditions", passed, primary ? 7 : 2, new()
|
|
{
|
|
["role"] = featured.Serving.Role,
|
|
["capabilities"] = new { withoutHeader = new { operations = plain.Operations, conditions = plain.Conditions?.ToString() },
|
|
withHeader = new { operations = featured.Operations, conditions = featured.Conditions?.ToString() } },
|
|
["ackStatus"] = ackStatus, ["total"] = total, ["snapshotComplete"] = complete,
|
|
["snapshot"] = snapshot.Select(Record).ToArray(), ["deltas"] = deltas.Select(Record).ToArray(),
|
|
["frames"] = frames, ["rawPathLeaked"] = leaked, ["remoteAck"] = ackEvidence,
|
|
}));
|
|
if (primary && flipped) await SetScalar(150); // restore for the other node
|
|
}
|
|
}
|
|
if (scenario == "condition-records")
|
|
{
|
|
// A4 (A04): one root-scoped condition item, opened on ONE named SOURCE listener under a NAMED principal's data key
|
|
// (`--key-name` = a manifest data_key_files alias), returning its complete snapshot records (placements included).
|
|
// `--forbid` must occur nowhere in the records (a UNS-only principal: no RawPath); `--expect` must occur (positive control).
|
|
failurePhase = ProbeFailurePhase.WireOperation;
|
|
var name = arguments["--node"];
|
|
if (name is not ("source-1" or "source-2")) throw new ArgumentException("SOURCE listener required.");
|
|
failureTarget = name;
|
|
var principalKeyPath = root.GetProperty("credentials").GetProperty("data_key_files").GetProperty(arguments["--key-name"]).GetString()!;
|
|
Restricted(principalKeyPath);
|
|
var principalKey = (await File.ReadAllTextAsync(principalKeyPath)).Trim();
|
|
var realmName = arguments["--realm"];
|
|
var realm = realmName == "raw" ? DataRealm.Raw : realmName == "uns" ? DataRealm.Uns : throw new ArgumentException("realm");
|
|
var view = new W.View { Address = new() { OriginClusterId = "SOURCE", IdentifierKind = "string", Identifier = arguments["--identifier"],
|
|
NamespaceUri = root.GetProperty("fixture").GetProperty("namespace_uris").GetProperty(realmName).GetString()! },
|
|
Realm = (int)realm, Subject = arguments["--subject"] };
|
|
var nodeId = sourceNodes.Single(item => item.Name == name).Value.GetProperty("node_id").GetString()!;
|
|
var headers = Headers(principalKey, "Node", nodeId);
|
|
headers.Add("x-otopcua-data-features", "conditions");
|
|
using var handler = security.Handler(name);
|
|
using var channel = GrpcChannel.ForAddress($"https://{name}:4057", new() { HttpHandler = handler });
|
|
var client = new W.DataConnectionService.DataConnectionServiceClient(channel);
|
|
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(45));
|
|
using var call = client.Subscribe(headers, cancellationToken: cts.Token);
|
|
var open = new W.SubscriptionCommand { SubscriptionId = "records-" + Guid.NewGuid().ToString("N")[..8], StreamEpoch = 1, CommandId = "open-1",
|
|
AcknowledgementTimeoutTicks = TimeSpan.FromSeconds(10).Ticks, Open = new() { SessionLifetimeTicks = TimeSpan.FromMinutes(5).Ticks,
|
|
SnapshotBudget = new() { TimeoutTicks = TimeSpan.FromSeconds(20).Ticks, MaxItems = 64, MaxBytes = 4 * 1024 * 1024 } } };
|
|
open.Open.Items.Add(new W.SubscriptionItem { ClientItemId = "records", View = view, Settings = new() { Trigger = 2 }, ConditionScope = new() { IncludeInfo = true } });
|
|
await call.RequestStream.WriteAsync(open);
|
|
int? ackStatus = null, total = null;
|
|
var snapshot = new List<W.ConditionState>();
|
|
var complete = false;
|
|
string? ended = null;
|
|
try
|
|
{
|
|
while (await call.ResponseStream.MoveNext(cts.Token))
|
|
{
|
|
var frame = call.ResponseStream.Current;
|
|
if (frame.Ack is { } ack) { ackStatus = ack.Items.Single().Status; if (ackStatus != 1) break; continue; }
|
|
if (frame.ConditionStates is not { IsSnapshot: true } states) continue;
|
|
if (states.HasTotal) { total = states.Total; snapshot.Clear(); }
|
|
snapshot.AddRange(states.Items);
|
|
if (states.SnapshotComplete) { complete = true; break; }
|
|
}
|
|
}
|
|
catch (RpcException error) { ended = error.StatusCode.ToString(); }
|
|
await cts.CancelAsync();
|
|
var records = snapshot.Select(r => (object)new
|
|
{
|
|
key = r.ConditionKey, r.StateKnown, r.Active, r.Acknowledged, r.Severity, r.Message,
|
|
info = r.Info is null ? null : new { r.Info.ConditionType, r.Info.ConditionName, r.Info.SourceKind,
|
|
placements = r.Info.Placements.Select(p => new { realm = p.Realm, ns = p.Address.NamespaceUri, id = p.Address.Identifier, subject = p.Subject }).ToArray() },
|
|
raw = r.ToString(),
|
|
}).ToArray();
|
|
var text = JsonSerializer.Serialize(records);
|
|
var forbid = arguments.GetValueOrDefault("--forbid");
|
|
var expect = arguments.GetValueOrDefault("--expect");
|
|
var forbidden = forbid is not null && text.Contains(forbid, StringComparison.Ordinal);
|
|
var expected = expect is null || text.Contains(expect, StringComparison.Ordinal);
|
|
results.Add(new("condition-records-" + name, "condition-records", ackStatus == 1 && complete && snapshot.Count >= 1 && !forbidden && expected, 4, new()
|
|
{
|
|
["principal"] = arguments["--key-name"], ["realm"] = realmName, ["subject"] = view.Subject, ["ackStatus"] = ackStatus, ["total"] = total,
|
|
["snapshotComplete"] = complete, ["ended"] = ended, ["records"] = records, ["forbid"] = forbid, ["forbiddenFound"] = forbidden,
|
|
["expect"] = expect, ["expectedFound"] = expected,
|
|
}));
|
|
}
|
|
if (scenario is not ("D13" or "history" or "conditions" or "condition-records"))
|
|
{
|
|
var fixture = root.GetProperty("fixture");
|
|
var rawUri = fixture.GetProperty("namespace_uris").GetProperty("raw").GetString()!;
|
|
var unsUri = fixture.GetProperty("namespace_uris").GetProperty("uns").GetString()!;
|
|
foreach (var mode in new[] { DataTargetMode.Node, DataTargetMode.Cluster })
|
|
{
|
|
foreach (var source in mode == DataTargetMode.Node ? sourceNodes : sourceNodes.Take(1))
|
|
{
|
|
failurePhase = ProbeFailurePhase.WireOperation;
|
|
failureTarget = source.Name is "source-1" or "source-2" ? source.Name : null;
|
|
var target = new DataTarget(mode, "SOURCE", mode == DataTargetMode.Node ? source.Value.GetProperty("node_id").GetString() : null,
|
|
mode == DataTargetMode.Node ? DataConsistency.ReadyReplica : DataConsistency.Primary);
|
|
using var scope = new DataConnectionScopeLease(1, CancellationToken.None, () => { });
|
|
await using var connection = new GrpcDataConnection("wire-probe", target,
|
|
(mode == DataTargetMode.Node ? [source] : sourceNodes).Select(item => new Uri($"https://{item.Name}:4057")),
|
|
security, scope, 1024 * 1024, 2, eligibleNodeIds: sourceNodes.Select(item => item.Value.GetProperty("node_id").GetString()!).ToHashSet());
|
|
foreach (var realm in new[] { "raw", "uns" })
|
|
{
|
|
var path = fixture.GetProperty("origin_paths").GetProperty(realm).GetString()!;
|
|
foreach (var operation in new[] { "capabilities", "metadata", "read", "browse" })
|
|
{
|
|
var command = new ProbeCommand($"{mode}-{source.Name}-{realm}-{operation}", "wire-probe", operation,
|
|
realm, "SOURCE", realm == "raw" ? rawUri : unsUri,
|
|
operation == "browse" ? fixture.GetProperty("browse_roots").GetProperty(realm).GetString()! : path,
|
|
ExpectedNodeId: mode == DataTargetMode.Node ? source.Value.GetProperty("node_id").GetString() : null);
|
|
results.Add(await ProbeEngine.RunAsync(connection, command, CancellationToken.None));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
var output = JsonSerializer.Serialize(new { schemaVersion = 1, scenario, passed = results.Count > 0 && results.All(result => result.Passed && result.Assertions > 0), results }, ProbeEngine.Json);
|
|
if (arguments.TryGetValue("--output", out var outputPath))
|
|
{
|
|
await File.WriteAllTextAsync(outputPath, output);
|
|
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(outputPath, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
|
}
|
|
Console.WriteLine(output);
|
|
return results.Count > 0 && results.All(result => result.Passed && result.Assertions > 0) ? 0 : 1;
|
|
}
|
|
catch (Exception error) when (error is not OutOfMemoryException)
|
|
{
|
|
var failure = ProbeFailureClassifier.Capture(error, failurePhase);
|
|
var output = JsonSerializer.Serialize(new { passed = false, failure = failure.Category,
|
|
failurePhase = failure.Phase, targetNode = failureTarget, failureEvidence = failure,
|
|
results = results.Take(128).ToArray(), partialResultsTruncated = results.Count > 128 }, ProbeEngine.Json);
|
|
if (failureOutput is not null && Path.IsPathFullyQualified(failureOutput))
|
|
{
|
|
try
|
|
{
|
|
if (new FileInfo(failureOutput).LinkTarget is null)
|
|
{
|
|
await File.WriteAllTextAsync(failureOutput, output);
|
|
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(failureOutput, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
|
}
|
|
}
|
|
catch (Exception) { /* Preserve the original wire failure and exit status. */ }
|
|
}
|
|
Console.Error.WriteLine(output);
|
|
return 2;
|
|
}
|
|
|
|
static void Restricted(string path)
|
|
{
|
|
var file = new FileInfo(path);
|
|
if (!file.Exists || file.LinkTarget is not null || !Path.IsPathFullyQualified(path) || file.Length > 1024 * 1024) throw new InvalidOperationException();
|
|
if (!OperatingSystem.IsWindows() && (File.GetUnixFileMode(path) & (UnixFileMode.GroupRead | UnixFileMode.GroupWrite | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherWrite | UnixFileMode.OtherExecute)) != 0)
|
|
throw new InvalidOperationException();
|
|
}
|
|
|
|
static Metadata Headers(string key, string mode, string nodeId) => new()
|
|
{
|
|
{ "authorization", "Bearer " + key }, { "x-data-target-mode", mode }, { "x-data-cluster-id", "SOURCE" },
|
|
{ "x-data-node-id", nodeId }, { "x-data-consistency", "ReadyReplica" }
|
|
};
|
|
|
|
sealed class ProbeSecurity(Dictionary<string, int> routes, X509Certificate2 root, string key) : IDataConnectionSecurityProvider, IDisposable
|
|
{
|
|
private readonly X509Certificate2 _untrustedRoot = UntrustedRoot();
|
|
private static X509Certificate2 UntrustedRoot()
|
|
{
|
|
using var signingKey = ECDsa.Create(ECCurve.NamedCurves.nistP256);
|
|
var request = new CertificateRequest("CN=unrelated-grpc-data-probe-ca", signingKey, HashAlgorithmName.SHA256);
|
|
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
|
|
return request.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-1), DateTimeOffset.UtcNow.AddHours(1));
|
|
}
|
|
public void Dispose() => _untrustedRoot.Dispose();
|
|
public event Action<string>? Changed { add { } remove { } }
|
|
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) =>
|
|
ValueTask.FromResult<DataConnectionSecurity?>(new("fixture-key-v1", Convert.ToHexString(SHA256.HashData(root.RawData)), key,
|
|
() => Handler(endpoint.Host)));
|
|
|
|
public HttpMessageHandler Handler(string host, bool correctCa = true, bool correctName = true, int? overridePort = null)
|
|
{
|
|
if (!routes.TryGetValue(host, out var port)) throw new InvalidOperationException();
|
|
return new SocketsHttpHandler
|
|
{
|
|
UseProxy = false,
|
|
ConnectTimeout = TimeSpan.FromSeconds(5),
|
|
ConnectCallback = async (_, token) =>
|
|
{
|
|
var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
|
|
try { await socket.ConnectAsync(IPAddress.Loopback, overridePort ?? port, token); return new NetworkStream(socket, ownsSocket: true); }
|
|
catch { socket.Dispose(); throw; }
|
|
},
|
|
SslOptions = new SslClientAuthenticationOptions
|
|
{
|
|
EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13,
|
|
RemoteCertificateValidationCallback = (_, certificate, _, _) =>
|
|
{
|
|
if (certificate is null) return false;
|
|
using var leaf = X509CertificateLoader.LoadCertificate(certificate.GetRawCertData());
|
|
if (!leaf.MatchesHostname(correctName ? host : "wrong-san.grpc-data.invalid", allowWildcards: false, allowCommonName: false)) return false;
|
|
using var chain = new X509Chain();
|
|
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
|
|
chain.ChainPolicy.CustomTrustStore.Add(correctCa ? root : _untrustedRoot);
|
|
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
|
|
chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.1"));
|
|
return chain.Build(leaf);
|
|
}
|
|
}
|
|
};
|
|
}
|
|
}
|