using OpenWaf.Domain.Engine; using OpenWaf.Domain.Policy; 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. // --------------------------------------------------------------------------- /// 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. public sealed record ExportedBlock(string Ip, string? Reason, string? RedirectTo, DateTimeOffset? ExpiresAt); /// An exemption. Same expiry ruling as a block. public sealed record ExportedAllow(string Match, string? Note, DateTimeOffset? ExpiresAt); /// A path rule. Action is the lowercase spelling the API uses, /// and the order in the document is the order the engine evaluates them in. public sealed record ExportedRule(string Pattern, string? Action, string? Note, DateTimeOffset? ExpiresAt); /// A request budget for one path (OPEN-68). The numbers are nullable so /// a document written by a hand that left them out means "use this build's /// defaults", which is the same thing an absent action means for a path rule. public sealed record ExportedRateRule( string Pattern, int? LimitPerWindow, int? WindowSeconds, string? Note, DateTimeOffset? ExpiresAt); /// A country decision. public sealed record ExportedCountry(string Code, bool Allowed); public static class ConfigTransfer { /// The version this build writes, and the only one it reads. A /// document from another version is refused rather than half-applied. public const int CurrentVersion = 1; /// 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. public const int MaxItemsPerSection = 2_000; /// Body cap, checked before the document is parsed. public const long MaxBodyBytes = 2_000_000; /// 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. 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"; /// Is this row already past its expiry at ? /// 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. public static bool IsExpired(DateTimeOffset? expiresAt, DateTimeOffset now) => expiresAt is not null && expiresAt <= now; /// The same guards POST /admin-api/blocks applies, in the /// order it applies them, so an item that would be refused one at a time is /// refused in a document too. public static string? ExplainBlock(ExportedBlock block) { if (string.IsNullOrWhiteSpace(block.Ip)) return "ip is required"; // An address or a network (OPEN-66): the document that carries an // edge's decisions has to carry the range ban too, and the guard here is // the one POST /admin-api/blocks applies, so a row refused one at a time // is refused in a document too. if (!NetworkBans.TryNormalize(block.Ip, out _, out var targetProblem)) return targetProblem; 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? ExplainRateRule(ExportedRateRule 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}"; // The same bounds the live endpoint applies to a typed request, so a // document cannot bring in a budget the API would have refused. var limit = rule.LimitPerWindow ?? RateRule.DefaultLimitPerWindow; if (!PolicyBounds.RateLimitPerWindowOk(limit)) return $"limitPerWindow must be {PolicyBounds.RateLimitPerWindowMin}..{PolicyBounds.RateLimitPerWindowMax}; got {limit}"; var window = rule.WindowSeconds ?? RateRule.DefaultWindowSeconds; if (!PolicyBounds.RateWindowSecondsOk(window)) return $"windowSeconds must be {PolicyBounds.RateWindowSecondsMin:0}..{PolicyBounds.RateWindowSecondsMax:0}; got {window}"; 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; } /// The action in the spelling the table stores, or null when the /// document did not name one this build knows. Absent is observe, /// which is what POST /admin-api/rules does with a missing action. 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; } /// 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. 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; } /// Address or CIDR, as the allow endpoint reads it. 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 _); } }