fix(localdb): sync endpoint enforces the configured ApiKey (scadaproj#36)

LocalDbSyncService never read request headers, so setting
LocalDb:Replication:ApiKey on both nodes left the passive endpoint open
(LocalDb-001). It now requires Authorization: Bearer <key> (constant-time)
before the handshake and before newest-wins takeover, refusing anything else
with Unauthenticated. A blank key keeps the old accept-all behaviour and
logs a startup warning. Wire-compatible: the initiator has always sent the
header when the key is set; ScadaBridge/OtOpcUa interceptors use the same key.

LocalDb 0.3.5 -> 0.3.6 (unpublished).

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
Joseph Doherty
2026-11-09 14:49:20 -05:00
parent d549a782fd
commit 48813bba6f
8 changed files with 228 additions and 18 deletions
@@ -156,6 +156,119 @@ public sealed class GrpcAdapterTests : IAsyncLifetime
await bg.StopAsync(CancellationToken.None);
}
// ---- LocalDb-001 (scadaproj#36): the passive endpoint enforces ApiKey ------------------
[Fact]
public async Task ApiKeyConfigured_BothSides_TwoNodesConverge()
{
var serverHost = await BuildServerAsync(NewDbPath(), apiKey: "pair-key", sink: null);
var serverDb = serverHost.Services.GetRequiredService<ILocalDb>();
await serverDb.ExecuteAsync("INSERT INTO orders (id, sku, qty) VALUES (2, 'S', 20)");
var handler = serverHost.GetTestServer().CreateHandler();
var (clientProvider, bg) = BuildClient(NewDbPath(), "http://localhost", apiKey: "pair-key", () => ChannelOver(handler));
var clientDb = clientProvider.GetRequiredService<ILocalDb>();
await clientDb.ExecuteAsync("INSERT INTO orders (id, sku, qty) VALUES (1, 'C', 10)");
using var cts = new CancellationTokenSource(RunTimeout);
await bg.StartAsync(cts.Token);
await WaitForAsync(
async () => (await ReadOrders(clientDb)).Count == 2 && (await ReadOrders(serverDb)).Count == 2,
RunTimeout);
await bg.StopAsync(CancellationToken.None);
}
[Theory]
[InlineData(null)]
[InlineData("Bearer wrong-key")]
[InlineData("pair-key")] // no Bearer scheme
[InlineData("Bearer pair-key-and-more")]
public async Task ApiKeyConfigured_StreamWithoutTheKey_IsRefused_BeforeTheHandshake(string? authorization)
{
var serverHost = await BuildServerAsync(NewDbPath(), apiKey: "pair-key", sink: null);
var handler = serverHost.GetTestServer().CreateHandler();
var client = new LocalDbSync.LocalDbSyncClient(ChannelOver(handler));
var headers = new Metadata();
if (authorization is not null)
headers.Add("Authorization", authorization);
using var cts = new CancellationTokenSource(RunTimeout);
using var call = client.Sync(headers, cancellationToken: cts.Token);
var ex = await Assert.ThrowsAsync<RpcException>(() => call.ResponseStream.MoveNext(cts.Token));
Assert.Equal(StatusCode.Unauthenticated, ex.StatusCode);
}
[Fact]
public async Task ApiKeyConfigured_StreamWithTheKey_GetsTheHandshake()
{
var serverHost = await BuildServerAsync(NewDbPath(), apiKey: "pair-key", sink: null);
var client = new LocalDbSync.LocalDbSyncClient(ChannelOver(serverHost.GetTestServer().CreateHandler()));
using var cts = new CancellationTokenSource(RunTimeout);
using var call = client.Sync(new Metadata { { "Authorization", "Bearer pair-key" } }, cancellationToken: cts.Token);
Assert.True(await call.ResponseStream.MoveNext(cts.Token));
Assert.Equal(SyncMessage.MsgOneofCase.Handshake, call.ResponseStream.Current.MsgCase);
}
[Fact]
public async Task ApiKeyConfigured_UnauthenticatedStream_DoesNotDisplaceThePeer()
{
var serverHost = await BuildServerAsync(NewDbPath(), apiKey: "pair-key", sink: null);
var serverDb = serverHost.Services.GetRequiredService<ILocalDb>();
var handler = serverHost.GetTestServer().CreateHandler();
var (clientProvider, bg) = BuildClient(NewDbPath(), "http://localhost", apiKey: "pair-key", () => ChannelOver(handler));
var clientDb = clientProvider.GetRequiredService<ILocalDb>();
await clientDb.ExecuteAsync("INSERT INTO orders (id, sku, qty) VALUES (1, 'C', 10)");
using var cts = new CancellationTokenSource(RunTimeout);
await bg.StartAsync(cts.Token);
await WaitForAsync(async () => (await ReadOrders(serverDb)).Count == 1, RunTimeout);
var attemptsBefore = bg.ConnectionAttempts;
var intruder = new LocalDbSync.LocalDbSyncClient(ChannelOver(handler));
using var call = intruder.Sync(cancellationToken: cts.Token);
var ex = await Assert.ThrowsAsync<RpcException>(() => call.ResponseStream.MoveNext(cts.Token));
Assert.Equal(StatusCode.Unauthenticated, ex.StatusCode);
// The real peer's stream is untouched: it neither redials nor stops replicating.
await clientDb.ExecuteAsync("INSERT INTO orders (id, sku, qty) VALUES (3, 'C2', 30)");
await WaitForAsync(async () => (await ReadOrders(serverDb)).Count == 2, RunTimeout);
Assert.Equal(attemptsBefore, bg.ConnectionAttempts);
await bg.StopAsync(CancellationToken.None);
}
[Fact]
public async Task NoApiKeyOnServer_ClientKeyIsIgnored_Unchanged()
{
// Mixed config during a rollout: the key is set on the initiator first. The passive node has
// none, so it keeps accepting — exactly the pre-0.3.6 behaviour.
var serverHost = await BuildServerAsync(NewDbPath(), apiKey: null, sink: null);
var serverDb = serverHost.Services.GetRequiredService<ILocalDb>();
var handler = serverHost.GetTestServer().CreateHandler();
var (clientProvider, bg) = BuildClient(NewDbPath(), "http://localhost", apiKey: "pair-key", () => ChannelOver(handler));
var clientDb = clientProvider.GetRequiredService<ILocalDb>();
await clientDb.ExecuteAsync("INSERT INTO orders (id, sku, qty) VALUES (1, 'C', 10)");
using var cts = new CancellationTokenSource(RunTimeout);
await bg.StartAsync(cts.Token);
await WaitForAsync(async () => (await ReadOrders(serverDb)).Count == 1, RunTimeout);
await bg.StopAsync(CancellationToken.None);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public void IsAuthorized_NoConfiguredKey_AdmitsEveryCaller(string? key)
{
Assert.True(LocalDbSyncService.IsAuthorized(key, new Metadata(), out _));
}
// Shipped variant: in-proc against GrpcSyncDuplex with a flow-control-stalled fake writer
// (WriteAsync never completes until its token fires) — pins requirement 2 (Send honors its
// CancellationToken even when transport-blocked) deterministically; a true stalled-gRPC-peer