Files
Pavlo Ratushnyi 5c1a2950d0
ci / lint the workflow and the shell (push) Successful in 22s
ci / build, test, smoke (push) Successful in 4m36s
ci / the operator page in a real browser (push) Successful in 4m48s
ci / build the image and smoke it (push) Successful in 8m34s
ci / the same smoke on an image with no base (push) Failing after 8m44s
two more wire shapes stop being anonymous, and the count of the ones left gets re-measured
`countries/summary` answered with a `List<anonymous>`: the anonymous shape is what
EF translates — the record-constructor form compiles and then fails at query time
with "could not be translated", which is a test's finding, not a guess — so the
projection stays inside the query and the *response* becomes a named record,
`CountrySummaryDto(Code, Sources, Refusals)`, mapped after `ToListAsync` with the
sort left where it was. Registered in `EdgeJson`. `Code` stays nullable in the
model and non-null in these rows: the query filters `LastCountryCode != null`,
which the compiler cannot see and EF does apply. The second literal is one the
first pass missed because it spans three lines — a `Results.BadRequest` whose body
was `new { error = … }`, now `ErrorDto`.

The counts in `README.md` and `docs/ARCHITECTURE.md` are corrected, and the
correction is stated rather than quietly applied: `fb75890` records **130
anonymous-object literals in 51 shapes**, and its message repeats that. Those two
figures came from a first-pass scanner that walked braces without skipping string
literals, so every `{` inside an interpolated string was counted as code. The same
tree re-measured with a scanner that skips strings, char literals and comments:
**144 literals in 27 shapes** before this change, **31 in 25 shapes** after it.
The **111** that became `ErrorDto` is the one figure both scanners agree on, which
is why the first commit still moved the wall it claimed to move.

Measured on this tree: `dotnet build OpenWaf.Edge -c Release` 0 warnings, unit
**378/378**, integration **407/407 in 34 s** (unsandboxed; the sandboxed run of
this suite is not a measurement — see the loopback-bind note in the README).
2026-10-07 09:06:57 +02:00

219 lines
8.1 KiB
C#

