Every operator write already changes a row; what was missing is the answer an operator actually asks at 03:00 - when did this rule get here, who cleared that ban, did a document bring this edge's config. Since the transfer landed, an edge can be different from yesterday with nothing on it saying how.
config_changes carries one row per deliberate change: the instant, the section (block, allow, rule, country, policy, config), the action (added, removed, changed, imported), the target the operator typed, their own sentence where one was given, and the surface the change came through. GET /admin-api/changes answers it newest first, capped and paged like every other listing, filterable by section and since, readable by the read-only token because it is a read. A policy record says what moved ("mode Enforce->Off, streakThreshold 3->4") rather than only that something did. /admin-api/state counts the rows and the write failures.
The rulings, because each is a decision and not a detail:
* Engine bans are not in the log. A ban the engine earned is not a decision somebody made, and the block row already carries its evidence - consecutive refusals, status code, path, user agent, country, city. Logging bans would answer a different question and grow the table at the rate of traffic.
* An import is one record per section, not one per row: "3 added, 1 already there, 0 past expiry, 0 rejected". A 2 000-row document would otherwise bury a table whose whole use is being readable.
* The record names the surface, never a person. The edge has one admin token; a log that implied per-person attribution it cannot provide would be a false record, which is worse than no record.
* A record that cannot be written never undoes the change it describes. Enforcement is the product, so the change stands and the failure is counted - changeWriteFailures, changesNotWritten, changeLastError - because "the config changed and the record of it did not land" has to be a sentence an operator can read rather than one that silently never happened.
* Bounded twice, both keys the operator's: ChangeRetentionDays (30) and ChangeLogMaxRows (5000, oldest dropped first). The age window alone would let a scripted churn grow the table without limit; the cap alone would drop last month's incident record the week someone did a lot of editing.
What the run caught, in order: (1) Two gate assertions were wrong rather than the product - a policy record was asserted in a scene where no policy write had happened yet, and "one imported record per section" was asserted against a stack that had already imported twice, so the assertion now reads the newest imported record instead of counting them. (2) DELETE /admin-api/countries/{code} answers 204, and the new assertion expected 200. (3) A shell trap in the new scene: a $VAR inside a single-quoted python -c is not interpolated, so the first version would have handed python a literal "$CHANGES_BEFORE" instead of a number.
Gates on this tree: build 0 warnings / 0 errors, unit 313/313, integration 298/298 in 23s, smoke 127 passed / 0 failed (14 new), image 262 MB, compose-smoke 278 passed / 0 failed with 0 containers left behind (11 new, against the shipped image), console 90 assertions / 0 failed.
Refs OPEN-64.
545 lines
28 KiB
C#
545 lines
28 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);
|
|
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);
|
|
|
|
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,
|
|
allow = allowRows.Count,
|
|
rules = ruleRows.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),
|
|
blocks = blockRows.Select(b => new ExportedBlock(b.SourceKey, 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)),
|
|
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, 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 countriesIn = doc.Countries ?? [];
|
|
foreach (var (section, count) in new[]
|
|
{
|
|
("blocks", blocksIn.Length), ("allow", allowIn.Length),
|
|
("rules", rulesIn.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);
|
|
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}";
|
|
}
|
|
|
|
// --- 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 + 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.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 },
|
|
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.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();
|
|
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.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);
|
|
}
|