feat(transport): fleet-wide bundle-unlock throttle window (register row 52)

The per-IP unlock throttle's counters were a process-local ConcurrentDictionary
on each central node, so the effective fleet cap was N x
MaxUnlockAttemptsPerIpPerHour per client (failing over to the other node handed
the client a fresh budget) and a node restart cleared the window outright.

The window now lives in the central MS SQL BundleUnlockAttempt table — the HA
store both central nodes already share, so no new infrastructure, no new port,
no consensus protocol:

- Commons: BundleUnlockAttempt entity + IBundleUnlockAttemptRepository.
- ConfigurationDatabase: entity config (one index,
  IX_BundleUnlockAttempt_Client_Attempted, serving both the windowed count and
  the prune), repository (AsNoTracking count, ExecuteDeleteAsync prune),
  DbSet, DI registration, migration AddBundleUnlockAttemptTable + the
  hand-written idempotent production script under docs/plans/sql/.
- Transport: IBundleUnlockAttemptWindow seam + SqlBundleUnlockAttemptWindow
  (singleton; resolves the scoped repository from its own scope per call, like
  the central purge singletons). BundleUnlockRateLimiter keeps the policy and
  gains TryRegisterAttemptAsync; BundleImporter.LoadAsync calls it.

Behaviour preserved from row 44: locked bundles spend no hourly budget (the
lockout check still runs first), throttle denials burn no per-bundle strike and
are NOT recorded so they cannot roll the window forward, unattributable clients
share the stricter <unattributed> bucket, and the budget counts attempts rather
than failures. Config keys and their semantics are unchanged, so the rig's 500
override stays valid.

Three deliberate trades, documented in both Transport docs:
- FAILS OPEN. A store error logs a Warning naming the client and cap, and
  permits the attempt. This is a best-effort rate cap over an already
  authenticated, Administrator-gated surface — the availability of legitimate
  imports outranks the cap, and a DB blip must not make the import wizard
  unusable. Falling back to the process-local window was considered and
  rejected: it would still block a legitimate operator's 11th import.
- Approximate. Count-then-insert is not atomic across nodes, so simultaneous
  attempts can overshoot by the number in flight — bounded, self-correcting
  within the window, and not worth provider-specific raw SQL.
- Pruned opportunistically on the unlock path (CAS-claimed at most every 15
  min per process, bounded to 1000 rows, retaining 2x the window, best-effort
  try/catch) rather than by a new background service — Transport owns no
  central scheduler. Same shape as DeploymentService's terminal-record sweep.

