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.
173 lines
8.6 KiB
C#
173 lines
8.6 KiB
C#
using OpenWaf.Domain.Engine;
|
|
using OpenWaf.Domain.Policy;
|
|
|
|
namespace OpenWaf.Domain.Security;
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// The portable shape of an operator's decisions (OPEN-61).
|
|
//
|
|
// Every one of these rows can already be written through the admin API, one
|
|
// call per row. What cannot be done today is move them: an operator running N
|
|
// edges writes every rule N times, a new deployment starts empty, and a
|
|
// destructive change has nothing to be undone from. This is the multi-instance
|
|
// finding of research/2026-10-01-multi-instance/ one level up — SharedStreaks
|
|
// shares the counters, nothing shares the decisions.
|
|
//
|
|
// The document is deliberately small and deliberately not a database dump: it
|
|
// carries the operator's decisions and the policy that bounds them, and nothing
|
|
// that belongs to one edge's traffic (observations, alerts, streaks, engine
|
|
// bans). The rulings below are the ones a reader has to be able to check, so
|
|
// they live here as pure functions rather than being scattered through the
|
|
// endpoint.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/// <summary>An operator block, as it travels. The expiry is an instant, not a
|
|
/// duration: a block that expires in ten minutes expires in ten minutes on the
|
|
/// other edge, not a week from the import.</summary>
|
|
public sealed record ExportedBlock(string Ip, string? Reason, string? RedirectTo, DateTimeOffset? ExpiresAt);
|
|
|
|
/// <summary>An exemption. Same expiry ruling as a block.</summary>
|
|
public sealed record ExportedAllow(string Match, string? Note, DateTimeOffset? ExpiresAt);
|
|
|
|
/// <summary>A path rule. <c>Action</c> is the lowercase spelling the API uses,
|
|
/// and the order in the document is the order the engine evaluates them in.</summary>
|
|
public sealed record ExportedRule(string Pattern, string? Action, string? Note, DateTimeOffset? ExpiresAt);
|
|
|
|
/// <summary>A request budget for one path (OPEN-68). The numbers are nullable so
|
|
/// a document written by a hand that left them out means "use this build's
|
|
/// defaults", which is the same thing an absent action means for a path rule.</summary>
|
|
public sealed record ExportedRateRule(
|
|
string Pattern,
|
|
int? LimitPerWindow,
|
|
int? WindowSeconds,
|
|
string? Note,
|
|
DateTimeOffset? ExpiresAt);
|
|
|
|
/// <summary>A country decision.</summary>
|
|
public sealed record ExportedCountry(string Code, bool Allowed);
|
|
|
|
public static class ConfigTransfer
|
|
{
|
|
/// <summary>The version this build writes, and the only one it reads. A
|
|
/// document from another version is refused rather than half-applied.</summary>
|
|
public const int CurrentVersion = 1;
|
|
|
|
/// <summary>Per-section cap. An import is one request and one transaction
|
|
/// per section; a document with a million rows is not a config transfer, it
|
|
/// is a data load asked to behave like one.</summary>
|
|
public const int MaxItemsPerSection = 2_000;
|
|
|
|
/// <summary>Body cap, checked before the document is parsed.</summary>
|
|
public const long MaxBodyBytes = 2_000_000;
|
|
|
|
/// <summary>How many rejected items the answer names before it says
|
|
/// "and more". A report that prints every rejection of a 2000-row document
|
|
/// is a report nobody reads.</summary>
|
|
public const int MaxReportedRejections = 20;
|
|
|
|
public static string? ExplainVersion(int version) =>
|
|
version == CurrentVersion
|
|
? null
|
|
: $"unsupported document version {version}; this edge reads version {CurrentVersion}";
|
|
|
|
public static string? ExplainSectionSize(string section, int count) =>
|
|
count <= MaxItemsPerSection
|
|
? null
|
|
: $"\"{section}\" holds {count} items; an import carries at most {MaxItemsPerSection} per section";
|
|
|
|
/// <summary>Is this row already past its expiry at <paramref name="now"/>?
|
|
/// A row that is not live where it came from is not a decision the operator
|
|
/// is asking for, so it is skipped and counted rather than imported as a
|
|
/// live row on the receiving edge.</summary>
|
|
public static bool IsExpired(DateTimeOffset? expiresAt, DateTimeOffset now)
|
|
=> expiresAt is not null && expiresAt <= now;
|
|
|
|
/// <summary>The same guards <c>POST /admin-api/blocks</c> applies, in the
|
|
/// order it applies them, so an item that would be refused one at a time is
|
|
/// refused in a document too.</summary>
|
|
public static string? ExplainBlock(ExportedBlock block)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(block.Ip)) return "ip is required";
|
|
// An address or a network (OPEN-66): the document that carries an
|
|
// edge's decisions has to carry the range ban too, and the guard here is
|
|
// the one POST /admin-api/blocks applies, so a row refused one at a time
|
|
// is refused in a document too.
|
|
if (!NetworkBans.TryNormalize(block.Ip, out _, out var targetProblem)) return targetProblem;
|
|
if (!EntryLimits.NoteOk(block.Reason))
|
|
return $"reason must be at most {EntryLimits.NoteMaxLength} characters; got {block.Reason!.Length}";
|
|
if (block.RedirectTo is not null && !RedirectTarget.IsSendable(block.RedirectTo))
|
|
return $"redirectTo must be an absolute http(s) URL with no spaces or control characters; got \"{block.RedirectTo}\"";
|
|
return null;
|
|
}
|
|
|
|
public static string? ExplainAllow(ExportedAllow allow)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(allow.Match) || !IsValidMatch(allow.Match))
|
|
return "match must be an address or CIDR";
|
|
if (!EntryLimits.NoteOk(allow.Note))
|
|
return $"note must be at most {EntryLimits.NoteMaxLength} characters; got {allow.Note!.Length}";
|
|
return null;
|
|
}
|
|
|
|
public static string? ExplainRule(ExportedRule rule)
|
|
{
|
|
var patternProblem = PathPattern.ExplainRejection(rule.Pattern);
|
|
if (patternProblem is not null) return patternProblem;
|
|
if (!EntryLimits.NoteOk(rule.Note))
|
|
return $"note must be at most {EntryLimits.NoteMaxLength} characters; got {rule.Note!.Length}";
|
|
if (RuleAction(rule.Action) is null)
|
|
return $"action must be observe|block; got \"{rule.Action}\"";
|
|
return null;
|
|
}
|
|
|
|
public static string? ExplainRateRule(ExportedRateRule rule)
|
|
{
|
|
var patternProblem = PathPattern.ExplainRejection(rule.Pattern);
|
|
if (patternProblem is not null) return patternProblem;
|
|
if (!EntryLimits.NoteOk(rule.Note))
|
|
return $"note must be at most {EntryLimits.NoteMaxLength} characters; got {rule.Note!.Length}";
|
|
// The same bounds the live endpoint applies to a typed request, so a
|
|
// document cannot bring in a budget the API would have refused.
|
|
var limit = rule.LimitPerWindow ?? RateRule.DefaultLimitPerWindow;
|
|
if (!PolicyBounds.RateLimitPerWindowOk(limit))
|
|
return $"limitPerWindow must be {PolicyBounds.RateLimitPerWindowMin}..{PolicyBounds.RateLimitPerWindowMax}; got {limit}";
|
|
var window = rule.WindowSeconds ?? RateRule.DefaultWindowSeconds;
|
|
if (!PolicyBounds.RateWindowSecondsOk(window))
|
|
return $"windowSeconds must be {PolicyBounds.RateWindowSecondsMin:0}..{PolicyBounds.RateWindowSecondsMax:0}; got {window}";
|
|
return null;
|
|
}
|
|
|
|
public static string? ExplainCountry(ExportedCountry country)
|
|
{
|
|
if (CountryCode(country.Code) is null)
|
|
return $"code must be a two-letter ISO country code; got \"{country.Code}\"";
|
|
return null;
|
|
}
|
|
|
|
/// <summary>The action in the spelling the table stores, or null when the
|
|
/// document did not name one this build knows. Absent is <c>observe</c>,
|
|
/// which is what <c>POST /admin-api/rules</c> does with a missing action.</summary>
|
|
public static string? RuleAction(string? action)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(action)) return "observe";
|
|
var trimmed = action.Trim().ToLowerInvariant();
|
|
return trimmed is "observe" or "block" ? trimmed : null;
|
|
}
|
|
|
|
/// <summary>Upper-cased two-letter code, or null. The same rule the country
|
|
/// endpoints apply, so a document cannot smuggle a code the API would
|
|
/// refuse row by row.</summary>
|
|
public static string? CountryCode(string? raw)
|
|
{
|
|
var code = (raw ?? string.Empty).Trim().ToUpperInvariant();
|
|
return code.Length == 2 && char.IsAsciiLetter(code[0]) && char.IsAsciiLetter(code[1]) ? code : null;
|
|
}
|
|
|
|
/// <summary>Address or CIDR, as the allow endpoint reads it.</summary>
|
|
public static bool IsValidMatch(string match)
|
|
{
|
|
if (match.Contains('/')) return NetworkMatch.Matches("203.0.113.1", match) || match.Split('/')[1].Length <= 3;
|
|
return SourceKey.TryParse(match, out _, out _);
|
|
}
|
|
}
|