78 lines
2.5 KiB
C#
78 lines
2.5 KiB
C#
using System.Net;
|
|
using Flypaper.Core.Abstractions;
|
|
using Flypaper.Core.Models;
|
|
using Flypaper.Core.Networking;
|
|
using Flypaper.Core.Runtime;
|
|
using Flypaper.Http.Matching;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.AspNetCore.Http.Features;
|
|
using Microsoft.AspNetCore.Server.Kestrel.Core.Features;
|
|
|
|
namespace Flypaper.Http.Middleware;
|
|
|
|
internal sealed class FlypaperMiddleware(
|
|
RequestDelegate next,
|
|
TrapMatcher matcher,
|
|
TrapRunner runner,
|
|
TimeProvider timeProvider)
|
|
{
|
|
public async Task InvokeAsync(HttpContext context)
|
|
{
|
|
var request = context.Request;
|
|
if (IsInternalHealthProbe(context) || matcher.Match(request.Host.Host, request.Path.Value) == TrapMatch.None)
|
|
{
|
|
await next(context);
|
|
return;
|
|
}
|
|
|
|
var session = new TrapSession(
|
|
Guid.NewGuid(),
|
|
TrapProtocol.Http,
|
|
context.Connection.RemoteIpAddress ?? IPAddress.None,
|
|
timeProvider.GetUtcNow());
|
|
|
|
var trapContext = new TrapContext(
|
|
session,
|
|
$"{request.Method} {request.Host}{request.Path}{request.QueryString}",
|
|
request.Headers.UserAgent.ToString());
|
|
|
|
var outcome = await runner.RunAsync(
|
|
trapContext,
|
|
ct => OpenChannelAsync(context, session, ct),
|
|
context.RequestAborted);
|
|
|
|
if (outcome == TrapOutcome.Rejected && !context.Response.HasStarted)
|
|
{
|
|
context.Response.StatusCode = StatusCodes.Status404NotFound;
|
|
}
|
|
}
|
|
|
|
private static bool IsInternalHealthProbe(HttpContext context) =>
|
|
context.Request.Path.Equals(HttpTrapOptions.HealthPath, StringComparison.OrdinalIgnoreCase)
|
|
&& context.Connection.RemoteIpAddress is { } remoteIp
|
|
&& PrivateNetworks.Contains(remoteIp);
|
|
|
|
private static async ValueTask<ITrapChannel> OpenChannelAsync(
|
|
HttpContext context,
|
|
TrapSession session,
|
|
CancellationToken ct)
|
|
{
|
|
var minDataRate = context.Features.Get<IHttpMinResponseDataRateFeature>();
|
|
if (minDataRate is not null)
|
|
{
|
|
minDataRate.MinDataRate = null;
|
|
}
|
|
|
|
context.Features.Get<IHttpResponseBodyFeature>()?.DisableBuffering();
|
|
|
|
var response = context.Response;
|
|
response.StatusCode = StatusCodes.Status200OK;
|
|
response.ContentType = "text/html; charset=utf-8";
|
|
response.Headers.CacheControl = "no-store";
|
|
response.Headers["X-Accel-Buffering"] = "no";
|
|
await response.StartAsync(ct);
|
|
|
|
return new HttpTrapChannel(session, response);
|
|
}
|
|
}
|