feat(security): opt-in authentication for /metrics (SEC-14)

New MxGateway:Metrics:RequireAuthentication (default false). When true,
/metrics requires an API key with the admin scope (verified through the
cached verifier and the shared API-key failure limiter) or a dashboard
login with a real dashboard role; anonymous localhost and
Authentication:Mode=Disabled do not qualify. An anonymous scrape gets a
plain 401 Bearer challenge, a throttled peer 429. /health stays anonymous
because the off-repo Overview dashboard polls /health/active.

MapZbMetrics returns IEndpointConventionBuilder, so the policy is attached
with RequireAuthorization.
This commit is contained in:
Joseph Doherty
2026-10-22 06:37:31 -04:00
parent ed3a2c9c8b
commit 65bca804bb
10 changed files with 619 additions and 3 deletions
@@ -1078,7 +1078,6 @@ public sealed class GatewayGrpcAuthorizationInterceptorTests
}
}
/// <summary>An <see cref="IAsyncStreamReader{T}"/> that yields no messages.</summary>
/// <typeparam name="T">The streamed message type.</typeparam>
private sealed class EmptyStreamReader<T> : IAsyncStreamReader<T>
@@ -0,0 +1,249 @@
using System.Security.Claims;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
using ZB.MOM.WW.MxGateway.Server.Dashboard;
using ZB.MOM.WW.MxGateway.Server.Metrics;
using ZB.MOM.WW.MxGateway.Server.Security.Authorization;
using LibApiKeyIdentity = ZB.MOM.WW.Auth.Abstractions.ApiKeys.ApiKeyIdentity;
namespace ZB.MOM.WW.MxGateway.Tests.Security.Authorization;
/// <summary>
/// The optional <c>/metrics</c> authentication (<c>MxGateway:Metrics:RequireAuthentication</c>,
/// SEC-14): the scheme that authenticates a scrape and the requirement that authorizes it.
/// </summary>
public sealed class MetricsAuthorizationTests
{
private const string AdminHeader = "Bearer mxgw_scraper_secret";
/// <summary>A verified API key authenticates and carries its scopes as claims.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Authenticate_WithValidApiKey_SucceedsWithScopeClaims()
{
CountingVerifier verifier = new(Success(GatewayScopes.Admin));
DefaultHttpContext httpContext = ContextWithAuthorization(AdminHeader);
AuthenticateResult result = await AuthenticateAsync(verifier, httpContext);
Assert.True(result.Succeeded);
Assert.Equal("scraper", result.Principal!.Identity!.Name);
Assert.True(result.Principal.HasClaim(MetricsAuthorizationDefaults.ScopeClaimType, GatewayScopes.Admin));
Assert.Equal(AdminHeader, verifier.LastHeader);
}
/// <summary>An invalid key fails authentication with an opaque reason.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Authenticate_WithInvalidApiKey_Fails()
{
CountingVerifier verifier = new(new ApiKeyVerification(false, null, ApiKeyFailure.SecretMismatch));
AuthenticateResult result = await AuthenticateAsync(verifier, ContextWithAuthorization(AdminHeader));
Assert.False(result.Succeeded);
Assert.NotNull(result.Failure);
Assert.DoesNotContain("secret", result.Failure!.Message, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Repeated bad keys from one peer trip the shared failure limiter, after which the verifier is
/// no longer reached and the challenge answers 429 — /metrics is not a bypass of the gRPC throttle.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Authenticate_AfterRepeatedFailures_IsThrottledBeforeVerification()
{
CountingVerifier verifier = new(new ApiKeyVerification(false, null, ApiKeyFailure.SecretMismatch));
ApiKeyFailureLimiter limiter = new(
limit: 2,
TimeSpan.FromMinutes(1),
maxPartitions: 16,
aggregateLimit: 0,
probeInterval: TimeSpan.Zero,
TimeProvider.System);
for (int attempt = 0; attempt < 2; attempt++)
{
await AuthenticateAsync(verifier, ContextWithAuthorization(AdminHeader), limiter);
}
DefaultHttpContext throttled = ContextWithAuthorization(AdminHeader);
MetricsAuthenticationHandler handler = await CreateHandlerAsync(verifier, throttled, limiter);
AuthenticateResult result = await handler.AuthenticateAsync();
await handler.ChallengeAsync(new AuthenticationProperties());
Assert.False(result.Succeeded);
Assert.Equal(2, verifier.CallCount);
Assert.Equal(StatusCodes.Status429TooManyRequests, throttled.Response.StatusCode);
}
/// <summary>An anonymous scrape is challenged with a plain 401 Bearer, not a login redirect.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Challenge_WithoutCredentials_Returns401Bearer()
{
DefaultHttpContext httpContext = new();
MetricsAuthenticationHandler handler = await CreateHandlerAsync(
new CountingVerifier(Success(GatewayScopes.Admin)),
httpContext);
AuthenticateResult result = await handler.AuthenticateAsync();
await handler.ChallengeAsync(new AuthenticationProperties());
Assert.True(result.None);
Assert.Equal(StatusCodes.Status401Unauthorized, httpContext.Response.StatusCode);
Assert.Equal("Bearer", httpContext.Response.Headers.WWWAuthenticate.ToString());
}
/// <summary>An API key holding the admin scope satisfies the metrics requirement.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Requirement_ApiKeyWithAdminScope_Succeeds()
{
Assert.True(await EvaluateAsync(ApiKeyPrincipal(GatewayScopes.Admin)));
}
/// <summary>An API key without the admin scope does not satisfy the requirement.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Requirement_ApiKeyWithoutAdminScope_Fails()
{
Assert.False(await EvaluateAsync(ApiKeyPrincipal(GatewayScopes.EventsRead, GatewayScopes.InvokeRead)));
}
/// <summary>A scope claim counts only on an identity the metrics scheme minted from a verified key.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Requirement_ScopeClaimOnForeignIdentity_Fails()
{
ClaimsPrincipal principal = new(new ClaimsIdentity(
[new Claim(MetricsAuthorizationDefaults.ScopeClaimType, GatewayScopes.Admin)],
DashboardAuthenticationDefaults.AuthenticationScheme));
Assert.False(await EvaluateAsync(principal));
}
/// <summary>A dashboard login holding a real dashboard role satisfies the requirement.</summary>
/// <param name="role">The dashboard role.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
[Theory]
[InlineData(DashboardRoles.Admin)]
[InlineData(DashboardRoles.Viewer)]
public async Task Requirement_DashboardLoginWithRole_Succeeds(string role)
{
ClaimsPrincipal principal = new(new ClaimsIdentity(
[new Claim(ClaimTypes.Name, "operator"), new Claim(ClaimTypes.Role, role)],
DashboardAuthenticationDefaults.AuthenticationScheme));
Assert.True(await EvaluateAsync(principal));
}
/// <summary>An unauthenticated principal (anonymous localhost included) never satisfies it.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Requirement_Unauthenticated_Fails()
{
ClaimsPrincipal principal = new(new ClaimsIdentity([new Claim(ClaimTypes.Role, DashboardRoles.Admin)]));
Assert.False(await EvaluateAsync(principal));
}
private static async Task<bool> EvaluateAsync(ClaimsPrincipal principal)
{
MetricsAccessRequirement requirement = new();
AuthorizationHandlerContext context = new([requirement], principal, resource: null);
await new MetricsAccessHandler().HandleAsync(context);
return context.HasSucceeded;
}
private static ClaimsPrincipal ApiKeyPrincipal(params string[] scopes)
{
List<Claim> claims = [new Claim(ClaimTypes.Name, "scraper")];
claims.AddRange(scopes.Select(scope => new Claim(MetricsAuthorizationDefaults.ScopeClaimType, scope)));
return new ClaimsPrincipal(new ClaimsIdentity(claims, MetricsAuthorizationDefaults.AuthenticationScheme));
}
private static async Task<AuthenticateResult> AuthenticateAsync(
IApiKeyVerifier verifier,
HttpContext httpContext,
ApiKeyFailureLimiter? limiter = null)
{
MetricsAuthenticationHandler handler = await CreateHandlerAsync(verifier, httpContext, limiter);
return await handler.AuthenticateAsync();
}
private static async Task<MetricsAuthenticationHandler> CreateHandlerAsync(
IApiKeyVerifier verifier,
HttpContext httpContext,
ApiKeyFailureLimiter? limiter = null)
{
MetricsAuthenticationHandler handler = new(
new StaticOptionsMonitor(),
NullLoggerFactory.Instance,
UrlEncoder.Default,
verifier,
limiter ?? new ApiKeyFailureLimiter(1000, TimeSpan.FromMinutes(1), 1024, 0, TimeSpan.Zero, TimeProvider.System),
new AuthenticationSchemeProvider(Options.Create(new AuthenticationOptions())),
new GatewayMetrics());
await handler.InitializeAsync(
new AuthenticationScheme(
MetricsAuthorizationDefaults.AuthenticationScheme,
displayName: null,
typeof(MetricsAuthenticationHandler)),
httpContext);
return handler;
}
private static DefaultHttpContext ContextWithAuthorization(string header)
{
DefaultHttpContext context = new();
context.Request.Headers.Authorization = header;
context.Connection.RemoteIpAddress = System.Net.IPAddress.Parse("198.51.100.7");
return context;
}
private static ApiKeyVerification Success(params string[] scopes) => new(
Succeeded: true,
Identity: new LibApiKeyIdentity(
KeyId: "scraper",
DisplayName: "Scraper",
Scopes: new HashSet<string>(scopes, StringComparer.Ordinal),
Constraints: null),
Failure: null);
private sealed class CountingVerifier(ApiKeyVerification result) : IApiKeyVerifier
{
/// <summary>Gets the number of verifications performed.</summary>
public int CallCount { get; private set; }
/// <summary>Gets the last authorization header presented.</summary>
public string? LastHeader { get; private set; }
/// <inheritdoc />
public Task<ApiKeyVerification> VerifyAsync(string authorizationHeader, CancellationToken ct)
{
CallCount++;
LastHeader = authorizationHeader;
return Task.FromResult(result);
}
}
private sealed class StaticOptionsMonitor : IOptionsMonitor<AuthenticationSchemeOptions>
{
/// <inheritdoc />
public AuthenticationSchemeOptions CurrentValue { get; } = new();
/// <inheritdoc />
public AuthenticationSchemeOptions Get(string? name) => CurrentValue;
/// <inheritdoc />
public IDisposable? OnChange(Action<AuthenticationSchemeOptions, string?> listener) => null;
}
}