Files
openwaf/dotnet/OpenWaf.Edge/Pipeline/EdgeGuardMiddleware.cs
T
Pavlo Ratushnyi 892cec172f the edge answers /metrics in the format the operator's alerting already reads
OPEN-58. The edge had one push surface — the alert webhook, at-most-once, for the four things it can alert about — and every other number it keeps was readable by a human on /admin-api/state and by nothing else. 'The ban writes have been failing for forty minutes' is a pull question with a threshold on it, so it belongs in Prometheus, where the operator already keeps their alerting.

The exposition is a pure type in the domain project (PrometheusText) rather than a metrics library: the numbers already exist in one place, and the parts that break a scrape — label escaping, HELP on one line, the name alphabet, NaN, sample ordering — are testable as a string without a running edge. EdgeCounterLedger adds the one piece of new state, counted at the single place that may refuse a request, so the verdict totals add up to the requests answered.

Three rules, each a decision: aggregate only (no source key, address, path, user agent or operator note anywhere in the body, and the only labels are bounded sets written in the code — a label per source is a cardinality explosion and an IP leak); no query per scrape (every number is already in memory, so a scrape cannot be what makes an unhealthy database unhealthy for the request path); and behind the same token as the admin API, on an always-pass prefix, so an edge that has blocked the operator's own address is still watchable. The token check moved out of the admin group into AdminAuth rather than being copied.

Three things the run caught. The 'closed surface' assertion passed alone and failed under the gate: Program falls back to OPENWAF_ADMIN_TOKEN when the configured token is blank and the gate scripts export a throwaway value into the test process, so a blank token there is an OPEN surface — 401, not 404. The smoke and compose sample helpers grepped for the metric name and matched the '# HELP' line first, answering with the help text's last word; they now match the line prefix. And EndpointFilterDelegate is not what AddEndpointFilter accepts — the two have different arities, which only shows when the filter is a method rather than a lambda at the call site.

Gates on this tree: build 0 warnings / 0 errors, unit 250/250, integration 236/236, smoke 60/0, compose 223/0 against the built image (261 MB), console 90/0.
2026-10-05 01:00:10 +02:00

271 lines
13 KiB
C#

