513fa1aa16
Comment/XML-doc changes only: - add summaries to ~10k test methods, fixtures, fakes and helpers (+ <param> on theories, <returns> on async Task methods, <inheritdoc/> on interface implementations the checker can resolve) - strip ~2.6k project-tracking references (WP*, P*-*, row-NN, Task N, #NN, Component-0NN) from comments, keeping the explanatory text; reword false positives in comments only - real docs on fakes implementing BCL/library interfaces (IDisposable, ILogger, IOptionsMonitor, IAsyncLifetime) - reword the last 5 src/ false positives (CWE-1236, failures-1, year-0001, M365) Only non-comment edits: four one-line nested classes split across lines so members can carry docs. Build 0 errors / 0 warnings.
209 lines
9.0 KiB
C#
209 lines
9.0 KiB
C#
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.AspNetCore.Http.Features;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace ZB.MOM.WW.ScadaBridge.InboundAPI.Tests;
|
|
|
|
/// <summary>
|
|
/// The POST /api/{methodName} endpoint must be
|
|
/// gated to the active central node and must cap the request body size. These
|
|
/// behaviours are enforced by <see cref="InboundApiEndpointFilter"/>.
|
|
/// </summary>
|
|
public class EndpointGatingTests
|
|
{
|
|
private static InboundApiEndpointFilter CreateFilter(InboundApiOptions? options = null) =>
|
|
new(NullLogger<InboundApiEndpointFilter>.Instance,
|
|
new TestOptionsMonitor<InboundApiOptions>(options ?? new InboundApiOptions()));
|
|
|
|
private static (DefaultHttpContext ctx, DefaultEndpointFilterInvocationContext invocation)
|
|
BuildInvocation(bool? activeNode, long? contentLength)
|
|
{
|
|
var services = new ServiceCollection();
|
|
if (activeNode.HasValue)
|
|
services.AddSingleton<IActiveNodeGate>(new StubActiveNodeGate(activeNode.Value));
|
|
|
|
var ctx = new DefaultHttpContext
|
|
{
|
|
RequestServices = services.BuildServiceProvider()
|
|
};
|
|
ctx.Request.Method = "POST";
|
|
if (contentLength.HasValue)
|
|
ctx.Request.ContentLength = contentLength.Value;
|
|
|
|
return (ctx, new DefaultEndpointFilterInvocationContext(ctx));
|
|
}
|
|
|
|
private static EndpointFilterDelegate NextSentinel(out Func<bool> wasCalled)
|
|
{
|
|
var called = false;
|
|
wasCalled = () => called;
|
|
return _ =>
|
|
{
|
|
called = true;
|
|
return ValueTask.FromResult<object?>(Results.Ok("handler-ran"));
|
|
};
|
|
}
|
|
|
|
// --- Standby node must not serve inbound API calls ---
|
|
|
|
/// <summary>Verifies that a standby node short-circuits with a 503 and does not run the handler.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task StandbyNode_ShortCircuitsWith503_AndDoesNotRunHandler()
|
|
{
|
|
var (_, invocation) = BuildInvocation(activeNode: false, contentLength: 2);
|
|
var next = NextSentinel(out var handlerRan);
|
|
|
|
var result = await CreateFilter().InvokeAsync(invocation, next);
|
|
|
|
Assert.False(handlerRan());
|
|
var status = Assert.IsAssignableFrom<IStatusCodeHttpResult>(result);
|
|
Assert.Equal(StatusCodes.Status503ServiceUnavailable, status.StatusCode);
|
|
}
|
|
|
|
/// <summary>Verifies that an active node passes the gate and runs the handler.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task ActiveNode_PassesGate_RunsHandler()
|
|
{
|
|
var (_, invocation) = BuildInvocation(activeNode: true, contentLength: 2);
|
|
var next = NextSentinel(out var handlerRan);
|
|
|
|
await CreateFilter().InvokeAsync(invocation, next);
|
|
|
|
Assert.True(handlerRan());
|
|
}
|
|
|
|
/// <summary>Verifies that the handler runs when no gate is registered.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task NoGateRegistered_PassesGate_RunsHandler()
|
|
{
|
|
// When no IActiveNodeGate is registered (non-clustered host), gating is
|
|
// opt-in and defaults to "allow" so the endpoint is still served.
|
|
var (_, invocation) = BuildInvocation(activeNode: null, contentLength: 2);
|
|
var next = NextSentinel(out var handlerRan);
|
|
|
|
await CreateFilter().InvokeAsync(invocation, next);
|
|
|
|
Assert.True(handlerRan());
|
|
}
|
|
|
|
// --- Request body size must be capped ---
|
|
|
|
/// <summary>Verifies that an oversized body short-circuits with a 413 and does not run the handler.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task OversizedBody_ShortCircuitsWith413_AndDoesNotRunHandler()
|
|
{
|
|
var options = new InboundApiOptions();
|
|
var (_, invocation) = BuildInvocation(
|
|
activeNode: true, contentLength: options.MaxRequestBodyBytes + 1);
|
|
var next = NextSentinel(out var handlerRan);
|
|
|
|
var result = await CreateFilter(options).InvokeAsync(invocation, next);
|
|
|
|
Assert.False(handlerRan());
|
|
var status = Assert.IsAssignableFrom<IStatusCodeHttpResult>(result);
|
|
Assert.Equal(StatusCodes.Status413PayloadTooLarge, status.StatusCode);
|
|
}
|
|
|
|
/// <summary>Verifies that a body exactly at the limit runs the handler.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task BodyAtLimit_RunsHandler()
|
|
{
|
|
var options = new InboundApiOptions();
|
|
var (_, invocation) = BuildInvocation(
|
|
activeNode: true, contentLength: options.MaxRequestBodyBytes);
|
|
var next = NextSentinel(out var handlerRan);
|
|
|
|
await CreateFilter(options).InvokeAsync(invocation, next);
|
|
|
|
Assert.True(handlerRan());
|
|
}
|
|
|
|
/// <summary>Verifies that the filter caps the max request body size feature.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task FilterCapsMaxRequestBodySizeFeature()
|
|
{
|
|
// For chunked/unknown-length requests there is no Content-Length, so the
|
|
// filter must also cap the per-request body size feature so Kestrel rejects
|
|
// an oversized stream while it is being read.
|
|
var options = new InboundApiOptions();
|
|
var (ctx, invocation) = BuildInvocation(activeNode: true, contentLength: null);
|
|
ctx.Features.Set<IHttpMaxRequestBodySizeFeature>(new StubMaxBodySizeFeature());
|
|
var next = NextSentinel(out _);
|
|
|
|
await CreateFilter(options).InvokeAsync(invocation, next);
|
|
|
|
var feature = ctx.Features.Get<IHttpMaxRequestBodySizeFeature>();
|
|
Assert.Equal(options.MaxRequestBodyBytes, feature!.MaxRequestBodySize);
|
|
}
|
|
|
|
private sealed class StubActiveNodeGate : IActiveNodeGate
|
|
{
|
|
private readonly bool _isActive;
|
|
/// <summary>Initializes the gate with a fixed active-node answer.</summary>
|
|
/// <param name="isActive">Whether this node reports itself as active.</param>
|
|
public StubActiveNodeGate(bool isActive) => _isActive = isActive;
|
|
/// <inheritdoc />
|
|
public bool IsActiveNode => _isActive;
|
|
}
|
|
|
|
private sealed class StubMaxBodySizeFeature : IHttpMaxRequestBodySizeFeature
|
|
{
|
|
/// <summary>Gets a value indicating the feature is writable (always false).</summary>
|
|
public bool IsReadOnly => false;
|
|
/// <summary>Gets or sets the maximum request body size in bytes.</summary>
|
|
public long? MaxRequestBodySize { get; set; }
|
|
}
|
|
|
|
// --- InboundAPI hot-reload: options must be re-read per request, not cached at ctor time ---
|
|
|
|
/// <summary>Verifies that the body size cap hot-reloads without a restart.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task BodySizeCap_HotReloads_WithoutRestart()
|
|
{
|
|
var monitor = new TestOptionsMonitor<InboundApiOptions>(new InboundApiOptions { MaxRequestBodyBytes = 10 });
|
|
var filter = new InboundApiEndpointFilter(NullLogger<InboundApiEndpointFilter>.Instance, monitor);
|
|
|
|
var (_, firstInvocation) = BuildInvocation(activeNode: true, contentLength: 20);
|
|
var firstNext = NextSentinel(out var firstHandlerRan);
|
|
var firstResult = await filter.InvokeAsync(firstInvocation, firstNext);
|
|
|
|
Assert.False(firstHandlerRan());
|
|
var firstStatus = Assert.IsAssignableFrom<IStatusCodeHttpResult>(firstResult);
|
|
Assert.Equal(StatusCodes.Status413PayloadTooLarge, firstStatus.StatusCode);
|
|
|
|
monitor.CurrentValue = new InboundApiOptions { MaxRequestBodyBytes = 1024 * 1024 };
|
|
|
|
var (_, secondInvocation) = BuildInvocation(activeNode: true, contentLength: 20);
|
|
var secondNext = NextSentinel(out var secondHandlerRan);
|
|
await filter.InvokeAsync(secondInvocation, secondNext);
|
|
|
|
Assert.True(secondHandlerRan());
|
|
}
|
|
|
|
private sealed class TestOptionsMonitor<T> : IOptionsMonitor<T>
|
|
{
|
|
/// <summary>Initializes the monitor with a fixed current value.</summary>
|
|
/// <param name="currentValue">The value returned by the monitor.</param>
|
|
public TestOptionsMonitor(T currentValue) => CurrentValue = currentValue;
|
|
/// <summary>Gets the fixed options instance.</summary>
|
|
public T CurrentValue { get; set; }
|
|
/// <summary>Returns the fixed options instance regardless of name.</summary>
|
|
/// <param name="name">The named-options key, ignored.</param>
|
|
/// <returns>The fixed options instance.</returns>
|
|
public T Get(string? name) => CurrentValue;
|
|
/// <summary>Does nothing; the fake never raises change notifications.</summary>
|
|
/// <param name="listener">The change listener, ignored.</param>
|
|
/// <returns>Always null.</returns>
|
|
public IDisposable? OnChange(Action<T, string?> listener) => null;
|
|
}
|
|
}
|