fix(archreview): security authz+hub cluster (SEC-07/05/08/11) + validation hardening

SEC-07: add QueryActiveAlarmsRequest -> events:read scope arm; fix two tests that
  constructed StreamAlarmsRequest instead of QueryActiveAlarmsRequest.
SEC-05: shorten hub-token lifetime 30m -> 5m; document that the ?access_token= query
  carriage must never be request-logged.
SEC-08: gateway-side CachingApiKeyVerifier (short TTL, keyed on a hash of the presented
  secret) skips the per-call store read+last_used write; CoalescingMarkApiKeyStore bounds
  last_used writes to <=1/key/min; identity constraints are cached. Invalidation is wired
  at the gateway admin sites (revoke/rotate/delete); short TTL backstops out-of-process CLI.
SEC-11: fixed-window rate limit on POST /auth/login + a per-peer (key-id) failure limiter
  checked before VerifyAsync; new MxGateway:Security options bound + validated.

Also fixes regressions from the SEC-01/04/06 commit (c185f62) that a narrow test filter
missed (all now covered by a full-suite checkpoint):
- Rooting check is cross-platform: accepts Windows C:\/UNC forms on Unix so the shipped
  appsettings path validates on the macOS dev box, still rejecting bare filenames.
- AddGatewayConfiguration TryAdds a non-production IHostEnvironment fallback so the validator
  resolves in minimal test/tooling containers; the real host + apikey CLI register the actual
  environment first (TryAdd no-op there).
- Test assembly defaults ASPNETCORE_ENVIRONMENT=Development (ModuleInitializer) so full-host
  tests exercise wiring instead of tripping the SEC-04/06 production guards.
- GatewayOptionsTests asserts the SEC-01 CommonApplicationData-derived default (platform-correct).

