fix(secrets): Grpc hub client — per-row parse isolation (review Critical) + real-client CallInvoker tests
A single malformed row or manifest entry poisoned the whole sweep, permanently. WireToDomain.ToRows/ToManifest materialized eagerly, so one unparseable element threw out of the fetch callback, past SecretReplicationReconciler's per-batch handling, into SweepSafelyAsync's whole-sweep catch. The follower's pull set is derived from the hub's manifest, so the identical bad element arrived in the identical batch on every interval and nothing ever converged — logged as "sync failed", indistinguishable from a hub outage. Isolation now matches the Akka sibling's split exactly: WireToDomain stays a strict per-item parser and loses its two batch entry points (their absence is pinned by a reflection test), while GrpcSecretsHubClient converts each item inside its own try — the same shape as SecretReplicationActor.Materialize. A dropped item costs one warning naming the secret and a reason category, and every well-formed sibling still converges. Only parse-shaped exceptions are caught (ArgumentException, FormatException); a defect still propagates. A row whose own name is unparseable is logged under a marker rather than echoing the untrusted string, and no ciphertext, DEK or credential reaches a log line. GrpcSecretsHubClient had zero coverage — the existing fake implements the ISecretsHubReader seam directly, bypassing the header, the deadline and the conversion, which are the only things that class does. It is now driven for real through a fake CallInvoker handed to the generated client. The stale doc comment claiming the reconciler isolated the failure is replaced by one describing the mechanism that actually exists, and Endpoint gains a note that a plain-http hub sends the bearer token cleartext (doc only, no validation change). Tests 52 -> 67 in the package suite; solution green, no new warnings. Claude-Session: https://claude.ai/code/session_014WNM4vjoVksyyBraTXSZE1
This commit is contained in:
+2
@@ -2,6 +2,7 @@ using Grpc.Net.Client;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZB.MOM.WW.Secrets.Abstractions;
|
||||
using ZB.MOM.WW.Secrets.Replicator.Grpc.V1;
|
||||
@@ -85,6 +86,7 @@ public static class SecretsGrpcHubClientExtensions
|
||||
new SecretsHub.SecretsHubClient(
|
||||
sp.GetRequiredKeyedService<GrpcChannel>(ChannelServiceKey)),
|
||||
sp.GetRequiredService<IOptions<SecretsGrpcHubClientOptions>>(),
|
||||
sp.GetRequiredService<ILogger<GrpcSecretsHubClient>>(),
|
||||
sp.GetService<TimeProvider>()));
|
||||
|
||||
services.AddHostedService<GrpcSecretSyncService>();
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Grpc.Core;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZB.MOM.WW.Secrets.Abstractions;
|
||||
using ZB.MOM.WW.Secrets.Replicator.Grpc.V1;
|
||||
@@ -29,7 +30,11 @@ internal interface ISecretsHubReader
|
||||
/// <returns>The hub's manifest entries.</returns>
|
||||
Task<IReadOnlyList<SecretManifestEntry>> GetManifestAsync(CancellationToken ct);
|
||||
|
||||
/// <summary>Fetches several encrypted rows by name; names absent from the hub are omitted.</summary>
|
||||
/// <summary>
|
||||
/// Fetches several encrypted rows by name. Names absent from the hub are omitted, and so is any
|
||||
/// row the follower cannot parse — an implementation returns the well-formed rows rather than
|
||||
/// failing the batch.
|
||||
/// </summary>
|
||||
/// <param name="names">The names to fetch.</param>
|
||||
/// <param name="ct">A token to cancel the operation.</param>
|
||||
/// <returns>The matching encrypted rows.</returns>
|
||||
@@ -42,33 +47,60 @@ internal interface ISecretsHubReader
|
||||
/// <see cref="WireToDomain"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Faults are deliberately <b>not</b> caught here. An <see cref="RpcException"/> is the honest signal
|
||||
/// that the hub did not answer, and the sweep — the only caller — is where that is turned into "keep
|
||||
/// serving the last-known-good local store and retry next tick". Swallowing it here would make an
|
||||
/// unreachable hub indistinguishable from an empty one, which is the one failure mode this
|
||||
/// <para>
|
||||
/// <b>Transport faults are deliberately not caught.</b> An <see cref="RpcException"/> is the honest
|
||||
/// signal that the hub did not answer, and the sweep — the only caller — is where that is turned
|
||||
/// into "keep serving the last-known-good local store and retry next tick". Swallowing it here would
|
||||
/// make an unreachable hub indistinguishable from an empty one, which is the one failure mode this
|
||||
/// subsystem must never have.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Parse faults are caught, per item.</b> That is not the same decision: the hub answered, and
|
||||
/// the answer is mostly good. Failing the whole response over one unparseable element would stall
|
||||
/// convergence permanently rather than transiently — the follower's pull set comes from the hub's
|
||||
/// manifest, so the identical bad element would arrive in the identical batch on every interval and
|
||||
/// nothing would ever be applied, while the log said only "sync failed" exactly as it does for an
|
||||
/// outage. So each item is converted inside its own <c>try</c>, one warning names what was dropped
|
||||
/// and why, and every well-formed sibling is returned. This is the same containment the Akka
|
||||
/// replicator applies in <c>SecretReplicationActor.Materialize</c>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// A dropped item is dropped whole and never coerced — the fail-closed half of the same rule. Only
|
||||
/// parse-shaped exceptions are caught (<see cref="ArgumentException"/>, <see cref="FormatException"/>);
|
||||
/// anything else is a defect rather than bad input and is left to propagate.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal sealed class GrpcSecretsHubClient : ISecretsHubReader
|
||||
internal sealed partial class GrpcSecretsHubClient : ISecretsHubReader
|
||||
{
|
||||
private const string AuthorizationHeader = "Authorization";
|
||||
|
||||
/// <summary>
|
||||
/// Stands in for a name in a log line when the name itself is what failed to parse. The hub's
|
||||
/// raw string is deliberately not echoed: it is the untrusted value under suspicion.
|
||||
/// </summary>
|
||||
private const string UnnameableItem = "(unparseable name)";
|
||||
|
||||
private readonly SecretsHub.SecretsHubClient _client;
|
||||
private readonly SecretsGrpcHubClientOptions _options;
|
||||
private readonly ILogger<GrpcSecretsHubClient> _logger;
|
||||
private readonly TimeProvider _timeProvider;
|
||||
|
||||
/// <summary>Creates the hub client.</summary>
|
||||
/// <param name="client">The generated gRPC client, bound to the configured channel.</param>
|
||||
/// <param name="options">Endpoint, credential, and per-call deadline.</param>
|
||||
/// <param name="logger">Logger for items the hub sent that this node could not parse.</param>
|
||||
/// <param name="timeProvider">Clock used to compute the per-call deadline.</param>
|
||||
public GrpcSecretsHubClient(
|
||||
SecretsHub.SecretsHubClient client,
|
||||
IOptions<SecretsGrpcHubClientOptions> options,
|
||||
ILogger<GrpcSecretsHubClient> logger,
|
||||
TimeProvider? timeProvider = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
|
||||
_client = client ?? throw new ArgumentNullException(nameof(client));
|
||||
_options = options.Value;
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
_timeProvider = timeProvider ?? TimeProvider.System;
|
||||
}
|
||||
|
||||
@@ -79,7 +111,23 @@ internal sealed class GrpcSecretsHubClient : ISecretsHubReader
|
||||
.GetManifestAsync(new GetManifestRequest(), CreateCallOptions(ct))
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return WireToDomain.ToManifest(response.Entries);
|
||||
var entries = new List<SecretManifestEntry>(response.Entries.Count);
|
||||
|
||||
foreach (ManifestEntry wire in response.Entries)
|
||||
{
|
||||
try
|
||||
{
|
||||
entries.Add(WireToDomain.ToEntry(wire));
|
||||
}
|
||||
catch (Exception ex) when (IsParseFailure(ex))
|
||||
{
|
||||
// Dropping a manifest entry costs only that name's convergence: it is simply not in
|
||||
// this sweep's pull set, and a corrected entry converges on the next one.
|
||||
LogManifestEntryDiscarded(ex, Describe(wire.Name), Categorize(ex));
|
||||
}
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -99,7 +147,23 @@ internal sealed class GrpcSecretsHubClient : ISecretsHubReader
|
||||
.GetSecretsAsync(request, CreateCallOptions(ct))
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return WireToDomain.ToRows(response.Secrets);
|
||||
var rows = new List<StoredSecret>(response.Secrets.Count);
|
||||
|
||||
foreach (SecretRow wire in response.Secrets)
|
||||
{
|
||||
try
|
||||
{
|
||||
rows.Add(WireToDomain.ToRow(wire));
|
||||
}
|
||||
catch (Exception ex) when (IsParseFailure(ex))
|
||||
{
|
||||
// The reconciler treats a missing row exactly as it treats a name the hub no longer
|
||||
// holds, so the batch applies its siblings and returns a smaller count.
|
||||
LogRowDiscarded(ex, Describe(wire.Name), Categorize(ex));
|
||||
}
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
// Built per call rather than once: the deadline is an absolute instant, so a cached CallOptions
|
||||
@@ -108,4 +172,46 @@ internal sealed class GrpcSecretsHubClient : ISecretsHubReader
|
||||
headers: new Metadata { { AuthorizationHeader, $"Bearer {_options.BearerToken}" } },
|
||||
deadline: _timeProvider.GetUtcNow().UtcDateTime.Add(_options.CallDeadline),
|
||||
cancellationToken: ct);
|
||||
|
||||
// The exceptions WireToDomain raises for input the domain refuses: SecretName and the content
|
||||
// type check throw ArgumentException, the round-trip timestamp parse throws FormatException.
|
||||
// Narrow on purpose — a NullReferenceException or an OutOfMemoryException is a defect or a
|
||||
// resource failure, and silently dropping rows over either would hide it behind a warning.
|
||||
private static bool IsParseFailure(Exception exception) =>
|
||||
exception is ArgumentException or FormatException;
|
||||
|
||||
// The name is the only field of an item that may reach a log sink, and only once the domain has
|
||||
// accepted it. Nothing else is logged: a row is ciphertext, a wrapped DEK and two nonces, and a
|
||||
// warning is not a place any of that belongs.
|
||||
private static string Describe(string name)
|
||||
{
|
||||
try
|
||||
{
|
||||
return new SecretName(name).Value;
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
return UnnameableItem;
|
||||
}
|
||||
}
|
||||
|
||||
// A category rather than a restatement of the exception, so an operator reading the warning
|
||||
// knows which authored field to go and look at.
|
||||
private static string Categorize(Exception exception) => exception switch
|
||||
{
|
||||
FormatException => "malformed timestamp",
|
||||
_ => "invalid name or content type",
|
||||
};
|
||||
|
||||
[LoggerMessage(
|
||||
EventId = 1,
|
||||
Level = LogLevel.Warning,
|
||||
Message = "Discarding a malformed manifest entry for {SecretName} sent by the secrets hub ({Reason}); every other entry is reconciled normally.")]
|
||||
private partial void LogManifestEntryDiscarded(Exception exception, string secretName, string reason);
|
||||
|
||||
[LoggerMessage(
|
||||
EventId = 2,
|
||||
Level = LogLevel.Warning,
|
||||
Message = "Discarding a malformed secret row for {SecretName} sent by the secrets hub ({Reason}); every other row in the batch is applied normally.")]
|
||||
private partial void LogRowDiscarded(Exception exception, string secretName, string reason);
|
||||
}
|
||||
|
||||
@@ -17,6 +17,15 @@ public sealed class SecretsGrpcHubClientOptions
|
||||
/// The hub's gRPC address, as an absolute <c>http</c> or <c>https</c> URI (for example
|
||||
/// <c>https://central:5001</c>). Required.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A plain <c>http</c> endpoint is accepted so an h2c-only or in-cluster deployment can be
|
||||
/// stood up, but it sends <see cref="BearerToken"/> in cleartext on <em>every</em> call — anyone
|
||||
/// on the path reads the hub credential and can then pull central's entire secret inventory.
|
||||
/// Treat <c>http</c> as a development and loopback-only convenience; a site node reaching
|
||||
/// central across a plant network must use <c>https</c>. This is documentation rather than a
|
||||
/// rule the validator enforces, because "internal" is a property of a deployment's network and
|
||||
/// cannot be decided from a URI string.
|
||||
/// </remarks>
|
||||
public string Endpoint { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -10,16 +10,24 @@ namespace ZB.MOM.WW.Secrets.Replicator.Grpc.Wire;
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Parsing here is <b>strict, and rejection is per row</b>: a value protobuf accepted but the domain
|
||||
/// Parsing here is <b>strict and one item at a time</b>: a value protobuf accepted but the domain
|
||||
/// would not — a name that is rooted or path-traversing, a content type naming no enum member, a
|
||||
/// timestamp that is not round-trip ISO-8601 — throws rather than being coerced. The sweep's
|
||||
/// reconciler isolates the failure to that one row (see <c>SecretReplicationReconciler.ApplyAsync</c>),
|
||||
/// so a single bad row is logged and skipped instead of poisoning the batch behind it.
|
||||
/// timestamp that is not round-trip ISO-8601 — throws rather than being coerced.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// This mirrors the Akka replicator's <c>SecretRowDto.ToStoredSecret</c> deliberately — one
|
||||
/// fail-closed parse shape family-wide, so the two transports cannot disagree about what a
|
||||
/// replicated row is allowed to contain.
|
||||
/// There is deliberately <b>no batch entry point here</b>, and that absence is the design. A method
|
||||
/// converting a whole response would fail the whole response on one bad element, and because a
|
||||
/// follower's pull set is derived from the hub's manifest, the identical bad element would re-fail
|
||||
/// the identical sweep on every interval forever — a permanent stall that reads in the log exactly
|
||||
/// like a hub outage. Isolation therefore lives one layer up, in
|
||||
/// <c>GrpcSecretsHubClient</c>, which converts each item inside its own <c>try</c>, logs one warning
|
||||
/// naming the item, drops it, and returns every well-formed sibling.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// That split mirrors the Akka replicator exactly — <c>SecretRowDto.ToStoredSecret</c> throws and
|
||||
/// <c>SecretReplicationActor.Materialize</c> catches per row — so the two transports share one
|
||||
/// fail-closed parse shape and one containment rule, and cannot disagree about what a replicated row
|
||||
/// is allowed to contain.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Two checks the Akka DTO makes are <em>absent</em> here on purpose. Protobuf cannot express a null
|
||||
@@ -32,16 +40,6 @@ namespace ZB.MOM.WW.Secrets.Replicator.Grpc.Wire;
|
||||
/// </remarks>
|
||||
internal static class WireToDomain
|
||||
{
|
||||
/// <summary>Rebuilds a manifest from the wire form, in the order the hub sent it.</summary>
|
||||
/// <param name="entries">The wire manifest entries.</param>
|
||||
/// <returns>The domain manifest entries.</returns>
|
||||
public static IReadOnlyList<SecretManifestEntry> ToManifest(IEnumerable<ManifestEntry> entries)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(entries);
|
||||
|
||||
return [.. entries.Select(ToEntry)];
|
||||
}
|
||||
|
||||
/// <summary>Rebuilds one manifest entry from the wire form.</summary>
|
||||
/// <param name="entry">The wire manifest entry.</param>
|
||||
/// <returns>The domain manifest entry.</returns>
|
||||
@@ -62,16 +60,6 @@ internal static class WireToDomain
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Rebuilds encrypted rows from the wire form, in the order the hub sent them.</summary>
|
||||
/// <param name="rows">The wire rows.</param>
|
||||
/// <returns>The domain rows.</returns>
|
||||
public static IReadOnlyList<StoredSecret> ToRows(IEnumerable<SecretRow> rows)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(rows);
|
||||
|
||||
return [.. rows.Select(ToRow)];
|
||||
}
|
||||
|
||||
/// <summary>Rebuilds one encrypted row from the wire form.</summary>
|
||||
/// <param name="row">The wire row.</param>
|
||||
/// <returns>The domain row.</returns>
|
||||
|
||||
Reference in New Issue
Block a user