The edge-wide budget is one number for the whole site, and for a login path that number is always wrong: a hundred requests a minute does not stop a credential-stuffing run that makes twenty attempts a minute — twenty looks like a person — while five a minute locks an honest office behind one NAT out of every page they own. The only way to make both statements true is to price the paths differently. The rulings this had to make, and the answer each one got: * A rate rule is not a path rule. A path rule refuses a request because of what it asked for; a budget refuses it because of how often that source asked. The pattern language is shared because the thing being described — this path and what hangs off it — is the same. * Crossing a budget writes no engine ban. The claim is about one path, so a ban would refuse the rest of the site as punishment for a login-page rate. The answer is 429 with Retry-After for the rest of that source's window, and the reason names the rule, its count, its limit and the pattern it was written for. * The counters are a separate tracker, not a scope inside RateTracker. The edge-wide counter reads its limit and window from the policy; a rule carries its own. One map whose parameters change per entry is a map whose eviction and idle rules stop meaning anything. * The budgets hang off rateMode rather than getting a switch of their own: Enforce refuses, Observe counts and raises one rate_breach alert per source per window naming the pattern, Off counts nothing at all. A half-counting edge is the state an operator cannot reason about. * A second live budget for one pattern is a 409 — two live numbers for one path mean the stricter one wins by accident rather than by the operator's choice. * The bounds are the policy's own (1..100000 requests, 1..3600 seconds), so one vocabulary of numbers covers both budgets and a document cannot bring in a budget the API would have refused. * The listing answers with three counters — sources counted, windows running, over budget now — because "nobody has blown this" and "nobody can" look identical on paper and are different decisions. What the runs caught, in order: * The smoke scene first ran on 198.51.100.0/24, which an earlier scene of the same gate allowlists. An allowlisted source never reaches the counter, so the scene would have printed a row of 200s while measuring nothing. It runs on TEST-NET-1 now. * The console scene drew three 404s of its own and the streak pillar banned the address, so the reopen assertion read the streak's 403 instead of the absence of the budget. The engine list is cleared before that probe and the comment says which pillar the clearing belongs to. * The compose assertion compared a JSON boolean against the word "yes". * The change-log vocabulary test still listed six sections; there are seven now. * A unit expectation counted requests where the tracker holds windows: one (rule, source) pair is one window, and the count inside it is what the budget is measured against. Gates at this commit, each stage on its own: build 0 warnings / 0 errors, unit 361/361, integration 337/337 in 30 s, console 120 assertions 0 failed, smoke passed 169 failed 0, compose 300 passed 0 failed against the built image at 262 MB, 0 containers left behind. Refs OPEN-68.
350 lines
17 KiB
C#
350 lines
17 KiB
C#
using OpenWaf.Domain.Engine;
|
|
using OpenWaf.Domain.Policy;
|
|
using OpenWaf.Domain.Security;
|
|
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,
|
|
RateRuleTracker rateRules,
|
|
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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// One source against one path budget (OPEN-68). True means the answer is
|
|
/// already written. The refusal is a pause on that path for the rest of that
|
|
/// rule's window and nothing more: no engine ban is written, because the
|
|
/// claim a path budget makes is about one path, and banning the source would
|
|
/// refuse the rest of the site for a login-page rate.
|
|
/// </summary>
|
|
/// <summary>Every live path budget whose pattern covers this path. The scan
|
|
/// is the same linear loop the path rules already pay, over a list capped by
|
|
/// the same bound, so the cost on a request is bounded by what the operator
|
|
/// wrote rather than by what the visitor sent.</summary>
|
|
private async Task<bool> RateRulePillarAsync(
|
|
HttpContext ctx, EdgeSnapshot snapshot, string key, string path, DateTimeOffset now)
|
|
{
|
|
foreach (var rule in snapshot.RateRules)
|
|
{
|
|
if (!rule.IsLive(now)) continue;
|
|
if (!PathPattern.Matches(rule.Pattern, path)) continue;
|
|
if (await RateRulePillarAsync(ctx, rule, key, path, now)) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
private async Task<bool> RateRulePillarAsync(
|
|
HttpContext ctx, RateRule rule, string key, string path, DateTimeOffset now)
|
|
{
|
|
var counted = rateRules.Record(rule, key, now);
|
|
if (!counted.OverBudget) return false;
|
|
|
|
if (ctx.Items.TryGetValue("openwaf.rateMode", out var mode) && mode is RateMode.Observe)
|
|
{
|
|
// The dry run for a path budget, same as the edge-wide one: the
|
|
// operator finds out whether the number is a defence or their own
|
|
// traffic before it refuses anything.
|
|
if (counted.BreachStarted)
|
|
await alerts.RaiseAsync(
|
|
"rate_breach", key, counted.Count, null, path,
|
|
$"{counted.Count} requests in {rule.WindowSeconds} s against a path budget of "
|
|
+ $"{rule.LimitPerWindow} for {rule.Pattern} (mode=Observe, nothing was blocked)",
|
|
ctx.RequestAborted);
|
|
return false;
|
|
}
|
|
|
|
ctx.Response.StatusCode = 429;
|
|
var seconds = Math.Max(1, (int)Math.Ceiling((counted.WindowEnd - now).TotalSeconds));
|
|
ctx.Response.Headers.RetryAfter = seconds.ToString();
|
|
var reason = $"rate_rule_{rule.Id}_{counted.Count}_of_{rule.LimitPerWindow}_for_{rule.Pattern}";
|
|
log.LogInformation("edge: {Verdict} {Ip} {Path} ({Count} over a path budget of {Limit} for {Pattern})",
|
|
EdgeVerdict.BlockRate, ctx.Connection.RemoteIpAddress, path, counted.Count,
|
|
rule.LimitPerWindow, rule.Pattern);
|
|
await WriteRefusalAsync(ctx, BlockPage.PrefersHtml(ctx.Request.Headers.Accept.ToString()),
|
|
EdgeVerdict.BlockRate, reason, counted.WindowEnd, seconds, now,
|
|
() => ctx.Response.WriteAsJsonAsync(new BlockedBody(
|
|
"rate_limited",
|
|
reason,
|
|
counted.WindowEnd.ToString("O"),
|
|
"This source asked for this part of the site more often than it allows. "
|
|
+ "The pause ends on its own and covers only this path; an operator can raise "
|
|
+ "or remove the budget, or allowlist the address.")));
|
|
|
|
if (!counted.BreachStarted) return true;
|
|
|
|
// One breach per source per window, one alert. No ban row: see the
|
|
// comment on this method.
|
|
await alerts.RaiseAsync(
|
|
"rate_breach", key, counted.Count, null, path,
|
|
$"{counted.Count} requests in {rule.WindowSeconds} s against a path budget of "
|
|
+ $"{rule.LimitPerWindow} for {rule.Pattern} (mode=Enforce, 429 on that path for the rest "
|
|
+ "of the window; no ban was written, the pause is for this path only)",
|
|
CancellationToken.None);
|
|
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)
|
|
{
|
|
ctx.Items["openwaf.rateMode"] = snapshot.Policy.Rate;
|
|
if (await RatePillarAsync(ctx, snapshot.Policy, rateKey, path, country, now)
|
|
|| await RateRulePillarAsync(ctx, snapshot, rateKey, path, 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);
|