Files
ScadaBridge/src/ZB.MOM.WW.ScadaBridge.Host/SitePskProvider.cs
T
Joseph Doherty 3a31dd2de7 fix(host): follow an in-place site PSK rotation without a central restart (ScadaBridge#96)
SitePskProvider cached each site's gRPC preshared key forever; only site removal
invalidated it, so rotating SB-GRPC-PSK-{site} broke the central<->site link on
both central nodes until they restarted. The cached key is now dropped when:

- the secret is written through /admin/secrets: central replaces the secrets
  library's ISecretCacheInvalidator with SitePskRotationInvalidator, which also
  publishes SitePskInvalidated on a new DistributedPubSub topic
  (site-psk-invalidation) so the peer central node drops its copy and its
  resolver cache entry too (SitePskInvalidationSubscriber);
- a site rejects a central->site call with PermissionDenied/Unauthenticated:
  WithSiteCredentials wraps every per-site channel's handler in
  PskRejectionRefreshHandler, so the next call re-reads the key (covers
  out-of-process writes such as the secret CLI);
- a site->central call presents a token that does not match the cached key:
  CentralControlAuthInterceptor invalidates and re-reads once before refusing;
- ScadaBridge:Communication:SitePsks reloads.

Invalidation is case-insensitive because SecretName lowercases names. Rotation
runbook (topology-guide), Component-Communication/Host and the #85 cache audit
(D2) updated.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-09 14:30:17 -05:00

226 lines
10 KiB
C#

using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.ScadaBridge.Communication;
using ZB.MOM.WW.ScadaBridge.Communication.Grpc;
using ZB.MOM.WW.Secrets.Abstractions;
namespace ZB.MOM.WW.ScadaBridge.Host;
/// <summary>
/// Central's <see cref="ISitePskProvider"/>: resolves each site's gRPC preshared key at
/// channel-build time — from <c>ScadaBridge:Communication:SitePsks</c> if the site is listed
/// there, otherwise from the secrets store under the name <c>SB-GRPC-PSK-{siteId}</c>.
/// </summary>
/// <remarks>
/// <para>
/// <b>Why resolved at runtime rather than expanded into config at boot.</b> Site nodes get their
/// single key through the pre-host <c>SecretReferenceExpander</c> — a <c>${secret:…}</c> in
/// appsettings, resolved once before the host is built. Central cannot do that: its set of sites
/// comes from the configuration database and changes while the process runs, so there is no
/// fixed list of references to expand at boot. This mirrors the pattern the MxGateway data
/// connection already uses for its per-connection API keys.
/// </para>
/// <para>
/// <b>Caching.</b> Successful resolves are cached until something says the key may have changed.
/// Failures are deliberately NOT cached, so a key seeded after the first (failed) dial is picked
/// up on the next attempt instead of requiring a restart. <see cref="Invalidate"/> drops an entry,
/// and four things call it (Gitea #96 — before that only site removal did, so an in-place
/// rotation left both central nodes dialling with the old key until they restarted):
/// </para>
/// <list type="bullet">
/// <item>site removal (the gRPC client paths);</item>
/// <item>a write to <c>SB-GRPC-PSK-{siteId}</c> through this node's secret write path
/// (<c>/admin/secrets</c>) — <see cref="SitePskRotationInvalidator"/>, which also tells the peer
/// central node over <c>DistributedPubSub</c>;</item>
/// <item>a site rejecting a call with <c>PermissionDenied</c>/<c>Unauthenticated</c>
/// (<c>ControlPlaneCredentials.WithSiteCredentials</c>), so a key rotated out of band (the
/// <c>secret</c> CLI, a direct SQL write) is re-read on the next call — after the secret
/// resolver's own <c>Secrets:ResolveCacheTtl</c> at most;</item>
/// <item>a reload of <c>ScadaBridge:Communication:SitePsks</c>, which clears the whole cache.</item>
/// </list>
/// <para>
/// <para>
/// <b>Fail-closed.</b> A key absent from BOTH sources throws, and the dial that needed it fails.
/// It never degrades to an unauthenticated call. The message names the exact config key and the
/// exact secret name, so the fix is one setting or one <c>secret</c> CLI seed.
/// </para>
/// </remarks>
public sealed class SitePskProvider : ISitePskProvider, IDisposable
{
/// <summary>Prefix of the per-site secret name; the site identifier is appended verbatim.</summary>
public const string SecretNamePrefix = "SB-GRPC-PSK-";
private readonly ConcurrentDictionary<string, string> _cache = new(StringComparer.Ordinal);
private readonly ISecretResolver _resolver;
private readonly IOptionsMonitor<CommunicationOptions> _options;
private readonly ILogger<SitePskProvider> _logger;
private readonly IDisposable? _optionsChange;
/// <summary>Creates the provider over the host's secret resolver.</summary>
/// <param name="resolver">Runtime secret resolver from the host container.</param>
/// <param name="options">
/// Communication options supplying the optional <c>SitePsks</c> map. Read through an
/// <see cref="IOptionsMonitor{TOptions}"/> so a reloaded configuration is honoured on the
/// next uncached resolve rather than pinned at construction.
/// </param>
/// <param name="logger">Logger for resolution diagnostics.</param>
public SitePskProvider(
ISecretResolver resolver,
IOptionsMonitor<CommunicationOptions> options,
ILogger<SitePskProvider> logger)
{
ArgumentNullException.ThrowIfNull(resolver);
ArgumentNullException.ThrowIfNull(options);
ArgumentNullException.ThrowIfNull(logger);
_resolver = resolver;
_options = options;
_logger = logger;
// A reloaded SitePsks map may carry a rotated key for any site; drop everything so the
// next dial to each site re-reads its source. Re-reading is cheap (a dictionary lookup,
// or the secret resolver's own cache), so clearing all is simpler than diffing.
_optionsChange = options.OnChange((_, _) => _cache.Clear());
}
/// <summary>Builds the secret name for a site.</summary>
/// <param name="siteId">Site identifier.</param>
/// <returns>The secret name, e.g. <c>SB-GRPC-PSK-site-a</c>.</returns>
public static string SecretNameFor(string siteId) => SecretNamePrefix + siteId;
/// <inheritdoc />
public async ValueTask<string> GetAsync(string siteId, CancellationToken ct)
{
ArgumentException.ThrowIfNullOrWhiteSpace(siteId);
if (_cache.TryGetValue(siteId, out var cached))
{
return cached;
}
// Configured map first: it is the explicit, operator-stated answer for this site, and
// it is the only source available to a host running without a secrets master key.
var configured = _options.CurrentValue.SitePsks;
if (configured.TryGetValue(siteId, out var fromConfig) && !string.IsNullOrEmpty(fromConfig))
{
_cache[siteId] = fromConfig;
return fromConfig;
}
// Otherwise the store, which is the only source that can serve a site added at runtime.
var secretName = SecretNameFor(siteId);
var value = await ResolveFromStoreAsync(secretName, siteId, ct).ConfigureAwait(false);
if (string.IsNullOrEmpty(value))
{
_logger.LogError(
"gRPC control-plane key for site {SiteId} could not be resolved: it is absent from "
+ "ScadaBridge:Communication:SitePsks and secret '{SecretName}' is missing, empty or "
+ "tombstoned. Calls to this site are refused until one of the two is set (the site "
+ "node must carry the same value in ScadaBridge:Communication:GrpcPsk).",
siteId, secretName);
throw new InvalidOperationException(
$"gRPC preshared key for site '{siteId}' could not be resolved from "
+ $"ScadaBridge:Communication:SitePsks or secret '{secretName}'.");
}
// Two concurrent first dials may both resolve; the read is idempotent and the values
// identical, so the loser simply overwrites with the same string.
_cache[siteId] = value;
return value;
}
/// <summary>
/// Reads the key from the secrets store. A store fault (unreachable SQL Server, no master
/// key) surfaces as <see cref="SecretStoreUnavailableException"/>, distinct from a secret
/// that is simply missing (null return), and is never cached.
/// </summary>
private async Task<string?> ResolveFromStoreAsync(string secretName, string siteId, CancellationToken ct)
{
try
{
return await _resolver.GetAsync(new SecretName(secretName), ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
// A store fault is NOT "secret missing": telling the operator to seed a secret that
// exists (while the shared store is merely unreachable) sends them the wrong way.
// Surface it as a distinct exception type and keep the cause visible at Warning.
_logger.LogWarning(ex,
"Secret store lookup for '{SecretName}' (site {SiteId}) faulted; the key could not be "
+ "read (this is a store fault, not a missing secret).",
secretName, siteId);
throw new SecretStoreUnavailableException(secretName, siteId, ex);
}
}
/// <inheritdoc />
/// <remarks>
/// Case-insensitive: the rotation hook derives the site id from a <c>SecretName</c>, which the
/// secrets library lowercases, and a secret name addresses the same secret in any case.
/// </remarks>
public void Invalidate(string siteId)
{
if (string.IsNullOrWhiteSpace(siteId))
{
return;
}
foreach (var key in _cache.Keys)
{
if (string.Equals(key, siteId, StringComparison.OrdinalIgnoreCase))
{
_cache.TryRemove(key, out _);
}
}
}
/// <summary>
/// Returns the site identifier a secret name is the PSK of, or <c>null</c> when the name is
/// not a <see cref="SecretNamePrefix"/> name. The prefix matches in any case, because the
/// secrets library stores names lowercased.
/// </summary>
/// <param name="secretName">A secret name.</param>
/// <returns>The site identifier, or <c>null</c>.</returns>
public static string? SiteIdFromSecretName(string secretName) =>
secretName is not null
&& secretName.Length > SecretNamePrefix.Length
&& secretName.StartsWith(SecretNamePrefix, StringComparison.OrdinalIgnoreCase)
? secretName[SecretNamePrefix.Length..]
: null;
/// <inheritdoc />
public void Dispose() => _optionsChange?.Dispose();
}
/// <summary>
/// The secrets store could not be read while resolving a site's gRPC preshared key — a store
/// fault, as opposed to the secret being absent (review 2026-10-21 05/U2).
/// </summary>
public sealed class SecretStoreUnavailableException : InvalidOperationException
{
/// <summary>Initializes the exception.</summary>
/// <param name="secretName">The secret that was being read.</param>
/// <param name="siteId">The site whose key was being resolved.</param>
/// <param name="inner">The underlying store fault.</param>
public SecretStoreUnavailableException(string secretName, string siteId, Exception inner)
: base($"The secret store could not be read while resolving gRPC preshared key '{secretName}' "
+ $"for site '{siteId}' ({inner.GetType().Name}: {inner.Message}); the secret may exist — "
+ "this is a store fault, not a missing secret.", inner)
{
SecretName = secretName;
SiteId = siteId;
}
/// <summary>Gets the secret that was being read.</summary>
public string SecretName { get; }
/// <summary>Gets the site whose key was being resolved.</summary>
public string SiteId { get; }
}