diff --git a/README.md b/README.md index a46121e..19dc906 100644 --- a/README.md +++ b/README.md @@ -859,6 +859,54 @@ scrape cannot be the thing that makes an unhealthy database unhealthy for the request path, and an edge whose storage is down still answers with the numbers that describe the failure. +### The operator's config leaves the edge as one document + +`GET /admin-api/export` answers one JSON document — `version`, `exportedAt`, +`edgeId`, the `policy` this edge is enforcing, and the operator's own rows: +`blocks`, `allow`, `rules`, `countries`. `POST /admin-api/import` applies a +document like it. + +```bash +curl -H "X-Admin-Token: $TOKEN" http://edge:8080/admin-api/export > openwaf-config.json +curl -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + --data-binary @openwaf-config.json http://other-edge:8080/admin-api/import +``` + +It exists because of the same finding `SharedStreaks` answers, one level up +(`research/2026-10-01-multi-instance/`): with N edges and one database each, an +operator types every rule N times and the edges drift, a new deployment starts +empty, and a change that turns out wrong has nothing to be rebuilt from. + +What the transfer does **not** do is the part worth reading: + +* **Engine bans do not travel.** 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 answers `engineBlocksLeftBehind` with the count + it left out, so "0 blocks" and "0 operator blocks, 7 engine bans left behind" + stay different sentences. +* **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 — and a row that is already there is reported as + `alreadyThere`, not rewritten. Importing the same document twice lands each row + once. +* **Expiry travels as an instant.** A block that expires in ten minutes where it + came from expires in ten minutes here; a row already past its expiry is + `skippedExpired`, not imported as a live row. +* **A bad item does not stop the document.** Each item is checked by the same guard + the write endpoint uses, and the answer reports per section — `added`, + `alreadyThere`, `skippedExpired`, `rejected` — plus the first 20 rejections named + by section, index and reason. A document this build cannot read (unknown + `version`, a section over 2 000 items, a body over 2 MB, malformed JSON) is + refused by name and writes nothing at all. +* **The `policy` section goes through the same write path as + `PUT /admin-api/policy`** — same bounds, same refusal by name. If it is refused, + the rows still land and the report says the policy was not changed and why. +* **A storage failure is a 503 with the counts.** What landed is reported; the + status says the rest did not. + +After an import the guard enforces it on the next request — the snapshot is +invalidated, as it is for every other mutation. + ## Console `GET /admin` serves a single page over those endpoints — mode and snapshot age, @@ -1042,10 +1090,10 @@ Rehearsed 2026-10-02, most recently at `dc88f36`, each stage run on its own. On the head of this file the host suite has been re-run and the container stages have not, so the two sets of numbers are labelled separately rather than merged into one green line. macOS host, this tree, re-measured 2026-10-05 with the durable -alert-push queue on it: build 0 warnings / 0 errors, unit **277/277**, integration -**251/251 in 34 s**, console **90 assertions, 0 failed**, smoke **passed 68, -failed 0**, and compose **232 passed, 0 failed** against the built image at -261 MB, 0 containers left behind. The smoke count moved by more than its new scene: the edge was being +alert-push queue and the config transfer on it: build 0 warnings / 0 errors, unit **285/285**, +integration **257/257 in 20 s**, console **90 assertions, 0 failed**, smoke **passed 82, +failed 0**, and compose **243 passed, 0 failed** against the built image at +262 MB, 0 containers left behind. The smoke count moved by more than its new scene: the edge was being started from the repository root, where there is no `appsettings.json`, so it loaded no `ReverseProxy` section, logged "Request reached the end of the middleware pipeline without being handled by application code" for every request, @@ -1232,6 +1280,14 @@ Stated, because a defence that hides its failure modes is not a defence. same surface as the admin API with the same token, so a scrape is a credentialed request. Per-source metrics are out for the same reason the project keeps no request log. +* **The exported document is a capability, not a backup.** It carries the + operator's decisions — every operator block, exemption, path rule, country + decision and the policy that bounds them — and nothing about traffic: no + observations, no alerts, no engine bans. So it rebuilds what an edge enforces, + it does not restore what an edge knows, and it is only as secret as the admin + token that reads it. Import is additive for the same reason: a document that + could delete rows the operator never wrote would make a leak of the file worse + than a leak of the file already is. * **The push queue is durable; the delivery is still not guaranteed.** What is owed is a row in `alert_pushes`, so a restart picks it up and two edges over one database claim a row before sending it — but the bound is attempts, not time. diff --git a/dotnet/OpenWaf.Domain/Security/ConfigTransfer.cs b/dotnet/OpenWaf.Domain/Security/ConfigTransfer.cs new file mode 100644 index 0000000..ad52b60 --- /dev/null +++ b/dotnet/OpenWaf.Domain/Security/ConfigTransfer.cs @@ -0,0 +1,140 @@ +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. +// --------------------------------------------------------------------------- + +/// 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 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"; + 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; + } + + /// 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 _); + } +} diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.ConfigTransfer.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.ConfigTransfer.cs new file mode 100644 index 0000000..15538b6 --- /dev/null +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.ConfigTransfer.cs @@ -0,0 +1,471 @@ +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; + +/// +/// 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: +/// +/// * Engine bans do not travel. 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. +/// * 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 — and a row that is +/// already there is reported as already there, not rewritten. +/// * Expiry travels as an instant. 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. +/// +internal static partial class AdminEndpoints +{ + private static void MapConfigTransfer(RouteGroupBuilder group) + { + 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); + 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, + 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), + blocks = blockRows.Select(b => new ExportedBlock(b.SourceKey, 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)) + }); + }); + + group.MapPost("/import", async (OpenWafDbContext db, EdgeStateStore state, EdgePolicyProvider policy, + IStreakTracker streaks, RateTracker rates, BlockStore blocks, 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(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(); + 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); + + 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); + }); + } + + /// + /// The one place a policy request becomes the overrides the policy store + /// keeps. PUT /admin-api/policy and the policy 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. + /// + private static bool PolicyOverrides( + PolicyUpdateRequest req, out Dictionary overrides, out string? problem) + { + overrides = new Dictionary(); + problem = null; + + if (req.Mode is not null) + { + if (!Enum.TryParse(req.Mode, true, out var mode)) + { + problem = $"mode must be one of {string.Join('|', Enum.GetNames())}"; + return false; + } + overrides["mode"] = mode.ToString(); + } + if (req.Geo is not null) + { + if (!Enum.TryParse(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(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(); + return true; + } +} + +/// The document as it arrives. The sections are optional: a document +/// that carries only rules is a legitimate way to move rules. +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); + +/// 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. +internal sealed record RejectedItem(string Section, int Index, string? Item, string Error); + +/// 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. +internal static class WebJson +{ + public static readonly JsonSerializerOptions Options = new(JsonSerializerDefaults.Web); +} diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs index 0545946..52ccfbe 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs @@ -17,7 +17,7 @@ namespace OpenWaf.Edge.Admin; /// clear that provenance, and every mutation invalidates the guard snapshot so /// the change lands on the next request instead of after the TTL. /// -internal static class AdminEndpoints +internal static partial class AdminEndpoints { public static IEndpointRouteBuilder MapAdminApi(this IEndpointRouteBuilder app, string? adminToken) { @@ -280,49 +280,19 @@ internal static class AdminEndpoints IStreakTracker streaks, RateTracker rates, HttpContext ctx, CancellationToken ct) => { if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { error = unknown }); - var overrides = new Dictionary(); - if (req.Mode is not null) - { - if (!Enum.TryParse(req.Mode, true, out var mode)) - return Results.BadRequest(new { error = $"mode must be one of {string.Join('|', Enum.GetNames())}" }); - overrides["mode"] = mode.ToString(); - } - if (req.Geo is not null) - { - if (!Enum.TryParse(req.Geo, true, out var geo)) - return Results.BadRequest(new { error = "geo must be Off|DenyList|AllowList" }); - overrides["geo"] = geo.ToString(); - } - if (req.RateMode is not null) - { - if (!Enum.TryParse(req.RateMode, true, out var rateMode)) - return Results.BadRequest(new { error = "rateMode must be one of Off|Observe|Enforce" }); - overrides["rateMode"] = rateMode.ToString(); - } + // The same path an imported document's `policy` section goes through: + // one place turns a policy request into the overrides the store keeps, + // so a document cannot be held to a looser rule than a typed request. + // // A field that is present but out of range is a 400, not a silent // no-op. The old shape — `if (req.X is > 0)` — answered 200 with the // old policy in the body for streakThreshold=0, maxTrackedSources=0, - // banDurationMinutes=-1 and refusalRange="not-a-range", and it - // stored engineBlockStatus=1000 and ipv4KeyPrefixLength=0, which the - // edge then obeyed: the first closed the connection on every banned - // request, the second made one ban apply to every IPv4 address. - var problem = PolicyProblem(req); - if (problem is not null) return Results.BadRequest(new { error = problem }); - - 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(); + // banDurationMinutes=-1 and refusalRange="not-a-range", and it stored + // engineBlockStatus=1000 and ipv4KeyPrefixLength=0, which the edge then + // obeyed: the first closed the connection on every banned request, the + // second made one ban apply to every IPv4 address. + if (!PolicyOverrides(req, out var overrides, out var problem)) + return Results.BadRequest(new { error = problem! }); // The toggle is a policy change, never a data change: switching // automatic banning off must leave every row — manual or engine — @@ -837,6 +807,10 @@ note = t.Note }); }); + // The operator's config as one document (OPEN-61), on the same group so it + // carries the same token check and the same unknown-query rule. + MapConfigTransfer(group); + return app; } diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/AlertNotifier.cs b/dotnet/OpenWaf.Infrastructure/Persistence/AlertNotifier.cs index c81d1c3..d45f2df 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/AlertNotifier.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/AlertNotifier.cs @@ -163,29 +163,68 @@ public sealed class AlertNotifier : BackgroundService // Nothing is replayed from memory on purpose: whatever this process was // holding is in the table, and whatever a previous process left is picked // up here. That is the whole of "eventually". - while (!stoppingToken.IsCancellationRequested) + try { - try + while (!stoppingToken.IsCancellationRequested) { - await DrainAsync(stoppingToken); - } - catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) - { - return; - } - catch (Exception ex) - { - // The queue itself is unreachable. Counted, because a worker that - // cannot read its own queue is the same blindness as an endpoint - // that is down, and quieter. - _health.RecordFailure(Pillar, ex); - _log.LogWarning(ex, "AlertNotifier: the delivery queue could not be read."); - } + try + { + await DrainAsync(stoppingToken); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + return; + } + catch (Exception ex) + { + // The queue itself is unreachable. Counted, because a worker that + // cannot read its own queue is the same blindness as an endpoint + // that is down, and quieter. + _health.RecordFailure(Pillar, ex); + _log.LogWarning(ex, "AlertNotifier: the delivery queue could not be read."); + } - using var wait = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); - wait.CancelAfter(TimeSpan.FromSeconds(PollSeconds)); - try { _ = await _wake.Reader.ReadAsync(wait.Token); } - catch (OperationCanceledException) { } + using var wait = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); + wait.CancelAfter(TimeSpan.FromSeconds(PollSeconds)); + try { _ = await _wake.Reader.ReadAsync(wait.Token); } + catch (OperationCanceledException) { } + } + } + finally + { + // A row this process claimed but never finished must not sit behind its + // own claim until the reclaim window expires. The window exists for a + // process that was killed and cannot say anything; a process that is + // being stopped can, and saying it is the difference between "the next + // process picks up what is owed" and "it picks it up five minutes + // later". Measured: with no release here, the restart test below stalled + // on the claim its own predecessor left. + await ReleaseOwnClaimsAsync(); + } + } + + /// Give back the owed rows this process holds a claim on. Runs after + /// the stopping token has fired, so it uses its own bounded one: a database + /// that is already gone must not hold the process open on shutdown, and the + /// reclaim window is the backstop for exactly that case. + private async Task ReleaseOwnClaimsAsync() + { + try + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + var released = await db.AlertPushes + .Where(p => p.ClaimedBy == _processId && p.PushedAt == null && p.GivenUpAt == null) + .ExecuteUpdateAsync(s => s + .SetProperty(p => p.ClaimedBy, (string?)null) + .SetProperty(p => p.ClaimedAt, (DateTimeOffset?)null), timeout.Token); + if (released > 0) + _log.LogInformation("AlertNotifier: released {Rows} owed deliveries this process had claimed.", released); + } + catch (Exception ex) + { + _log.LogWarning(ex, "AlertNotifier: could not release this process's claims; the reclaim window will do it."); } } diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/BlockStore.cs b/dotnet/OpenWaf.Infrastructure/Persistence/BlockStore.cs index 8866225..37bcbcc 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/BlockStore.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/BlockStore.cs @@ -373,6 +373,69 @@ public sealed class BlockStore return (AddResult.StorageFailure, "the block list could not be written: the block is NOT in effect"); } + /// What an imported operator block ended as. Different from + /// because an import is not a re-write: a row that + /// is already there is reported as already there and left alone, so the + /// same document applied twice lands once (OPEN-61). + public enum ImportResult { Added, AlreadyThere, StorageFailure } + + /// + /// Land one operator block from a transferred document. + /// + /// Two differences from , and both are the + /// transfer's rulings rather than implementation detail. The expiry is an + /// instant carried by the document, not a number of minutes from now — a + /// block that expires in ten minutes on the edge it came from expires in ten + /// minutes here. And a live row for the same source is not refreshed: the + /// operator who imports twice gets the same table, not a table whose expiry + /// moved under them. + /// + public async Task<(ImportResult Result, string? Error)> ImportOperatorAsync( + string address, string? reason, string? redirectTo, DateTimeOffset? expiresAt, + DateTimeOffset now, CancellationToken ct = default) + { + if (!SourceKey.TryParse(address, out _, out var normalized)) + return (ImportResult.StorageFailure, $"not an IP address: {address}"); + + var key = SourceKey.For(normalized.ToString(), _policy.Current); + + for (var attempt = 0; attempt < 2; attempt++) + { + try + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var live = await db.Blocks.AnyAsync( + b => b.SourceKey == key && b.Source == BlockSource.Operator + && (b.ExpiresAt == null || b.ExpiresAt > now), ct); + if (live) return (ImportResult.AlreadyThere, null); + + db.Blocks.Add(new BlockEntry + { + SourceKey = key, + Source = BlockSource.Operator, + CreatedAt = now, + Reason = reason, + RedirectTo = redirectTo, + ExpiresAt = expiresAt + }); + await db.SaveChangesAsync(ct); + return (ImportResult.Added, null); + } + catch (DbUpdateException ex) when (attempt == 0) + { + _log.LogWarning(ex, "BlockStore: concurrent import on {Key}; retrying against the winner's row.", key); + } + catch (Exception ex) + { + _log.LogWarning(ex, "BlockStore: import of an operator block failed for {Key}.", key); + return (ImportResult.StorageFailure, "the block list could not be written: the block is NOT in effect"); + } + } + + return (ImportResult.StorageFailure, "the block list could not be written: the block is NOT in effect"); + } + /// /// Delete blocks, optionally restricted to one provenance. The provenance /// filter is not cosmetic: "clear the automatic bans" must never be able to diff --git a/dotnet/OpenWaf.Tests.Integration/AlertPushQueueTests.cs b/dotnet/OpenWaf.Tests.Integration/AlertPushQueueTests.cs index faaa118..0e38f00 100644 --- a/dotnet/OpenWaf.Tests.Integration/AlertPushQueueTests.cs +++ b/dotnet/OpenWaf.Tests.Integration/AlertPushQueueTests.cs @@ -132,6 +132,12 @@ public sealed class AlertPushQueueTests // Second process, same database, working endpoint. It raised nothing and // nobody asked it to remember anything: the queue is rows, so the promise // outlives the process that made it. + // + // The 25 s the wait allows is the assertion. A row the first process + // claimed and never finished would otherwise sit behind that claim until + // the reclaim window expires — five minutes — and this test would fail on + // a queue that is durable and merely waiting. The notifier releases what + // it holds on the way out; the window is for a process that was killed. await using var second = new EdgeFixture( threshold: 3, alertWebhookPath: "/hook", dbPath: dbPath, maxPushAttempts: 20, pushRetrySeconds: 1); second.Upstream.StatusFor = _ => StatusCodes.Status200OK; @@ -273,7 +279,12 @@ public sealed class AlertPushQueueTests request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken); using var response = await f.Client.SendAsync(request); body = await response.Content.ReadAsStringAsync(); - if (System.Text.RegularExpressions.Regex.IsMatch(body, "openwaf_alert_push_pending [1-9]")) break; + // Both numbers, not just the first: a pass that refreshes the cache + // between an enqueue and its first attempt sees a row that is owed + // and not yet tried, so "pending > 0" alone can be true a moment + // before "attempts > 0" ever can. + if (System.Text.RegularExpressions.Regex.IsMatch(body, "openwaf_alert_push_pending [1-9]") + && System.Text.RegularExpressions.Regex.IsMatch(body, "openwaf_alert_push_attempts_total [1-9]")) break; await Task.Delay(250); } diff --git a/dotnet/OpenWaf.Tests.Integration/ConfigTransferTests.cs b/dotnet/OpenWaf.Tests.Integration/ConfigTransferTests.cs new file mode 100644 index 0000000..3fb7794 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/ConfigTransferTests.cs @@ -0,0 +1,275 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text; +using System.Text.Json; + +namespace OpenWaf.Tests.Integration; + +/// +/// The operator's config as one document (OPEN-61). +/// +/// Every row in it could already be written one at a time, so the interesting +/// question is not "can it be stored" but "does the second edge behave like the +/// first afterwards". That is what these tests ask: a real edge writes a block, +/// an exemption, a path rule and a country decision; a second edge with an empty +/// database imports what the first exported; and the assertions are made on the +/// wire of the second edge, not in its tables. +/// +/// The rulings under test are the ones the feature could quietly get wrong: +/// engine bans do not travel, import is additive and idempotent, expiry is an +/// instant, and a document this build cannot read writes nothing. +/// +public sealed class ConfigTransferTests +{ + private const string Blocked = "203.0.113.141"; + private const string Exempt = "203.0.113.142"; + private const string Bystander = "203.0.113.143"; + private const string EngineBanned = "203.0.113.144"; + + private static async Task GetAsync(EdgeFixture f, string path, string ip) + { + using var request = new HttpRequestMessage(HttpMethod.Get, path); + request.Headers.TryAddWithoutValidation("X-Forwarded-For", ip); + return await f.Client.SendAsync(request); + } + + private static async Task ExportAsync(EdgeFixture f) + { + using var response = await f.Client.GetAsync($"/admin-api/export?token={EdgeFixture.AdminToken}"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + return await response.Content.ReadAsStringAsync(); + } + + private static async Task<(HttpStatusCode Status, JsonElement Body)> ImportAsync(EdgeFixture f, string document) + { + using var content = new StringContent(document, Encoding.UTF8, "application/json"); + using var response = await f.Client.PostAsync($"/admin-api/import?token={EdgeFixture.AdminToken}", content); + return (response.StatusCode, JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.Clone()); + } + + /// An edge with a hand-written config, and one engine ban it earned + /// by serving refusals — the thing that must not travel. + private static async Task<(EdgeFixture Fixture, string Document)> WriteConfigAndExportAsync() + { + var f = new EdgeFixture(); + using (var b = await f.Client.PostAsJsonAsync($"/admin-api/blocks?token={EdgeFixture.AdminToken}", + new { ip = Blocked, reason = "incident: written by hand" })) + Assert.Equal(HttpStatusCode.NoContent, b.StatusCode); + using (var a = await f.Client.PostAsJsonAsync($"/admin-api/allow?token={EdgeFixture.AdminToken}", + new { match = Exempt, note = "office" })) + Assert.Equal(HttpStatusCode.NoContent, a.StatusCode); + using (var r = await f.Client.PostAsJsonAsync($"/admin-api/rules?token={EdgeFixture.AdminToken}", + new { pattern = "/wp-admin*", action = "block", note = "cms" })) + Assert.Equal(HttpStatusCode.NoContent, r.StatusCode); + using (var c = await f.Client.PutAsync( + $"/admin-api/countries/de?allowed=false&token={EdgeFixture.AdminToken}", null)) + Assert.Equal(HttpStatusCode.NoContent, c.StatusCode); + + // Three upstream refusals at the default threshold: an engine ban, earned + // by this edge's own traffic. + for (var i = 0; i < 3; i++) + using (var probe = await GetAsync(f, "/anything", EngineBanned)) + Assert.Equal(HttpStatusCode.NotFound, probe.StatusCode); + + return (f, await ExportAsync(f)); + } + + [Fact] + public async Task An_exported_document_replays_the_operators_decisions_on_another_edge() + { + var (source, document) = await WriteConfigAndExportAsync(); + await using (source) + { + var exported = JsonDocument.Parse(document).RootElement; + Assert.Equal(1, exported.GetProperty("counts").GetProperty("blocks").GetInt32()); + Assert.Equal(1, exported.GetProperty("counts").GetProperty("rules").GetInt32()); + Assert.Equal(1, exported.GetProperty("counts").GetProperty("countries").GetInt32()); + // The sentence the AC asks for: the ban this edge earned stays here, + // and the export says how many it left out. + Assert.True(exported.GetProperty("engineBlocksLeftBehind").GetInt32() >= 1, document); + Assert.DoesNotContain(EngineBanned, + exported.GetProperty("blocks").EnumerateArray().Select(b => b.GetProperty("ip").GetString())); + + await using var target = new EdgeFixture(); + + var (status, report) = await ImportAsync(target, document); + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal(1, report.GetProperty("blocks").GetProperty("added").GetInt32()); + Assert.Equal(1, report.GetProperty("allow").GetProperty("added").GetInt32()); + Assert.Equal(1, report.GetProperty("rules").GetProperty("added").GetInt32()); + Assert.Equal(1, report.GetProperty("countries").GetProperty("added").GetInt32()); + Assert.True(report.GetProperty("policy").GetProperty("applied").GetBoolean(), report.ToString()); + + // The claim is on the wire, not in the tables. + using (var blocked = await GetAsync(target, "/anything", Blocked)) + Assert.Equal(HttpStatusCode.MovedPermanently, blocked.StatusCode); + using (var exempt = await GetAsync(target, "/anything", Exempt)) + Assert.Equal(HttpStatusCode.NotFound, exempt.StatusCode); + using (var rule = await GetAsync(target, "/wp-admin", Bystander)) + Assert.Equal(HttpStatusCode.Forbidden, rule.StatusCode); + using (var bystander = await GetAsync(target, "/anything", Bystander)) + Assert.Equal(HttpStatusCode.NotFound, bystander.StatusCode); + + // The engine ban did not come with it. + using (var engine = await target.Client.GetAsync( + $"/admin-api/blocks?source=engine&token={EdgeFixture.AdminToken}")) + Assert.Empty(JsonDocument.Parse(await engine.Content.ReadAsStringAsync()).RootElement.EnumerateArray()); + + using (var countries = await target.Client.GetAsync( + $"/admin-api/countries?token={EdgeFixture.AdminToken}")) + { + var rows = JsonDocument.Parse(await countries.Content.ReadAsStringAsync()) + .RootElement.EnumerateArray().ToList(); + var de = rows.FirstOrDefault(r => r.GetProperty("code").GetString() == "DE"); + Assert.Equal(JsonValueKind.Object, de.ValueKind); + Assert.False(de.GetProperty("isAllowed").GetBoolean()); + } + } + } + + [Fact] + public async Task Importing_the_same_document_twice_lands_each_row_once() + { + var (source, document) = await WriteConfigAndExportAsync(); + await using (source) + { + await using var target = new EdgeFixture(); + + var (first, _) = await ImportAsync(target, document); + Assert.Equal(HttpStatusCode.OK, first); + var (second, report) = await ImportAsync(target, document); + Assert.Equal(HttpStatusCode.OK, second); + + Assert.Equal(0, report.GetProperty("blocks").GetProperty("added").GetInt32()); + Assert.Equal(1, report.GetProperty("blocks").GetProperty("alreadyThere").GetInt32()); + Assert.Equal(0, report.GetProperty("rules").GetProperty("added").GetInt32()); + Assert.Equal(1, report.GetProperty("rules").GetProperty("alreadyThere").GetInt32()); + Assert.Equal(0, report.GetProperty("countries").GetProperty("added").GetInt32()); + Assert.Equal(1, report.GetProperty("countries").GetProperty("alreadyThere").GetInt32()); + + using (var blocks = await target.Client.GetAsync( + $"/admin-api/blocks?source=operator&token={EdgeFixture.AdminToken}")) + Assert.Single(JsonDocument.Parse(await blocks.Content.ReadAsStringAsync()).RootElement.EnumerateArray()); + } + } + + [Fact] + public async Task A_row_past_its_expiry_is_skipped_and_counted_rather_than_imported_live() + { + await using var target = new EdgeFixture(); + var document = JsonSerializer.Serialize(new + { + version = 1, + blocks = new[] + { + new { ip = Blocked, reason = "already over", expiresAt = DateTimeOffset.UtcNow.AddMinutes(-30) }, + new { ip = Exempt, reason = "still running", expiresAt = DateTimeOffset.UtcNow.AddMinutes(30) } + } + }); + + var (status, report) = await ImportAsync(target, document); + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal(1, report.GetProperty("blocks").GetProperty("added").GetInt32()); + Assert.Equal(1, report.GetProperty("blocks").GetProperty("skippedExpired").GetInt32()); + + using (var expired = await GetAsync(target, "/anything", Blocked)) + Assert.Equal(HttpStatusCode.NotFound, expired.StatusCode); + using (var live = await GetAsync(target, "/anything", Exempt)) + Assert.Equal(HttpStatusCode.MovedPermanently, live.StatusCode); + + // And the expiry that did travel is an instant, not a fresh duration: + // the row says when it stops, within the minute the document named. + using (var blocks = await target.Client.GetAsync( + $"/admin-api/blocks?source=operator&token={EdgeFixture.AdminToken}")) + { + var rows = JsonDocument.Parse(await blocks.Content.ReadAsStringAsync()).RootElement.EnumerateArray().ToList(); + var mine = rows.Single(r => r.GetProperty("sourceKey").GetString() == Exempt); + Assert.InRange(mine.GetProperty("expiresAt").GetDateTimeOffset(), + DateTimeOffset.UtcNow.AddMinutes(28), DateTimeOffset.UtcNow.AddMinutes(32)); + } + } + + [Fact] + public async Task A_bad_item_is_named_by_section_and_position_and_the_rest_still_lands() + { + await using var target = new EdgeFixture(); + var document = JsonSerializer.Serialize(new + { + version = 1, + blocks = new object[] + { + new { ip = Blocked, reason = "good" }, + new { ip = "not-an-ip", reason = "bad" } + }, + rules = new object[] { new { pattern = "no-slash", action = "block" } } + }); + + var (status, report) = await ImportAsync(target, document); + Assert.Equal(HttpStatusCode.OK, status); + Assert.Equal(1, report.GetProperty("blocks").GetProperty("added").GetInt32()); + Assert.Equal(1, report.GetProperty("blocks").GetProperty("rejected").GetInt32()); + Assert.Equal(1, report.GetProperty("rules").GetProperty("rejected").GetInt32()); + + var bad = report.GetProperty("rejected").EnumerateArray().ToList(); + Assert.Contains(bad, r => r.GetProperty("section").GetString() == "blocks" + && r.GetProperty("index").GetInt32() == 1 + && r.GetProperty("error").GetString()!.Contains("not an IP address")); + Assert.Contains(bad, r => r.GetProperty("section").GetString() == "rules"); + + using (var blocked = await GetAsync(target, "/anything", Blocked)) + Assert.Equal(HttpStatusCode.MovedPermanently, blocked.StatusCode); + } + + [Fact] + public async Task A_document_this_build_cannot_read_is_refused_by_name_and_writes_nothing() + { + await using var target = new EdgeFixture(); + + var future = JsonSerializer.Serialize(new + { + version = 999, + blocks = new[] { new { ip = Blocked, reason = "would have landed" } } + }); + var (versionStatus, versionBody) = await ImportAsync(target, future); + Assert.Equal(HttpStatusCode.BadRequest, versionStatus); + Assert.Contains("999", versionBody.ToString()); + + var (jsonStatus, jsonBody) = await ImportAsync(target, "{\"version\": 1, \"blocks\": ["); + Assert.Equal(HttpStatusCode.BadRequest, jsonStatus); + Assert.Contains("not valid JSON", jsonBody.ToString()); + + using (var blocks = await target.Client.GetAsync( + $"/admin-api/blocks?live=false&token={EdgeFixture.AdminToken}")) + Assert.Empty(JsonDocument.Parse(await blocks.Content.ReadAsStringAsync()).RootElement.EnumerateArray()); + } + + [Fact] + public async Task An_out_of_range_policy_in_a_document_is_refused_by_the_same_bounds_as_a_typed_request() + { + var (source, document) = await WriteConfigAndExportAsync(); + await using (source) + { + // The same document, with one policy field the API would refuse from + // a keyboard: streakThreshold=0. + var broken = document.Replace("\"streakThreshold\":10", "\"streakThreshold\":0") + .Replace("\"streakThreshold\":3", "\"streakThreshold\":0"); + + await using var target = new EdgeFixture(); + var before = await target.Client.GetAsync($"/admin-api/policy?token={EdgeFixture.AdminToken}"); + var beforeThreshold = JsonDocument.Parse(await before.Content.ReadAsStringAsync()) + .RootElement.GetProperty("streakThreshold").GetInt32(); + + var (status, report) = await ImportAsync(target, broken); + Assert.Equal(HttpStatusCode.OK, status); + Assert.False(report.GetProperty("policy").GetProperty("applied").GetBoolean(), report.ToString()); + Assert.Contains("streakThreshold", report.GetProperty("policy").GetProperty("error").GetString()); + // The rows are not held hostage to a bad policy section: the report + // says which half happened. + Assert.Equal(1, report.GetProperty("blocks").GetProperty("added").GetInt32()); + + var after = await target.Client.GetAsync($"/admin-api/policy?token={EdgeFixture.AdminToken}"); + Assert.Equal(beforeThreshold, JsonDocument.Parse(await after.Content.ReadAsStringAsync()) + .RootElement.GetProperty("streakThreshold").GetInt32()); + } + } +} diff --git a/dotnet/OpenWaf.Tests.Unit/ConfigTransferTests.cs b/dotnet/OpenWaf.Tests.Unit/ConfigTransferTests.cs new file mode 100644 index 0000000..dd7dcc9 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Unit/ConfigTransferTests.cs @@ -0,0 +1,108 @@ +using OpenWaf.Domain.Security; + +namespace OpenWaf.Tests.Unit; + +/// +/// The rulings of a config transfer, away from an edge (OPEN-61). +/// +/// The endpoint decides what to write; these functions decide whether a row is +/// worth writing at all, and every one of them is a ruling that could be +/// silently inverted in the handler — an expired row imported as live, a version +/// accepted that this build cannot read, a section size that turns one request +/// into a data load. Checked here, where they are arithmetic. +/// +public sealed class ConfigTransferTests +{ + private static readonly DateTimeOffset Now = new(2026, 10, 5, 12, 0, 0, TimeSpan.Zero); + + [Fact] + public void The_version_this_build_writes_is_the_only_one_it_reads() + { + Assert.Null(ConfigTransfer.ExplainVersion(ConfigTransfer.CurrentVersion)); + var problem = ConfigTransfer.ExplainVersion(ConfigTransfer.CurrentVersion + 1)!; + Assert.Contains((ConfigTransfer.CurrentVersion + 1).ToString(), problem); + Assert.Contains(ConfigTransfer.CurrentVersion.ToString(), problem); + // A document that never named a version arrives as 0, and 0 is not a + // version this build can honour. + Assert.NotNull(ConfigTransfer.ExplainVersion(0)); + } + + [Fact] + public void A_section_over_the_cap_is_refused_naming_the_cap() + { + Assert.Null(ConfigTransfer.ExplainSectionSize("blocks", ConfigTransfer.MaxItemsPerSection)); + var problem = ConfigTransfer.ExplainSectionSize("blocks", ConfigTransfer.MaxItemsPerSection + 1)!; + Assert.Contains("blocks", problem); + Assert.Contains(ConfigTransfer.MaxItemsPerSection.ToString(), problem); + } + + [Fact] + public void A_row_without_an_expiry_never_expires_and_a_past_instant_always_has() + { + Assert.False(ConfigTransfer.IsExpired(null, Now)); + Assert.False(ConfigTransfer.IsExpired(Now.AddSeconds(1), Now)); + Assert.True(ConfigTransfer.IsExpired(Now.AddSeconds(-1), Now)); + // The instant itself is already past: "expires at 12:00" is not enforced + // at 12:00, which is the same rule the engine's IsLive applies. + Assert.True(ConfigTransfer.IsExpired(Now, Now)); + } + + [Fact] + public void A_block_is_checked_by_the_same_guards_the_write_endpoint_uses() + { + Assert.Null(ConfigTransfer.ExplainBlock(new ExportedBlock("203.0.113.9", "incident", null, null))); + Assert.Null(ConfigTransfer.ExplainBlock(new ExportedBlock( + "2001:db8::1", null, "https://example.org/blocked", Now.AddDays(1)))); + Assert.Contains("ip is required", ConfigTransfer.ExplainBlock(new ExportedBlock(" ", null, null, null))!); + // Not "203.0.113": IPAddress.TryParse reads the abbreviated form as + // 203.0.113.0, so that string is an address as far as this guard goes. + Assert.Contains("not an IP address", ConfigTransfer.ExplainBlock(new ExportedBlock("203.0.113.999", null, null, null))!); + Assert.Contains("reason must be at most", + ConfigTransfer.ExplainBlock(new ExportedBlock("203.0.113.9", new string('x', EntryLimits.NoteMaxLength + 1), null, null))!); + Assert.Contains("redirectTo must be an absolute http(s) URL", + ConfigTransfer.ExplainBlock(new ExportedBlock("203.0.113.9", null, "javascript:alert(1)", null))!); + } + + [Fact] + public void An_allow_row_takes_an_address_or_a_cidr_and_nothing_else() + { + Assert.Null(ConfigTransfer.ExplainAllow(new ExportedAllow("198.51.100.0/24", "office", null))); + Assert.Null(ConfigTransfer.ExplainAllow(new ExportedAllow("198.51.100.7", null, null))); + Assert.Contains("address or CIDR", ConfigTransfer.ExplainAllow(new ExportedAllow("office.example", null, null))!); + Assert.Contains("address or CIDR", ConfigTransfer.ExplainAllow(new ExportedAllow("", null, null))!); + Assert.Contains("note must be at most", + ConfigTransfer.ExplainAllow(new ExportedAllow("198.51.100.7", new string('x', EntryLimits.NoteMaxLength + 1), null))!); + } + + [Fact] + public void A_rule_pattern_that_can_never_match_is_refused_before_it_is_stored() + { + Assert.Null(ConfigTransfer.ExplainRule(new ExportedRule("/wp-admin*", "block", "cms", null))); + // Absent is observe, exactly as POST /admin-api/rules reads a missing action. + Assert.Null(ConfigTransfer.ExplainRule(new ExportedRule("/anything", null, null, null))); + Assert.Contains("action must be observe|block", + ConfigTransfer.ExplainRule(new ExportedRule("/anything", "deny", null, null))!); + Assert.NotNull(ConfigTransfer.ExplainRule(new ExportedRule("wp-admin*", "block", null, null))); + Assert.NotNull(ConfigTransfer.ExplainRule(new ExportedRule("", "block", null, null))); + } + + [Fact] + public void A_country_code_is_the_two_letter_code_the_engine_matches() + { + Assert.Null(ConfigTransfer.ExplainCountry(new ExportedCountry("de", false))); + Assert.Equal("DE", ConfigTransfer.CountryCode(" de ")); + Assert.Null(ConfigTransfer.CountryCode("12")); + Assert.Null(ConfigTransfer.CountryCode("DEU")); + Assert.Null(ConfigTransfer.CountryCode(null)); + Assert.Contains("two-letter", ConfigTransfer.ExplainCountry(new ExportedCountry("12", false))!); + } + + [Fact] + public void The_action_travels_in_the_spelling_the_table_stores() + { + Assert.Equal("observe", ConfigTransfer.RuleAction(null)); + Assert.Equal("observe", ConfigTransfer.RuleAction(" ")); + Assert.Equal("block", ConfigTransfer.RuleAction(" BLOCK ")); + Assert.Null(ConfigTransfer.RuleAction("deny")); + } +} diff --git a/scripts/compose-smoke.sh b/scripts/compose-smoke.sh index 4dbc2a0..857401c 100755 --- a/scripts/compose-smoke.sh +++ b/scripts/compose-smoke.sh @@ -1438,6 +1438,44 @@ OPEN59_RULE=$(admin "$EDGE/admin-api/rules" | jget "o['pattern']=='/preview-only check 'and the rule is removable again, so the volume is left clean' '204' \ "$(code -X DELETE -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/admin-api/rules/$OPEN59_RULE")" +echo "- the operator's config leaves the shipped edge as one document (OPEN-61)" +# The transfer on the image an operator would deploy. The in-process suite proves +# the round trip between two fixtures; what could go wrong here is the deployment: +# the route being behind the token, the document surviving the wire, and the +# imported row being enforced by the guard rather than only written to the table. +OPEN61_IP="203.0.113.$(( 150 + RANDOM % 20 ))" +admin -X POST -H 'Content-Type: application/json' \ + -d "{\"ip\":\"$OPEN61_IP\",\"reason\":\"compose: written for the transfer\"}" \ + "$EDGE/admin-api/blocks" >/dev/null +check 'the block the transfer scene needs is in force on the image' '301' \ + "$(code -H "X-Forwarded-For: $OPEN61_IP" "$EDGE/anything")" +OPEN61_DOC=$(admin "$EDGE/admin-api/export") +check 'the shipped export names the version this build reads' '1' \ + "$(printf '%s' "$OPEN61_DOC" | jval version)" +check 'and counts the sections it carries' 'yes' \ + "$(printf '%s' "$OPEN61_DOC" | python3 -c 'import sys,json;c=json.load(sys.stdin)["counts"];print("yes" if all(k in c for k in ("blocks","allow","rules","countries")) else "no")')" +check 'and says how many engine bans it deliberately left out' 'yes' \ + "$(printf '%s' "$OPEN61_DOC" | python3 -c 'import sys,json;print("yes" if isinstance(json.load(sys.stdin).get("engineBlocksLeftBehind"), int) else "no")')" +admin -X DELETE "$EDGE/admin-api/blocks?source=operator&key=$OPEN61_IP" >/dev/null +check 'deleting the block takes it off the wire' '404' \ + "$(code -H "X-Forwarded-For: $OPEN61_IP" "$EDGE/anything")" +OPEN61_IMPORT=$(admin -X POST -H 'Content-Type: application/json' --data-binary "$OPEN61_DOC" "$EDGE/admin-api/import") +check 'importing the document lands the block again' '1' \ + "$(printf '%s' "$OPEN61_IMPORT" | python3 -c 'import sys,json;print(json.load(sys.stdin)["blocks"]["added"])')" +check 'and the guard enforces the imported row, not only the table' '301' \ + "$(code -H "X-Forwarded-For: $OPEN61_IP" "$EDGE/anything")" +check 'importing the same document again adds nothing' '0' \ + "$(admin -X POST -H 'Content-Type: application/json' --data-binary "$OPEN61_DOC" "$EDGE/admin-api/import" \ + | python3 -c 'import sys,json;print(json.load(sys.stdin)["blocks"]["added"])')" +check 'a document from another version is refused naming the version' 'yes' \ + "$(admin -X POST -H 'Content-Type: application/json' -d '{"version":999,"blocks":[]}' "$EDGE/admin-api/import" \ + | grep -q '999' && echo yes || echo no)" +check 'and the closed surface stays closed over it' '401' \ + "$(code -X POST -H 'Content-Type: application/json' -d '{"version":1}' "$EDGE/admin-api/import")" +check 'the transfer row is removable again, so the volume is left clean' '200' \ + "$(code -X DELETE -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" \ + "$EDGE/admin-api/blocks?source=operator&key=$OPEN61_IP")" + echo printf 'compose smoke: %d passed, %d failed\n' "$PASS" "$FAIL" [ "$FAIL" -eq 0 ] diff --git a/scripts/smoke.sh b/scripts/smoke.sh index 5a4ca0c..87307d2 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -244,6 +244,54 @@ check 'and the path flows again once it is gone' 404 \ # only the count does. index.html is the 200 this upstream will give. echo 'openwaf smoke' > /tmp/openwaf-upstream/index.html RATE_IP=203.0.113.88 +echo '- the operator config leaves the edge as one document (OPEN-61)' +# The transfer. A block is written, the whole config is exported, the block is +# deleted, and the exported document is imported back. The assertions are on the +# wire, not on the JSON: the document has to be enough to rebuild what the edge +# enforces, including the redirect the operator typed. +TRANSFER_IP=203.0.113.151 +TRANSFER_JSON='{"ip":"203.0.113.151","reason":"written for the transfer","redirectTo":"https://honeypot.example.org/seen"}' +check 'the block this scene starts with is in force' 204 \ + "$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + --data-binary "$TRANSFER_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks")" +check 'and the wire says so' 301 "$(code -H "X-Forwarded-For: $TRANSFER_IP" "$(from anything)")" +EXPORT_JSON="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/export")" +check 'the export names the version this build reads' 1 \ + "$(printf '%s' "$EXPORT_JSON" | python3 -c 'import sys,json;print(json.load(sys.stdin)["version"])')" +check 'the export counts its sections' yes \ + "$(printf '%s' "$EXPORT_JSON" | python3 -c 'import sys,json;c=json.load(sys.stdin)["counts"];print("yes" if all(k in c for k in ("blocks","allow","rules","countries")) else "no")')" +check 'and says how many engine bans it deliberately left out' yes \ + "$(printf '%s' "$EXPORT_JSON" | python3 -c 'import sys,json;print("yes" if isinstance(json.load(sys.stdin).get("engineBlocksLeftBehind"), int) else "no")')" +check 'the exported document carries no engine ban' yes \ + "$(printf '%s' "$EXPORT_JSON" | python3 -c 'import sys,json;print("yes" if all("203.0.113.66" != b["ip"] for b in json.load(sys.stdin)["blocks"]) else "no")')" +check 'deleting the block takes it off the wire' 200 \ + "$(code -X DELETE -H "X-Admin-Token: $TOKEN" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=operator&key=$TRANSFER_IP")" +check 'and the path flows again' 404 "$(code -H "X-Forwarded-For: $TRANSFER_IP" "$(from anything)")" +IMPORT_JSON="$(curl -s -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + --data-binary "$EXPORT_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/import")" +check 'importing the document lands the block again' 1 \ + "$(printf '%s' "$IMPORT_JSON" | python3 -c 'import sys,json;print(json.load(sys.stdin)["blocks"]["added"])')" +check 'and the wire enforces it, redirect and all' yes \ + "$(curl -s -D- -o /dev/null -H "X-Forwarded-For: $TRANSFER_IP" "$(from anything)" \ + | tr -d '\r' | grep -qi '^location: https://honeypot.example.org/seen' && echo yes || echo no)" +check 'importing the same document again adds nothing' '0 0' \ + "$(curl -s -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + --data-binary "$EXPORT_JSON" "http://127.0.0.1:$EDGE_PORT/admin-api/import" \ + | python3 -c 'import sys,json;d=json.load(sys.stdin);print(d["blocks"]["added"], d["rules"]["added"])')" +BEFORE_IMPORT_BLOCKS="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?live=false" \ + | python3 -c 'import sys,json;print(len(json.load(sys.stdin)))')" +check 'a document from another version is refused naming the version' yes \ + "$(curl -s -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \ + -d '{"version":999,"blocks":[{"ip":"203.0.113.152"}]}' \ + "http://127.0.0.1:$EDGE_PORT/admin-api/import" | grep -q '999' && echo yes || echo no)" +check 'and it wrote nothing' "$BEFORE_IMPORT_BLOCKS" \ + "$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?live=false" \ + | python3 -c 'import sys,json;print(len(json.load(sys.stdin)))')" +check 'the transfer row is removable again, so the run ends clean' 200 \ + "$(code -X DELETE -H "X-Admin-Token: $TOKEN" \ + "http://127.0.0.1:$EDGE_PORT/admin-api/blocks?source=operator&key=$TRANSFER_IP")" + echo '- volume budget' STATE0_JSON="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/state")" check 'the budget is off until an operator writes one' Off \