Tests: Transport.IntegrationTests 116 passed (+10 — two limiter instances over
one store enforcing a single combined window, restart durability, denials
burning no budget, sliding release, bucket isolation, store-failure fail-open,
caller-cancellation not swallowed, no-shared-window fallback, prune and its
negative control); ConfigurationDatabase 395 passed (+5).
This commit is contained in:
Joseph Doherty
2026-08-15 11:52:34 -04:00
parent 372ea4df1b
commit 677263af57
21 changed files with 3157 additions and 30 deletions
@@ -293,11 +293,18 @@ public sealed class BundleImporter : IBundleImporter
// operator is legitimately importing.
// Registered on every unlock attempt (successful ones included) because the
// documented budget counts attempts, not failures.
//
// Register row 52: the async overload consults the FLEET-WIDE window (central
// MS SQL) so the cap is not multiplied by the number of central nodes and does
// not reset on a node restart. It fails open on a store error — see
// BundleUnlockRateLimiter's remarks.
var throttleKey = string.IsNullOrWhiteSpace(clientKey)
? UnattributedClientKey
: clientKey;
var perIpCap = _options.Value.MaxUnlockAttemptsPerIpPerHour;
if (!_unlockRateLimiter.TryRegisterAttempt(throttleKey, perIpCap))
if (!await _unlockRateLimiter
.TryRegisterAttemptAsync(throttleKey, perIpCap, ct)
.ConfigureAwait(false))
{
_logger?.LogWarning(
"Bundle unlock throttled: client {ClientKey} exceeded {Cap} attempts in the trailing hour.",
@@ -1,26 +1,37 @@
using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace ZB.MOM.WW.ScadaBridge.Transport.Import;
/// <summary>
/// In-memory sliding-window rate limiter for bundle-unlock passphrase
/// attempts, keyed by client IP. The design doc (§11) declares a per-IP-per-hour cap
/// (default 10) as a brute-force defence against a stolen bundle; this class is the
/// minimal server-side implementation.
/// Sliding-window rate limiter for bundle-unlock passphrase attempts, keyed by client IP.
/// The design doc (§11) declares a per-IP-per-hour cap (default 10) as a brute-force
/// defence against a stolen bundle; this class owns that policy.
/// <para>
/// Algorithm: each key (an IP string, or any opaque caller identifier) holds a queue
/// of attempt timestamps. <see cref="TryRegisterAttempt"/> first prunes entries older
/// than the configured window, then either appends the current timestamp and returns
/// <c>true</c> if the count is still under the threshold, or refuses to append and
/// returns <c>false</c> if appending would cross it. The trailing-hour count is the
/// queue length post-prune.
/// <b>The window is fleet-wide when an <see cref="IBundleUnlockAttemptWindow"/> is
/// supplied (register row 52).</b> The counters used to be per-node AND per-process, so
/// the effective cap was N x limit per client across the central pair and a node restart
/// silently cleared the window. <see cref="TryRegisterAttemptAsync"/> now consults the
/// shared central-MS-SQL window instead, which both central nodes already share. The
/// production composition root always supplies one.
/// </para>
/// <para>
/// Storage is a process-local <see cref="ConcurrentDictionary{TKey,TValue}"/>. The
/// counters do not survive a host restart — that is by design: a restart resets the
/// brute-force window in favour of legitimate operators after an outage. Persisting
/// the counters would require a multi-node consensus story the simple in-memory
/// design avoids.
/// <b>Fail-open is deliberate.</b> A store failure in the throttle path logs a Warning and
/// PERMITS the attempt. This is a best-effort rate cap layered over a surface that is
/// already authenticated and role-gated (Administrator-only bundle import), so the
/// availability of legitimate imports outranks the cap: a database blip must not make the
/// import wizard unusable. Falling back to the process-local window instead was considered
/// and rejected — it would still block a legitimate operator's 11th import during an
/// outage, which is the outcome fail-open exists to prevent.
/// </para>
/// <para>
/// Algorithm (the process-local fallback used when no shared window is registered): each
/// key holds a queue of attempt timestamps. <see cref="TryRegisterAttempt"/> first prunes
/// entries older than the configured window, then either appends the current timestamp and
/// returns <c>true</c> if the count is still under the threshold, or refuses to append and
/// returns <c>false</c> if appending would cross it. Either way a REJECTED attempt is never
/// appended, so a denial burns no budget — the same contract the shared window implements.
/// </para>
/// <para>
/// Thread-safety: the per-key queue is protected by a per-key lock taken inside the
@@ -39,10 +50,13 @@ public sealed class BundleUnlockRateLimiter
private readonly ConcurrentDictionary<string, AttemptBucket> _buckets = new(StringComparer.OrdinalIgnoreCase);
private readonly TimeProvider _timeProvider;
private readonly TimeSpan _window;
private readonly IBundleUnlockAttemptWindow? _sharedWindow;
private readonly ILogger<BundleUnlockRateLimiter> _logger;
/// <summary>
/// Initializes a new <see cref="BundleUnlockRateLimiter"/> using the documented
/// 1-hour trailing window and the system clock. Suitable for production DI.
/// 1-hour trailing window and the system clock, with no shared window (process-local
/// counters only).
/// </summary>
public BundleUnlockRateLimiter() : this(TimeProvider.System, DefaultWindow)
{
@@ -50,11 +64,28 @@ public sealed class BundleUnlockRateLimiter
/// <summary>
/// Initializes a new <see cref="BundleUnlockRateLimiter"/> with an injected clock
/// (for deterministic tests) and a custom trailing window.
/// (for deterministic tests) and a custom trailing window, with no shared window.
/// </summary>
/// <param name="timeProvider">Clock used for both timestamping new attempts and pruning expired ones.</param>
/// <param name="window">Trailing window over which attempts are counted (typically 1 hour).</param>
public BundleUnlockRateLimiter(TimeProvider timeProvider, TimeSpan window)
: this(timeProvider, window, sharedWindow: null, logger: null)
{
}
/// <summary>
/// Initializes a new <see cref="BundleUnlockRateLimiter"/> over a fleet-wide shared
/// window (register row 52). This is the overload the production composition root uses.
/// </summary>
/// <param name="timeProvider">Clock used for the process-local fallback window.</param>
/// <param name="window">Trailing window over which attempts are counted (typically 1 hour).</param>
/// <param name="sharedWindow">Shared cross-node attempt window; when null the limiter falls back to process-local counters.</param>
/// <param name="logger">Optional logger. Used for the fail-open Warning when the shared window is unavailable.</param>
public BundleUnlockRateLimiter(
TimeProvider timeProvider,
TimeSpan window,
IBundleUnlockAttemptWindow? sharedWindow,
ILogger<BundleUnlockRateLimiter>? logger)
{
ArgumentNullException.ThrowIfNull(timeProvider);
if (window <= TimeSpan.Zero)
@@ -64,13 +95,81 @@ public sealed class BundleUnlockRateLimiter
_timeProvider = timeProvider;
_window = window;
_sharedWindow = sharedWindow;
_logger = logger ?? NullLogger<BundleUnlockRateLimiter>.Instance;
}
/// <summary>
/// Attempts to register a new passphrase try against the configured per-key
/// limit. Returns <c>true</c> when the attempt is permitted (and recorded);
/// returns <c>false</c> when the key has exhausted its budget for the trailing
/// window — the caller should reject the unlock request with a 429-equivalent.
/// Gets a value indicating whether this limiter is backed by a fleet-wide shared
/// window. False means the cap degrades to per-node, per-process counters.
/// </summary>
public bool IsFleetWide => _sharedWindow is not null;
/// <summary>
/// Registers a passphrase try against the configured per-key limit, using the
/// fleet-wide shared window when one is registered and the process-local window
/// otherwise. This is the method the importer calls.
/// </summary>
/// <param name="clientKey">Opaque caller identifier — typically the remote IP.</param>
/// <param name="maxAttemptsPerWindow">The trailing-window cap (<c>MaxUnlockAttemptsPerIpPerHour</c>).</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>
/// <c>true</c> if the attempt is permitted; <c>false</c> if the caller has exhausted
/// its budget. Also <c>true</c> when the shared window is unavailable — see the
/// class remarks on why the throttle fails open.
/// </returns>
public async Task<bool> TryRegisterAttemptAsync(
string clientKey, int maxAttemptsPerWindow, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(clientKey);
if (maxAttemptsPerWindow < 1)
{
throw new ArgumentOutOfRangeException(
nameof(maxAttemptsPerWindow), "Limit must be at least 1.");
}
if (_sharedWindow is null)
{
return TryRegisterAttempt(clientKey, maxAttemptsPerWindow);
}
try
{
return await _sharedWindow
.TryRegisterAttemptAsync(clientKey, maxAttemptsPerWindow, _window, ct)
.ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// The caller's own cancellation, not a store failure — do not swallow it.
throw;
}
catch (Exception ex)
{
// Fail OPEN: a best-effort rate cap must never take the import surface down
// with the database. The Warning is the operator's signal that the fleet cap
// is currently not being enforced.
_logger.LogWarning(
ex,
"Fleet-wide bundle-unlock throttle unavailable; permitting the unlock attempt for client "
+ "{ClientKey} without enforcing the {Cap}/hour cap.",
clientKey, maxAttemptsPerWindow);
return true;
}
}
/// <summary>
/// Attempts to register a new passphrase try against the configured per-key limit in
/// the PROCESS-LOCAL window. Returns <c>true</c> when the attempt is permitted (and
/// recorded); returns <c>false</c> when the key has exhausted its budget for the
/// trailing window — the caller should reject the unlock request with a 429-equivalent.
/// <para>
/// Register row 52: this bypasses the fleet-wide window. Callers on the unlock path
/// must use <see cref="TryRegisterAttemptAsync"/>, which routes to the shared window
/// when one is registered and falls back here otherwise. This overload remains public
/// for hosts that register Transport without a shared window, and for the tests that
/// pin the sliding-window arithmetic directly.
/// </para>
/// </summary>
/// <param name="clientKey">
/// Opaque caller identifier — typically the remote IP, but any stable per-source
@@ -0,0 +1,28 @@
namespace ZB.MOM.WW.ScadaBridge.Transport.Import;
/// <summary>
/// Register row 52: a sliding window of bundle-unlock attempts that is shared across the
/// central pair, so <c>TransportOptions.MaxUnlockAttemptsPerIpPerHour</c> is a FLEET cap
/// rather than a per-node, per-process one.
/// <para>
/// Implementations are expected to THROW on store failure. The fail-open decision belongs
/// to <see cref="BundleUnlockRateLimiter"/>, which owns the policy (log a Warning and
/// permit the attempt), not to the storage layer.
/// </para>
/// </summary>
public interface IBundleUnlockAttemptWindow
{
/// <summary>
/// Registers one unlock attempt against the shared window and reports whether it was
/// within budget. Implementations must NOT record an attempt they are rejecting —
/// a denial burns no budget, matching the in-memory limiter's contract (register
/// row 44), so a client that keeps hammering cannot extend its own lockout.
/// </summary>
/// <param name="clientKey">Throttle bucket — the caller's remote IP, or the shared unattributed bucket.</param>
/// <param name="maxAttemptsPerWindow">The trailing-window cap (<c>MaxUnlockAttemptsPerIpPerHour</c>).</param>
/// <param name="window">Trailing window the attempts are counted over (one hour in production).</param>
/// <param name="ct">Cancellation token.</param>
/// <returns><c>true</c> when the attempt was recorded (within budget); <c>false</c> when the bucket is exhausted.</returns>
Task<bool> TryRegisterAttemptAsync(
string clientKey, int maxAttemptsPerWindow, TimeSpan window, CancellationToken ct = default);
}
@@ -0,0 +1,167 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
namespace ZB.MOM.WW.ScadaBridge.Transport.Import;
/// <summary>
/// Register row 52: <see cref="IBundleUnlockAttemptWindow"/> backed by the central MS SQL
/// <c>BundleUnlockAttempt</c> table — the HA store both central nodes already share, so
/// the fleet-wide cap needs no new infrastructure, no new port and no consensus protocol.
/// <para>
/// Registered as a singleton (the limiter that consumes it is one) and therefore resolves
/// a scoped <see cref="IBundleUnlockAttemptRepository"/> from its own
/// <see cref="IServiceScopeFactory"/> scope per call, the same way the central purge
/// singletons reach the database.
/// </para>
/// <para>
/// <b>Accuracy is deliberately approximate.</b> The count-then-insert pair is not atomic
/// across the two central nodes, so genuinely simultaneous attempts can overshoot the cap
/// by up to the number in flight. A conditional single-statement insert would close that,
/// at the cost of provider-specific SQL for a best-effort rate cap layered over an
/// already-authenticated, role-gated surface. Overshoot is bounded and self-corrects
/// within the window; it is not worth raw SQL.
/// </para>
/// </summary>
public sealed class SqlBundleUnlockAttemptWindow : IBundleUnlockAttemptWindow
{
/// <summary>
/// Minimum wall-clock gap between opportunistic prunes. The prune runs on the unlock
/// path (Transport owns no central scheduler, and the design constraint was "no new
/// background service"), so it is claimed at most this often per process — the same
/// rate-limited opportunistic-sweep shape <c>DeploymentService</c> uses for terminal
/// deployment records.
/// </summary>
internal static readonly TimeSpan PruneMinInterval = TimeSpan.FromMinutes(15);
/// <summary>
/// Upper bound on rows deleted by one opportunistic prune pass. Bounded so a sweep on
/// a request path can never become a long-running delete, even if the table grew while
/// prunes were failing.
/// </summary>
internal const int PruneBatchSize = 1000;
/// <summary>
/// Multiple of the trailing window that rows are retained for before becoming
/// prunable. Kept above 1 so a prune racing a count can never delete a row the count
/// still needs.
/// </summary>
internal const int PruneRetentionWindows = 2;
private readonly IServiceScopeFactory _scopeFactory;
private readonly TimeProvider _timeProvider;
private readonly ILogger<SqlBundleUnlockAttemptWindow> _logger;
/// <summary>Ticks of the last claimed prune, as a CAS-guarded process-local claim.</summary>
private long _lastPruneTicks;
/// <summary>
/// Initializes a new <see cref="SqlBundleUnlockAttemptWindow"/>.
/// </summary>
/// <param name="scopeFactory">Scope factory used to resolve the scoped attempt repository per call.</param>
/// <param name="timeProvider">Clock used for the window boundary and the prune cadence.</param>
/// <param name="logger">Optional logger for prune diagnostics.</param>
public SqlBundleUnlockAttemptWindow(
IServiceScopeFactory scopeFactory,
TimeProvider timeProvider,
ILogger<SqlBundleUnlockAttemptWindow>? logger = null)
{
_scopeFactory = scopeFactory ?? throw new ArgumentNullException(nameof(scopeFactory));
_timeProvider = timeProvider ?? throw new ArgumentNullException(nameof(timeProvider));
_logger = logger ?? NullLogger<SqlBundleUnlockAttemptWindow>.Instance;
// Seed the prune claim to "now" so a freshly started node does not prune on its
// very first unlock — the table is almost certainly already tidy, and a node that
// restarts under load would otherwise prune on every restart.
_lastPruneTicks = _timeProvider.GetUtcNow().UtcTicks;
}
/// <inheritdoc />
public async Task<bool> TryRegisterAttemptAsync(
string clientKey, int maxAttemptsPerWindow, TimeSpan window, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(clientKey);
if (maxAttemptsPerWindow < 1)
{
throw new ArgumentOutOfRangeException(
nameof(maxAttemptsPerWindow), "Limit must be at least 1.");
}
if (window <= TimeSpan.Zero)
{
throw new ArgumentOutOfRangeException(nameof(window), "Window must be positive.");
}
var now = _timeProvider.GetUtcNow().UtcDateTime;
var key = clientKey.Trim();
using var scope = _scopeFactory.CreateScope();
var repo = scope.ServiceProvider.GetRequiredService<IBundleUnlockAttemptRepository>();
// Two round trips rather than one conditional insert — see the class remarks on
// why the resulting overshoot is accepted. Exceptions propagate: the fail-open
// decision lives in BundleUnlockRateLimiter.
var used = await repo.CountAttemptsSinceAsync(key, now - window, ct).ConfigureAwait(false);
if (used >= maxAttemptsPerWindow)
{
// Rejected attempts are NOT recorded — a denial burns no budget, so a client
// hammering the endpoint cannot roll its own window forward indefinitely.
return false;
}
await repo.RecordAttemptAsync(key, now, ct).ConfigureAwait(false);
await TryPruneAsync(repo, now, window, ct).ConfigureAwait(false);
return true;
}
/// <summary>
/// Opportunistic, rate-limited, bounded prune of aged-out attempt rows. Best-effort:
/// any failure is logged and swallowed, because retention maintenance must never fail
/// the operator's actual unlock.
/// </summary>
/// <param name="repo">Repository resolved for the current call's scope.</param>
/// <param name="nowUtc">Current UTC instant.</param>
/// <param name="window">The trailing window; rows older than a multiple of it are prunable.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>A task that completes when the prune attempt has finished (or been skipped).</returns>
private async Task TryPruneAsync(
IBundleUnlockAttemptRepository repo, DateTime nowUtc, TimeSpan window, CancellationToken ct)
{
var previous = Interlocked.Read(ref _lastPruneTicks);
if (nowUtc.Ticks - previous < PruneMinInterval.Ticks)
{
return;
}
// Claim the sweep so concurrent unlocks on this node don't all prune at once.
if (Interlocked.CompareExchange(ref _lastPruneTicks, nowUtc.Ticks, previous) != previous)
{
return;
}
try
{
var cutoff = nowUtc - (window * PruneRetentionWindows);
var deleted = await repo
.PruneAttemptsOlderThanAsync(cutoff, PruneBatchSize, ct)
.ConfigureAwait(false);
if (deleted > 0)
{
_logger.LogDebug(
"Pruned {Deleted} bundle-unlock attempt row(s) older than {Cutoff:o}.", deleted, cutoff);
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
throw;
}
catch (Exception ex)
{
// Never fail the unlock for a retention sweep.
_logger.LogWarning(ex, "Opportunistic bundle-unlock attempt prune failed; will retry on a later attempt.");
}
}
}
@@ -1,5 +1,6 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Transport;
using ZB.MOM.WW.ScadaBridge.TemplateEngine.Validation;
@@ -43,10 +44,22 @@ public static class ServiceCollectionExtensions
services.AddScoped<DependencyResolver>();
services.AddScoped<IBundleExporter, BundleExporter>();
services.AddSingleton<IBundleSessionStore, BundleSessionStore>();
// T-004: per-IP-per-hour unlock rate limiter — design doc §11. Singleton
// so the trailing-hour window is shared across every importer scope; the
// counters live in-memory and reset on host restart (by design).
services.AddSingleton<BundleUnlockRateLimiter>();
// T-004: per-IP-per-hour unlock rate limiter — design doc §11. Singleton so the
// trailing-hour window is shared across every importer scope.
//
// Register row 52: the window is FLEET-WIDE, backed by the central MS SQL
// BundleUnlockAttempt table that both central nodes already share — the counters
// used to be per-node and per-process, so the effective cap was N x limit per
// client and a restart cleared the window. The window resolves its scoped
// repository from its own scope per call, so it is safe as a singleton.
// Constructed explicitly rather than by convention so it is unambiguous which
// constructor overload production uses.
services.AddSingleton<IBundleUnlockAttemptWindow, SqlBundleUnlockAttemptWindow>();
services.AddSingleton(sp => new BundleUnlockRateLimiter(
sp.GetRequiredService<TimeProvider>(),
BundleUnlockRateLimiter.DefaultWindow,
sp.GetRequiredService<IBundleUnlockAttemptWindow>(),
sp.GetService<ILogger<BundleUnlockRateLimiter>>()));
// T-007: periodic eviction sweep so abandoned sessions clear without
// needing a fresh Get() to trigger lazy eviction.
services.AddHostedService<BundleSessionEvictionService>();