using OpenWaf.Domain.Engine; using OpenWaf.Domain.Policy; using OpenWaf.Infrastructure.Geo; using OpenWaf.Infrastructure.Persistence; namespace OpenWaf.Edge.Pipeline; /// /// The only place in the pipeline that may refuse a request. Everything else /// observes; this decides. That is the point of the design (OPEN-2): the /// reference repo runs three guards that each short-circuit on their own, which /// makes precedence a function of registration order. Here the order is fixed /// in and the answer is one value. /// /// It reads an in-memory snapshot and never touches the database, so the cost /// on the request path is a dictionary lookup plus, when the geo pillar is on, /// one memory-mapped MMDB read. /// public sealed class EdgeGuardMiddleware( RequestDelegate next, EdgeStateStore state, IGeoIpLookup geo, ILogger log) { public async Task InvokeAsync(HttpContext ctx) { var snapshot = state.GetOrRefresh(); var path = ctx.Request.Path.Value ?? "/"; var now = DateTimeOffset.UtcNow; var ip = ClientIp.Resolve(ctx, snapshot.Policy.TrustProxyHeaders); var country = snapshot.Policy.Geo == GeoMode.Off ? null : ClientIp.HeaderCountry(ctx) ?? geo.Lookup(ip); var decision = DecisionEngine.Decide(snapshot, ip, path, now, country); if (!decision.IsBlocked) { await next(ctx); return; } log.LogInformation( "edge: {Verdict} {Ip} {Path} ({Reason})", decision.Verdict, ip, path, decision.Reason ?? "-"); ctx.Response.StatusCode = decision.StatusCode; switch (decision.Verdict) { case EdgeVerdict.BlockOperator when decision.Location is not null: ctx.Response.Headers.Location = decision.Location; await ctx.Response.WriteAsync(string.Empty); break; case EdgeVerdict.BlockEngine: if (decision.Location is not null) ctx.Response.Headers.Location = decision.Location; if (decision.ExpiresAt is { } expires) { var seconds = Math.Max(1, (int)Math.Ceiling((expires - now).TotalSeconds)); ctx.Response.Headers.RetryAfter = seconds.ToString(); } await ctx.Response.WriteAsJsonAsync(new BlockedBody( "blocked_by_policy", decision.Reason, decision.ExpiresAt?.ToString("O"), "This decision was made automatically from the responses your source produced. " + "If it is wrong, an operator can clear it.")); break; case EdgeVerdict.GeoReject: await ctx.Response.WriteAsJsonAsync(new BlockedBody( "region_not_supported", decision.Reason, null, "Location is inferred from the address, not known about you; VPNs and misattributed " + "ranges are wrong sometimes. If you are a real customer, an operator can allow you in.")); break; default: await ctx.Response.WriteAsync(string.Empty); break; } } } internal sealed record BlockedBody(string Error, string? Reason, string? ExpiresAt, string Note);