Files
openwaf/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.ConfigTransfer.cs
T
Pavlo Ratushnyi 718dcaaba3 a second token can read the operator's surfaces and change none of them
One admin secret meant one thing: whatever could read /admin-api/state could also delete every block and rewrite the policy. A Prometheus scrape therefore held a key that can lift a ban, a second operator checking why a visitor was refused held a key that can change what the edge enforces, and OPEN-61's export put a whole edge's config behind the same single GET. The operator's question was never "does this thing know the secret" but "what is it allowed to do", and the shipped answer could only be all or nothing.

OpenWaf:Admin:ReadOnlyToken (env OPENWAF_READ_ONLY_TOKEN) is the second level. Unset is the default and the whole of the previous behaviour. The rulings:

 * A known token without the right is answered 403, not 401, and the body names the key that would grant the write. Collapsing the two sentences sends someone debugging a failing script to check the secret when what is wrong is the endpoint it was sent to.
 * The line is drawn by the request method, not by a flag per endpoint: GET/HEAD/OPTIONS read, everything else writes. A write endpoint added tomorrow is behind the rule the moment it is written; a per-endpoint flag would fail the other way, and one forgotten flag would open the write.
 * GET /admin-api/export is the one read held to the admin token. It is a read and it is still the whole config, so it is the surface where "can read" and "can take" are the same act - and the dashboard token is exactly the one that must not be able to lift a fleet's config.
 * A read-only token sees byte-identical answers to the admin token. Read-only is about what a token may do, not about a weaker view: two people comparing answers must not get different answers because of who asked.
 * A read-only token equal to the admin token (compared after trimming, because env files add newlines) aborts startup naming both keys and never the secret. /admin-api/state answers readOnlyTokenConfigured, so the operator can check the key took effect instead of guessing from a 401.

What the run caught, in order: (1) A real defect, and the interesting one. On the shipped image the startup refusal printed its reason and then the process sat at 100% CPU inside the runtime's crash path - the container stayed "Up (unhealthy)" forever, no exit code, nothing for a supervisor to react to. Refusing to start is only useful if the process leaves, so the refusal now writes the reason to stderr and returns 1; measured again on the image, it exits in 2 s with code 1 and the same sentence. (2) The gate's own assertion for that case had the same blind spot as the bug: waiting on a foreground docker compose run cannot tell "refused" from "hung", so the container is now started detached and polled for an exit within 30 s, and the assertion is that it left. (3) Two smoke asserts were wrong rather than the product: the blocks listing field is sourceKey, not ip, so the first version read an empty answer, and a two-code assertion compared a newline-separated pair against a space-separated literal. (4) An integration assert compared JsonElement.ToString() against "true" - a bool element prints True, so it now reads GetBoolean().

Gates on this tree: build 0 warnings / 0 errors, unit 307/307, integration 286/286 in 26s, smoke 105 passed / 0 failed (23 new), image 262 MB, compose-smoke 261 passed / 0 failed with 0 containers left behind (18 new, against the shipped image), console 90 assertions / 0 failed.

Refs OPEN-62.
2026-10-05 04:57:59 +02:00

484 lines
23 KiB
C#

