using Grpc.Core; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Shouldly; using Xunit; using ZB.MOM.WW.LocalDb.Replication; using ZB.MOM.WW.OtOpcUa.Host.Configuration; namespace ZB.MOM.WW.OtOpcUa.Host.IntegrationTests; /// /// LocalDb Phase 1 (Task 3) — the passive sync endpoint's inbound gate. /// /// /// The replication library's LocalDbSyncService verifies nothing; inbound auth is /// explicitly the host's job. Without this interceptor, anything able to reach a driver node's /// sync port could stream arbitrary rows straight into that node's deployment-artifact cache — /// which is exactly what the node boots from when central SQL is unreachable. /// public sealed class LocalDbSyncAuthInterceptorTests { private const string SyncMethod = "/localdb_sync.v1.LocalDbSync/Sync"; private const string OtherMethod = "/otopcua.SomethingElse/Call"; private static LocalDbSyncAuthInterceptor CreateInterceptor(string? apiKey) => new( Options.Create(new ReplicationOptions { ApiKey = apiKey }), NullLogger.Instance); private static ServerCallContext CreateContext(string method, string? authorizationHeader) { var headers = new Metadata(); if (authorizationHeader is not null) headers.Add("authorization", authorizationHeader); return new FakeServerCallContext(method, headers); } /// /// Minimal carrying just a method name and request headers — /// the only two things the interceptor reads. /// /// /// Hand-rolled rather than using Grpc.Core.Testing.TestServerCallContext: that type /// ships in the retired native Grpc.Core package and does not exist on the grpc-dotnet /// stack this solution runs on. /// private sealed class FakeServerCallContext(string method, Metadata requestHeaders) : ServerCallContext { protected override string MethodCore => method; protected override string HostCore => "localhost"; protected override string PeerCore => "ipv4:127.0.0.1:12345"; protected override DateTime DeadlineCore => DateTime.UtcNow.AddMinutes(1); protected override Metadata RequestHeadersCore => requestHeaders; protected override CancellationToken CancellationTokenCore => CancellationToken.None; protected override Metadata ResponseTrailersCore { get; } = []; protected override Status StatusCore { get; set; } protected override WriteOptions? WriteOptionsCore { get; set; } protected override AuthContext AuthContextCore { get; } = new(null, new Dictionary>()); protected override ContextPropagationToken CreatePropagationTokenCore( ContextPropagationOptions? options) => throw new NotSupportedException(); protected override Task WriteResponseHeadersAsyncCore(Metadata responseHeaders) => Task.CompletedTask; } /// Invokes the interceptor's unary path with a trivial continuation. private static Task Invoke( LocalDbSyncAuthInterceptor interceptor, ServerCallContext context) => interceptor.UnaryServerHandler( "request", context, (_, _) => Task.FromResult("ok")); [Fact] public async Task NonSyncMethod_PassesThrough_EvenWithNoKeyConfigured() { // The interceptor is registered on the whole AddGrpc pipeline, so it sees every call. // It must be scoped strictly to the sync service. var interceptor = CreateInterceptor(apiKey: null); var context = CreateContext(OtherMethod, authorizationHeader: null); (await Invoke(interceptor, context)).ShouldBe("ok"); } [Fact] public async Task SyncMethod_WithNoKeyConfigured_IsDenied_EvenWithABearerToken() { // Fail-closed. "No key configured" is the DEFAULT every node ships with, so treating it // as "no auth required" would silently expose the endpoint on exactly the configuration // that is most common. Presenting a token must not help. var interceptor = CreateInterceptor(apiKey: null); var context = CreateContext(SyncMethod, "Bearer anything-at-all"); var ex = await Should.ThrowAsync(() => Invoke(interceptor, context)); ex.StatusCode.ShouldBe(StatusCode.PermissionDenied); } [Fact] public async Task SyncMethod_WithNoBearerToken_IsDenied() { var interceptor = CreateInterceptor("the-shared-key"); var context = CreateContext(SyncMethod, authorizationHeader: null); var ex = await Should.ThrowAsync(() => Invoke(interceptor, context)); ex.StatusCode.ShouldBe(StatusCode.PermissionDenied); } [Fact] public async Task SyncMethod_WithWrongBearerToken_IsDenied() { var interceptor = CreateInterceptor("the-shared-key"); var context = CreateContext(SyncMethod, "Bearer the-wrong-key"); var ex = await Should.ThrowAsync(() => Invoke(interceptor, context)); ex.StatusCode.ShouldBe(StatusCode.PermissionDenied); } [Fact] public async Task SyncMethod_WithCorrectBearerToken_PassesThrough() { var interceptor = CreateInterceptor("the-shared-key"); var context = CreateContext(SyncMethod, "Bearer the-shared-key"); (await Invoke(interceptor, context)).ShouldBe("ok"); } [Fact] public async Task SyncMethod_WithCorrectKey_ButNoBearerScheme_IsDenied() { // A raw key with no "Bearer " prefix is not what SyncBackgroundService sends, and // accepting it would widen the accepted credential shape for no reason. var interceptor = CreateInterceptor("the-shared-key"); var context = CreateContext(SyncMethod, "the-shared-key"); var ex = await Should.ThrowAsync(() => Invoke(interceptor, context)); ex.StatusCode.ShouldBe(StatusCode.PermissionDenied); } [Fact] public async Task SyncMethod_TokenComparison_IsNotAPrefixMatch() { // A prefix/StartsWith comparison would accept a truncated key and make the secret // recoverable one character at a time. var interceptor = CreateInterceptor("the-shared-key"); var context = CreateContext(SyncMethod, "Bearer the-shared-ke"); var ex = await Should.ThrowAsync(() => Invoke(interceptor, context)); ex.StatusCode.ShouldBe(StatusCode.PermissionDenied); } [Fact] public async Task DuplexStreaming_IsGated_BecauseThatIsHowSyncActuallyRuns() { // The sync RPC is a bidirectional stream. Gating only the unary path would leave the real // endpoint wide open while every unary test still passed. var interceptor = CreateInterceptor("the-shared-key"); var context = CreateContext(SyncMethod, "Bearer the-wrong-key"); var ex = await Should.ThrowAsync(() => interceptor.DuplexStreamingServerHandler( requestStream: null!, responseStream: null!, context, (_, _, _) => Task.CompletedTask)); ex.StatusCode.ShouldBe(StatusCode.PermissionDenied); } }