Files
openwaf/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.ConfigTransfer.cs
T
Pavlo Ratushnyi dd10dd9839 the edge notices the netblock behind its bans and offers it as a range
A scanner farm inside one /24 is twenty engine bans and twenty operator
decisions: the streak rule works per source, and nothing in the edge connected
the rows. OPEN-66 made a range enforceable; this is the half that notices the
range is there.

The rulings:

- The evidence is the edge's own live engine bans. An operator's row is a
  decision already taken, and an expired ban is a row the edge stopped
  honouring; neither is evidence about a netblock. Nothing new is observed and
  nothing new is stored.
- An offer is not a ban. A candidate changes nothing on the wire: the operator's
  POST /admin-api/blocks with the CIDR is what enforces it, and the console
  button is that same call. Twenty honest visitors of one provider and one farm
  inside one rented block produce the same number, and only a human tells them
  apart.
- Grouping is one allocation up from the key: v4 to /24, v6 to /48, because the
  v6 streak key is already a /64 and grouping there would only repeat the key.
  The count and both prefixes are policy keys with bounds, because a host that
  hands out /22s should be shown the block it can act on.
- A ban keyed on a block wider than the netblock prefix is skipped: that row
  already claims more than a /24, and counting it as one ban inside a /24 would
  invent a candidate out of it.
- Reading the list is not news — the scan that answers the surface raises no
  alert, so refreshing a page cannot manufacture alert rows. The timer's scan
  raises netblock_candidate through the same durable alert table and push queue
  as every other kind, at most once per block per six hours, and never for a
  block the operator has already banned.
- A failed scan retires the offers instead of repeating the last ones, and
  /admin-api/state says which of off / failed / found-nothing this is.

What the run caught:

- The console's "ban this range" button posted a body with no content type, and
  the edge refused it: the button did nothing and the page looked idle rather
  than wrong. It uses the page's own postJson now, and the console gate asserts
  the row it writes, the wire answer for a source inside it, and the offer
  turning into "already banned".
- The grouping parsed ban keys with SourceKey.TryParse, which fails on the
  "2001:db8:1:2::/64" spelling the engine stores v6 bans under — so no v6 ban
  was ever grouped. Keys are parsed as keys, prefix included.
- An assertion claimed 203.0.113.137 sits under 203.0.113.128/24. That is a /25:
  the arithmetic was wrong in the test, not in the mask.

build 0 warnings / 0 errors, unit 353/353, integration 326/326 in 31 s, console
114 assertions 0 failed, smoke passed 149 failed 0, compose 293 passed 0 failed
against the built image at 262 MB.

Refs OPEN-67.
2026-10-05 07:55:06 +02:00

566 lines
29 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);
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,
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)),
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.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.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);
}