513fa1aa16
Comment/XML-doc changes only: - add summaries to ~10k test methods, fixtures, fakes and helpers (+ <param> on theories, <returns> on async Task methods, <inheritdoc/> on interface implementations the checker can resolve) - strip ~2.6k project-tracking references (WP*, P*-*, row-NN, Task N, #NN, Component-0NN) from comments, keeping the explanatory text; reword false positives in comments only - real docs on fakes implementing BCL/library interfaces (IDisposable, ILogger, IOptionsMonitor, IAsyncLifetime) - reword the last 5 src/ false positives (CWE-1236, failures-1, year-0001, M365) Only non-comment edits: four one-line nested classes split across lines so members can carry docs. Build 0 errors / 0 warnings.
200 lines
9.2 KiB
C#
200 lines
9.2 KiB
C#
using Grpc.Core;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using Microsoft.Extensions.Options;
|
|
using ZB.MOM.WW.LocalDb.Replication;
|
|
using ZB.MOM.WW.ScadaBridge.Host;
|
|
|
|
namespace ZB.MOM.WW.ScadaBridge.Host.Tests;
|
|
|
|
/// <summary>
|
|
/// LocalDb Phase 1 — the passive sync endpoint's inbound gate.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// The replication library's <c>LocalDbSyncService</c> verifies nothing; inbound auth is
|
|
/// explicitly the host's job. Without this interceptor, anything able to reach a site
|
|
/// node's gRPC port could stream arbitrary rows straight into the consolidated site
|
|
/// database — including into <c>OperationTracking</c>, which central reconciles from.
|
|
/// </remarks>
|
|
public class LocalDbSyncAuthInterceptorTests
|
|
{
|
|
private const string SyncMethod = "/localdb_sync.v1.LocalDbSync/Sync";
|
|
private const string SiteStreamMethod = "/scadabridge.SiteStream/Connect";
|
|
|
|
private static LocalDbSyncAuthInterceptor CreateInterceptor(string? apiKey)
|
|
=> new(
|
|
Options.Create(new ReplicationOptions { ApiKey = apiKey }),
|
|
NullLogger<LocalDbSyncAuthInterceptor>.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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Minimal <see cref="ServerCallContext"/> carrying just a method name and request
|
|
/// headers — the only two things the interceptor reads.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Hand-rolled rather than using <c>Grpc.Core.Testing.TestServerCallContext</c>: that
|
|
/// type ships in the retired native <c>Grpc.Core</c> package and does not exist on the
|
|
/// grpc-dotnet stack this solution runs on. Pulling in the dead package to get one
|
|
/// test helper would be a worse trade than these few overrides.
|
|
/// </remarks>
|
|
private sealed class FakeServerCallContext(string method, Metadata requestHeaders)
|
|
: ServerCallContext
|
|
{
|
|
/// <inheritdoc />
|
|
protected override string MethodCore => method;
|
|
/// <inheritdoc />
|
|
protected override string HostCore => "localhost";
|
|
/// <inheritdoc />
|
|
protected override string PeerCore => "ipv4:127.0.0.1:12345";
|
|
/// <inheritdoc />
|
|
protected override DateTime DeadlineCore => DateTime.UtcNow.AddMinutes(1);
|
|
/// <inheritdoc />
|
|
protected override Metadata RequestHeadersCore => requestHeaders;
|
|
/// <inheritdoc />
|
|
protected override CancellationToken CancellationTokenCore => CancellationToken.None;
|
|
/// <inheritdoc />
|
|
protected override Metadata ResponseTrailersCore { get; } = [];
|
|
/// <inheritdoc />
|
|
protected override Status StatusCore { get; set; }
|
|
/// <inheritdoc />
|
|
protected override WriteOptions? WriteOptionsCore { get; set; }
|
|
/// <inheritdoc />
|
|
protected override AuthContext AuthContextCore { get; } =
|
|
new(null, new Dictionary<string, List<AuthProperty>>());
|
|
|
|
/// <inheritdoc />
|
|
protected override ContextPropagationToken CreatePropagationTokenCore(
|
|
ContextPropagationOptions? options)
|
|
=> throw new NotSupportedException();
|
|
|
|
/// <inheritdoc />
|
|
protected override Task WriteResponseHeadersAsyncCore(Metadata responseHeaders)
|
|
=> Task.CompletedTask;
|
|
}
|
|
|
|
/// <summary>Invokes the interceptor's unary path with a trivial continuation.</summary>
|
|
private static Task<string> Invoke(
|
|
LocalDbSyncAuthInterceptor interceptor, ServerCallContext context)
|
|
=> interceptor.UnaryServerHandler<string, string>(
|
|
"request", context, (_, _) => Task.FromResult("ok"));
|
|
|
|
/// <summary>Verifies that a non-sync method passes through even when no key is configured.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task NonSyncMethod_PassesThrough_EvenWithNoKeyConfigured()
|
|
{
|
|
// The interceptor is registered on the shared site AddGrpc pipeline, so it sees
|
|
// every call. It must be scoped strictly to the sync service — gating SiteStream
|
|
// would break site↔central communication outright.
|
|
var interceptor = CreateInterceptor(apiKey: null);
|
|
var context = CreateContext(SiteStreamMethod, authorizationHeader: null);
|
|
|
|
Assert.Equal("ok", await Invoke(interceptor, context));
|
|
}
|
|
|
|
/// <summary>Verifies that a sync method is denied when no key is configured, even with a bearer token.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task SyncMethod_WithNoKeyConfigured_IsDenied_EvenWithABearerToken()
|
|
{
|
|
// Fail-closed. "No key configured" is the DEFAULT every site 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 Assert.ThrowsAsync<RpcException>(() => Invoke(interceptor, context));
|
|
Assert.Equal(StatusCode.PermissionDenied, ex.StatusCode);
|
|
}
|
|
|
|
/// <summary>Verifies that a sync method without a bearer token is denied.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task SyncMethod_WithNoBearerToken_IsDenied()
|
|
{
|
|
var interceptor = CreateInterceptor("the-shared-key");
|
|
var context = CreateContext(SyncMethod, authorizationHeader: null);
|
|
|
|
var ex = await Assert.ThrowsAsync<RpcException>(() => Invoke(interceptor, context));
|
|
Assert.Equal(StatusCode.PermissionDenied, ex.StatusCode);
|
|
}
|
|
|
|
/// <summary>Verifies that a sync method with the wrong bearer token is denied.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task SyncMethod_WithWrongBearerToken_IsDenied()
|
|
{
|
|
var interceptor = CreateInterceptor("the-shared-key");
|
|
var context = CreateContext(SyncMethod, "Bearer the-wrong-key");
|
|
|
|
var ex = await Assert.ThrowsAsync<RpcException>(() => Invoke(interceptor, context));
|
|
Assert.Equal(StatusCode.PermissionDenied, ex.StatusCode);
|
|
}
|
|
|
|
/// <summary>Verifies that a sync method with the correct bearer token passes through.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task SyncMethod_WithCorrectBearerToken_PassesThrough()
|
|
{
|
|
var interceptor = CreateInterceptor("the-shared-key");
|
|
var context = CreateContext(SyncMethod, "Bearer the-shared-key");
|
|
|
|
Assert.Equal("ok", await Invoke(interceptor, context));
|
|
}
|
|
|
|
/// <summary>Verifies that a sync method with the correct key but no Bearer scheme is denied.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[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 Assert.ThrowsAsync<RpcException>(() => Invoke(interceptor, context));
|
|
Assert.Equal(StatusCode.PermissionDenied, ex.StatusCode);
|
|
}
|
|
|
|
/// <summary>Verifies that the token comparison is not a prefix match.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[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 Assert.ThrowsAsync<RpcException>(() => Invoke(interceptor, context));
|
|
Assert.Equal(StatusCode.PermissionDenied, ex.StatusCode);
|
|
}
|
|
|
|
/// <summary>Verifies that duplex streaming calls are gated, because that is how sync actually runs.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[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 Assert.ThrowsAsync<RpcException>(() =>
|
|
interceptor.DuplexStreamingServerHandler<string, string>(
|
|
requestStream: null!,
|
|
responseStream: null!,
|
|
context,
|
|
(_, _, _) => Task.CompletedTask));
|
|
|
|
Assert.Equal(StatusCode.PermissionDenied, ex.StatusCode);
|
|
}
|
|
}
|