Files
scadaproj/ZB.MOM.WW.Secrets/src/ZB.MOM.WW.Secrets.Replicator.Grpc/DependencyInjection/SecretsGrpcHubClientExtensions.cs
T
Joseph Doherty 1c31e6bcb8 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
2026-08-07 06:29:51 -04:00

97 lines
5.2 KiB
C#

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;
namespace ZB.MOM.WW.Secrets.Replicator.Grpc.DependencyInjection;
/// <summary>
/// Dependency-injection entry point for a site node that follows the central-hosted secrets hub.
/// </summary>
/// <remarks>
/// <para>
/// <b>The hub and every follower need the same KEK.</b> Only ciphertext crosses the wire, so a node
/// whose master key differs cannot decrypt rows central wrote — it fails closed on resolve with a
/// <c>kek_id</c> mismatch, which reads like data corruption but is a deployment error.
/// </para>
/// <para>
/// <b>This is the follower half only.</b> Central hosts the hub service and must not register this
/// client; a site node registers this client and must not host the service. Nothing here can push a
/// row hub-ward — the contract has no write RPC — so the direction of replication is a property of
/// the deployment topology rather than a setting that could be got wrong.
/// </para>
/// </remarks>
public static class SecretsGrpcHubClientExtensions
{
/// <summary>
/// Service key under which this package's <see cref="GrpcChannel"/> is registered, so it can
/// never be confused with a channel the application registered for something else.
/// </summary>
public const string ChannelServiceKey = "zb-secrets-grpc-hub";
/// <summary>
/// Registers the pull-only hub client and its background sweep: a channel to the configured
/// endpoint, the generated gRPC client, the reader seam over it, and a hosted service that keeps
/// the node's local store converged with central.
/// </summary>
/// <remarks>
/// The local <see cref="ISecretStore"/> is <b>not</b> registered or decorated here — call
/// <c>AddZbSecrets</c> as usual and this sits alongside it. That is the whole difference from the
/// SQL-Server hub-replication mode, which wraps the store in a publishing decorator: pull-only
/// means local writes never leave the node, so there is nothing to publish and the store stays
/// exactly as the application configured it. A host that forgets <c>AddZbSecrets</c> fails loudly
/// at startup when the sweep cannot resolve the store, rather than silently replicating nothing.
/// </remarks>
/// <param name="services">The service collection to add to.</param>
/// <param name="configuration">The application configuration.</param>
/// <param name="sectionPath">Configuration section holding the hub-client options.</param>
/// <returns>The same <paramref name="services"/> instance, for chaining.</returns>
/// <exception cref="InvalidOperationException">
/// The bound options are unusable — see <see cref="SecretsGrpcHubClientOptions.Validate"/>.
/// </exception>
public static IServiceCollection AddZbSecretsGrpcHubClient(
this IServiceCollection services,
IConfiguration configuration,
string sectionPath = SecretsGrpcHubClientOptions.DefaultSectionPath)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(configuration);
ArgumentException.ThrowIfNullOrWhiteSpace(sectionPath);
IConfigurationSection section = configuration.GetSection(sectionPath);
services.Configure<SecretsGrpcHubClientOptions>(section);
// Bind and validate NOW as well as through the options pipeline: a missing endpoint or an
// unset bearer token should fail at startup with a message naming the key, not surface as a
// sweep that warns once every interval and never converges. The eagerly-bound instance is
// discarded immediately — it is a credential holder, and everything downstream reads the
// options from IOptions rather than closing over it.
var eager = new SecretsGrpcHubClientOptions();
section.Bind(eager);
eager.Validate(sectionPath);
// Singleton, so the container owns its disposal — a channel per sweep would leak an HTTP/2
// connection every interval. KEYED, because GrpcChannel is a framework type an application
// very plausibly registers for one of its own gRPC dependencies: an unkeyed TryAddSingleton
// would silently lose to that registration and this client would then dial someone else's
// endpoint with the hub credential attached.
services.TryAddKeyedSingleton(ChannelServiceKey, (sp, _) => GrpcChannel.ForAddress(
sp.GetRequiredService<IOptions<SecretsGrpcHubClientOptions>>().Value.Endpoint));
services.TryAddSingleton<ISecretsHubReader>(sp => new GrpcSecretsHubClient(
new SecretsHub.SecretsHubClient(
sp.GetRequiredKeyedService<GrpcChannel>(ChannelServiceKey)),
sp.GetRequiredService<IOptions<SecretsGrpcHubClientOptions>>(),
sp.GetRequiredService<ILogger<GrpcSecretsHubClient>>(),
sp.GetService<TimeProvider>()));
services.AddHostedService<GrpcSecretSyncService>();
return services;
}
}