Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/DataConnections/GrpcDataTlsWireTests.cs
T

191 lines
12 KiB
C#

using System.Net;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Grpc.Core;
using Grpc.Net.Client;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.Host.Configuration;
using ZB.MOM.WW.OtOpcUa.Host.Grpc;
using ZB.MOM.WW.OtOpcUa.Host.OpcUa;
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
namespace ZB.MOM.WW.OtOpcUa.Host.IntegrationTests.DataConnections;
[Trait("Category", "Integration"), Trait("Feature", "GrpcData"), Trait("Phase", "P07Wire"), Trait("Phase", "P10")]
public sealed class GrpcDataTlsWireTests
{
[Fact(Timeout = 30000)]
public async Task Trusted_ca_and_san_reach_the_authenticated_service_wrong_ca_and_name_fail_tls()
{
await using var fixture = await GrpcDataWireFixture.StartAsync(HttpProtocols.Http2);
using (var channel = fixture.TlsChannel(fixture.Ca, "localhost"))
{
var response = await new W.DataConnectionService.DataConnectionServiceClient(channel)
.GetCapabilitiesAsync(new() { ProtocolMajor = 1 }, fixture.Headers(), cancellationToken: TestContext.Current.CancellationToken);
response.Serving.NodeId.ShouldBe("node");
fixture.Factory.Created.ShouldBeGreaterThan(0);
}
var accepted = fixture.Factory.Created;
using var other = GrpcDataWireFixture.CreateCa();
using (var channel = fixture.TlsChannel(other, "localhost"))
{
var error = await Should.ThrowAsync<RpcException>(async () => await new W.DataConnectionService.DataConnectionServiceClient(channel)
.GetCapabilitiesAsync(new() { ProtocolMajor = 1 }, fixture.Headers(), cancellationToken: TestContext.Current.CancellationToken));
AssertTlsValidationFailure(error);
}
using (var channel = fixture.TlsChannel(fixture.Ca, "127.0.0.1"))
{
var error = await Should.ThrowAsync<RpcException>(async () => await new W.DataConnectionService.DataConnectionServiceClient(channel)
.GetCapabilitiesAsync(new() { ProtocolMajor = 1 }, fixture.Headers(), cancellationToken: TestContext.Current.CancellationToken));
AssertTlsValidationFailure(error);
}
fixture.Factory.Created.ShouldBe(accepted, "TLS failures must not reach the authenticated data facade");
}
private static void AssertTlsValidationFailure(RpcException error)
{
(error.StatusCode is StatusCode.Unavailable or StatusCode.Internal).ShouldBeTrue();
var cause = error.Status.DebugException;
var sawAuthenticationFailure = false;
while (cause is not null)
{
if (cause is System.Security.Authentication.AuthenticationException) sawAuthenticationFailure = true;
cause = cause.InnerException;
}
sawAuthenticationFailure.ShouldBeTrue("the connection must fail during TLS certificate validation");
}
[Theory(Timeout = 30000)]
[InlineData(null)]
[InlineData("invalid")]
public async Task Missing_or_bad_key_is_rejected_on_the_real_tls_listener(string? bearer)
{
await using var fixture = await GrpcDataWireFixture.StartAsync(HttpProtocols.Http2);
using var channel = fixture.TlsChannel(fixture.Ca, "localhost");
var failure = await Should.ThrowAsync<RpcException>(async () => await new W.DataConnectionService.DataConnectionServiceClient(channel)
.GetCapabilitiesAsync(new() { ProtocolMajor = 1 }, fixture.Headers(bearer, useDefaultBearer: false), cancellationToken: TestContext.Current.CancellationToken));
failure.StatusCode.ShouldBe(StatusCode.Unauthenticated);
fixture.Factory.Created.ShouldBe(0);
}
}
/// <summary>Ephemeral loopback Kestrel plus in-memory CA and production data admission/service wiring.</summary>
internal sealed class GrpcDataWireFixture : IAsyncDisposable
{
private readonly WebApplication _app;
private readonly X509Certificate2 _server;
private readonly RSA _caKey, _serverKey;
private readonly string _bearer;
internal X509Certificate2 Ca { get; }
internal string Bearer => _bearer;
internal Uri TlsAddress { get; }
internal Uri OtherAddress { get; }
internal WireFactory Factory { get; }
private GrpcDataWireFixture(WebApplication app, X509Certificate2 ca, X509Certificate2 server, RSA caKey, RSA serverKey,
string bearer, Uri tlsAddress, Uri otherAddress, WireFactory factory)
{ _app = app; Ca = ca; _server = server; _caKey = caKey; _serverKey = serverKey; _bearer = bearer; TlsAddress = tlsAddress; OtherAddress = otherAddress; Factory = factory; }
internal static X509Certificate2 CreateCa()
{
using var key = RSA.Create(2048);
var request = new CertificateRequest("CN=grpc-data-unrelated-ca", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign, true));
return request.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-5), DateTimeOffset.UtcNow.AddHours(1));
}
internal static async Task<GrpcDataWireFixture> StartAsync(HttpProtocols otherProtocol, WireFactory? suppliedFactory = null)
{
var caKey = RSA.Create(2048); var serverKey = RSA.Create(2048);
var caRequest = new CertificateRequest("CN=grpc-data-test-ca", caKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
caRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
caRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign, true));
var ca = caRequest.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-5), DateTimeOffset.UtcNow.AddHours(1));
var leafRequest = new CertificateRequest("CN=unused", serverKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
leafRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true));
leafRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, true));
leafRequest.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new("1.3.6.1.5.5.7.3.1") }, true));
var san = new SubjectAlternativeNameBuilder(); san.AddDnsName("localhost"); leafRequest.CertificateExtensions.Add(san.Build());
using var unsigned = leafRequest.Create(ca, DateTimeOffset.UtcNow.AddMinutes(-1), DateTimeOffset.UtcNow.AddMinutes(30), [1, 2, 3, 4]);
var server = unsigned.CopyWithPrivateKey(serverKey);
var (bearer, id, hash) = ApiKeySecret.Generate("pepper");
var authority = new DataPlaneAuthorityState();
authority.Apply("cluster", "v1", [new ApiKey { ApiKeyId = id, Name = "wire", Principal = "peer", SecretHash = hash, Enabled = true }],
[], new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
var options = new DataConnectionOptions { Enabled = true, AllowedHosts = ["localhost"], MaxMessageBytes = 65536 };
var factory = suppliedFactory ?? new WireFactory();
var builder = WebApplication.CreateBuilder();
builder.Environment.ApplicationName = typeof(GrpcDataWireFixture).Assembly.GetName().Name!;
builder.WebHost.ConfigureKestrel(k =>
{
k.Listen(IPAddress.Loopback, 0, endpoint => { endpoint.Protocols = HttpProtocols.Http2; endpoint.UseHttps(server); });
k.Listen(IPAddress.Loopback, 0, endpoint => endpoint.Protocols = otherProtocol);
});
builder.Services.AddSingleton<IOptions<DataConnectionOptions>>(Options.Create(options));
builder.Services.AddSingleton<IOptions<ApiKeyOptions>>(Options.Create(new ApiKeyOptions { Pepper = "pepper" }));
builder.Services.AddSingleton<IDataPlaneAuthoritySource>(authority);
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddSingleton<DataConnectionAuthenticator>();
builder.Services.AddSingleton<IDataConnectionFactory>(factory);
builder.Services.AddGrpc(grpc => grpc.Interceptors.Add<DataConnectionAuthInterceptor>());
var app = builder.Build();
app.UseDataConnectionAdmission();
app.MapGet("/healthz", () => "ok");
app.MapGrpcService<DataConnectionGrpcService>().AllowAnonymous();
await app.StartAsync(TestContext.Current.CancellationToken);
var addresses = app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses.Select(x => new Uri(x)).ToArray();
var tls = addresses.Single(x => x.Scheme == "https"); var other = addresses.Single(x => x.Scheme == "http");
options.ListenPort = tls.Port;
return new(app, ca, server, caKey, serverKey, bearer, tls, other, factory);
}
internal Metadata Headers(string? bearer = null, bool useDefaultBearer = true)
{
var headers = new Metadata { { "x-data-target-mode", "Node" }, { "x-data-consistency", "Primary" },
{ "x-data-cluster-id", "cluster" }, { "x-data-node-id", "node" } };
var credential = useDefaultBearer ? _bearer : bearer;
if (credential is not null) headers.Add("authorization", "Bearer " + credential);
return headers;
}
internal GrpcChannel TlsChannel(X509Certificate2 ca, string host) => GrpcChannel.ForAddress(
new UriBuilder("https", host, TlsAddress.Port).Uri, new GrpcChannelOptions { HttpHandler = new DataConnectionTrustPolicy(1, [ca]).CreateHandler() });
internal Task StopAsync() => _app.StopAsync(TestContext.Current.CancellationToken);
public async ValueTask DisposeAsync()
{
await _app.DisposeAsync(); _server.Dispose(); Ca.Dispose(); _serverKey.Dispose(); _caKey.Dispose();
}
internal sealed class WireFactory(Func<DataTarget, IDataConnection>? create = null) : IDataConnectionFactory
{
private int _created;
internal int Created => Volatile.Read(ref _created);
public IDataConnection Create(DataAuthenticatedContext context, DataTarget target)
{ Interlocked.Increment(ref _created); return create?.Invoke(target) ?? new WireConnection(target); }
}
private sealed class WireConnection(DataTarget target) : IDataConnection, IDataConnectionDiscoveryGate
{
private static readonly ServingIdentity Serving = new("node", "boot", "Primary", 1, 1, 1);
public DataTarget Target => target;
public TimeProvider Clock => TimeProvider.System;
public bool CanPublishCapabilities(DataCapabilities expected) => expected.Serving == Serving;
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken token) => Task.FromResult(new DataCapabilities(1, 3, Serving,
DataReadiness.Ready, DataOperations.Browse | DataOperations.Read | DataOperations.Subscribe,
new HashSet<DataValueKind> { DataValueKind.Int32 }, new(16, 16, 65536, 16, 4, 65536,
TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5)), true, 1, "cluster", true, true));
public Task<IDataSubscription> SubscribeAsync(CancellationToken token) => throw new NotSupportedException();
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken token) => throw new NotSupportedException();
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken token) => throw new NotSupportedException();
public Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken token) => throw new NotSupportedException();
public Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken token) => throw new NotSupportedException();
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}