362 lines
26 KiB
C#
362 lines
26 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")) 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.
|
|
var unhist = (await client.HistoryReadAsync(Raw(View(unhistorized), null), With(key, true), deadline())).Items.Single();
|
|
var denied = (await client.HistoryReadAsync(Raw(View(historized), null), With(otherKey, true), deadline())).Items.Single();
|
|
var identical = Shape(unhist).AsSpan().SequenceEqual(Shape(denied));
|
|
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 && denied.StatusCode == 0x80720000u && identical && precondition == "FailedPrecondition", 4, new()
|
|
{
|
|
["unhistorized"] = new { statusCode = Hex(unhist.StatusCode), unhist.Samples.Count, unhist.HasContinuation, unhist.HasDiagnostic, bytes = Convert.ToHexString(Shape(unhist)) },
|
|
["deniedPrincipal"] = new { statusCode = Hex(denied.StatusCode), denied.Samples.Count, denied.HasContinuation, denied.HasDiagnostic, bytes = Convert.ToHexString(Shape(denied)) },
|
|
["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 is not ("D13" or "history"))
|
|
{
|
|
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);
|
|
}
|
|
}
|
|
};
|
|
}
|
|
}
|