archreview: SEC-07/05/08/11 (P1). Verified: NonWindows build clean; full gateway suite
747 passed / 42 failed, where all 42 are the pre-existing macOS named-pipe-harness failures
(Unix-socket path limit) and 0 are validation/regression failures.
This commit is contained in:
Joseph Doherty
2026-07-09 07:31:35 -04:00
parent 970613eebd
commit 17f16ea181
29 changed files with 1521 additions and 18 deletions
@@ -1,4 +1,7 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using ZB.MOM.WW.Configuration;
namespace ZB.MOM.WW.MxGateway.Server.Configuration;
@@ -12,6 +15,14 @@ public static class GatewayConfigurationServiceCollectionExtensions
public static IServiceCollection AddGatewayConfiguration(
this IServiceCollection services, IConfiguration configuration)
{
// GatewayOptionsValidator depends on IHostEnvironment to gate the production-only rules
// (SEC-04/06). The real host and the apikey CLI both build through WebApplicationBuilder,
// which registers IHostEnvironment before this call — so TryAdd is a no-op there. Minimal
// containers (unit tests, tooling) have none; fall back to a non-production environment so
// the validator still activates and the production guards stay off outside a real
// deployment (the fail-fast guards only make sense against a real host environment).
services.TryAddSingleton<IHostEnvironment>(new FallbackHostEnvironment());
services.AddValidatedOptions<GatewayOptions, GatewayOptionsValidator>(
configuration, GatewayOptions.SectionName);
@@ -19,4 +30,19 @@ public static class GatewayConfigurationServiceCollectionExtensions
return services;
}
/// <summary>
/// Non-production <see cref="IHostEnvironment"/> used only when no real host registered one
/// (minimal test/tooling containers). The real host's registration always wins via TryAdd.
/// </summary>
private sealed class FallbackHostEnvironment : IHostEnvironment
{
public string EnvironmentName { get; set; } = Environments.Development;
public string ApplicationName { get; set; } = typeof(FallbackHostEnvironment).Assembly.GetName().Name ?? "MxGateway";
public string ContentRootPath { get; set; } = AppContext.BaseDirectory;
public IFileProvider ContentRootFileProvider { get; set; } = new NullFileProvider();
}
}
@@ -46,4 +46,10 @@ public sealed class GatewayOptions
/// <summary>Gets self-signed TLS certificate auto-generation options.</summary>
public TlsOptions Tls { get; init; } = new();
/// <summary>
/// Gets security hot-path options (API-key verification cache / last-used coalescing and
/// login / API-key rate limiting).
/// </summary>
public SecurityOptions Security { get; init; } = new();
}
@@ -48,6 +48,43 @@ public sealed class GatewayOptionsValidator : OptionsValidatorBase<GatewayOption
ValidateProtocol(options.Protocol, builder);
ValidateAlarms(options.Alarms, builder);
ValidateTls(options.Tls, builder);
ValidateSecurity(options.Security, builder);
}
private static void ValidateSecurity(SecurityOptions options, ValidationBuilder builder)
{
// Cache/coalesce windows may be 0 (disables that mechanism); negatives are invalid.
AddIfNegative(
options.ApiKeyVerificationCacheSeconds,
"MxGateway:Security:ApiKeyVerificationCacheSeconds must be greater than or equal to zero (0 disables the verification cache).",
builder);
AddIfNegative(
options.ApiKeyLastUsedCoalesceSeconds,
"MxGateway:Security:ApiKeyLastUsedCoalesceSeconds must be greater than or equal to zero (0 forwards every last_used write).",
builder);
// Rate-limit knobs must be positive: a zero permit/window/limit is a misconfiguration that
// would either reject every request or divide by zero rather than express an intent.
AddIfNotPositive(
options.LoginRateLimitPermitLimit,
"MxGateway:Security:LoginRateLimitPermitLimit must be greater than zero.",
builder);
AddIfNotPositive(
options.LoginRateLimitWindowSeconds,
"MxGateway:Security:LoginRateLimitWindowSeconds must be greater than zero.",
builder);
AddIfNotPositive(
options.ApiKeyFailureLimit,
"MxGateway:Security:ApiKeyFailureLimit must be greater than zero.",
builder);
AddIfNotPositive(
options.ApiKeyFailureWindowSeconds,
"MxGateway:Security:ApiKeyFailureWindowSeconds must be greater than zero.",
builder);
AddIfNotPositive(
options.ApiKeyFailureTrackedPeers,
"MxGateway:Security:ApiKeyFailureTrackedPeers must be greater than zero.",
builder);
}
private static void ValidateAuthentication(AuthenticationOptions options, ValidationBuilder builder)
@@ -456,12 +493,41 @@ public sealed class GatewayOptionsValidator : OptionsValidatorBase<GatewayOption
return;
}
if (!Path.IsPathRooted(value))
if (!IsRootedForAnyPlatform(value))
{
builder.Add(message);
}
}
/// <summary>
/// Determines whether <paramref name="value"/> is an absolute path for <em>any</em> platform,
/// not just the host running the validator. This matters on the macOS dev box, where the
/// production <c>appsettings.json</c> ships Windows-absolute paths (<c>C:\ProgramData\...</c>)
/// that <see cref="Path.IsPathRooted(string)"/> reports as non-rooted on Unix. The intent of the
/// rooting check is to reject bare filenames that resolve against the launch working directory,
/// so a valid Windows drive-qualified or UNC path must pass regardless of the current OS.
/// </summary>
private static bool IsRootedForAnyPlatform(string value)
{
// Rooted on the current OS (Unix "/...", or a Windows drive/UNC path when on Windows).
if (Path.IsPathRooted(value))
{
return true;
}
// Windows drive-qualified path ("C:\..." or "C:/...") checked on a non-Windows host.
if (value.Length >= 3
&& char.IsLetter(value[0])
&& value[1] == ':'
&& (value[2] == '\\' || value[2] == '/'))
{
return true;
}
// Windows UNC path ("\\server\share") checked on a non-Windows host.
return value.StartsWith(@"\\", StringComparison.Ordinal);
}
private static void AddIfInvalidPath(string? value, string message, ValidationBuilder builder)
{
if (string.IsNullOrWhiteSpace(value))
@@ -0,0 +1,65 @@
namespace ZB.MOM.WW.MxGateway.Server.Configuration;
/// <summary>
/// Security hot-path options bound from <c>MxGateway:Security</c>. Groups the API-key verification
/// cache and <c>last_used</c> write-coalescing knobs (SEC-08) with the login and API-key
/// rate-limiting knobs (SEC-11). Defaults preserve safe, low-overhead behaviour without requiring
/// operators to configure anything.
/// </summary>
public sealed class SecurityOptions
{
/// <summary>The configuration sub-section this binds from.</summary>
public const string SectionName = "MxGateway:Security";
/// <summary>
/// Gets the time-to-live, in seconds, of a cached successful API-key verification. A cache hit
/// within this window skips the per-call SQLite read (and the library verifier's coupled
/// <c>last_used</c> write). Explicit invalidation on gateway-initiated revoke/rotate is the
/// primary correctness mechanism; this short TTL is the backstop for out-of-band mutations.
/// Set to <c>0</c> to disable caching. Default is 15 seconds.
/// </summary>
public int ApiKeyVerificationCacheSeconds { get; init; } = 15;
/// <summary>
/// Gets the coalescing window, in seconds, for the <c>last_used_utc</c> write. The library
/// verifier couples the write into every verification; this decorator forwards at most one
/// <c>MarkUsed</c> per key per window, so a hammered key produces at most one write per window
/// rather than one per authenticated RPC. Set to <c>0</c> to forward every write. Default is
/// 60 seconds (at most one write per key per minute).
/// </summary>
public int ApiKeyLastUsedCoalesceSeconds { get; init; } = 60;
/// <summary>
/// Gets the maximum number of <c>POST /auth/login</c> attempts permitted per remote IP within
/// <see cref="LoginRateLimitWindowSeconds"/> before requests are rejected with HTTP 429. Default
/// is 10.
/// </summary>
public int LoginRateLimitPermitLimit { get; init; } = 10;
/// <summary>
/// Gets the fixed-window length, in seconds, for the <c>POST /auth/login</c> per-IP rate limit.
/// Default is 60 seconds.
/// </summary>
public int LoginRateLimitWindowSeconds { get; init; } = 60;
/// <summary>
/// Gets the number of consecutive failed API-key verifications, per peer, within
/// <see cref="ApiKeyFailureWindowSeconds"/> that trips the in-process short-circuit. Once tripped,
/// the gRPC auth path rejects further attempts before the store read; a successful verification
/// resets the peer's counter. Default is 10.
/// </summary>
public int ApiKeyFailureLimit { get; init; } = 10;
/// <summary>
/// Gets the sliding-window length, in seconds, over which API-key verification failures are
/// counted per peer. Default is 60 seconds.
/// </summary>
public int ApiKeyFailureWindowSeconds { get; init; } = 60;
/// <summary>
/// Gets the maximum number of distinct peers tracked by the API-key failure counter. The counter
/// is a bounded LRU so a spray of unique peer keys cannot grow memory without limit. Default is
/// 4096.
/// </summary>
public int ApiKeyFailureTrackedPeers { get; init; } = 4096;
}