f10f4c3754
TelemetryStreamAuthInterceptor, ConfigServeAuthInterceptor and LocalDbSyncAuthInterceptor all decided "is a key configured?" with string.IsNullOrEmpty. A whitespace-only configured value therefore passed that guard and fell through to the constant-time comparison — where it is satisfied by a whitespace-only bearer token. The gate would be open to anyone who guessed a blank credential. This backports the check the two NEW mesh interceptors already use: MeshCommandAuthInterceptor (and its central-side clone) validate with string.IsNullOrWhiteSpace, so the four/five planes now answer the same way to the same misconfiguration. Nothing else changes — the denial status codes (PermissionDenied / Unauthenticated / PermissionDenied respectively) and every denial message are untouched, and no key material is logged. No deployment configures a whitespace key: the docker-dev rig and production both set real keys, so this is a fail-closed hardening of an unreachable-today misconfiguration rather than a live exposure. Tests: each of the three test files gains a ..._WithBlankKeyConfigured_IsDenied fact mirroring MeshCommandAuthInterceptorTests.ExecuteMethod_WithBlankPskConfigured_IsDenied (configured key " ", presented "Bearer "), verified red before the fix. ConfigServeAuthInterceptor and LocalDbSyncAuthInterceptor also gain the HasExactlyOnePublicConstructor pin their two siblings already had — Grpc.AspNetCore silently stops invoking an interceptor with more than one public constructor, which would disable auth without failing anything. Claude-Session: https://claude.ai/code/session_014WNM4vjoVksyyBraTXSZE1
168 lines
7.2 KiB
C#
168 lines
7.2 KiB
C#
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using Grpc.Core;
|
|
using Grpc.Core.Interceptors;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Options;
|
|
using ZB.MOM.WW.OtOpcUa.Cluster;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Host.Configuration;
|
|
|
|
/// <summary>
|
|
/// Gates the driver-node telemetry stream endpoint (per-cluster mesh Phase 5). The
|
|
/// <c>TelemetryStreamService.Subscribe</c> RPC streams a node's live alerts / script-logs /
|
|
/// driver-health / driver-resilience-status to whoever dials it; anything able to reach a driver
|
|
/// node's telemetry port could otherwise pull that live feed out-of-band. This interceptor is the
|
|
/// ONLY inbound auth on that endpoint.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// <b>Scoped by method path.</b> Only calls under
|
|
/// <c>/telemetry.v1.TelemetryStreamService/</c> are gated; every other method on the shared
|
|
/// gRPC pipeline (config-serve, LocalDb sync) passes through untouched, so this can share one
|
|
/// <c>AddGrpc</c> registration with <see cref="ConfigServeAuthInterceptor"/> and
|
|
/// <see cref="LocalDbSyncAuthInterceptor"/>.
|
|
/// </para>
|
|
/// <para>
|
|
/// <b>Fail-closed.</b> With no <c>Telemetry:ApiKey</c> configured, NO dial is accepted,
|
|
/// authenticated or not. Treating "no key" as "no auth required" would expose the live
|
|
/// telemetry feed on exactly the default shape most nodes ship with. The caller dialing in
|
|
/// must present the same <c>TelemetryDial:ApiKey</c> (the shared node key), so a key typo
|
|
/// stops telemetry delivery outright rather than degrading to unauthenticated.
|
|
/// </para>
|
|
/// <para>
|
|
/// Comparison is <see cref="CryptographicOperations.FixedTimeEquals"/> over UTF-8 bytes, so a
|
|
/// wrong key cannot be recovered byte-by-byte from response timing. Length differences are
|
|
/// unavoidably observable and are not sensitive.
|
|
/// </para>
|
|
/// <para>
|
|
/// <b>Exactly one public constructor.</b> <c>Grpc.AspNetCore</c> silently stops invoking an
|
|
/// interceptor that has more than one public ctor — see
|
|
/// <c>TelemetryStreamAuthInterceptorTests.HasExactlyOnePublicConstructor</c>.
|
|
/// </para>
|
|
/// </remarks>
|
|
public sealed class TelemetryStreamAuthInterceptor : Interceptor
|
|
{
|
|
private const string ServicePrefix = "/telemetry.v1.TelemetryStreamService/";
|
|
private const string AuthorizationHeader = "authorization";
|
|
private const string BearerPrefix = "Bearer ";
|
|
|
|
private readonly IOptions<TelemetryOptions> _options;
|
|
private readonly ILogger<TelemetryStreamAuthInterceptor> _logger;
|
|
|
|
/// <summary>Creates the interceptor.</summary>
|
|
/// <param name="options">Telemetry options; <c>ApiKey</c> is the expected bearer token.</param>
|
|
/// <param name="logger">Logger for denial diagnostics.</param>
|
|
public TelemetryStreamAuthInterceptor(
|
|
IOptions<TelemetryOptions> options,
|
|
ILogger<TelemetryStreamAuthInterceptor> logger)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(options);
|
|
ArgumentNullException.ThrowIfNull(logger);
|
|
|
|
_options = options;
|
|
_logger = logger;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public override Task<TResponse> UnaryServerHandler<TRequest, TResponse>(
|
|
TRequest request,
|
|
ServerCallContext context,
|
|
UnaryServerMethod<TRequest, TResponse> continuation)
|
|
{
|
|
Authorize(context);
|
|
return continuation(request, context);
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public override Task DuplexStreamingServerHandler<TRequest, TResponse>(
|
|
IAsyncStreamReader<TRequest> requestStream,
|
|
IServerStreamWriter<TResponse> responseStream,
|
|
ServerCallContext context,
|
|
DuplexStreamingServerMethod<TRequest, TResponse> continuation)
|
|
{
|
|
Authorize(context);
|
|
return continuation(requestStream, responseStream, context);
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public override Task<TResponse> ClientStreamingServerHandler<TRequest, TResponse>(
|
|
IAsyncStreamReader<TRequest> requestStream,
|
|
ServerCallContext context,
|
|
ClientStreamingServerMethod<TRequest, TResponse> continuation)
|
|
{
|
|
Authorize(context);
|
|
return continuation(requestStream, context);
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public override Task ServerStreamingServerHandler<TRequest, TResponse>(
|
|
TRequest request,
|
|
IServerStreamWriter<TResponse> responseStream,
|
|
ServerCallContext context,
|
|
ServerStreamingServerMethod<TRequest, TResponse> continuation)
|
|
{
|
|
Authorize(context);
|
|
return continuation(request, responseStream, context);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Throws <see cref="RpcException"/> with <see cref="StatusCode.PermissionDenied"/> if this is
|
|
/// a telemetry-stream call that does not carry the configured bearer token. Non-telemetry
|
|
/// calls return immediately.
|
|
/// </summary>
|
|
private void Authorize(ServerCallContext context)
|
|
{
|
|
if (!context.Method.StartsWith(ServicePrefix, StringComparison.Ordinal))
|
|
return;
|
|
|
|
var expected = _options.Value.ApiKey;
|
|
// Whitespace-only counts as unconfigured: an all-blank expected key would otherwise be
|
|
// satisfied by an all-blank bearer token, which is no gate at all.
|
|
if (string.IsNullOrWhiteSpace(expected))
|
|
{
|
|
_logger.LogWarning(
|
|
"Rejected a telemetry stream call to {Method}: no Telemetry:ApiKey is configured, so " +
|
|
"the telemetry endpoint is closed. Configure the shared node key on this node and every " +
|
|
"dialing caller.",
|
|
context.Method);
|
|
throw new RpcException(new Status(
|
|
StatusCode.PermissionDenied,
|
|
"Telemetry stream is not accepting connections: no API key is configured on this node."));
|
|
}
|
|
|
|
var presented = ExtractBearerToken(context.RequestHeaders);
|
|
if (presented is null || !FixedTimeEquals(presented, expected))
|
|
{
|
|
_logger.LogWarning(
|
|
"Rejected a telemetry stream call to {Method}: {Reason}.",
|
|
context.Method,
|
|
presented is null ? "no bearer token presented" : "bearer token did not match");
|
|
throw new RpcException(new Status(
|
|
StatusCode.PermissionDenied,
|
|
"Telemetry stream authentication failed."));
|
|
}
|
|
}
|
|
|
|
private static string? ExtractBearerToken(Metadata headers)
|
|
{
|
|
// gRPC lowercases header keys on the wire; compare case-insensitively anyway so a hand-built
|
|
// Metadata in a test behaves the same as a real request.
|
|
foreach (var entry in headers)
|
|
{
|
|
if (!string.Equals(entry.Key, AuthorizationHeader, StringComparison.OrdinalIgnoreCase))
|
|
continue;
|
|
|
|
var value = entry.Value;
|
|
if (value is not null && value.StartsWith(BearerPrefix, StringComparison.OrdinalIgnoreCase))
|
|
return value[BearerPrefix.Length..];
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
private static bool FixedTimeEquals(string presented, string expected)
|
|
=> CryptographicOperations.FixedTimeEquals(
|
|
Encoding.UTF8.GetBytes(presented), Encoding.UTF8.GetBytes(expected));
|
|
}
|