using System.Text;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using OpenWaf.Domain.Engine;
using OpenWaf.Domain.Policy;
using OpenWaf.Domain.Security;
using OpenWaf.Infrastructure.Persistence;
namespace OpenWaf.Edge.Admin;
/// <summary>
/// The operator's config as one document (OPEN-61).
///
/// Every row in it can already be written one at a time. What could not be done
/// was move them: an operator running several edges types every rule several
/// times, a new deployment starts empty, and a change that turns out wrong has
/// nothing to be restored from. This is the multi-instance finding of
/// research/2026-10-01-multi-instance/ one level up — `SharedStreaks` shares the
/// counters, nothing shared the decisions.
///
/// Three rulings shape the endpoints, and each is a decision rather than a
/// detail:
///
/// * <b>Engine bans do not travel.</b> A ban the engine earned is a claim about
/// this edge's own traffic; enforcing it on an edge that never saw that
/// traffic is a decision nobody made. The export names how many it left
/// behind, so "0 blocks" and "0 operator blocks, 7 engine bans left behind"
/// stay different sentences.
/// * <b>Import is additive and idempotent.</b> It never deletes a row the
/// document does not mention — a transfer that silently clears a fleet's
/// exemptions is worse than one that duplicates a block — and a row that is
/// already there is reported as already there, not rewritten.
/// * <b>Expiry travels as an instant.</b> A block that expires in ten minutes
/// where it came from expires in ten minutes here; a row already past its
/// expiry is skipped and counted, not imported as a live row.
/// </summary>
internal static partial class AdminEndpoints
{
private static void MapConfigTransfer(RouteGroupBuilder group)
{
// The one read on this surface that a read-only token may not do (OPEN-62),
// and the exception is deliberate rather than an oversight: the document
// is every block, exemption, rule and policy override the edge holds -
// the capability OPEN-61 files under "not a backup". The token meant for
// a dashboard and a second pair of eyes is exactly the one that must not
// be able to lift the whole config, so this GET is held to the admin
// token while every other GET is not.
var export = group.MapGet("/export", async (OpenWafDbContext db, EdgePolicyProvider policy,
HttpContext ctx, CancellationToken ct) =>
{
if (!TryKnownQuery(ctx, out var unknown)) return Results.BadRequest(new { 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))
});
});
export.AddEndpointFilter(AdminAuth.RequireFull(
"the exported document is the whole operator config of this edge - every block, "
+ "exemption, path rule, country rule and policy override - so it is a capability "
+ "and not a view: it needs the admin token (OpenWaf__Admin__Token), not the "
+ "read-only one"));
group.MapPost("/import", async (OpenWafDbContext db, EdgeStateStore state, EdgePolicyProvider policy,
IStreakTracker streaks, RateTracker rates, 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<ConfigImportDocument>(body, WebJson.Options);
}
catch (JsonException ex)
{
// Named as a malformed document, not as an empty one: the two
// need different fixes and the operator is holding the file.
return Results.BadRequest(new { 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<RejectedItem>();
string? storageFailure = null;
// --- policy: the same write path as PUT /admin-api/policy -------
var policyApplied = false;
string? policyError = null;
int policyFields = 0;
if (doc.Policy is { } requested)
{
if (!PolicyOverrides(requested, out var overrides, out var problem))
{
policyError = problem;
}
else
{
policyFields = overrides.Count;
if (await policy.SaveAsync(overrides, ct))
{
await state.InvalidateAsync(ct);
streaks.Configure(policy.Current);
rates.Configure(policy.Current);
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);
});
}
/// <summary>
/// The one place a policy request becomes the overrides the policy store
/// keeps. <c>PUT /admin-api/policy</c> and the <c>policy</c> section of an
/// imported document both come through here, so a document cannot be held to
/// a looser rule than a hand-typed request — and cannot be applied by a
/// different path either.
/// </summary>
private static bool PolicyOverrides(
PolicyUpdateRequest req, out Dictionary<string, string?> overrides, out string? problem)
{
overrides = new Dictionary<string, string?>();
problem = null;
if (req.Mode is not null)
{
if (!Enum.TryParse<EnforcementMode>(req.Mode, true, out var mode))
{
problem = $"mode must be one of {string.Join('|', Enum.GetNames<EnforcementMode>())}";
return false;
}
overrides["mode"] = mode.ToString();
}
if (req.Geo is not null)
{
if (!Enum.TryParse<GeoMode>(req.Geo, true, out var geo))
{
problem = "geo must be Off|DenyList|AllowList";
return false;
}
overrides["geo"] = geo.ToString();
}
if (req.RateMode is not null)
{
if (!Enum.TryParse<RateMode>(req.RateMode, true, out var rateMode))
{
problem = "rateMode must be one of Off|Observe|Enforce";
return false;
}
overrides["rateMode"] = rateMode.ToString();
}
// A field that is present but out of range is a refusal, not a silent
// no-op — the same ruling PUT /admin-api/policy carries.
if (PolicyProblem(req) is { } bounds)
{
problem = bounds;
return false;
}
if (req.StreakThreshold is { } streakThreshold) overrides["streakThreshold"] = streakThreshold.ToString();
if (req.StreakWindowMinutes is { } windowMinutes) overrides["streakWindowMinutes"] = windowMinutes.ToString();
if (req.BanDurationMinutes is { } banMinutes) overrides["banDurationMinutes"] = banMinutes.ToString();
if (req.RefusalRange is not null) overrides["refusalRange"] = req.RefusalRange.Trim();
if (req.ServerErrorRange is not null) overrides["serverErrorRange"] = req.ServerErrorRange.Trim();
if (req.TrustProxyHeaders is not null) overrides["trustProxyHeaders"] = req.TrustProxyHeaders.Value.ToString().ToLowerInvariant();
if (req.MaxTrackedSources is { } maxSources) overrides["maxTrackedSources"] = maxSources.ToString();
if (req.Ipv4KeyPrefixLength is { } v4) overrides["ipv4KeyPrefixLength"] = v4.ToString();
if (req.Ipv6KeyPrefixLength is { } v6) overrides["ipv6KeyPrefixLength"] = v6.ToString();
if (req.EngineBlockStatus is { } engineStatus) overrides["engineBlockStatus"] = engineStatus.ToString();
if (req.OperatorBlockStatus is { } operatorStatus) overrides["operatorBlockStatus"] = operatorStatus.ToString();
if (req.DefaultRedirectTargets is { Length: > 0 }) overrides["redirectTargets"] = string.Join(',', req.DefaultRedirectTargets);
if (req.RateLimitPerWindow is { } rateLimit) overrides["rateLimitPerWindow"] = rateLimit.ToString();
if (req.RateWindowSeconds is { } rateWindow) overrides["rateWindowSeconds"] = rateWindow.ToString();
return true;
}
}
/// <summary>The document as it arrives. The sections are optional: a document
/// that carries only rules is a legitimate way to move rules.</summary>
internal sealed record ConfigImportDocument(
int Version,
DateTimeOffset? ExportedAt,
string? EdgeId,
PolicyUpdateRequest? Policy,
OpenWaf.Domain.Security.ExportedBlock[]? Blocks,
OpenWaf.Domain.Security.ExportedAllow[]? Allow,
OpenWaf.Domain.Security.ExportedRule[]? Rules,
OpenWaf.Domain.Security.ExportedCountry[]? Countries);
/// <summary>One item the document carried that this edge would not take, named
/// by section and position so the operator can find it in the file.</summary>
internal sealed record RejectedItem(string Section, int Index, string? Item, string Error);
/// <summary>The options minimal-API binding uses, applied to the hand-read body
/// so an imported document is parsed exactly as a request body would be.</summary>
internal static class WebJson
{
public static readonly JsonSerializerOptions Options = new(JsonSerializerDefaults.Web);
}