using OpenWaf.Domain.Security;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Edge.Admin;
internal sealed record BlockDto(
long Id,
string SourceKey,
string Source,
/// <summary>"address" or "range" (OPEN-66). One list, two shapes, and the
/// row has to say which it is: a /24 that refuses every visitor inside it is
/// not a narrower claim than one address, and a page that draws them the same
/// way teaches an operator to mis-read their own list.</summary>
string Kind,
DateTimeOffset CreatedAt,
DateTimeOffset? ExpiresAt,
bool Live,
string? Reason,
string? RedirectTo,
int? ConsecutiveRefusals,
int? LastStatusCode,
string? LastPath,
string? LastUserAgent,
string? LastCountryCode,
string? LastCity);
internal sealed record NewBlockRequest(string Ip, string? Reason, string? RedirectTo,
int? ExpiresInMinutes);
internal sealed record StreakDto(
string SourceKey,
int ConsecutiveRefusals,
int ConsecutiveServerErrors,
int? LastStatusCode,
string? LastPath,
string? LastCountryCode,
DateTimeOffset LastSeenAt);
internal sealed record AllowDto(
long Id,
string Match,
string? Note,
DateTimeOffset CreatedAt,
DateTimeOffset? ExpiresAt,
/// <summary>What the engine will answer for this match right now. The
/// expiry is a column; this is the decision made from it, and the two
/// disagree the moment a row ages — which is the whole reason the row is
/// not the answer.</summary>
bool Live);
internal sealed record NewAllowRequest(string Match, string? Note, int? ExpiresInMinutes);
/// <summary>An operator-written request rule, with what it has matched since it
/// was last reported — an observe rule that reports nothing is indistinguishable
/// from one that matches nothing, and the whole point of observe is to answer
/// that question.</summary>
internal sealed record RuleDto(
long Id,
string Pattern,
string Action,
string? Note,
DateTimeOffset CreatedAt,
DateTimeOffset? ExpiresAt,
bool Live,
int Matches);
internal sealed record NewRuleRequest(string Pattern, string? Action, string? Note, int? ExpiresInMinutes);
/// <summary>A request budget written for one path, with what it is counting
/// right now: a budget nobody has blown yet and a budget nobody can blow look
/// the same on paper, and only one of them is worth keeping.</summary>
internal sealed record RateRuleDto(
long Id,
string Pattern,
int LimitPerWindow,
int WindowSeconds,
string? Note,
DateTimeOffset CreatedAt,
DateTimeOffset? ExpiresAt,
bool Live,
int TrackedSources,
int OverBudgetNow,
int LiveWindows);
internal sealed record NewRateRuleRequest(
string Pattern,
int? LimitPerWindow,
int? WindowSeconds,
string? Note,
int? ExpiresInMinutes);
internal sealed record PolicyDto(
string Mode,
int StreakThreshold,
double StreakWindowMinutes,
double BanDurationMinutes,
string RefusalRange,
string ServerErrorRange,
string Geo,
bool TrustProxyHeaders,
int MaxTrackedSources,
int Ipv4KeyPrefixLength,
int Ipv6KeyPrefixLength,
int EngineBlockStatus,
int OperatorBlockStatus,
IReadOnlyList<string> DefaultRedirectTargets,
int ObservationRetentionDays,
int BanRetentionDays,
string RateMode,
int RateLimitPerWindow,
double RateWindowSeconds,
int NetblockCandidateBans,
int NetblockPrefixV4,
int NetblockPrefixV6);
/// <summary>Every field is optional and null means "leave it alone" — a
/// partial update is the only sane shape for a live policy knob.</summary>
internal sealed record PolicyUpdateRequest(
string? Mode,
int? StreakThreshold,
double? StreakWindowMinutes,
double? BanDurationMinutes,
string? RefusalRange,
string? ServerErrorRange,
string? Geo,
bool? TrustProxyHeaders,
int? MaxTrackedSources,
int? Ipv4KeyPrefixLength,
int? Ipv6KeyPrefixLength,
int? EngineBlockStatus,
int? OperatorBlockStatus,
string[]? DefaultRedirectTargets,
string? RateMode,
int? RateLimitPerWindow,
double? RateWindowSeconds,
int? NetblockCandidateBans,
int? NetblockPrefixV4,
int? NetblockPrefixV6);
/// <summary>A block the edge's own bans point at (OPEN-67), as the surface
/// shows it. Nothing here is a decision: the row says how many live engine bans
/// sit inside the block and whether the operator already banned it.</summary>
internal sealed record NetblockDto(
/// <summary>The block, in the CIDR spelling the block form takes.</summary>
string Match,
int Prefix,
int Bans,
DateTimeOffset FirstBanAt,
DateTimeOffset LastBanAt,
IReadOnlyList<string> Sample,
bool AlreadyBanned);
/// <summary>One source's live volume window, as the limiter is counting it
/// right now (OPEN-56).</summary>
internal sealed record RateSourceDto(
string SourceKey,
int Count,
DateTimeOffset WindowStart,
DateTimeOffset WindowEnd,
bool OverBudget);
internal sealed record ObservationDto(
string SourceKey,
DateTimeOffset LastSeenAt,
int MaxConsecutiveRefusals,
int TotalRefusals,
int TotalServerErrorStreak,
int? LastStatusCode,
string? LastPath,
string? LastCountryCode,
string? LastCity);
/// <summary>One country in the countries summary: how many sources the edge saw
/// there and how many refusals they account for. Named because the response needs
/// a compiled JSON contract; the anonymous shape EF translates stays inside the
/// query (see the countries/summary endpoint).</summary>
internal sealed record CountrySummaryDto(string Code, int Sources, int Refusals);
/// <summary>The edge's one error body: <c>{"error": "…"}</c>.
///
/// It used to be written 111 times as the anonymous literal <c>new { error = … }</c>.
/// That is not a style question: a NativeAOT binary has no reflection-based JSON
/// resolver to fall back on, and a source-generated contract cannot describe an
/// anonymous type at all — so the shape the operator reads had to become a type
/// before the wire shape could be compiled in. Measured 2026-10-06: 130 anonymous
/// literals in this project, 111 of them this one shape, in 51 distinct shapes.
/// The camelCase of the wire name comes from <see cref="EdgeJson"/>, which is what
/// keeps the JSON byte-identical to what the console and the smoke gate read today.
/// <c>Error</c> is nullable because the anonymous literal it replaces was: the
/// validators that answer "unknown query parameter" hand back a <c>string?</c>
/// alongside the false they return, and a record that refused it would be a
/// second, different change hiding inside a mechanical one.
/// </summary>
internal sealed record ErrorDto(string? Error);
/// <summary>The 403 a read-only token gets: the same error body plus the level the
/// token actually had, because the difference between "wrong token" and "right
/// token, endpoint it may not call" is the whole point of the second token
/// (OPEN-61/OPEN-62).</summary>
internal sealed record ReadOnlyRefusalDto(string Error, string TokenLevel);
internal static class DtoMapper
{
public static BlockDto ToDto(this BlockEntry b, DateTimeOffset now) => new(
b.Id, b.SourceKey, b.Source == BlockSource.Operator ? "operator" : "engine", "address",
b.CreatedAt, b.ExpiresAt, b.IsLive(now), b.Reason, b.RedirectTo, b.ConsecutiveRefusals,
b.LastStatusCode, b.LastPath, b.LastUserAgent, b.LastCountryCode, b.LastCity);
// The operator's list is one list (OPEN-66), so the row shape is one shape
// whichever table it came from. A range carries no per-source evidence —
// there is no source behind it yet — so those fields are null rather than
// invented.
public static BlockDto ToDto(this BlockStore.BlockRow row, DateTimeOffset now) => new(
row.Id, row.Target, row.Source, row.IsRange ? "range" : "address",
row.CreatedAt, row.ExpiresAt, row.IsLive(now), row.Reason, row.RedirectTo,
row.Entry?.ConsecutiveRefusals, row.Entry?.LastStatusCode, row.Entry?.LastPath,
row.Entry?.LastUserAgent, row.Entry?.LastCountryCode, row.Entry?.LastCity);
}