Files
openwaf/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.ConfigTransfer.cs
Pavlo Ratushnyi fb758900b8 the admin API's error body stops being anonymous, and the AOT build prices a reflection resolver
Wall 2 of the generator slice (OPEN-79) is the web host, not the database: the
AOT edge never reaches `Now listening` because the admin API's request DTOs have
no compiled JSON contract, and a NativeAOT binary has no reflection resolver to
fall back on. The wire shapes have to be types before a contract can exist for
them, so this starts with the shapes.

Counted in `dotnet/OpenWaf.Edge` before the change: **130 anonymous object
literals** in the JSON path, in **51 distinct shapes**, of which **111 are the
one shape `new { error = … }`**. Those 111 are now `ErrorDto`, and the two
read-only-token refusals that carried a second property are `ReadOnlyRefusalDto`.
`ErrorDto.Error` is nullable because the literal it replaces was — the
unknown-query-parameter validators hand back a `string?` next to the false they
return, and making it non-null would hide a second change inside a mechanical
one. `Admin/EdgeJson.cs` is the edge's `JsonSerializerContext`: 24 registered
types (5 request bodies, the 14 response records the tree already had, the two new
ones, the config-transfer document and its rejected-item row), with
`[JsonSourceGenerationOptions(PropertyNamingPolicy = CamelCase)]` because the
generated contract carries the property names — without that line the same record
answers `{"Error": …}` and the console, the smoke gate and every integration
assertion read a body with no error in it. The recipe is the neighbouring
deployment's (`app/lib/Kernel/KernelJson.cs`, `api/Domain/AppJson.cs`, one line in
its `Program.cs`), not an invention here. **18 anonymous literals in 50 shapes
remain**; they are the rest of the wall, and this commit does not pretend
otherwise.

Two measurements decided the wiring, and both were paid for:

  * A non-empty `TypeInfoResolverChain` **replaces** the reflection resolver, it
    does not extend it. With only the context in the chain, a type it does not
    know fails on a *JIT* build with the sentence the AOT probe reports —
    `JsonTypeInfo metadata for type '<>f__AnonymousType0`1[System.String]' was not
    provided by TypeInfoResolver of type '[EdgeJson]'` — reproduced with a
    standalone probe. So on a build that can reflect, reflection stays at the end
    of the chain: the 18 remaining literals kept served and visible rather than a
    break smuggled into a slice.
  * That fallback is not free on the other side. Naming `DefaultJsonTypeInfoResolver`
    in an AOT publish pulls the reflection-based JSON stack into the native image:
    the publish step ran **66 minutes and never finished**, against **232 s** for
    the same Dockerfile an hour earlier. The branch is now gated on
    `RuntimeFeature.IsDynamicCodeCompiled`, which the AOT compiler substitutes as
    a constant, so the shipped binary contains neither the branch nor the resolver.
    The 66-minute figure was taken at load average 26–34 against the earlier run's
    ~12, so that ratio is an upper bound, not a clean A/B; the weekly runner is
    where the clean number will come from.

`AotJsonContractTests` (2 new) asks the running edge which body types its
endpoints accept — `IAcceptsMetadata`, read from the live `EndpointDataSource`,
with the measured count of 5 asserted so the guard cannot pass on an empty set —
and demands a compiled contract for each; the second test asserts the generated
contract really says `error` and `tokenLevel`. An endpoint added without a
contract is therefore red in the suite, not in next Monday's probe.

Measured on this tree: `dotnet build OpenWaf.Edge -c Release` 0 warnings, unit
**378/378**, integration **407/407 in 2 m 16 s** (unsandboxed). The same suite run
inside the sandbox answered **8 failures of 407**, every one of them `Timed out
waiting for the entry point to build the IHost after 00:05:00` — the loopback-bind
symptom the README already recorded on 2026-10-04 and 2026-10-05, reproduced here
rather than re-diagnosed; the 407 figure is the unsandboxed one.

NOT measured on this tree: whether the AOT edge now reaches `Now listening`. The
rebuild that would answer it was interrupted, so the README and
`docs/ARCHITECTURE.md` say so in those words, and `.github/workflows/aot-probe.yml`
now prints `lines where the edge started listening` — 0 means the host still dies
before serving, 1 means it serves. The 18 remaining anonymous shapes are what
stands between the two.
2026-10-07 08:35:51 +02:00

639 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 ErrorDto(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 ErrorDto(unknown));
if (ctx.Request.ContentLength is { } declared && declared > ConfigTransfer.MaxBodyBytes)
return Results.BadRequest(new ErrorDto($"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 ErrorDto($"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 ErrorDto($"the document is not valid JSON: {ex.Message}"));
}
if (doc is null) return Results.BadRequest(new ErrorDto("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 ErrorDto(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 ErrorDto(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);
}