Files
Flypaper/test/Flypaper.Tests/Http/RequestCaptureTests.cs
T
TomandClaude Sonnet 5.5 b559f83550
Build and deploy / build (push) Successful in 1m29s
Release / image (push) Successful in 1m53s
Build and deploy / deploy (push) Successful in 30s
Release / release (push) Successful in 6s
Record request headers and bodies and show them per catch
Headers and the first 8 KB of the body are stored unmasked for 30 days,
read alongside the response so the trap answers as before. MCP get_request
and the expanded catch row show them. Changelog prepared for 0.10.0.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 21:47:28 +01:00

121 lines
4.9 KiB
C#

using System.Net.Sockets;
using System.Text;
using Flypaper.Core;
using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
using Flypaper.Http;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NSubstitute;
using Shouldly;
namespace Flypaper.Tests.Http;
public sealed class RequestCaptureTests
{
[Fact]
public async Task Records_headers_and_body_without_masking_and_without_proxy_headers()
{
var (trapEvent, _) = await SendAsync(
"POST /wp-login.php HTTP/1.1\r\nHost: trap.example\r\nAuthorization: Basic YWRtaW46YWRtaW4=\r\nCookie: session=abc\r\n"
+ "X-Real-IP: 203.0.113.9\r\nX-Forwarded-For: 203.0.113.9\r\nContent-Length: 17\r\n\r\nlog=admin&pwd=123");
var request = trapEvent.Request.ShouldNotBeNull();
request.Body.ShouldBe("log=admin&pwd=123");
request.ContentLength.ShouldBe(17);
request.Truncated.ShouldBeFalse();
request.Headers.ShouldContain("Authorization: Basic YWRtaW46YWRtaW4=");
request.Headers.ShouldContain("Cookie: session=abc");
request.Headers.ShouldNotContain("X-Real-IP");
request.Headers.ShouldNotContain("X-Forwarded-For");
}
[Fact]
public async Task Cuts_large_bodies_and_escapes_binary_data()
{
var body = "\0\u0001A" + new string('x', 20_000);
var (trapEvent, _) = await SendAsync($"POST / HTTP/1.1\r\nHost: trap.example\r\nContent-Length: {body.Length}\r\n\r\n{body}");
var request = trapEvent.Request.ShouldNotBeNull();
request.Body.ShouldNotBeNull().ShouldStartWith("\\x00\\x01Axxx");
request.Body.Length.ShouldBe(8192 + 6);
request.ContentLength.ShouldBe(body.Length);
request.Truncated.ShouldBeTrue();
}
[Fact]
public async Task A_body_that_never_arrives_neither_delays_nor_ends_the_drip()
{
var (trapEvent, firstByte) = await SendAsync(
"POST /.env HTTP/1.1\r\nHost: trap.example\r\nContent-Length: 500\r\n\r\npartial",
holdFor: TimeSpan.FromSeconds(8));
firstByte.ShouldBeLessThan(TimeSpan.FromSeconds(2));
trapEvent.Outcome.ShouldBe(TrapOutcome.Timeout);
trapEvent.Duration.ShouldBeGreaterThan(TimeSpan.FromSeconds(7));
trapEvent.Request.ShouldNotBeNull().Body.ShouldBe("partial");
trapEvent.Request!.Truncated.ShouldBeTrue();
}
[Fact]
public async Task Records_nothing_when_switched_off()
{
var (trapEvent, _) = await SendAsync("GET /.env HTTP/1.1\r\nHost: trap.example\r\n\r\n", capture: false);
trapEvent.Request.ShouldBeNull();
}
private static async Task<(TrapEvent Event, TimeSpan FirstByte)> SendAsync(string rawRequest, TimeSpan? holdFor = null, bool capture = true)
{
var published = new TaskCompletionSource<TrapEvent>(TaskCreationOptions.RunContinuationsAsynchronously);
var sink = Substitute.For<ITrapEventSink>();
sink.When(s => s.Publish(Arg.Any<TrapEvent>())).Do(call => published.TrySetResult(call.Arg<TrapEvent>()));
var builder = WebApplication.CreateBuilder();
builder.WebHost.UseUrls("http://127.0.0.1:0");
builder.Configuration["Flypaper:MaxHoldDuration"] = (holdFor ?? TimeSpan.FromMilliseconds(500)).ToString("c");
builder.Configuration["Flypaper:IgnorePrivateNetworks"] = "false";
builder.Configuration["Flypaper:CaptureRequests"] = capture ? "true" : "false";
builder.Services.AddSingleton(sink);
builder.Services.AddFlypaperCore(builder.Configuration);
builder.Services.AddFlypaperHttp(builder.Configuration);
await using var app = builder.Build();
app.UseFlypaper();
await app.StartAsync();
var address = new Uri(app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses.First());
using var client = new TcpClient();
await client.ConnectAsync(address.Host, address.Port);
var stream = client.GetStream();
var started = System.Diagnostics.Stopwatch.StartNew();
await stream.WriteAsync(Encoding.Latin1.GetBytes(rawRequest));
var buffer = new byte[4096];
await stream.ReadAsync(buffer).AsTask().WaitAsync(TimeSpan.FromSeconds(10));
var firstByte = started.Elapsed;
_ = DrainAsync(stream, buffer);
var trapEvent = await published.Task.WaitAsync(TimeSpan.FromSeconds(20));
client.Close();
await app.StopAsync();
return (trapEvent, firstByte);
}
private static async Task DrainAsync(Stream stream, byte[] buffer)
{
try
{
while (await stream.ReadAsync(buffer) > 0)
{
}
}
catch (Exception ex) when (ex is IOException or ObjectDisposedException)
{
}
}
}