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.
641 lines
33 KiB
C#
641 lines
33 KiB
C#
using System.Text;
|
|
using System.Text.Json;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using OpenWaf.Domain.Engine;
|
|
using OpenWaf.Domain.Policy;
|
|
using OpenWaf.Domain.Security;
|
|
using OpenWaf.Infrastructure.Persistence;
|
|
|
|
namespace OpenWaf.Edge.Admin;
|
|
|
|
/// <summary>
|
|
/// The operator's config as one document (OPEN-61).
|
|
///
|
|
/// Every row in it can already be written one at a time. What could not be done
|
|
/// was move them: an operator running several edges types every rule several
|
|
/// times, a new deployment starts empty, and a change that turns out wrong has
|
|
/// nothing to be restored from. This is the multi-instance finding of
|
|
/// research/2026-10-01-multi-instance/ one level up — `SharedStreaks` shares the
|
|
/// counters, nothing shared the decisions.
|
|
///
|
|
/// Three rulings shape the endpoints, and each is a decision rather than a
|
|
/// detail:
|
|
///
|
|
/// * <b>Engine bans do not travel.</b> A ban the engine earned is a claim about
|
|
/// this edge's own traffic; enforcing it on an edge that never saw that
|
|
/// traffic is a decision nobody made. The export names how many it left
|
|
/// behind, so "0 blocks" and "0 operator blocks, 7 engine bans left behind"
|
|
/// stay different sentences.
|
|
/// * <b>Import is additive and idempotent.</b> It never deletes a row the
|
|
/// document does not mention — a transfer that silently clears a fleet's
|
|
/// exemptions is worse than one that duplicates a block — and a row that is
|
|
/// already there is reported as already there, not rewritten.
|
|
/// * <b>Expiry travels as an instant.</b> A block that expires in ten minutes
|
|
/// where it came from expires in ten minutes here; a row already past its
|
|
/// expiry is skipped and counted, not imported as a live row.
|
|
/// </summary>
|
|
internal static partial class AdminEndpoints
|
|
{
|
|
private static void MapConfigTransfer(RouteGroupBuilder group)
|
|
{
|
|
// The one read on this surface that a read-only token may not do (OPEN-62),
|
|
// and the exception is deliberate rather than an oversight: the document
|
|
// is every block, exemption, rule and policy override the edge holds -
|
|
// the capability OPEN-61 files under "not a backup". The token meant for
|
|
// a dashboard and a second pair of eyes is exactly the one that must not
|
|
// be able to lift the whole config, so this GET is held to the admin
|
|
// token while every other GET is not.
|
|
var export = group.MapGet("/export", async (OpenWafDbContext db, EdgePolicyProvider policy,
|
|
HttpContext ctx, CancellationToken ct) =>
|
|
{
|
|
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown });
|
|
|
|
var now = DateTimeOffset.UtcNow;
|
|
|
|
// Projected into anonymous shapes and mapped in memory: EF's
|
|
// constructor binding for record DTOs has failed at query time in
|
|
// this schema before (see /countries/summary), and an export that
|
|
// throws is an export that says nothing.
|
|
var blockRows = await db.Blocks.AsNoTracking()
|
|
.Where(b => b.Source == BlockSource.Operator && (b.ExpiresAt == null || b.ExpiresAt > now))
|
|
.OrderBy(b => b.SourceKey)
|
|
.Select(b => new { b.SourceKey, b.Reason, b.RedirectTo, b.ExpiresAt })
|
|
.ToListAsync(ct);
|
|
// A range ban travels in the same section as an address block
|
|
// (OPEN-66), because it is the same kind of claim — the operator's —
|
|
// and a document whose blocks section means "the operator's blocks
|
|
// except the wide ones" is a document that has to be read twice to be
|
|
// trusted. The expiry ruling is identical: an instant, not a duration.
|
|
var rangeRows = await db.NetworkBans.AsNoTracking()
|
|
.Where(b => b.ExpiresAt == null || b.ExpiresAt > now)
|
|
.OrderBy(b => b.Match)
|
|
.Select(b => new { b.Match, b.Reason, b.RedirectTo, b.ExpiresAt })
|
|
.ToListAsync(ct);
|
|
var engineLeftBehind = await db.Blocks.AsNoTracking()
|
|
.CountAsync(b => b.Source == BlockSource.Engine && (b.ExpiresAt == null || b.ExpiresAt > now), ct);
|
|
|
|
var allowRows = await db.AllowEntries.AsNoTracking()
|
|
.Where(a => a.ExpiresAt == null || a.ExpiresAt > now)
|
|
.OrderBy(a => a.Match)
|
|
.Select(a => new { a.Match, a.Note, a.ExpiresAt })
|
|
.ToListAsync(ct);
|
|
|
|
// Ordered by id, because for rules the order in the document is the
|
|
// order the engine evaluates them in.
|
|
var ruleRows = await db.RequestRules.AsNoTracking()
|
|
.Where(r => r.ExpiresAt == null || r.ExpiresAt > now)
|
|
.OrderBy(r => r.Id)
|
|
.Select(r => new { r.Pattern, r.Action, r.Note, r.ExpiresAt })
|
|
.ToListAsync(ct);
|
|
|
|
// The per-path budgets (OPEN-68). Ordered by id for the same reason
|
|
// the path rules are: on the receiving edge these become rows in this
|
|
// order, and a document that shuffled them would describe a different
|
|
// edge than the one it came from.
|
|
var rateRuleRows = await db.RateRules.AsNoTracking()
|
|
.Where(r => r.ExpiresAt == null || r.ExpiresAt > now)
|
|
.OrderBy(r => r.Id)
|
|
.Select(r => new { r.Pattern, r.LimitPerWindow, r.WindowSeconds, r.Note, r.ExpiresAt })
|
|
.ToListAsync(ct);
|
|
|
|
var countryRows = await db.CountryRules.AsNoTracking()
|
|
.OrderBy(c => c.Code)
|
|
.Select(c => new { c.Code, c.IsAllowed })
|
|
.ToListAsync(ct);
|
|
|
|
var p = policy.Current;
|
|
return Results.Ok(new
|
|
{
|
|
version = ConfigTransfer.CurrentVersion,
|
|
exportedAt = now,
|
|
edgeId = Environment.MachineName,
|
|
counts = new
|
|
{
|
|
blocks = blockRows.Count + rangeRows.Count,
|
|
allow = allowRows.Count,
|
|
rules = ruleRows.Count,
|
|
rateRules = rateRuleRows.Count,
|
|
countries = countryRows.Count
|
|
},
|
|
// The sentence the AC asks for: what this document deliberately
|
|
// does not carry.
|
|
engineBlocksLeftBehind = engineLeftBehind,
|
|
policy = new PolicyUpdateRequest(
|
|
p.Mode.ToString(), p.StreakThreshold, p.StreakWindow.TotalMinutes, p.BanDuration.TotalMinutes,
|
|
p.RefusalRange.ToString(), p.ServerErrorRange.ToString(), p.Geo.ToString(), p.TrustProxyHeaders,
|
|
p.MaxTrackedSources, p.Ipv4KeyPrefixLength, p.Ipv6KeyPrefixLength, p.EngineBlockStatus,
|
|
p.OperatorBlockStatus, p.DefaultRedirectTargets.ToArray(), p.Rate.ToString(),
|
|
p.RateLimitPerWindow, p.RateWindow.TotalSeconds,
|
|
p.NetblockCandidateBans, p.NetblockPrefixV4, p.NetblockPrefixV6),
|
|
blocks = blockRows.Select(b => new ExportedBlock(b.SourceKey, b.Reason, b.RedirectTo, b.ExpiresAt))
|
|
.Concat(rangeRows.Select(b => new ExportedBlock(b.Match, b.Reason, b.RedirectTo, b.ExpiresAt))),
|
|
allow = allowRows.Select(a => new ExportedAllow(a.Match, a.Note, a.ExpiresAt)),
|
|
rules = ruleRows.Select(r => new ExportedRule(
|
|
r.Pattern, r.Action.ToString().ToLowerInvariant(), r.Note, r.ExpiresAt)),
|
|
rateRules = rateRuleRows.Select(r => new ExportedRateRule(
|
|
r.Pattern, r.LimitPerWindow, r.WindowSeconds, r.Note, r.ExpiresAt)),
|
|
countries = countryRows.Select(c => new ExportedCountry(c.Code, c.IsAllowed))
|
|
});
|
|
});
|
|
export.AddEndpointFilter(AdminAuth.RequireFull(
|
|
"the exported document is the whole operator config of this edge - every block, "
|
|
+ "exemption, path rule, country rule and policy override - so it is a capability "
|
|
+ "and not a view: it needs the admin token (OpenWaf__Admin__Token), not the "
|
|
+ "read-only one"));
|
|
|
|
group.MapPost("/import", async (OpenWafDbContext db, EdgeStateStore state, EdgePolicyProvider policy,
|
|
IStreakTracker streaks, RateTracker rates, RateRuleTracker rateRules, BlockStore blocks, ConfigChangeWriter changes,
|
|
HttpContext ctx, CancellationToken ct) =>
|
|
{
|
|
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown });
|
|
if (ctx.Request.ContentLength is { } declared && declared > ConfigTransfer.MaxBodyBytes)
|
|
return Results.BadRequest(new {
|
|
error = $"the document is {declared} bytes; an import carries at most {ConfigTransfer.MaxBodyBytes}" });
|
|
|
|
var body = await new StreamReader(ctx.Request.Body, Encoding.UTF8).ReadToEndAsync(ct);
|
|
if (body.Length > ConfigTransfer.MaxBodyBytes)
|
|
return Results.BadRequest(new {
|
|
error = $"the document is {body.Length} bytes; an import carries at most {ConfigTransfer.MaxBodyBytes}" });
|
|
|
|
ConfigImportDocument? doc;
|
|
try
|
|
{
|
|
doc = JsonSerializer.Deserialize<ConfigImportDocument>(body, WebJson.Options);
|
|
}
|
|
catch (JsonException ex)
|
|
{
|
|
// Named as a malformed document, not as an empty one: the two
|
|
// need different fixes and the operator is holding the file.
|
|
return Results.BadRequest(new { error = $"the document is not valid JSON: {ex.Message}" });
|
|
}
|
|
|
|
if (doc is null) return Results.BadRequest(new { error = "the document is empty" });
|
|
|
|
// Nothing is written before the document is readable in full: a
|
|
// half-applied transfer is the state an operator cannot reason about.
|
|
var versionProblem = ConfigTransfer.ExplainVersion(doc.Version);
|
|
if (versionProblem is not null) return Results.BadRequest(new { error = versionProblem });
|
|
|
|
var blocksIn = doc.Blocks ?? [];
|
|
var allowIn = doc.Allow ?? [];
|
|
var rulesIn = doc.Rules ?? [];
|
|
var rateRulesIn = doc.RateRules ?? [];
|
|
var countriesIn = doc.Countries ?? [];
|
|
foreach (var (section, count) in new[]
|
|
{
|
|
("blocks", blocksIn.Length), ("allow", allowIn.Length),
|
|
("rules", rulesIn.Length), ("rate rules", rateRulesIn.Length),
|
|
("countries", countriesIn.Length)
|
|
})
|
|
{
|
|
var sizeProblem = ConfigTransfer.ExplainSectionSize(section, count);
|
|
if (sizeProblem is not null) return Results.BadRequest(new { error = sizeProblem });
|
|
}
|
|
|
|
var now = DateTimeOffset.UtcNow;
|
|
var rejected = new List<RejectedItem>();
|
|
string? storageFailure = null;
|
|
|
|
// --- policy: the same write path as PUT /admin-api/policy -------
|
|
var policyApplied = false;
|
|
string? policyError = null;
|
|
int policyFields = 0;
|
|
if (doc.Policy is { } requested)
|
|
{
|
|
if (!PolicyOverrides(requested, out var overrides, out var problem))
|
|
{
|
|
policyError = problem;
|
|
}
|
|
else
|
|
{
|
|
policyFields = overrides.Count;
|
|
if (await policy.SaveAsync(overrides, ct))
|
|
{
|
|
await state.InvalidateAsync(ct);
|
|
streaks.Configure(policy.Current);
|
|
rates.Configure(policy.Current);
|
|
rateRules.Configure(policy.Current);
|
|
policyApplied = true;
|
|
}
|
|
else
|
|
{
|
|
policyError = "the policy could not be written: the change is NOT in effect";
|
|
storageFailure ??= policyError;
|
|
}
|
|
}
|
|
}
|
|
|
|
// --- blocks -----------------------------------------------------
|
|
var (blocksAdded, blocksThere, blocksExpired, blocksRejected) = (0, 0, 0, 0);
|
|
for (var i = 0; i < blocksIn.Length; i++)
|
|
{
|
|
var item = blocksIn[i];
|
|
if (ConfigTransfer.ExplainBlock(item) is { } why)
|
|
{
|
|
blocksRejected++;
|
|
rejected.Add(new RejectedItem("blocks", i, item.Ip, why));
|
|
continue;
|
|
}
|
|
if (ConfigTransfer.IsExpired(item.ExpiresAt, now))
|
|
{
|
|
blocksExpired++;
|
|
continue;
|
|
}
|
|
var (result, error) = await blocks.ImportOperatorAsync(
|
|
item.Ip, item.Reason, item.RedirectTo, item.ExpiresAt, now, ct);
|
|
switch (result)
|
|
{
|
|
case BlockStore.ImportResult.Added: blocksAdded++; break;
|
|
case BlockStore.ImportResult.AlreadyThere: blocksThere++; break;
|
|
default:
|
|
blocksRejected++;
|
|
rejected.Add(new RejectedItem("blocks", i, item.Ip, error!));
|
|
storageFailure ??= error;
|
|
break;
|
|
}
|
|
}
|
|
|
|
// --- allow ------------------------------------------------------
|
|
var (allowAdded, allowThere, allowExpired, allowRejected) = (0, 0, 0, 0);
|
|
try
|
|
{
|
|
for (var i = 0; i < allowIn.Length; i++)
|
|
{
|
|
var item = allowIn[i];
|
|
if (ConfigTransfer.ExplainAllow(item) is { } why)
|
|
{
|
|
allowRejected++;
|
|
rejected.Add(new RejectedItem("allow", i, item.Match, why));
|
|
continue;
|
|
}
|
|
if (ConfigTransfer.IsExpired(item.ExpiresAt, now))
|
|
{
|
|
allowExpired++;
|
|
continue;
|
|
}
|
|
var match = item.Match.Trim();
|
|
if (await db.AllowEntries.AnyAsync(a => a.Match == match, ct))
|
|
{
|
|
allowThere++;
|
|
continue;
|
|
}
|
|
db.AllowEntries.Add(new AllowEntry
|
|
{
|
|
Match = match, Note = item.Note, ExpiresAt = item.ExpiresAt, CreatedAt = now
|
|
});
|
|
allowAdded++;
|
|
}
|
|
await db.SaveChangesAsync(ct);
|
|
}
|
|
catch (DbUpdateException ex)
|
|
{
|
|
allowRejected += allowAdded;
|
|
allowAdded = 0;
|
|
storageFailure ??= $"the allow list could not be written: {ex.Message}";
|
|
}
|
|
|
|
// --- rules ------------------------------------------------------
|
|
var (rulesAdded, rulesThere, rulesExpired, rulesRejected) = (0, 0, 0, 0);
|
|
try
|
|
{
|
|
var liveRules = await db.RequestRules.AsNoTracking()
|
|
.CountAsync(r => r.ExpiresAt == null || r.ExpiresAt > now, ct);
|
|
for (var i = 0; i < rulesIn.Length; i++)
|
|
{
|
|
var item = rulesIn[i];
|
|
if (ConfigTransfer.ExplainRule(item) is { } why)
|
|
{
|
|
rulesRejected++;
|
|
rejected.Add(new RejectedItem("rules", i, item.Pattern, why));
|
|
continue;
|
|
}
|
|
if (ConfigTransfer.IsExpired(item.ExpiresAt, now))
|
|
{
|
|
rulesExpired++;
|
|
continue;
|
|
}
|
|
var pattern = item.Pattern.Trim();
|
|
if (await db.RequestRules.AsNoTracking()
|
|
.AnyAsync(r => r.Pattern == pattern && (r.ExpiresAt == null || r.ExpiresAt > now), ct))
|
|
{
|
|
rulesThere++;
|
|
continue;
|
|
}
|
|
if (liveRules >= PathPattern.MaxRules)
|
|
{
|
|
rulesRejected++;
|
|
rejected.Add(new RejectedItem("rules", i, pattern,
|
|
$"at most {PathPattern.MaxRules} live rules; every request is checked against each of them"));
|
|
continue;
|
|
}
|
|
db.RequestRules.Add(new RequestRule
|
|
{
|
|
Pattern = pattern,
|
|
Action = ConfigTransfer.RuleAction(item.Action) == "block"
|
|
? RequestRuleAction.Block : RequestRuleAction.Observe,
|
|
Note = item.Note, ExpiresAt = item.ExpiresAt, CreatedAt = now
|
|
});
|
|
liveRules++;
|
|
rulesAdded++;
|
|
}
|
|
await db.SaveChangesAsync(ct);
|
|
}
|
|
catch (DbUpdateException ex)
|
|
{
|
|
rulesRejected += rulesAdded;
|
|
rulesAdded = 0;
|
|
storageFailure ??= $"the rule table could not be written: {ex.Message}";
|
|
}
|
|
|
|
// --- rate rules -------------------------------------------------
|
|
var (rateRulesAdded, rateRulesThere, rateRulesExpired, rateRulesRejected) = (0, 0, 0, 0);
|
|
try
|
|
{
|
|
var liveRateRules = await db.RateRules.AsNoTracking()
|
|
.CountAsync(r => r.ExpiresAt == null || r.ExpiresAt > now, ct);
|
|
for (var i = 0; i < rateRulesIn.Length; i++)
|
|
{
|
|
var item = rateRulesIn[i];
|
|
if (ConfigTransfer.ExplainRateRule(item) is { } why)
|
|
{
|
|
rateRulesRejected++;
|
|
rejected.Add(new RejectedItem("rate rules", i, item.Pattern, why));
|
|
continue;
|
|
}
|
|
if (ConfigTransfer.IsExpired(item.ExpiresAt, now))
|
|
{
|
|
rateRulesExpired++;
|
|
continue;
|
|
}
|
|
var pattern = item.Pattern.Trim();
|
|
// Two live budgets for one path is refused here exactly as the
|
|
// endpoint refuses it: the stricter one would win by accident.
|
|
if (await db.RateRules.AsNoTracking()
|
|
.AnyAsync(r => r.Pattern == pattern && (r.ExpiresAt == null || r.ExpiresAt > now), ct))
|
|
{
|
|
rateRulesThere++;
|
|
continue;
|
|
}
|
|
if (liveRateRules >= PathPattern.MaxRules)
|
|
{
|
|
rateRulesRejected++;
|
|
rejected.Add(new RejectedItem("rate rules", i, pattern,
|
|
$"at most {PathPattern.MaxRules} live rate rules; every request is checked against each of them"));
|
|
continue;
|
|
}
|
|
db.RateRules.Add(new RateRule
|
|
{
|
|
Pattern = pattern,
|
|
LimitPerWindow = item.LimitPerWindow ?? RateRule.DefaultLimitPerWindow,
|
|
WindowSeconds = item.WindowSeconds ?? RateRule.DefaultWindowSeconds,
|
|
Note = item.Note, ExpiresAt = item.ExpiresAt, CreatedAt = now
|
|
});
|
|
liveRateRules++;
|
|
rateRulesAdded++;
|
|
}
|
|
await db.SaveChangesAsync(ct);
|
|
}
|
|
catch (DbUpdateException ex)
|
|
{
|
|
rateRulesRejected += rateRulesAdded;
|
|
rateRulesAdded = 0;
|
|
storageFailure ??= $"the rate rule table could not be written: {ex.Message}";
|
|
}
|
|
|
|
// --- countries --------------------------------------------------
|
|
var (countriesAdded, countriesThere, countriesExpired, countriesRejected) = (0, 0, 0, 0);
|
|
try
|
|
{
|
|
foreach (var (i, item) in countriesIn.Select((c, i) => (i, c)))
|
|
{
|
|
if (ConfigTransfer.CountryCode(item.Code) is not { } code)
|
|
{
|
|
countriesRejected++;
|
|
rejected.Add(new RejectedItem("countries", i, item.Code,
|
|
$"code must be a two-letter ISO country code; got \"{item.Code}\""));
|
|
continue;
|
|
}
|
|
var row = await db.CountryRules.FindAsync([code], ct);
|
|
if (row is null)
|
|
{
|
|
db.CountryRules.Add(new CountryRule
|
|
{
|
|
Code = code, IsAllowed = item.Allowed, UpdatedAt = now
|
|
});
|
|
countriesAdded++;
|
|
}
|
|
else if (row.IsAllowed == item.Allowed)
|
|
{
|
|
countriesThere++;
|
|
}
|
|
else
|
|
{
|
|
// The decision moved, so the row moves with it: a country
|
|
// rule is one decision per code, not a list of them.
|
|
row.IsAllowed = item.Allowed;
|
|
row.UpdatedAt = now;
|
|
countriesAdded++;
|
|
}
|
|
}
|
|
await db.SaveChangesAsync(ct);
|
|
}
|
|
catch (DbUpdateException ex)
|
|
{
|
|
countriesRejected += countriesAdded;
|
|
countriesAdded = 0;
|
|
storageFailure ??= $"the country rules could not be written: {ex.Message}";
|
|
}
|
|
|
|
// Any row landed, so the guard's snapshot has to be dropped even when
|
|
// the policy section failed — every other mutation invalidates here,
|
|
// and an import that lands rows the wire does not obey is the bug
|
|
// this API already refuses to have.
|
|
if (blocksAdded + allowAdded + rulesAdded + rateRulesAdded + countriesAdded > 0)
|
|
await state.InvalidateAsync(ct);
|
|
|
|
// The change log (OPEN-64): one record per section that carried
|
|
// something, not one per imported item. A 2 000-row document would
|
|
// otherwise bury the table whose whole use is being readable, and
|
|
// the sentence an operator asks — "did a document bring this edge's
|
|
// rules?" — is answered by the section row either way.
|
|
foreach (var (section, added, there, expired, rejectedCount) in new[]
|
|
{
|
|
(ConfigChangeLog.SectionBlocks, blocksAdded, blocksThere, blocksExpired, blocksRejected),
|
|
(ConfigChangeLog.SectionAllow, allowAdded, allowThere, allowExpired, allowRejected),
|
|
(ConfigChangeLog.SectionRules, rulesAdded, rulesThere, rulesExpired, rulesRejected),
|
|
(ConfigChangeLog.SectionRateRules, rateRulesAdded, rateRulesThere, rateRulesExpired, rateRulesRejected),
|
|
(ConfigChangeLog.SectionCountries, countriesAdded, countriesThere, countriesExpired, countriesRejected)
|
|
})
|
|
{
|
|
if (added + there + expired + rejectedCount == 0) continue;
|
|
await changes.RecordAsync(section, ConfigChangeLog.ActionImported, section,
|
|
$"{added} added, {there} already there, {expired} past expiry, {rejectedCount} rejected",
|
|
ConfigChangeLog.ActorImport, ct);
|
|
}
|
|
if (policyApplied || policyError is not null)
|
|
await changes.RecordAsync(ConfigChangeLog.SectionPolicy, ConfigChangeLog.ActionImported, "policy",
|
|
policyApplied ? $"{policyFields} fields applied from the document" : policyError,
|
|
ConfigChangeLog.ActorImport, ct);
|
|
|
|
var report = new
|
|
{
|
|
version = ConfigTransfer.CurrentVersion,
|
|
appliedAt = now,
|
|
policy = new { applied = policyApplied, fields = policyFields, error = policyError },
|
|
blocks = new { added = blocksAdded, alreadyThere = blocksThere, skippedExpired = blocksExpired, rejected = blocksRejected },
|
|
allow = new { added = allowAdded, alreadyThere = allowThere, skippedExpired = allowExpired, rejected = allowRejected },
|
|
rules = new { added = rulesAdded, alreadyThere = rulesThere, skippedExpired = rulesExpired, rejected = rulesRejected },
|
|
rateRules = new { added = rateRulesAdded, alreadyThere = rateRulesThere, skippedExpired = rateRulesExpired, rejected = rateRulesRejected },
|
|
countries = new { added = countriesAdded, alreadyThere = countriesThere, skippedExpired = countriesExpired, rejected = countriesRejected },
|
|
rejected = rejected.Take(ConfigTransfer.MaxReportedRejections),
|
|
rejectedTruncated = rejected.Count > ConfigTransfer.MaxReportedRejections,
|
|
storageFailure
|
|
};
|
|
|
|
// A transfer that could not finish is not a 200 with a note: the
|
|
// counts say what landed and the status says the rest did not. The
|
|
// body travels with the 503 on purpose — an operator fixing a broken
|
|
// database needs to know how far the import got.
|
|
return storageFailure is null
|
|
? Results.Ok(report)
|
|
: Results.Json(report, statusCode: StatusCodes.Status503ServiceUnavailable);
|
|
});
|
|
}
|
|
|
|
/// <summary>
|
|
/// What a policy write changed, in one sentence (OPEN-64). The record says
|
|
/// what moved rather than only that something did: "the policy was changed"
|
|
/// tells an operator nothing about what happened at 03:00.
|
|
/// </summary>
|
|
private static string PolicyChangeSentence(OpenWaf.Domain.Policy.EdgePolicy before,
|
|
OpenWaf.Domain.Policy.EdgePolicy after)
|
|
{
|
|
var moved = new List<string>();
|
|
if (before.Mode != after.Mode) moved.Add($"mode {before.Mode}->{after.Mode}");
|
|
if (before.StreakThreshold != after.StreakThreshold)
|
|
moved.Add($"streakThreshold {before.StreakThreshold}->{after.StreakThreshold}");
|
|
if (before.StreakWindow != after.StreakWindow)
|
|
moved.Add($"streakWindow {before.StreakWindow}->{after.StreakWindow}");
|
|
if (before.BanDuration != after.BanDuration)
|
|
moved.Add($"banDuration {before.BanDuration}->{after.BanDuration}");
|
|
if (before.RefusalRange != after.RefusalRange)
|
|
moved.Add($"refusalRange {before.RefusalRange}->{after.RefusalRange}");
|
|
if (before.ServerErrorRange != after.ServerErrorRange)
|
|
moved.Add($"serverErrorRange {before.ServerErrorRange}->{after.ServerErrorRange}");
|
|
if (before.Geo != after.Geo) moved.Add($"geo {before.Geo}->{after.Geo}");
|
|
if (before.TrustProxyHeaders != after.TrustProxyHeaders)
|
|
moved.Add($"trustProxyHeaders {before.TrustProxyHeaders}->{after.TrustProxyHeaders}");
|
|
if (before.MaxTrackedSources != after.MaxTrackedSources)
|
|
moved.Add($"maxTrackedSources {before.MaxTrackedSources}->{after.MaxTrackedSources}");
|
|
if (before.EngineBlockStatus != after.EngineBlockStatus)
|
|
moved.Add($"engineBlockStatus {before.EngineBlockStatus}->{after.EngineBlockStatus}");
|
|
if (before.OperatorBlockStatus != after.OperatorBlockStatus)
|
|
moved.Add($"operatorBlockStatus {before.OperatorBlockStatus}->{after.OperatorBlockStatus}");
|
|
if (before.Rate != after.Rate) moved.Add($"rate {before.Rate}->{after.Rate}");
|
|
if (before.RateLimitPerWindow != after.RateLimitPerWindow)
|
|
moved.Add($"rateLimitPerWindow {before.RateLimitPerWindow}->{after.RateLimitPerWindow}");
|
|
if (before.NetblockCandidateBans != after.NetblockCandidateBans)
|
|
moved.Add($"netblockCandidateBans {before.NetblockCandidateBans}->{after.NetblockCandidateBans}");
|
|
if (before.NetblockPrefixV4 != after.NetblockPrefixV4)
|
|
moved.Add($"netblockPrefixV4 {before.NetblockPrefixV4}->{after.NetblockPrefixV4}");
|
|
if (before.NetblockPrefixV6 != after.NetblockPrefixV6)
|
|
moved.Add($"netblockPrefixV6 {before.NetblockPrefixV6}->{after.NetblockPrefixV6}");
|
|
if (!before.DefaultRedirectTargets.SequenceEqual(after.DefaultRedirectTargets))
|
|
moved.Add("redirectTargets changed");
|
|
return moved.Count == 0 ? "no field changed" : string.Join(", ", moved);
|
|
}
|
|
|
|
/// <summary>
|
|
/// The one place a policy request becomes the overrides the policy store
|
|
/// keeps. <c>PUT /admin-api/policy</c> and the <c>policy</c> section of an
|
|
/// imported document both come through here, so a document cannot be held to
|
|
/// a looser rule than a hand-typed request — and cannot be applied by a
|
|
/// different path either.
|
|
/// </summary>
|
|
private static bool PolicyOverrides(
|
|
PolicyUpdateRequest req, out Dictionary<string, string?> overrides, out string? problem)
|
|
{
|
|
overrides = new Dictionary<string, string?>();
|
|
problem = null;
|
|
|
|
if (req.Mode is not null)
|
|
{
|
|
if (!Enum.TryParse<EnforcementMode>(req.Mode, true, out var mode))
|
|
{
|
|
problem = $"mode must be one of {string.Join('|', Enum.GetNames<EnforcementMode>())}";
|
|
return false;
|
|
}
|
|
overrides["mode"] = mode.ToString();
|
|
}
|
|
if (req.Geo is not null)
|
|
{
|
|
if (!Enum.TryParse<GeoMode>(req.Geo, true, out var geo))
|
|
{
|
|
problem = "geo must be Off|DenyList|AllowList";
|
|
return false;
|
|
}
|
|
overrides["geo"] = geo.ToString();
|
|
}
|
|
if (req.RateMode is not null)
|
|
{
|
|
if (!Enum.TryParse<RateMode>(req.RateMode, true, out var rateMode))
|
|
{
|
|
problem = "rateMode must be one of Off|Observe|Enforce";
|
|
return false;
|
|
}
|
|
overrides["rateMode"] = rateMode.ToString();
|
|
}
|
|
|
|
// A field that is present but out of range is a refusal, not a silent
|
|
// no-op — the same ruling PUT /admin-api/policy carries.
|
|
if (PolicyProblem(req) is { } bounds)
|
|
{
|
|
problem = bounds;
|
|
return false;
|
|
}
|
|
|
|
if (req.StreakThreshold is { } streakThreshold) overrides["streakThreshold"] = streakThreshold.ToString();
|
|
if (req.StreakWindowMinutes is { } windowMinutes) overrides["streakWindowMinutes"] = windowMinutes.ToString();
|
|
if (req.BanDurationMinutes is { } banMinutes) overrides["banDurationMinutes"] = banMinutes.ToString();
|
|
if (req.RefusalRange is not null) overrides["refusalRange"] = req.RefusalRange.Trim();
|
|
if (req.ServerErrorRange is not null) overrides["serverErrorRange"] = req.ServerErrorRange.Trim();
|
|
if (req.TrustProxyHeaders is not null) overrides["trustProxyHeaders"] = req.TrustProxyHeaders.Value.ToString().ToLowerInvariant();
|
|
if (req.MaxTrackedSources is { } maxSources) overrides["maxTrackedSources"] = maxSources.ToString();
|
|
if (req.Ipv4KeyPrefixLength is { } v4) overrides["ipv4KeyPrefixLength"] = v4.ToString();
|
|
if (req.Ipv6KeyPrefixLength is { } v6) overrides["ipv6KeyPrefixLength"] = v6.ToString();
|
|
if (req.EngineBlockStatus is { } engineStatus) overrides["engineBlockStatus"] = engineStatus.ToString();
|
|
if (req.OperatorBlockStatus is { } operatorStatus) overrides["operatorBlockStatus"] = operatorStatus.ToString();
|
|
if (req.DefaultRedirectTargets is { Length: > 0 }) overrides["redirectTargets"] = string.Join(',', req.DefaultRedirectTargets);
|
|
if (req.RateLimitPerWindow is { } rateLimit) overrides["rateLimitPerWindow"] = rateLimit.ToString();
|
|
if (req.RateWindowSeconds is { } rateWindow) overrides["rateWindowSeconds"] = rateWindow.ToString();
|
|
if (req.NetblockCandidateBans is { } netblockBans) overrides["netblockCandidateBans"] = netblockBans.ToString();
|
|
if (req.NetblockPrefixV4 is { } netblockV4) overrides["netblockPrefixV4"] = netblockV4.ToString();
|
|
if (req.NetblockPrefixV6 is { } netblockV6) overrides["netblockPrefixV6"] = netblockV6.ToString();
|
|
return true;
|
|
}
|
|
}
|
|
|
|
/// <summary>The document as it arrives. The sections are optional: a document
|
|
/// that carries only rules is a legitimate way to move rules.</summary>
|
|
internal sealed record ConfigImportDocument(
|
|
int Version,
|
|
DateTimeOffset? ExportedAt,
|
|
string? EdgeId,
|
|
PolicyUpdateRequest? Policy,
|
|
OpenWaf.Domain.Security.ExportedBlock[]? Blocks,
|
|
OpenWaf.Domain.Security.ExportedAllow[]? Allow,
|
|
OpenWaf.Domain.Security.ExportedRule[]? Rules,
|
|
OpenWaf.Domain.Security.ExportedRateRule[]? RateRules,
|
|
OpenWaf.Domain.Security.ExportedCountry[]? Countries);
|
|
|
|
/// <summary>One item the document carried that this edge would not take, named
|
|
/// by section and position so the operator can find it in the file.</summary>
|
|
internal sealed record RejectedItem(string Section, int Index, string? Item, string Error);
|
|
|
|
/// <summary>The options minimal-API binding uses, applied to the hand-read body
|
|
/// so an imported document is parsed exactly as a request body would be.</summary>
|
|
internal static class WebJson
|
|
{
|
|
public static readonly JsonSerializerOptions Options = new(JsonSerializerDefaults.Web);
|
|
}
|