An operator running several edges types every rule several times: blocks, allowlist, request rules, country rules and the policy overrides have their own endpoints one row at a time, and nothing moved them as a set. A new deployment starts empty, and a change that turns out wrong has nothing to be restored from. This is the multi-instance finding one level up from the shared streak store: SharedStreaks shares the counters, nothing shared the decisions.
GET /admin-api/export answers one document — version, exportedAt, edgeId, per-section counts, the policy section, and blocks / allowlist / rules / country rules. Only live rows; rules keep their evaluation order; and the document names how many engine bans it left behind, because "0 blocks" and "0 operator blocks, 7 engine bans left behind" are different sentences. A ban the engine earned is a claim about this edge's own traffic, so enforcing it where that traffic was never seen is a decision nobody made.
POST /admin-api/import is additive and idempotent: 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 — a live row for the same source is reported as already there rather than rewritten, and expiry travels as an instant, so a block that expires in ten minutes where it came from expires in ten minutes here. Per-section counts (added / alreadyThere / skippedExpired / rejected) and a rejected[] list named by section and index; an unknown version, an oversize body or a malformed document writes nothing at all; a storage failure answers 503 with the report, because "it failed" and "it added 41 of 60" must not collapse into one sentence.
What the run caught, in order: (1) a unit assert used "203.0.113" as the invalid address and passed for the wrong reason — IPAddress.TryParse accepts it as 203.0.113.0, so the assert now names 203.0.113.999. (2) Two smoke asserts were wrong rather than the product: a helper printed a Python boolean where the gate compares text, and a blocks delete was asserted as 204 when the endpoint answers 200 with {"deleted":n}. (3) The metrics-as-a-number test could pass its wait on a cache refreshed between an enqueue and its first attempt — pending > 0 was true a moment before attempts > 0 could be — so the wait now requires both numbers. (4) A real defect, not a test one: the alert notifier left the rows it had claimed claimed when the process stopped, so the next process waited out the five-minute reclaim window to deliver an alert that was already owed. It now releases what it holds on the way out, and the reclaim window is back to being what it is for — a process that was killed and cannot say anything.
Gates on this tree: build 0 warnings / 0 errors, unit 285/285, integration 257/257 in 23s, smoke 82 passed / 0 failed (14 new), image 262 MB, compose-smoke 243 passed / 0 failed with 0 containers left behind (11 new, against the shipped image).
Refs OPEN-61.
141 lines
6.8 KiB
C#
141 lines
6.8 KiB
C#
using OpenWaf.Domain.Engine;
|
|
|
|
namespace OpenWaf.Domain.Security;
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// The portable shape of an operator's decisions (OPEN-61).
|
|
//
|
|
// Every one of these rows can already be written through the admin API, one
|
|
// call per row. What cannot be done today is move them: an operator running N
|
|
// edges writes every rule N times, a new deployment starts empty, and a
|
|
// destructive change has nothing to be undone from. This is the multi-instance
|
|
// finding of research/2026-10-01-multi-instance/ one level up — SharedStreaks
|
|
// shares the counters, nothing shares the decisions.
|
|
//
|
|
// The document is deliberately small and deliberately not a database dump: it
|
|
// carries the operator's decisions and the policy that bounds them, and nothing
|
|
// that belongs to one edge's traffic (observations, alerts, streaks, engine
|
|
// bans). The rulings below are the ones a reader has to be able to check, so
|
|
// they live here as pure functions rather than being scattered through the
|
|
// endpoint.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/// <summary>An operator block, as it travels. The expiry is an instant, not a
|
|
/// duration: a block that expires in ten minutes expires in ten minutes on the
|
|
/// other edge, not a week from the import.</summary>
|
|
public sealed record ExportedBlock(string Ip, string? Reason, string? RedirectTo, DateTimeOffset? ExpiresAt);
|
|
|
|
/// <summary>An exemption. Same expiry ruling as a block.</summary>
|
|
public sealed record ExportedAllow(string Match, string? Note, DateTimeOffset? ExpiresAt);
|
|
|
|
/// <summary>A path rule. <c>Action</c> is the lowercase spelling the API uses,
|
|
/// and the order in the document is the order the engine evaluates them in.</summary>
|
|
public sealed record ExportedRule(string Pattern, string? Action, string? Note, DateTimeOffset? ExpiresAt);
|
|
|
|
/// <summary>A country decision.</summary>
|
|
public sealed record ExportedCountry(string Code, bool Allowed);
|
|
|
|
public static class ConfigTransfer
|
|
{
|
|
/// <summary>The version this build writes, and the only one it reads. A
|
|
/// document from another version is refused rather than half-applied.</summary>
|
|
public const int CurrentVersion = 1;
|
|
|
|
/// <summary>Per-section cap. An import is one request and one transaction
|
|
/// per section; a document with a million rows is not a config transfer, it
|
|
/// is a data load asked to behave like one.</summary>
|
|
public const int MaxItemsPerSection = 2_000;
|
|
|
|
/// <summary>Body cap, checked before the document is parsed.</summary>
|
|
public const long MaxBodyBytes = 2_000_000;
|
|
|
|
/// <summary>How many rejected items the answer names before it says
|
|
/// "and more". A report that prints every rejection of a 2000-row document
|
|
/// is a report nobody reads.</summary>
|
|
public const int MaxReportedRejections = 20;
|
|
|
|
public static string? ExplainVersion(int version) =>
|
|
version == CurrentVersion
|
|
? null
|
|
: $"unsupported document version {version}; this edge reads version {CurrentVersion}";
|
|
|
|
public static string? ExplainSectionSize(string section, int count) =>
|
|
count <= MaxItemsPerSection
|
|
? null
|
|
: $"\"{section}\" holds {count} items; an import carries at most {MaxItemsPerSection} per section";
|
|
|
|
/// <summary>Is this row already past its expiry at <paramref name="now"/>?
|
|
/// A row that is not live where it came from is not a decision the operator
|
|
/// is asking for, so it is skipped and counted rather than imported as a
|
|
/// live row on the receiving edge.</summary>
|
|
public static bool IsExpired(DateTimeOffset? expiresAt, DateTimeOffset now)
|
|
=> expiresAt is not null && expiresAt <= now;
|
|
|
|
/// <summary>The same guards <c>POST /admin-api/blocks</c> applies, in the
|
|
/// order it applies them, so an item that would be refused one at a time is
|
|
/// refused in a document too.</summary>
|
|
public static string? ExplainBlock(ExportedBlock block)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(block.Ip)) return "ip is required";
|
|
if (!SourceKey.TryParse(block.Ip, out _, out _)) return $"not an IP address: {block.Ip}";
|
|
if (!EntryLimits.NoteOk(block.Reason))
|
|
return $"reason must be at most {EntryLimits.NoteMaxLength} characters; got {block.Reason!.Length}";
|
|
if (block.RedirectTo is not null && !RedirectTarget.IsSendable(block.RedirectTo))
|
|
return $"redirectTo must be an absolute http(s) URL with no spaces or control characters; got \"{block.RedirectTo}\"";
|
|
return null;
|
|
}
|
|
|
|
public static string? ExplainAllow(ExportedAllow allow)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(allow.Match) || !IsValidMatch(allow.Match))
|
|
return "match must be an address or CIDR";
|
|
if (!EntryLimits.NoteOk(allow.Note))
|
|
return $"note must be at most {EntryLimits.NoteMaxLength} characters; got {allow.Note!.Length}";
|
|
return null;
|
|
}
|
|
|
|
public static string? ExplainRule(ExportedRule rule)
|
|
{
|
|
var patternProblem = PathPattern.ExplainRejection(rule.Pattern);
|
|
if (patternProblem is not null) return patternProblem;
|
|
if (!EntryLimits.NoteOk(rule.Note))
|
|
return $"note must be at most {EntryLimits.NoteMaxLength} characters; got {rule.Note!.Length}";
|
|
if (RuleAction(rule.Action) is null)
|
|
return $"action must be observe|block; got \"{rule.Action}\"";
|
|
return null;
|
|
}
|
|
|
|
public static string? ExplainCountry(ExportedCountry country)
|
|
{
|
|
if (CountryCode(country.Code) is null)
|
|
return $"code must be a two-letter ISO country code; got \"{country.Code}\"";
|
|
return null;
|
|
}
|
|
|
|
/// <summary>The action in the spelling the table stores, or null when the
|
|
/// document did not name one this build knows. Absent is <c>observe</c>,
|
|
/// which is what <c>POST /admin-api/rules</c> does with a missing action.</summary>
|
|
public static string? RuleAction(string? action)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(action)) return "observe";
|
|
var trimmed = action.Trim().ToLowerInvariant();
|
|
return trimmed is "observe" or "block" ? trimmed : null;
|
|
}
|
|
|
|
/// <summary>Upper-cased two-letter code, or null. The same rule the country
|
|
/// endpoints apply, so a document cannot smuggle a code the API would
|
|
/// refuse row by row.</summary>
|
|
public static string? CountryCode(string? raw)
|
|
{
|
|
var code = (raw ?? string.Empty).Trim().ToUpperInvariant();
|
|
return code.Length == 2 && char.IsAsciiLetter(code[0]) && char.IsAsciiLetter(code[1]) ? code : null;
|
|
}
|
|
|
|
/// <summary>Address or CIDR, as the allow endpoint reads it.</summary>
|
|
public static bool IsValidMatch(string match)
|
|
{
|
|
if (match.Contains('/')) return NetworkMatch.Matches("203.0.113.1", match) || match.Split('/')[1].Length <= 3;
|
|
return SourceKey.TryParse(match, out _, out _);
|
|
}
|
|
}
|