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; /// /// Central's : resolves each site's gRPC preshared key at /// channel-build time — from ScadaBridge:Communication:SitePsks if the site is listed /// there, otherwise from the secrets store under the name SB-GRPC-PSK-{siteId}. /// /// /// /// Why resolved at runtime rather than expanded into config at boot. Site nodes get their /// single key through the pre-host SecretReferenceExpander — a ${secret:…} 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. /// /// /// Caching. 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. 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): /// /// /// site removal (the gRPC client paths); /// a write to SB-GRPC-PSK-{siteId} through this node's secret write path /// (/admin/secrets) — , which also tells the peer /// central node over DistributedPubSub; /// a site rejecting a call with PermissionDenied/Unauthenticated /// (ControlPlaneCredentials.WithSiteCredentials), so a key rotated out of band (the /// secret CLI, a direct SQL write) is re-read on the next call — after the secret /// resolver's own Secrets:ResolveCacheTtl at most; /// a reload of ScadaBridge:Communication:SitePsks, which clears the whole cache. /// /// /// /// Fail-closed. 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 secret CLI seed. /// /// public sealed class SitePskProvider : ISitePskProvider, IDisposable { /// Prefix of the per-site secret name; the site identifier is appended verbatim. public const string SecretNamePrefix = "SB-GRPC-PSK-"; private readonly ConcurrentDictionary _cache = new(StringComparer.Ordinal); private readonly ISecretResolver _resolver; private readonly IOptionsMonitor _options; private readonly ILogger _logger; private readonly IDisposable? _optionsChange; /// Creates the provider over the host's secret resolver. /// Runtime secret resolver from the host container. /// /// Communication options supplying the optional SitePsks map. Read through an /// so a reloaded configuration is honoured on the /// next uncached resolve rather than pinned at construction. /// /// Logger for resolution diagnostics. public SitePskProvider( ISecretResolver resolver, IOptionsMonitor options, ILogger 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()); } /// Builds the secret name for a site. /// Site identifier. /// The secret name, e.g. SB-GRPC-PSK-site-a. public static string SecretNameFor(string siteId) => SecretNamePrefix + siteId; /// public async ValueTask 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; } /// /// Reads the key from the secrets store. A store fault (unreachable SQL Server, no master /// key) surfaces as , distinct from a secret /// that is simply missing (null return), and is never cached. /// private async Task 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); } } /// /// /// Case-insensitive: the rotation hook derives the site id from a SecretName, which the /// secrets library lowercases, and a secret name addresses the same secret in any case. /// 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 _); } } } /// /// Returns the site identifier a secret name is the PSK of, or null when the name is /// not a name. The prefix matches in any case, because the /// secrets library stores names lowercased. /// /// A secret name. /// The site identifier, or null. public static string? SiteIdFromSecretName(string secretName) => secretName is not null && secretName.Length > SecretNamePrefix.Length && secretName.StartsWith(SecretNamePrefix, StringComparison.OrdinalIgnoreCase) ? secretName[SecretNamePrefix.Length..] : null; /// public void Dispose() => _optionsChange?.Dispose(); } /// /// 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). /// public sealed class SecretStoreUnavailableException : InvalidOperationException { /// Initializes the exception. /// The secret that was being read. /// The site whose key was being resolved. /// The underlying store fault. 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; } /// Gets the secret that was being read. public string SecretName { get; } /// Gets the site whose key was being resolved. public string SiteId { get; } }