Every defence this edge had reads something that already happened: the status the application answered, the country the address sits in, a list a human wrote. A source asking for a cheap path two hundred times a minute produces no refusal, so no streak matures, no path rule names it, and the origin serves all two hundred. The only signal is the count, and a count has to be kept while the requests are arriving — which is why this pillar is the one piece of live state on the request path, and why it runs after the ordered decision instead of inside it. `rateMode` off|observe|enforce, `rateLimitPerWindow`, `rateWindowSeconds` (policy_settings, so no schema change). Off is the default: a limit nobody wrote is a defence nobody asked for, and a false positive here locks out a whole office behind one address. `observe` counts and raises one `rate_breach` alert per source per window. `enforce` answers the request that crosses with 429 + Retry-After — the surplus never reaches the origin — and writes an engine ban, so the stop outlives the window, is shared with the other edges and survives a restart; from then on the answer is the ban's own 403. One breach, one alert, one ban write per source per window: a flood is exactly the traffic that turns a per-request durable write into the thing that takes the database down. Exempt by construction rather than by a second copy of the precedence rules: the counter runs only on a plain Pass, so an always-pass prefix, an allowlisted address, a matched rule, a block or a geo refusal never reaches it. The budget counts exactly the requests that would have cost the origin. Costs, stated rather than hidden: the counter is per process, so N edges allow N times the budget (the same trade `SharedStreaks` made for the streak, at a round trip per request instead of per observed response); the window is fixed, not sliding, so the worst sustained rate is twice the limit across one boundary — a sliding counter needs one entry per request, which is a map that grows at attack rate. Two things the run caught rather than the design assumed: * The guard wrote the 429 and then called next() anyway, so YARP answered "the request cannot be forwarded, the response has already started". The pillar now says whether the request may go through. * `StreakTracker.Configure` was called by nobody outside its own tests, so `maxTrackedSources` bounded nothing in a running edge — the map grew to the built-in 10000 whatever the operator had asked for. Both maps are configured at warm-up and on a policy write now. And the smoke gate was not testing what its first line says. The edge was started from the repository root, where there is no appsettings.json, so it loaded no ReverseProxy section at all, logged "Request reached the end of the middleware pipeline without being handled by application code" for every request, and answered 404 for a path the upstream was serving with 200. Every assertion in the file expects a 404 or a refusal, so the gate kept passing on an edge that never proxied anything. Naming the content root fixes it; the streak scene also waits for the ban row to exist before asking the wire whether it is enforced, because the ban is written out of band after the response that proved it. Gates on this tree: build 0 warnings 0 errors, unit 207/207, integration 219/219 in 20 s, smoke passed 48 failed 0, console 90 assertions 0 failed, compose 209 passed 0 failed, image 261 MB. OPEN-56
126 lines
6.5 KiB
C#
126 lines
6.5 KiB
C#
using OpenWaf.Domain.Policy;
|
|
|
|
namespace OpenWaf.Edge.Configuration;
|
|
|
|
/// <summary>
|
|
/// The configuration-shaped mirror of <see cref="EdgePolicy"/>. It exists
|
|
/// because <c>appsettings.json</c> is strings: <see cref="StatusRange"/> is a
|
|
/// record struct the configuration binder cannot build from "400-499", and a
|
|
/// TimeSpan written as "00:05:00" in a deployment file is friendlier than a
|
|
/// number of minutes. One explicit mapping, rather than a binder that quietly
|
|
/// leaves a default in place when the shape is wrong.
|
|
/// </summary>
|
|
internal sealed class EdgePolicyOptions
|
|
{
|
|
public string Mode { get; set; } = "Observe";
|
|
public int StreakThreshold { get; set; } = 10;
|
|
public string StreakWindow { get; set; } = "00:05:00";
|
|
public string BanDuration { get; set; } = "01:00:00";
|
|
public string RefusalRange { get; set; } = "400-499";
|
|
public string ServerErrorRange { get; set; } = "500-599";
|
|
public string Geo { get; set; } = "Off";
|
|
public bool TrustProxyHeaders { get; set; }
|
|
public int MaxTrackedSources { get; set; } = 10_000;
|
|
public int Ipv4KeyPrefixLength { get; set; } = 32;
|
|
public int Ipv6KeyPrefixLength { get; set; } = 64;
|
|
public int EngineBlockStatus { get; set; } = 403;
|
|
public int OperatorBlockStatus { get; set; } = 301;
|
|
|
|
// The volume pillar (OPEN-56). Off by default, and the limit is validated
|
|
// at startup rather than defaulted: a deployment that writes
|
|
// rateLimitPerWindow=0 meant something, and reading it as "100" or as
|
|
// "refuse everything" are both a lie about what was asked for.
|
|
public string Rate { get; set; } = "Off";
|
|
public int RateLimitPerWindow { get; set; } = 100;
|
|
public double RateWindowSeconds { get; set; } = 60;
|
|
|
|
// Where the streak counters live. Not a runtime knob: it selects which
|
|
// store the process registers at startup, so changing it is a redeploy.
|
|
// Off by default — the in-process map costs nothing on the request path,
|
|
// and a single-edge deployment loses nothing by it.
|
|
public bool SharedStreaks { get; set; }
|
|
// Empty by default: the configuration binder appends to an existing
|
|
// collection rather than replacing it, so a non-empty default here would
|
|
// leave a duplicate target in every deployment.
|
|
public string[] DefaultRedirectTargets { get; set; } = [];
|
|
|
|
// Retention is the privacy promise this project makes: aggregates about a
|
|
// source outlive the traffic that produced them by exactly this long
|
|
// (OPEN-19). It used to be a constant on the domain record, so the operator
|
|
// who wanted either end of that promise — a shorter window, or an incident
|
|
// from nine days ago that is still explainable — had no lever at all.
|
|
// Two keys, not one: an observation ages out a fact about a source, while a
|
|
// ban's evidence row stays readable after the ban itself stopped being
|
|
// live. They shared 7 days by coincidence, not by design.
|
|
// Out-of-range refuses startup rather than falling back to 7. A silently
|
|
// widened window keeps rows a month longer than the deployment asked for,
|
|
// and nothing on any surface would say so — the same class of lie this
|
|
// project keeps chasing elsewhere.
|
|
public int ObservationRetentionDays { get; set; } = 7;
|
|
public int BanRetentionDays { get; set; } = 7;
|
|
|
|
public const int RetentionDaysFloor = 1;
|
|
public const int RetentionDaysCeiling = 365;
|
|
|
|
public EdgePolicy ToPolicy() => new()
|
|
{
|
|
Mode = Enum.TryParse<EnforcementMode>(Mode, true, out var m) ? m : EnforcementMode.Observe,
|
|
StreakThreshold = StreakThreshold > 0 ? StreakThreshold : 10,
|
|
StreakWindow = ParseWindow(StreakWindow, TimeSpan.FromMinutes(5)),
|
|
BanDuration = ParseWindow(BanDuration, TimeSpan.FromHours(1)),
|
|
RefusalRange = StatusRange.Parse(RefusalRange, new StatusRange(400, 499)),
|
|
ServerErrorRange = StatusRange.Parse(ServerErrorRange, new StatusRange(500, 599)),
|
|
Geo = Enum.TryParse<GeoMode>(Geo, true, out var g) ? g : GeoMode.Off,
|
|
TrustProxyHeaders = TrustProxyHeaders,
|
|
MaxTrackedSources = MaxTrackedSources > 0 ? MaxTrackedSources : 10_000,
|
|
Ipv4KeyPrefixLength = Ipv4KeyPrefixLength,
|
|
Ipv6KeyPrefixLength = Ipv6KeyPrefixLength,
|
|
EngineBlockStatus = EngineBlockStatus,
|
|
OperatorBlockStatus = OperatorBlockStatus,
|
|
SharedStreaks = SharedStreaks,
|
|
Rate = Enum.TryParse<RateMode>(Rate, true, out var rm) ? rm : RateMode.Off,
|
|
RateLimitPerWindow = RateWindowLimit(RateLimitPerWindow),
|
|
RateWindow = TimeSpan.FromSeconds(RateWindow(RateWindowSeconds)),
|
|
DefaultRedirectTargets = DefaultRedirectTargets.Length == 0
|
|
? new[] { "https://www.iana.org/help/example-domains" }
|
|
: DefaultRedirectTargets,
|
|
ObservationRetention = RetentionDays(ObservationRetentionDays, "OpenWaf:Policy:ObservationRetentionDays"),
|
|
BanRetention = RetentionDays(BanRetentionDays, "OpenWaf:Policy:BanRetentionDays")
|
|
};
|
|
|
|
private static int RateWindowLimit(int v)
|
|
{
|
|
if (v < PolicyBounds.RateLimitPerWindowMin || v > PolicyBounds.RateLimitPerWindowMax)
|
|
throw new InvalidOperationException(
|
|
$"OpenWaf:Policy:RateLimitPerWindow must be {PolicyBounds.RangeOf("rateLimitPerWindow")}; got {v}");
|
|
return v;
|
|
}
|
|
|
|
private static double RateWindow(double v)
|
|
{
|
|
if (v < PolicyBounds.RateWindowSecondsMin || v > PolicyBounds.RateWindowSecondsMax)
|
|
throw new InvalidOperationException(
|
|
$"OpenWaf:Policy:RateWindowSeconds must be {PolicyBounds.RangeOf("rateWindowSeconds")}; got {v}");
|
|
return v;
|
|
}
|
|
|
|
/// <summary>Whole days, 1..365. Anything else is a deployment mistake and
|
|
/// is named as one at startup.</summary>
|
|
private static TimeSpan RetentionDays(int days, string configKey)
|
|
{
|
|
if (days < RetentionDaysFloor || days > RetentionDaysCeiling)
|
|
throw new InvalidOperationException(
|
|
$"{configKey} must be a whole number of days between {RetentionDaysFloor} and "
|
|
+ $"{RetentionDaysCeiling}; got {days}");
|
|
return TimeSpan.FromDays(days);
|
|
}
|
|
|
|
/// <summary>Accepts both <c>00:05:00</c> and a bare number of minutes.</summary>
|
|
private static TimeSpan ParseWindow(string value, TimeSpan fallback)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(value)) return fallback;
|
|
if (TimeSpan.TryParse(value, out var ts)) return ts;
|
|
return double.TryParse(value, out var minutes) && minutes > 0 ? TimeSpan.FromMinutes(minutes) : fallback;
|
|
}
|
|
}
|