using OpenWaf.Domain.Engine;
using OpenWaf.Domain.Policy;
using OpenWaf.Domain.Responses;
using OpenWaf.Edge.Observability;
using OpenWaf.Infrastructure.Geo;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Edge.Pipeline;
/// <summary>
/// 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 <see cref="DecisionEngine"/> 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.
/// </summary>
public sealed class EdgeGuardMiddleware(
RequestDelegate next,
EdgeStateStore state,
IGeoIpLookup geo,
RuleMatchLedger ledger,
RateTracker rates,
BlockStore blocks,
AlertWriter alerts,
EdgeCounterLedger counters,
ILogger<EdgeGuardMiddleware> log)
{
/// <summary>An observe-action rule matched and the request is going
/// through. Count it, and alert at most once per rule per interval — the
/// same storm rule the 5xx alerts learned.</summary>
private async Task ObserveRuleMatchAsync(EdgeDecision decision, string path, CancellationToken ct)
{
if (decision.Reason is not { Length: > 5 } reason) return;
if (!long.TryParse(reason[5..], out var ruleId)) return;
var report = ledger.RecordAndReport(ruleId, DateTimeOffset.UtcNow);
if (report is not (var matches, var since)) return;
await alerts.RaiseAsync(
"rule_match", decision.SourceKey ?? "unknown", matches, null, path,
$"an observe rule matched {matches} {(matches == 1 ? "time" : "times")} " +
$"since {since:O}: {decision.RulePattern} (action=observe, nothing was blocked)", ct);
}
/// <summary>
/// Count this source's request and, over the budget, answer it here.
/// True means the answer is already written and the request must not reach
/// the origin; false means it may go through.
/// </summary>
private async Task<bool> RatePillarAsync(
HttpContext ctx, EdgePolicy policy, string key, string path, string? country, DateTimeOffset now)
{
var rate = rates.Record(key, policy, now);
if (!rate.OverBudget) return false;
if (policy.Rate == RateMode.Observe)
{
// The dry run says so once per source per window, and lets the
// request through. This is how an operator finds out whether the
// budget is a defence or a denial of their own traffic before it
// refuses anything.
if (rate.BreachStarted)
await alerts.RaiseAsync(
"rate_breach", key, rate.Count, null, path,
$"{rate.Count} requests in {policy.RateWindow.TotalSeconds:0.#} s against a budget of "
+ $"{policy.RateLimitPerWindow} (mode=Observe, nothing was blocked)", ctx.RequestAborted);
return false;
}
ctx.Response.StatusCode = 429;
var seconds = Math.Max(1, (int)Math.Ceiling((rate.WindowEnd - now).TotalSeconds));
ctx.Response.Headers.RetryAfter = seconds.ToString();
log.LogInformation("edge: {Verdict} {Ip} {Path} ({Count} over a budget of {Limit})",
EdgeVerdict.BlockRate, ctx.Connection.RemoteIpAddress, ctx.Request.Path.Value ?? "/",
rate.Count, policy.RateLimitPerWindow);
await WriteRefusalAsync(ctx, BlockPage.PrefersHtml(ctx.Request.Headers.Accept.ToString()),
EdgeVerdict.BlockRate, $"rate_{rate.Count}_of_{policy.RateLimitPerWindow}",
rate.WindowEnd, seconds, now,
() => ctx.Response.WriteAsJsonAsync(new BlockedBody(
"rate_limited",
$"rate_{rate.Count}_of_{policy.RateLimitPerWindow}",
rate.WindowEnd.ToString("O"),
"This source asked more often than this site allows. The pause ends on its own; "
+ "if it is wrong, an operator can raise the budget or allowlist the address.")));
if (!rate.BreachStarted) return true;
// One breach, one alert, one ban. Everything else in the same window is
// the same news, and a write per request is how a defence turns into
// write amplification for the attacker to aim at the database.
var userAgent = ctx.Request.Headers.UserAgent.ToString();
if (userAgent.Length > 256) userAgent = userAgent[..256];
// Deliberately not ctx.RequestAborted: the 429 has already been
// written, so the client is free to hang up at this exact moment, and a
// cancelled token would drop the one row that makes the stop outlast the
// window. Same ruling as the streak ban in ResponseObservationMiddleware.
await alerts.RaiseAsync(
"rate_breach", key, rate.Count, null, path,
$"{rate.Count} requests in {policy.RateWindow.TotalSeconds:0.#} s against a budget of "
+ $"{policy.RateLimitPerWindow} (mode=Enforce, 429 for the rest of the window)",
CancellationToken.None);
var ban = await blocks.BanForRateAsync(
key, rate.Count, policy.RateLimitPerWindow, policy.RateWindow,
path.Length == 0 ? null : path, userAgent.Length == 0 ? null : userAgent,
country, null, null, now, CancellationToken.None);
if (ban is not null)
log.LogWarning("edge: rate ban {Key} until {Until} — {Count} over a budget of {Limit}",
key, ban.ExpiresAt, rate.Count, policy.RateLimitPerWindow);
return true;
}
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)
{
if (decision.Verdict == EdgeVerdict.PassRuleObserved)
await ObserveRuleMatchAsync(decision, path, ctx.RequestAborted);
// 7. rate — the volume pillar (OPEN-56), and the last thing that
// runs before the origin is asked. It sits here rather than inside
// DecisionEngine for one reason: every other pillar reads the
// snapshot, which is built off the request path, while a count has
// to be kept while the requests are arriving. Sitting below the
// whole ordered list is also what makes the exemptions exact — an
// always-pass prefix, an allowlisted address, a matched rule, a
// block or a geo refusal has already been answered, so it never
// reaches the counter and the budget counts exactly the requests
// that would have cost the origin.
if (snapshot.Policy.Rate != RateMode.Off && decision.Verdict == EdgeVerdict.Pass)
{
var rateKey = string.IsNullOrWhiteSpace(ip)
? string.Empty
: SourceKey.For(ip, snapshot.Policy);
if (rateKey.Length > 0
&& await RatePillarAsync(ctx, snapshot.Policy, rateKey, path, country, now))
{
counters.Record(EdgeVerdict.BlockRate);
return;
}
}
// OPEN-58: the one number for the one decision. Counted here, at the
// single place that may refuse a request, and counted as the final
// verdict — the rate pillar above has already returned for anything it
// refused, so nothing is counted twice and the verdict totals add up to
// the requests this edge answered.
counters.Record(decision.Verdict);
await next(ctx);
return;
}
counters.Record(decision.Verdict);
log.LogInformation(
"edge: {Verdict} {Ip} {Path} ({Reason})", decision.Verdict, ip, path, decision.Reason ?? "-");
ctx.Response.StatusCode = decision.StatusCode;
// OPEN-57: the refusal is written in the language of whoever asked. A
// browser named text/html in Accept, so it gets sentences; everything
// else — including `Accept: */*`, which is "I did not think about it"
// and is what curl, monitors and SDKs send — gets the JSON body it has
// always got. The status and the headers are decided before this line
// and are not touched by it: a 429 that turns into a friendly page must
// stay a 429.
var wantsHtml = BlockPage.PrefersHtml(ctx.Request.Headers.Accept.ToString());
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;
var engineRetry = 0;
if (decision.ExpiresAt is { } expires)
{
engineRetry = Math.Max(1, (int)Math.Ceiling((expires - now).TotalSeconds));
ctx.Response.Headers.RetryAfter = engineRetry.ToString();
}
await WriteRefusalAsync(ctx, wantsHtml, EdgeVerdict.BlockEngine, decision.Reason,
decision.ExpiresAt, engineRetry, now,
() => 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.BlockRule:
// The response names the rule by id, not by pattern. The id is
// enough for an operator — the page shows both side by side —
// while the pattern in a 403 body tells an anonymous visitor
// exactly which payload to change. The pattern goes to the log
// and to the alert, which are the operator's channels.
await WriteRefusalAsync(ctx, wantsHtml, EdgeVerdict.BlockRule, decision.Reason,
null, 0, now,
() => ctx.Response.WriteAsJsonAsync(new BlockedBody(
"blocked_by_rule",
decision.Reason,
null,
"This path matches a rule written for this site. If it is wrong, " +
"the operator who wrote it can remove it.")));
break;
case EdgeVerdict.GeoReject:
await WriteRefusalAsync(ctx, wantsHtml, EdgeVerdict.GeoReject, decision.Reason,
null, 0, now,
() => 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:
// An operator block that is not a redirect has no reference to
// show: its reason is the operator's own note about a source,
// not a message to this visitor. The page says the fact and
// points at the operator, which is all the visitor can act on.
if (wantsHtml)
{
ctx.Response.ContentType = "text/html; charset=utf-8";
await ctx.Response.WriteAsync(
BlockPage.Render(EdgeVerdict.BlockOperator, null, decision.ExpiresAt, 0, now));
}
else
{
await ctx.Response.WriteAsync(string.Empty);
}
break;
}
}
/// <summary>
/// One refusal, two bodies. The JSON is the answer that has always been
/// given, kept byte for byte for the clients that parse it; the page is the
/// same facts for the clients that render it.
/// </summary>
private static Task WriteRefusalAsync(
HttpContext ctx, bool wantsHtml, EdgeVerdict verdict, string? reference,
DateTimeOffset? expiresAt, int retryAfterSeconds, DateTimeOffset now, Func<Task> json)
{
if (!wantsHtml) return json();
ctx.Response.ContentType = "text/html; charset=utf-8";
return ctx.Response.WriteAsync(BlockPage.Render(verdict, reference, expiresAt, retryAfterSeconds, now));
}
}
internal sealed record BlockedBody(string Error, string? Reason, string? ExpiresAt, string Note);