using System.Net; using System.Net.Sockets; using Microsoft.AspNetCore.Http; namespace OpenWaf.Tests.Integration; /// /// The application behind the edge. It is deliberately dumb: it answers a /// configured status per path and counts what it was asked. The whole point of /// the feature is the edge reacting to what the upstream answered, so the test /// needs to control that answer and observe whether the edge noticed. /// internal sealed class FakeUpstream : IAsyncDisposable { private readonly HttpListener _listener = new(); private readonly CancellationTokenSource _cts = new(); public string Address { get; } public int RequestCount; public List Paths = []; /// What the upstream was asked to hold, per request that sent a /// body. The edge's alert push POSTs one, and the whole point of that /// feature is what arrives at the endpoint — a path alone cannot show it. /// Recorded only when a body was sent, so the proxy traffic that dominates /// a run stays an empty list. public List Bodies = []; /// What this upstream answers for a path. public Func StatusFor { get; set; } = _ => StatusCodes.Status404NotFound; public static FakeUpstream Start() { var port = FreePort(); var upstream = new FakeUpstream($"http://127.0.0.1:{port}/"); upstream._listener.Start(); _ = upstream.LoopAsync(); return upstream; } private FakeUpstream(string address) { Address = address; _listener.Prefixes.Add(address); } private async Task LoopAsync() { try { while (!_cts.IsCancellationRequested) { var context = await _listener.GetContextAsync(); var path = context.Request.Url?.AbsolutePath ?? "/"; Interlocked.Increment(ref RequestCount); lock (Paths) Paths.Add(path); if (context.Request.HasEntityBody) { using var reader = new System.IO.StreamReader(context.Request.InputStream); var body = reader.ReadToEnd(); lock (Bodies) Bodies.Add(body); } context.Response.StatusCode = StatusFor(path); context.Response.OutputStream.Close(); } } catch { // Listener closed at teardown — the expected way out. } } private static int FreePort() { var probe = new TcpListener(IPAddress.Loopback, 0); probe.Start(); var port = ((IPEndPoint)probe.LocalEndpoint).Port; probe.Stop(); return port; } public async ValueTask DisposeAsync() { _cts.Cancel(); _listener.Close(); await Task.CompletedTask; } }