diff --git a/README.md b/README.md index 32d76d0..7c6bf7f 100644 --- a/README.md +++ b/README.md @@ -756,6 +756,60 @@ absolute http(s) URL or a 400, and the decision point ignores a target it cannot send and answers the block's own default instead, for a row that arrived by a restored backup or a hand edit. +### The numbers leave the edge in Prometheus format + +`GET /metrics` answers the counters `/admin-api/state` shows a human, in the +exposition format (`text/plain; version=0.0.4; charset=utf-8`), so they land in +the alerting the operator already runs instead of being read off a page during an +incident. The edge has one push surface — the alert webhook, at-most-once, for +the four things it can alert about — and a threshold on "the ban writes have been +failing for forty minutes" is a pull question. + +Same token as the admin API: **no token configured closes it**, a wrong token is +a 401. It sits on an always-pass prefix like `/healthz`, so an edge that has +blocked the operator's own address is still watchable. + +What it exposes, and nothing else: + +* requests by verdict — `openwaf_requests_total{verdict="pass|pass_allowlisted| + pass_bypassed|pass_rule_observed|block_operator|block_engine|block_rule|geo_reject|block_rate"}`, + all nine from the first scrape, so "nothing happened" and "this build does not + count that" stay different answers in a graph; +* what is being enforced now — `openwaf_blocks_live{source="operator|engine"}`, + `openwaf_allow_entries{state="live|expired"}`, + `openwaf_streaks{state="tracked|standing|shared_store"}`; +* the volume pillar — `openwaf_rate_limit_per_window`, `openwaf_rate_window_seconds`, + `openwaf_rate_tracked_sources`; +* the write side — `openwaf_write_failures_total{pillar=…}`, + `openwaf_write_entries_lost_total{pillar=…}` and + `openwaf_write_last_success_timestamp_seconds{pillar=…}` for `bans`, + `observations`, `alerts`, `retention` and `alertWebhook`, plus + `openwaf_bans_pending_retry` and `openwaf_bans_never_enforced_total`; +* the alerting itself — `openwaf_alerts_raised_total{kind=…}` for the decision + and `openwaf_alert_webhook_total{outcome="delivered|failed|configured"}` for + the push, because "the edge saw a storm" and "the operator was told" are + different questions; +* how current the enforcement is — `openwaf_snapshot_age_seconds`, + `openwaf_snapshot_ttl_seconds`, `openwaf_snapshot_refresh_failures`, + `openwaf_policy_reload_failures`, `openwaf_policy_last_read_timestamp_seconds`, + `openwaf_request_rules_available`; +* the geo file — `openwaf_geo_database_loaded`, and when one is loaded its + `openwaf_geo_database_build_timestamp_seconds` and `openwaf_geo_database_stale`; +* the schema — `openwaf_schema_tables_added_total`, + `openwaf_schema_migrations_baselined_total`, `openwaf_schema_migrations_applied_total` + and `openwaf_schema_missing_tables`, where zero is the invariant; +* the mode — `openwaf_policy_mode_info{mode="enforce|observe|off"}`, because + `Observe` changes what every refusal count above means. + +Two rules the endpoint is built on. **Aggregate only**: no source key, address, +path, user agent or operator note appears anywhere in the body, and the only +labels are bounded sets written in this codebase — a label per source would be a +cardinality explosion and an IP leak into every dashboard and alert rule. **No +query per scrape**: every number is one the process already holds in memory, so a +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. + ## Console `GET /admin` serves a single page over those endpoints — mode and snapshot age, @@ -939,9 +993,9 @@ 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-04 with the -schema upgrade on it: build 0 warnings / 0 errors, unit **240/240**, integration -**230/230 in 22 s**, console **90 assertions, 0 failed**, smoke **passed 52, -failed 0**, and compose **216 passed, 0 failed** against the built image at +schema upgrade on it: build 0 warnings / 0 errors, unit **250/250**, integration +**236/236 in 32 s**, console **90 assertions, 0 failed**, smoke **passed 60, +failed 0**, and compose **223 passed, 0 failed** against the built image at 261 MB. 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 @@ -1117,6 +1171,14 @@ Stated, because a defence that hides its failure modes is not a defence. * **IPv6 is grouped to `/64`.** A subscriber holds a whole `/64`, so a bot rotating addresses inside one allocation is one source; a per-address v6 rule is unenforceable. A wider prefix over-blocks, which is worse. +* **The metrics are per edge, and there is no unauthenticated metrics port.** + `openwaf_requests_total` counts what one process answered; the fleet number is + the sum, which is what a PromQL query does anyway, and a shared counter would + cost a round trip on every request. A separate unauthenticated port is a + deployment decision this project does not make: the shipped image answers on the + 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. * **Geo is a probabilistic claim about an address**, not a fact about a person. The 451 body says so. The database is pinned by a build argument and ages with the image, so `/healthz` reports its build date and `geoStale`. @@ -1174,10 +1236,10 @@ dotnet/ OpenWaf.Domain/ pure decision core: source key, streak, ordered decision, refusal page OpenWaf.Infrastructure/ EF Core (sqlite/postgres), snapshot store, writers, MMDB geo, in-place schema upgrade OpenWaf.Edge/ the deployable: guard, observer, admin API, healthcheck mode - OpenWaf.Tests.Unit/ 240 tests over the decision logic, the budget window, the refusal wording, the schema baseline and the durability counters - OpenWaf.Tests.Integration/ 230 tests driving the real pipeline against a fake upstream + OpenWaf.Tests.Unit/ 250 tests over the decision logic, the budget window, the refusal wording, the schema baseline and the durability counters + OpenWaf.Tests.Integration/ 236 tests driving the real pipeline against a fake upstream scripts/smoke.sh 52 assertions against a running edge + a real upstream -scripts/compose-smoke.sh 216 assertions against the built image (compose + nginx) +scripts/compose-smoke.sh 223 assertions against the built image (compose + nginx) scripts/console-check.cjs 90 assertions against the page, in a real Chromium scripts/geo-db-freshness.sh the pinned geo database vs the vendor (0/1/2) .github/workflows/ci.yml runs the gates on every push diff --git a/dotnet/OpenWaf.Domain/Observability/PrometheusText.cs b/dotnet/OpenWaf.Domain/Observability/PrometheusText.cs new file mode 100644 index 0000000..1c77b86 --- /dev/null +++ b/dotnet/OpenWaf.Domain/Observability/PrometheusText.cs @@ -0,0 +1,199 @@ +using System.Globalization; +using System.Text; + +namespace OpenWaf.Domain.Observability; + +/// What a metric family is, in the one word the exposition format +/// spells after # TYPE. Counter and gauge are the two that mean +/// something to a scraper: a counter is expected to only ever go up, and a +/// PromQL rate() over it assumes exactly that, so labelling a level as a +/// counter is how a restart starts looking like a drop in traffic. +public enum MetricKind +{ + Counter, + Gauge +} + +/// +/// One metric family: a name, a type, a help line, and the samples under it. +/// +/// This is the whole Prometheus surface of the edge, so it is deliberately a +/// tiny pure type in the domain project rather than a dependency on a +/// metrics library. The reference repo pulls in a client library and hands it +/// counters scattered across the pipeline; here the numbers already exist in +/// one place (OPEN-58) and the only job left is to write them out in the +/// spelling a scraper accepts. A pure type is also what makes the format +/// testable: escaping, ordering and the empty case are the parts that break a +/// scrape, and none of them need a running edge to check. +/// +public sealed class MetricFamily +{ + private readonly List<(string Labels, double Value)> _samples = []; + + private MetricFamily(string name, MetricKind kind, string help) + { + Name = name; + Kind = kind; + Help = help; + } + + public string Name { get; } + public MetricKind Kind { get; } + public string Help { get; } + + /// A family with no sample renders nothing. A gauge that has no + /// meaning yet — "the geo database's build date" before a database is + /// loaded — is better absent than a zero that reads as an answer. + public bool HasSamples => _samples.Count > 0; + + public IReadOnlyList<(string Labels, double Value)> Samples => _samples; + + public static MetricFamily Counter(string name, string help) => New(name, MetricKind.Counter, help); + public static MetricFamily Gauge(string name, string help) => New(name, MetricKind.Gauge, help); + + private static MetricFamily New(string name, MetricKind kind, string help) + { + if (!IsValidMetricName(name)) + throw new ArgumentException($"'{name}' is not a valid Prometheus metric name.", nameof(name)); + return new MetricFamily(name, kind, help); + } + + /// Add one sample. Label values are escaped here rather than at + /// render time so a value can never reach the body unescaped by way of a + /// caller that forgot to think about it. + public MetricFamily With(double value, params (string Name, string Value)[] labels) + { + var sb = new StringBuilder(); + if (labels.Length > 0) + { + sb.Append('{'); + for (var i = 0; i < labels.Length; i++) + { + if (i > 0) sb.Append(','); + if (!IsValidLabelName(labels[i].Name)) + throw new ArgumentException( + $"'{labels[i].Name}' is not a valid Prometheus label name.", nameof(labels)); + sb.Append(labels[i].Name).Append("=\"").Append(EscapeLabelValue(labels[i].Value)).Append('"'); + } + sb.Append('}'); + } + + _samples.Add((sb.ToString(), value)); + return this; + } + + public MetricFamily With(long value, params (string Name, string Value)[] labels) + => With((double)value, labels); + + /// Metric names are a small alphabet. A name outside it is not + /// "unusual", it is a line a scraper rejects, and the failure lands in the + /// operator's alerting rather than in this process — so the throw is here, + /// where the mistake is made, and the tests can pin it. + private static bool IsValidMetricName(string name) + { + if (string.IsNullOrEmpty(name)) return false; + for (var i = 0; i < name.Length; i++) + { + var c = name[i]; + var ok = c is >= 'a' and <= 'z' or >= 'A' and <= 'Z' or '_' or ':' || (i > 0 && c is >= '0' and <= '9'); + if (!ok) return false; + } + return true; + } + + /// Label names may not start with a digit, and __ is + /// reserved for the scraper's own internal use. + private static bool IsValidLabelName(string name) + { + if (string.IsNullOrEmpty(name) || name.StartsWith("__", StringComparison.Ordinal)) return false; + for (var i = 0; i < name.Length; i++) + { + var c = name[i]; + if (c is not (>= 'a' and <= 'z' or >= 'A' and <= 'Z' or '_' or >= '0' and <= '9')) return false; + } + return char.IsAsciiLetter(name[0]) || name[0] == '_'; + } + + /// The three escapes the format defines for a quoted label value. + /// A backslash or a quote left raw ends the quoted string early and the + /// rest of the line is a parse error; a raw newline splits one sample into + /// two lines, and the second one reads as a malformed sample. + internal static string EscapeLabelValue(string value) + { + if (string.IsNullOrEmpty(value)) return string.Empty; + var needs = false; + for (var i = 0; i < value.Length && !needs; i++) + needs = value[i] is '"' or '\\' or '\n' or '\r'; + if (!needs) return value; + + var sb = new StringBuilder(value.Length + 8); + foreach (var c in value) + { + switch (c) + { + case '\\': sb.Append("\\\\"); break; + case '"': sb.Append("\\\""); break; + case '\n': sb.Append("\\n"); break; + case '\r': sb.Append("\\r"); break; + default: sb.Append(c); break; + } + } + return sb.ToString(); + } + +} + +/// Renders families as a Prometheus exposition. Pure: no I/O, no +/// clock, no state between calls, so the same families always render the same +/// bytes and the tests can compare the body itself. +public static class PrometheusText +{ + /// The format version is part of the content type, and a scraper + /// that is asked for a version it does not know behaves differently from one + /// that is asked for nothing. + public const string ContentType = "text/plain; version=0.0.4; charset=utf-8"; + + public static string Render(IEnumerable families) + { + var sb = new StringBuilder(); + foreach (var family in families) + { + if (family is null || !family.HasSamples) continue; + + sb.Append("# HELP ").Append(family.Name).Append(' ').Append(EscapeHelp(family.Help)).Append('\n'); + sb.Append("# TYPE ").Append(family.Name).Append(' ') + .Append(family.Kind == MetricKind.Counter ? "counter" : "gauge").Append('\n'); + + // Ordered, because the body is read by a human during an incident + // and diffed by the tests. An unordered body makes "this line + // changed" impossible to see. + foreach (var sample in family.Samples.OrderBy(s => s.Labels, StringComparer.Ordinal)) + { + // NaN and +Inf are legal in the format and useless here: a + // gauge that is NaN is a number this edge does not have, and + // exporting it as one is how an alert on "value dropped" fires. + if (double.IsNaN(sample.Value) || double.IsInfinity(sample.Value)) continue; + + sb.Append(family.Name).Append(sample.Labels).Append(' ') + .Append(Format(sample.Value)).Append('\n'); + } + } + + return sb.ToString(); + } + + /// HELP is free text, but it is free text on one line: a newline + /// in it would put an unparseable line into the body, and a backslash would + /// start an escape nothing is going to close. + private static string EscapeHelp(string help) + => help.Replace("\\", "\\\\").Replace("\n", " ").Replace("\r", " "); + + /// Whole numbers stay whole — a counter written as 3.0 is + /// legal but reads as a measurement rather than a count — and everything is + /// invariant-culture, because a comma as a decimal separator is a parse + /// error in a Prometheus file. + private static string Format(double value) + => value == Math.Truncate(value) && !double.IsInfinity(value) + ? value.ToString("0.###", CultureInfo.InvariantCulture) + : value.ToString("0.##########", CultureInfo.InvariantCulture); +} diff --git a/dotnet/OpenWaf.Domain/Policy/EdgePolicy.cs b/dotnet/OpenWaf.Domain/Policy/EdgePolicy.cs index b11d0c1..e7f97de 100644 --- a/dotnet/OpenWaf.Domain/Policy/EdgePolicy.cs +++ b/dotnet/OpenWaf.Domain/Policy/EdgePolicy.cs @@ -105,7 +105,7 @@ public sealed record EdgePolicy /// Paths that never consult the guard, so an operator who blocks /// their own address can still reach the admin API and undo it. public IReadOnlyList AlwaysPassPrefixes { get; init; } = - new[] { "/admin-api", "/admin", "/healthz", "/readyz", "/openapi", "/swagger" }; + new[] { "/admin-api", "/admin", "/healthz", "/readyz", "/metrics", "/openapi", "/swagger" }; public static EdgePolicy Default { get; } = new(); } diff --git a/dotnet/OpenWaf.Edge/Admin/AdminAuth.cs b/dotnet/OpenWaf.Edge/Admin/AdminAuth.cs new file mode 100644 index 0000000..46d3d10 --- /dev/null +++ b/dotnet/OpenWaf.Edge/Admin/AdminAuth.cs @@ -0,0 +1,86 @@ +using Microsoft.AspNetCore.Http; + +namespace OpenWaf.Edge.Admin; + +/// +/// The one token check the operator's surfaces share (OPEN-58). +/// +/// It used to live inline on the admin API group. It is a type now because the +/// metrics endpoint needs the same rule and a second copy of an auth check is +/// the kind of duplication that ends with one of the two being updated: the +/// admin surface was already carrying a decision about the query string that a +/// second implementation would not have known about. +/// +/// The rule itself is unchanged and the reasoning is unchanged — no token +/// configured means the surface is closed rather than open without auth, and +/// the query string is accepted but named out loud, because a URL is the part +/// of a request that access logs, proxies and browser histories keep. +/// +internal static class AdminAuth +{ + /// The header an operator is asked to use. The query string is + /// tolerated, not recommended, and the warning says so. + public const string Header = "X-Admin-Token"; + + /// The shape AddEndpointFilter takes. Named as a Func rather + /// than as EndpointFilterDelegate because that delegate type is the + /// inner link of the chain, not the thing the registration accepts — the + /// two have different arities, and the compiler only figures that out for a + /// lambda written inline at the call site. + public static Func> Require( + string? adminToken, string disabledMessage) + => async (filterCtx, next) => + { + if (string.IsNullOrWhiteSpace(adminToken)) + return Results.NotFound(new { error = disabledMessage }); + + var req = filterCtx.HttpContext.Request; + var provided = req.Headers[Header].ToString(); + var viaQuery = false; + if (string.IsNullOrWhiteSpace(provided)) + { + provided = req.Query["token"].ToString(); + viaQuery = !string.IsNullOrWhiteSpace(provided); + } + + if (!FixedTimeEquals(provided, adminToken)) return Results.Unauthorized(); + + // The query string is accepted for one reason: an operator typing + // curl at a keyboard does it without thinking, and refusing them is + // how an operator ends up disabling the auth instead of learning the + // header. What is NOT acceptable is doing it silently. A URL is the + // one part of a request that every access log, proxy log and browser + // history keeps, and at the shipped log level the edge does not log + // URLs - but raising Microsoft.AspNetCore to Information, which is + // the ordinary next move when something is misbehaving, makes + // Kestrel log the full URL including this token. Measured on the + // shipped image: one query-string request leaves 0 lines containing + // the token at the shipped level and 2 at Information ("Request + // starting" and "Request finished"), and a header request leaves 0 + // at either. So the request is served and the moment it happens is + // named, without ever repeating the secret. + if (viaQuery) + { + filterCtx.HttpContext.RequestServices + .GetRequiredService() + .CreateLogger("OpenWaf.Admin") + .LogWarning( + "admin token was presented in the query string on {Path}; URLs are what access logs, " + + "proxies and browser histories keep, so prefer the X-Admin-Token header. The token is " + + "not repeated here.", + req.Path.Value); + } + + return await next(filterCtx); + }; + + /// Constant-time on purpose: the comparison is against a secret, + /// and a comparison that returns early on the first wrong byte tells an + /// attacker how far their guess got. + private static bool FixedTimeEquals(string a, string b) + { + if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b)) return false; + return System.Security.Cryptography.CryptographicOperations.FixedTimeEquals( + System.Text.Encoding.UTF8.GetBytes(a), System.Text.Encoding.UTF8.GetBytes(b)); + } +} diff --git a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs index fbfe5c8..460cb1d 100644 --- a/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs +++ b/dotnet/OpenWaf.Edge/Admin/AdminEndpoints.cs @@ -23,53 +23,10 @@ internal static class AdminEndpoints { var group = app.MapGroup("/admin-api"); - // No token configured means the admin surface is closed, not open - // without auth. An edge that can ban people must not itself be the - // easiest way to ban everyone. - group.AddEndpointFilter(async (filterCtx, next) => - { - if (string.IsNullOrWhiteSpace(adminToken)) - return Results.NotFound(new { error = "admin api disabled: set OpenWaf__Admin__Token" }); - - var req = filterCtx.HttpContext.Request; - var provided = req.Headers["X-Admin-Token"].ToString(); - var viaQuery = false; - if (string.IsNullOrWhiteSpace(provided)) - { - provided = req.Query["token"].ToString(); - viaQuery = !string.IsNullOrWhiteSpace(provided); - } - - if (!FixedTimeEquals(provided, adminToken)) return Results.Unauthorized(); - - // The query string is accepted for one reason: an operator typing - // curl at a keyboard does it without thinking, and refusing them is - // how an operator ends up disabling the auth instead of learning the - // header. What is NOT acceptable is doing it silently. A URL is the - // one part of a request that every access log, proxy log and browser - // history keeps, and at the shipped log level the edge does not log - // URLs - but raising Microsoft.AspNetCore to Information, which is - // the ordinary next move when something is misbehaving, makes - // Kestrel log the full URL including this token. Measured on the - // shipped image: one query-string request leaves 0 lines containing - // the token at the shipped level and 2 at Information ("Request - // starting" and "Request finished"), and a header request leaves 0 - // at either. So the request is served and the moment it happens is - // named, without ever repeating the secret. - if (viaQuery) - { - filterCtx.HttpContext.RequestServices - .GetRequiredService() - .CreateLogger("OpenWaf.Admin") - .LogWarning( - "admin token was presented in the query string on {Path}; URLs are what access logs, " + - "proxies and browser histories keep, so prefer the X-Admin-Token header. The token is " + - "not repeated here.", - req.Path.Value); - } - - return await next(filterCtx); - }); + // The same check the metrics endpoint uses. One implementation, so the + // query-string rule cannot drift between the two surfaces. + group.AddEndpointFilter(AdminAuth.Require( + adminToken, "admin api disabled: set OpenWaf__Admin__Token")); group.MapGet("/blocks", async (string? source, bool? live, int? limit, int? offset, BlockStore store, HttpContext ctx, CancellationToken ct) => { @@ -957,13 +914,6 @@ internal static class AdminEndpoints private static IResult StorageUnavailable(string error) => Results.Json(new { error }, statusCode: StatusCodes.Status503ServiceUnavailable); - private static bool FixedTimeEquals(string a, string b) - { - if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b)) return false; - return System.Security.Cryptography.CryptographicOperations.FixedTimeEquals( - System.Text.Encoding.UTF8.GetBytes(a), System.Text.Encoding.UTF8.GetBytes(b)); - } - private static bool IsValidMatch(string match) { if (match.Contains('/')) return NetworkMatch.Matches("203.0.113.1", match) || match.Split('/')[1].Length <= 3; diff --git a/dotnet/OpenWaf.Edge/Admin/MetricsEndpoint.cs b/dotnet/OpenWaf.Edge/Admin/MetricsEndpoint.cs new file mode 100644 index 0000000..f5f6a33 --- /dev/null +++ b/dotnet/OpenWaf.Edge/Admin/MetricsEndpoint.cs @@ -0,0 +1,249 @@ +using System.Text; +using OpenWaf.Domain.Engine; +using OpenWaf.Domain.Observability; +using OpenWaf.Edge.Observability; +using OpenWaf.Edge.Startup; +using OpenWaf.Infrastructure.Geo; +using OpenWaf.Infrastructure.Persistence; + +namespace OpenWaf.Edge.Admin; + +/// +/// The edge's numbers in the format an operator's alerting already reads +/// (OPEN-58). +/// +/// Until now everything the edge measured was readable by a human on +/// /admin-api/state and by nothing else. That is a real gap at 03:00: the +/// edge has one push surface (the alert webhook, at-most-once, and only for the +/// four things it can alert about), while "the ban writes have been failing for +/// forty minutes" and "the snapshot is older than its TTL" are exactly the kind +/// of news a pull-based system with a threshold on it is for. +/// +/// Three rules this endpoint is built on, and each is a decision rather than a +/// default: +/// +/// Aggregate only. No source key, no address, no path, no user agent and +/// no operator note appears anywhere in the body. The project keeps aggregates, +/// not a request log, and a label per source would be both a cardinality +/// explosion and an IP leak into every dashboard and every alert rule. The only +/// labels are verdict kind, block provenance, pillar name, alert kind and mode — +/// all fixed sets written in this codebase, none of them visitor-shaped. +/// +/// No query per scrape. Every number here is one this process already +/// holds in memory. The endpoint issues no database read, so a scrape cannot be +/// the thing that makes an unhealthy database unhealthy for the request path, +/// and a scrape of an edge whose storage is down still returns the numbers that +/// describe the failure. +/// +/// Behind the same token as the admin API. The numbers are aggregate, but +/// they still describe how much traffic a site gets and when its defences fire. +/// A separate unauthenticated metrics port is a deployment decision and this +/// item does not make it; what the shipped image does is answer on the same +/// surface, with the same auth, on an always-pass prefix so an operator who has +/// blocked their own address can still be watched. +/// +internal static class MetricsEndpoint +{ + public static IEndpointRouteBuilder MapMetrics(this IEndpointRouteBuilder app, string? adminToken) + { + var endpoint = app.MapGet("/metrics", ( + EdgeStateStore state, + EdgePolicyProvider policyProvider, + EdgeCounterLedger counters, + DurabilityHealth durability, + AlertNotifier notifier, + AlertWriter alerts, + RateTracker rateTracker, + IStreakTracker streaks, + IGeoIpLookup geo, + BlockStore blockStore, + SchemaUpgradeReport schema) => + { + var now = DateTimeOffset.UtcNow; + var policy = state.Current.Policy; + var families = new List(); + + // 1. What this process did to the traffic it saw. + var requests = MetricFamily.Counter( + "openwaf_requests_total", + "Requests this edge answered, by the verdict it gave them. Per process: sum across " + + "instances for the fleet. The totals add up to the requests answered, because the " + + "count is taken at the one place that may refuse a request."); + var verdicts = counters.Snapshot(); + for (var i = 0; i < verdicts.Length; i++) + requests.With(verdicts[i], ("verdict", EdgeCounterLedger.LabelFor((EdgeVerdict)i))); + families.Add(requests); + + // 2. What it is enforcing right now. + var blocks = MetricFamily.Gauge( + "openwaf_blocks_live", + "Blocks the guard is honouring in its current snapshot, by provenance. An operator " + + "block and an engine ban are different answers and clearing one must never clear the other."); + blocks.With(state.Current.OperatorBlocks.Count, ("source", "operator")); + blocks.With(state.Current.EngineBans.Count, ("source", "engine")); + families.Add(blocks); + + var allow = MetricFamily.Gauge( + "openwaf_allow_entries", + "Exemptions in the snapshot. Expired rows are kept on purpose — they are the operator's " + + "own writes — so they are counted separately rather than hidden."); + var allowLive = state.Current.AllowEntries.Count(a => a.IsLive(now)); + allow.With(allowLive, ("state", "live")); + allow.With(state.Current.AllowEntries.Count - allowLive, ("state", "expired")); + families.Add(allow); + + // The two streak numbers that are not the same number: the map's + // size and the number actually standing. The admin listing learned + // that conflating them reads as a cut that never happened. + _ = streaks.LiveStreaks(now, policy, 1, 0, out var standingTotal); + var streakFamily = MetricFamily.Gauge( + "openwaf_streaks", + "Streak counters this process holds. 'tracked' is every source in the map, including " + + "the ones a clean answer ended; 'standing' is the ones still counting. The scope is " + + "this process or the shared database, chosen at startup."); + streakFamily.With(streaks.TrackedCount, ("state", "tracked")); + streakFamily.With(standingTotal, ("state", "standing")); + streakFamily.With(policyProvider.Current.SharedStreaks ? 1 : 0, ("state", "shared_store")); + families.Add(streakFamily); + + // 3. The volume pillar: the budget, and whether anything is being counted. + families.Add(MetricFamily.Gauge("openwaf_rate_tracked_sources", + "Sources the rate pillar is counting in this process. Zero with the pillar on means a " + + "quiet site; with it off it means the defence is not running.") + .With(rateTracker.TrackedCount)); + families.Add(MetricFamily.Gauge("openwaf_rate_limit_per_window", + "The budget the rate pillar enforces, requests per window.").With(policy.RateLimitPerWindow)); + families.Add(MetricFamily.Gauge("openwaf_rate_window_seconds", + "The window the budget is counted over.").With(policy.RateWindow.TotalSeconds)); + + // 4. The write side: what storage stopped accepting. + var failures = MetricFamily.Counter( + "openwaf_write_failures_total", + "Consecutive failed writes per pillar. A pillar keeps its last good value when a write " + + "fails, so the listings keep answering while rows are being lost — this is the number " + + "that says they are."); + var lost = MetricFamily.Counter( + "openwaf_write_entries_lost_total", + "Rows this edge decided to write and never did, cumulative per pillar. A dropped row is " + + "not recovered by a later successful write."); + var lastWrite = MetricFamily.Gauge( + "openwaf_write_last_success_timestamp_seconds", + "When this pillar last wrote something successfully, in Unix seconds. Zero means never " + + "in this process — which on a quiet site is normal and on a busy one is the alarm."); + foreach (var pillar in new[] + { + DurabilityHealth.Bans, DurabilityHealth.Observations, DurabilityHealth.Alerts, + DurabilityHealth.Retention, AlertNotifier.Pillar + }) + { + var name = ("pillar", pillar); + var p = durability.Get(pillar); + failures.With(p.Failures, name); + lost.With(p.EntriesLost, name); + lastWrite.With(p.LastSuccessAt?.ToUnixTimeSeconds() ?? 0, name); + } + + families.Add(failures); + families.Add(lost); + families.Add(lastWrite); + + // The bans that never reached storage and what became of them. These + // two are the difference between "storage healed" and "the bans this + // edge decided were simply never enforced by anyone". + families.Add(MetricFamily.Gauge("openwaf_bans_pending_retry", + "Bans decided and not yet written, waiting for a retry.").With(blockStore.PendingBanRetries)); + families.Add(MetricFamily.Counter("openwaf_bans_never_enforced_total", + "Bans decided, failed to reach storage, and whose sentence expired before a retry landed.") + .With(blockStore.BansNeverEnforced)); + + // 5. The alerting itself — both halves. + var raised = MetricFamily.Counter( + "openwaf_alerts_raised_total", + "Alerts this edge decided to raise, by kind. The kinds are a fixed set written in the " + + "code, never a value a visitor supplied. Counted at the decision: the write counters " + + "above say whether the row landed."); + foreach (var (kind, count) in alerts.RaisedByKind()) raised.With(count, ("kind", kind)); + families.Add(raised); + + var webhook = MetricFamily.Counter( + "openwaf_alert_webhook_total", + "Alert pushes attempted. 'failed' counts a push that did not arrive: the alert is still " + + "in the table, and this is the number that says the operator was not told about it."); + var push = durability.Get(AlertNotifier.Pillar); + webhook.With(push.EntriesWritten, ("outcome", "delivered")); + webhook.With(push.Failures, ("outcome", "failed")); + webhook.With(notifier.IsConfigured ? 1 : 0, ("outcome", "configured")); + families.Add(webhook); + + // 6. How current what this edge enforces actually is. + families.Add(MetricFamily.Gauge("openwaf_snapshot_age_seconds", + "How old the guard's snapshot is right now. Behind a load balancer this is the " + + "propagation delay for a block.") + .With(Math.Round((now - state.Current.GeneratedAt).TotalSeconds, 3))); + families.Add(MetricFamily.Gauge("openwaf_snapshot_ttl_seconds", + "The age this snapshot is allowed to reach before it is re-read. The age without the " + + "number it is measured against is half a number.") + .With(state.RefreshTtl.TotalSeconds)); + families.Add(MetricFamily.Gauge("openwaf_snapshot_refresh_failures", + "Consecutive failed snapshot refreshes. The guard keeps enforcing the last good snapshot, " + + "which is the right posture and was until recently invisible.") + .With(state.RefreshFailures)); + families.Add(MetricFamily.Gauge("openwaf_policy_reload_failures", + "Consecutive failed policy reads. A policy that stopped being re-read keeps answering " + + "with its last value until the process restarts.") + .With(policyProvider.ReloadFailures)); + families.Add(MetricFamily.Gauge("openwaf_policy_last_read_timestamp_seconds", + "When the policy was last read from storage, in Unix seconds. Zero means never.") + .With(policyProvider.LastReloadSuccessAt?.ToUnixTimeSeconds() ?? 0)); + families.Add(MetricFamily.Gauge("openwaf_request_rules_available", + "Whether the rules pillar is reading anything at all. 'no rules' and 'the rules table is " + + "not there' have to be different answers.") + .With(state.RulesAvailable ? 1 : 0)); + + // 7. The geo database, and how much it can be trusted. + families.Add(MetricFamily.Gauge("openwaf_geo_database_loaded", + "Whether a geo database is loaded in this process.") + .With(geo.IsLoaded ? 1 : 0)); + if (geo.Info?.BuildDate is { } built) + { + families.Add(MetricFamily.Gauge("openwaf_geo_database_build_timestamp_seconds", + "The build date of the loaded geo database, in Unix seconds. A country refusal is " + + "inferred from this file, so its age is part of the answer.") + .With(built.ToUnixTimeSeconds())); + families.Add(MetricFamily.Gauge("openwaf_geo_database_stale", + "Whether that file is older than 90 days, the same threshold the health surface uses.") + .With(geo.Info.IsStale(TimeSpan.FromDays(90)) ? 1 : 0)); + } + + // 8. The schema this build is serving against. + families.Add(MetricFamily.Counter("openwaf_schema_tables_added_total", + "Tables this start had to create because the database predated them.") + .With(schema.TablesAdded)); + families.Add(MetricFamily.Counter("openwaf_schema_migrations_baselined_total", + "Migrations written into a history table the database did not have.") + .With(schema.MigrationsBaselined)); + families.Add(MetricFamily.Counter("openwaf_schema_migrations_applied_total", + "Migrations that then ran.").With(schema.MigrationsApplied)); + families.Add(MetricFamily.Gauge("openwaf_schema_missing_tables", + "What is still missing after the upgrade ran. Zero is the invariant; anything else names " + + "a pillar this build is running with no storage behind it.") + .With(schema.MissingTables.Count)); + + // 9. The mode, as a label rather than a string a dashboard has to + // parse. Observe and Enforce change what every other number here + // means, so an alert rule needs to be able to see it. + families.Add(MetricFamily.Gauge("openwaf_policy_mode_info", + "The enforcement mode this edge is running in, as a labelled 1. Observe means the engine " + + "is deciding and not acting; every refusal count here is then a number of things that " + + "did not happen.") + .With(1, ("mode", policy.Mode.ToString().ToLowerInvariant()))); + + return Results.Text(PrometheusText.Render(families), PrometheusText.ContentType, Encoding.UTF8); + }); + + endpoint.AddEndpointFilter(AdminAuth.Require( + adminToken, "metrics disabled: set OpenWaf__Admin__Token")); + + return app; + } +} diff --git a/dotnet/OpenWaf.Edge/Observability/EdgeCounterLedger.cs b/dotnet/OpenWaf.Edge/Observability/EdgeCounterLedger.cs new file mode 100644 index 0000000..8f0709e --- /dev/null +++ b/dotnet/OpenWaf.Edge/Observability/EdgeCounterLedger.cs @@ -0,0 +1,81 @@ +using OpenWaf.Domain.Engine; + +namespace OpenWaf.Edge.Observability; + +/// +/// What this process has done to the traffic it has seen, one counter per +/// verdict (OPEN-58). +/// +/// The guard already names every request it refuses in the log and every +/// request it passes goes to the origin; what it did not have was a number +/// anyone could scrape. This is that number, and it is deliberately the only +/// new state the metrics endpoint needs: the rest of what /metrics reports is +/// state the edge was already keeping. +/// +/// Two things are on purpose here. +/// +/// It counts the FINAL verdict, in the guard, at the one place that decides — +/// counting in two places is how a request ends up counted twice and a counter +/// whose total does not add up is worse than no counter. +/// +/// It is per process, like the rate counter (OPEN-56) and unlike the block +/// list. A Prometheus counter is normally summed across instances by the query, +/// which is exactly the right answer for "how many requests did this fleet +/// refuse", and there is no shared version to choose because a shared counter +/// would cost a round trip on a path whose measured p95 is ~3 ms. +/// +public sealed class EdgeCounterLedger +{ + /// The verdicts are a contiguous enum from 0, so the counter store + /// is an array indexed by the value rather than a dictionary keyed by a + /// string: no allocation per request, and no way to count a name that is + /// not a verdict. + private const int VerdictCount = 9; + + private readonly long[] _counts = new long[VerdictCount]; + + /// The label the exposition gives this verdict. Lower-case, + /// snake_case, and spelled the way the log spells it, so the same word + /// appears in the alert and in the line an operator greps for. + public static string LabelFor(EdgeVerdict verdict) => verdict switch + { + EdgeVerdict.Pass => "pass", + EdgeVerdict.PassAllowlisted => "pass_allowlisted", + EdgeVerdict.PassBypassed => "pass_bypassed", + EdgeVerdict.PassRuleObserved => "pass_rule_observed", + EdgeVerdict.BlockOperator => "block_operator", + EdgeVerdict.BlockEngine => "block_engine", + EdgeVerdict.BlockRule => "block_rule", + EdgeVerdict.GeoReject => "geo_reject", + EdgeVerdict.BlockRate => "block_rate", + _ => "unknown" + }; + + /// Every verdict the edge can answer with, in label form. The + /// exposition emits all of them, including the zeros: a counter that is + /// absent until it fires is a query that returns nothing rather than zero, + /// and "nothing matched" and "this metric does not exist in this build" + /// look the same in a graph. + public static IReadOnlyList VerdictLabels { get; } = + Enum.GetValues().Select(LabelFor).ToArray(); + + public void Record(EdgeVerdict verdict) + { + var index = (int)verdict; + if (index < 0 || index >= VerdictCount) return; + Interlocked.Increment(ref _counts[index]); + } + + /// The counts as they stood at this instant. A scrape reads a + /// snapshot rather than the live array, so a burst of traffic in the middle + /// of a scrape cannot produce a body whose totals disagree with each other + /// by more than the traffic that arrived while it was being written. + public long[] Snapshot() + { + var copy = new long[VerdictCount]; + for (var i = 0; i < VerdictCount; i++) copy[i] = Interlocked.Read(ref _counts[i]); + return copy; + } + + public long Total() => Snapshot().Sum(); +} diff --git a/dotnet/OpenWaf.Edge/Pipeline/EdgeGuardMiddleware.cs b/dotnet/OpenWaf.Edge/Pipeline/EdgeGuardMiddleware.cs index a5bbca9..6a438c4 100644 --- a/dotnet/OpenWaf.Edge/Pipeline/EdgeGuardMiddleware.cs +++ b/dotnet/OpenWaf.Edge/Pipeline/EdgeGuardMiddleware.cs @@ -1,6 +1,7 @@ using OpenWaf.Domain.Engine; using OpenWaf.Domain.Policy; using OpenWaf.Domain.Responses; +using OpenWaf.Edge.Observability; using OpenWaf.Infrastructure.Geo; using OpenWaf.Infrastructure.Persistence; @@ -25,6 +26,7 @@ public sealed class EdgeGuardMiddleware( RateTracker rates, BlockStore blocks, AlertWriter alerts, + EdgeCounterLedger counters, ILogger log) { /// An observe-action rule matched and the request is going @@ -148,13 +150,23 @@ public sealed class EdgeGuardMiddleware( : SourceKey.For(ip, snapshot.Policy); if (rateKey.Length > 0 && await RatePillarAsync(ctx, snapshot.Policy, rateKey, path, country, now)) + { + counters.Record(EdgeVerdict.BlockRate); return; + } } + // OPEN-58: the one number for the one decision. Counted here, at the + // single place that may refuse a request, and counted as the final + // verdict — the rate pillar above has already returned for anything it + // refused, so nothing is counted twice and the verdict totals add up to + // the requests this edge answered. + counters.Record(decision.Verdict); await next(ctx); return; } + counters.Record(decision.Verdict); log.LogInformation( "edge: {Verdict} {Ip} {Path} ({Reason})", decision.Verdict, ip, path, decision.Reason ?? "-"); diff --git a/dotnet/OpenWaf.Edge/Program.cs b/dotnet/OpenWaf.Edge/Program.cs index c85053b..a8cac9a 100644 --- a/dotnet/OpenWaf.Edge/Program.cs +++ b/dotnet/OpenWaf.Edge/Program.cs @@ -62,6 +62,11 @@ builder.Services.AddSingleton(sp => new EdgeStateStore( RefreshTtl = EdgeStateStore.ParseRefreshTtl(builder.Configuration["OpenWaf:State:RefreshTtlSeconds"]) }); builder.Services.AddSingleton(); +// Requests by verdict, counted at the one place that decides (OPEN-58). Per +// process, like the rate counter: a Prometheus query sums the instances, which +// is the right answer for "how many did this fleet refuse", and a shared +// counter would cost a round trip on a path whose measured p95 is ~3 ms. +builder.Services.AddSingleton(); builder.Services.AddSingleton(); // The volume counter (OPEN-56). One per process, on purpose: the budget is a // count of requests this edge saw, and there is no shared implementation to @@ -227,6 +232,10 @@ app.MapGet("/readyz", async (OpenWafDbContext db, EdgeStateStore state, EdgePoli var adminToken = builder.Configuration["OpenWaf:Admin:Token"]; if (string.IsNullOrWhiteSpace(adminToken)) adminToken = Environment.GetEnvironmentVariable("OPENWAF_ADMIN_TOKEN"); app.MapAdminApi(adminToken); +// The operator's numbers, in the format their alerting reads (OPEN-58). Same +// token as the admin API, and on an always-pass prefix like /healthz — an edge +// that has blocked the operator's own address still has to be watchable. +app.MapMetrics(adminToken); app.MapAdminConsole(); if (!app.Environment.IsProduction()) diff --git a/dotnet/OpenWaf.Infrastructure/Persistence/AlertWriter.cs b/dotnet/OpenWaf.Infrastructure/Persistence/AlertWriter.cs index 73eae9d..b2bd689 100644 --- a/dotnet/OpenWaf.Infrastructure/Persistence/AlertWriter.cs +++ b/dotnet/OpenWaf.Infrastructure/Persistence/AlertWriter.cs @@ -1,3 +1,4 @@ +using System.Collections.Concurrent; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using OpenWaf.Domain.Security; @@ -28,6 +29,23 @@ public sealed class AlertWriter _notifier = notifier; } + /// Alerts this process decided to raise, per kind (OPEN-58). The + /// kinds are a fixed set written in this codebase — server_error_streak, + /// candidate_ban, rule_match, rate_breach — never a value + /// a visitor types, which is what makes it safe to expose as a label: the + /// cardinality is the number of things this edge can alert about, not the + /// number of things that have happened. + /// + /// It counts the decision, not the write. The durability counters next to it + /// say whether the row landed, and the two answers are different questions: + /// "the edge saw a storm" and "the operator can find the storm in the table". + /// + private readonly ConcurrentDictionary _raised = new(StringComparer.Ordinal); + + /// A snapshot for the scrape, not the live map. + public IReadOnlyDictionary RaisedByKind() + => new Dictionary(_raised, StringComparer.Ordinal); + public async Task RaiseAsync( string kind, string sourceKey, @@ -37,6 +55,7 @@ public sealed class AlertWriter string detail, CancellationToken ct = default) { + if (!string.IsNullOrWhiteSpace(kind)) _raised.AddOrUpdate(kind, 1, static (_, v) => v + 1); try { using var scope = _scopeFactory.CreateScope(); diff --git a/dotnet/OpenWaf.Tests.Integration/MetricsEndpointTests.cs b/dotnet/OpenWaf.Tests.Integration/MetricsEndpointTests.cs new file mode 100644 index 0000000..b700a20 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Integration/MetricsEndpointTests.cs @@ -0,0 +1,286 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.RegularExpressions; + +namespace OpenWaf.Tests.Integration; + +/// +/// The edge's own numbers, in the format an operator's alerting reads (OPEN-58). +/// +/// The unit tests hold the format; these hold the wiring, and the wiring is +/// where the two ways this endpoint could be wrong live. It could be unreachable +/// by the one person who needs it (an operator who has blocked their own +/// address), it could be reachable by everyone else (an auth check that drifted +/// from the admin API's), or it could be a leak: a body that looks aggregate and +/// carries a source key, an address, a path or an operator's note. The last one +/// is asserted over the whole body with a live streak, a live ban and a refused +/// path actually in the database, because an assertion written against a quiet +/// edge proves nothing about what an edge with traffic in it would say. +/// +public sealed class MetricsEndpointTests +{ + private const string Visitor = "203.0.113.77"; + private const string MarkerPath = "/wp-admin/marker-path"; + private const string MarkerUserAgent = "marker-user-agent-unique"; + private const string MarkerNote = "marker-operator-note-unique"; + + private static async Task<(HttpStatusCode Status, string ContentType, string Body)> MetricsAsync( + EdgeFixture f, string ip = Visitor, string? token = EdgeFixture.AdminToken, string? viaQuery = null) + { + using var request = new HttpRequestMessage( + HttpMethod.Get, viaQuery is null ? "/metrics" : $"/metrics?token={viaQuery}"); + request.Headers.TryAddWithoutValidation("X-Forwarded-For", ip); + if (token is not null) request.Headers.TryAddWithoutValidation("X-Admin-Token", token); + using var r = await f.Client.SendAsync(request); + return (r.StatusCode, r.Content.Headers.ContentType?.ToString() ?? "", await r.Content.ReadAsStringAsync()); + } + + private static async Task AdminAsync( + EdgeFixture f, HttpMethod method, string url, object? body = null) + { + using var request = new HttpRequestMessage(method, url); + request.Headers.TryAddWithoutValidation("X-Admin-Token", EdgeFixture.AdminToken); + if (body is not null) request.Content = JsonContent.Create(body); + return await f.Client.SendAsync(request); + } + + private static async Task WaitForBanAsync(EdgeFixture f) + { + for (var i = 0; i < 40; i++) + { + using var blocks = await AdminAsync(f, HttpMethod.Get, "/admin-api/blocks?source=engine"); + if ((await blocks.Content.ReadAsStringAsync()).Contains(Visitor)) return; + await Task.Delay(250); + } + } + + /// The sample line for a metric with one label, or null when the + /// body does not carry it. Reading the line rather than grepping for the + /// name is the point: a metric that exists with the wrong label value is the + /// failure a substring check misses. + private static string? Sample(string body, string name, string? label = null) + { + var wanted = label is null ? name : $"{name}{{{label}}}"; + return body.Split('\n').FirstOrDefault(l => l.StartsWith(wanted + " ", StringComparison.Ordinal)); + } + + private static double Value(string line) => double.Parse(line[(line.LastIndexOf(' ') + 1)..]); + + [Fact] + public async Task The_metrics_surface_answers_in_prometheus_text_and_the_token_is_the_door() + { + await using var f = new EdgeFixture(); + _ = await MetricsAsync(f, token: null); + + using var anonymous = await f.Client.GetAsync("/metrics"); + Assert.Equal(HttpStatusCode.Unauthorized, anonymous.StatusCode); + + var wrong = await MetricsAsync(f, token: "not-the-token"); + Assert.Equal(HttpStatusCode.Unauthorized, wrong.Status); + + var ok = await MetricsAsync(f); + Assert.Equal(HttpStatusCode.OK, ok.Status); + // The version is part of the content type because a scraper negotiates + // on it; a bare text/plain is a different answer. + Assert.Contains("text/plain", ok.ContentType); + Assert.Contains("version=0.0.4", ok.ContentType); + Assert.Contains("# TYPE openwaf_requests_total counter", ok.Body); + } + + [Fact] + public async Task No_token_configured_closes_the_metrics_surface_rather_than_opening_it() + { + // "Closed" has to be asked for in both places at once. Program reads the + // token from configuration and falls back to OPENWAF_ADMIN_TOKEN when the + // configured value is blank, and the gate scripts export a throwaway value + // into the test process — so a blank configured token with the environment + // set is an OPEN surface, and this assertion fails for the wrong reason + // (401, not 404) under the gate while passing on its own. Same dance as + // the admin-surface test: clear it for the duration, restore it after. + var saved = Environment.GetEnvironmentVariable("OPENWAF_ADMIN_TOKEN"); + Environment.SetEnvironmentVariable("OPENWAF_ADMIN_TOKEN", null); + try + { + await using var f = new EdgeFixture(adminToken: null); + var closed = await MetricsAsync(f, token: null, viaQuery: "anything"); + Assert.Equal(HttpStatusCode.NotFound, closed.Status); + Assert.Contains("metrics disabled", closed.Body); + } + finally + { + if (saved is not null) Environment.SetEnvironmentVariable("OPENWAF_ADMIN_TOKEN", saved); + } + } + + [Fact] + public async Task The_verdict_counters_move_when_the_edge_refuses() + { + await using var f = new EdgeFixture(); + + var before = await MetricsAsync(f); + Assert.Equal(HttpStatusCode.OK, before.Status); + var beforeEngine = Value(Sample(before.Body, "openwaf_requests_total", "verdict=\"block_engine\"")!); + + for (var i = 0; i < 3; i++) + { + using var request = new HttpRequestMessage(HttpMethod.Get, MarkerPath); + request.Headers.TryAddWithoutValidation("X-Forwarded-For", Visitor); + request.Headers.TryAddWithoutValidation("User-Agent", MarkerUserAgent); + using var r = await f.Client.SendAsync(request); + } + await WaitForBanAsync(f); + + using var refused = new HttpRequestMessage(HttpMethod.Get, "/anything"); + refused.Headers.TryAddWithoutValidation("X-Forwarded-For", Visitor); + using var refusedResponse = await f.Client.SendAsync(refused); + Assert.Equal(HttpStatusCode.Forbidden, refusedResponse.StatusCode); + + var after = await MetricsAsync(f); + var afterEngine = Value(Sample(after.Body, "openwaf_requests_total", "verdict=\"block_engine\"")!); + Assert.True(afterEngine > beforeEngine, + $"block_engine went from {beforeEngine} to {afterEngine} across a refusal"); + + // The verdicts are a closed set and every one of them is emitted from + // the first scrape, so "nothing happened" and "this build does not count + // that" are different answers in a graph. + foreach (var verdict in new[] + { + "pass", "pass_allowlisted", "pass_bypassed", "pass_rule_observed", + "block_operator", "block_engine", "block_rule", "geo_reject", "block_rate" + }) + Assert.NotNull(Sample(after.Body, "openwaf_requests_total", $"verdict=\"{verdict}\"")); + + // The metrics request itself went through the guard on an always-pass + // prefix, which is what pass_bypassed counts — the number is honest about + // the scrape too. + Assert.True(Value(Sample(after.Body, "openwaf_requests_total", "verdict=\"pass_bypassed\"")!) >= 1); + + // And the live state it reports is the state the guard is honouring. + Assert.Equal(1, Value(Sample(after.Body, "openwaf_blocks_live", "source=\"engine\"")!)); + } + + [Fact] + public async Task The_body_names_nothing_about_one_visitor_even_with_a_streak_a_ban_and_a_refused_path_live() + { + await using var f = new EdgeFixture(); + + for (var i = 0; i < 3; i++) + { + using var request = new HttpRequestMessage(HttpMethod.Get, MarkerPath); + request.Headers.TryAddWithoutValidation("X-Forwarded-For", Visitor); + request.Headers.TryAddWithoutValidation("User-Agent", MarkerUserAgent); + using var r = await f.Client.SendAsync(request); + } + await WaitForBanAsync(f); + + using (var note = await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", + new { ip = "198.51.100.4", reason = MarkerNote })) + { + Assert.True(note.IsSuccessStatusCode, await note.Content.ReadAsStringAsync()); + } + + var body = (await MetricsAsync(f)).Body; + + // Not "the response has no obvious field for it" — the whole body, with + // the markers actually present in the database behind it. + Assert.DoesNotContain(Visitor, body); + Assert.DoesNotContain("198.51.100.4", body); + Assert.DoesNotContain(MarkerPath, body); + Assert.DoesNotContain(MarkerUserAgent, body); + Assert.DoesNotContain(MarkerNote, body); + Assert.DoesNotContain("wp-admin", body); + // The general form of the same assertion: no address of any kind, and no + // path, anywhere in the body. + Assert.False(Regex.IsMatch(body, @"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"), body); + Assert.DoesNotContain("/admin-api", body); + // The only labels are the bounded sets. A label named after a visitor + // dimension is the leak, whatever its value. + Assert.DoesNotContain("{ip=", body); + Assert.DoesNotContain("path=", body); + Assert.DoesNotContain("user_agent=", body); + Assert.DoesNotContain("note=", body); + } + + [Fact] + public async Task An_operator_who_blocked_their_own_address_can_still_be_watched() + { + await using var f = new EdgeFixture(); + const string operatorIp = "198.51.100.9"; + + using (var block = await AdminAsync(f, HttpMethod.Post, "/admin-api/blocks", + new { ip = operatorIp, reason = "self-inflicted" })) + { + Assert.True(block.IsSuccessStatusCode, await block.Content.ReadAsStringAsync()); + } + + for (var i = 0; i < 10; i++) + { + using var blocked = new HttpRequestMessage(HttpMethod.Get, "/"); + blocked.Headers.TryAddWithoutValidation("X-Forwarded-For", operatorIp); + using var r = await f.Client.SendAsync(blocked); + if (r.StatusCode == HttpStatusCode.Moved) break; + await Task.Delay(250); + } + + using (var stillBlocked = await f.Client.GetAsync("/")) + { + using var probe = new HttpRequestMessage(HttpMethod.Get, "/"); + probe.Headers.TryAddWithoutValidation("X-Forwarded-For", operatorIp); + using var probeResponse = await f.Client.SendAsync(probe); + Assert.Equal(HttpStatusCode.Moved, probeResponse.StatusCode); + } + + // The whole point of the prefix: the defence cannot blind the thing that + // watches the defence. + var metrics = await MetricsAsync(f, ip: operatorIp); + Assert.Equal(HttpStatusCode.OK, metrics.Status); + Assert.Contains("openwaf_blocks_live{source=\"operator\"} 1", metrics.Body); + } + + [Fact] + public async Task Every_sample_line_is_declared_and_a_quiet_edge_still_answers_a_valid_body() + { + await using var f = new EdgeFixture(); + var scrape = await MetricsAsync(f); + Assert.Equal(HttpStatusCode.OK, scrape.Status); + + // Every family declares itself twice, and a family declared as one and + // sampled as the other is how a counter starts being queried as a level. + var typed = new HashSet(); + var helped = new HashSet(); + foreach (var line in scrape.Body.Split('\n')) + { + if (line.StartsWith("# TYPE ", StringComparison.Ordinal)) + { + typed.Add(line.Split(' ')[2]); + continue; + } + if (line.StartsWith("# HELP ", StringComparison.Ordinal)) + { + helped.Add(line.Split(' ')[2]); + continue; + } + if (line.Length == 0 || line.StartsWith('#')) continue; + + var name = line.Split('{', ' ')[0]; + Assert.True(typed.Contains(name), $"sample for an undeclared metric: {line}"); + // The value is a number, and NaN or Inf are not numbers a threshold + // can be put on. + var value = line[(line.LastIndexOf(' ') + 1)..]; + Assert.DoesNotContain("NaN", value); + Assert.DoesNotContain("Inf", value); + Assert.True(double.TryParse(value, out _), line); + } + + Assert.Equal(typed, helped); + + // A fresh edge has served nothing, and the body says so with zeros rather + // than by omitting the metrics. + Assert.Equal(0, Value(Sample(scrape.Body, "openwaf_requests_total", "verdict=\"block_engine\"")!)); + Assert.Equal(0, Value(Sample(scrape.Body, "openwaf_blocks_live", "source=\"engine\"")!)); + Assert.Contains("# TYPE openwaf_snapshot_age_seconds gauge", scrape.Body); + Assert.Contains("# TYPE openwaf_write_failures_total counter", scrape.Body); + foreach (var pillar in new[] { "bans", "observations", "alerts", "retention", "alertWebhook" }) + Assert.NotNull(Sample(scrape.Body, "openwaf_write_failures_total", $"pillar=\"{pillar}\"")); + } +} diff --git a/dotnet/OpenWaf.Tests.Unit/PrometheusTextTests.cs b/dotnet/OpenWaf.Tests.Unit/PrometheusTextTests.cs new file mode 100644 index 0000000..28765b0 --- /dev/null +++ b/dotnet/OpenWaf.Tests.Unit/PrometheusTextTests.cs @@ -0,0 +1,142 @@ +using OpenWaf.Domain.Observability; + +namespace OpenWaf.Tests.Unit; + +/// +/// The exposition format, tested as a string (OPEN-58). +/// +/// These are the parts of "it is Prometheus" that a scraper actually rejects: +/// an unescaped quote in a label value, a newline inside HELP, a name outside +/// the alphabet, a NaN, a family whose samples arrive in a different order on +/// every scrape. None of them need a running edge to check, and all of them +/// fail in the operator's alerting rather than here — which is the argument for +/// testing the renderer directly instead of only through an endpoint. +/// +public sealed class PrometheusTextTests +{ + [Fact] + public void A_family_renders_its_help_and_type_lines_before_its_samples() + { + var body = PrometheusText.Render([ + MetricFamily.Counter("openwaf_requests_total", "Requests answered.") + .With(3, ("verdict", "pass"))]); + + Assert.Equal( + "# HELP openwaf_requests_total Requests answered.\n" + + "# TYPE openwaf_requests_total counter\n" + + "openwaf_requests_total{verdict=\"pass\"} 3\n", + body); + } + + [Fact] + public void A_gauge_is_spelled_gauge_because_a_counter_promise_is_a_query() + { + var body = PrometheusText.Render([MetricFamily.Gauge("openwaf_snapshot_age_seconds", "Age.").With(12.5)]); + Assert.Contains("# TYPE openwaf_snapshot_age_seconds gauge", body); + // A decimal stays decimal, and it stays a dot: a comma is a parse error + // in this format whatever the machine's culture says. + Assert.Contains("openwaf_snapshot_age_seconds 12.5", body); + } + + [Fact] + public void Label_values_are_escaped_so_a_value_cannot_end_its_own_quoted_string() + { + var family = MetricFamily.Gauge("openwaf_test", "Help.") + .With(1, ("pillar", "b\"ans")) + .With(1, ("kind", "back\\slash")) + .With(1, ("state", "two\nlines")); + var body = PrometheusText.Render([family]); + + Assert.Contains("pillar=\"b\\\"ans\"", body); + Assert.Contains("kind=\"back\\\\slash\"", body); + Assert.Contains("state=\"two\\nlines\"", body); + // The newline became two characters, so the body is still one line per + // sample — the count is the assertion, not the substring. + Assert.Equal(5, body.Split('\n').Length - 1); + } + + [Fact] + public void A_newline_in_a_help_line_cannot_split_the_body() + { + var body = PrometheusText.Render([ + MetricFamily.Gauge("openwaf_test", "two\nlines with a \\ backslash").With(1)]); + Assert.Equal("# HELP openwaf_test two lines with a \\\\ backslash\n" + + "# TYPE openwaf_test gauge\n" + + "openwaf_test 1\n", body); + } + + [Fact] + public void Samples_are_ordered_by_labels_so_a_scrape_is_diffable() + { + var family = MetricFamily.Counter("openwaf_requests_total", "Help.") + .With(1, ("verdict", "pass")) + .With(1, ("verdict", "block_engine")) + .With(1, ("verdict", "block_operator")) + .With(1, ("verdict", "geo_reject")); + var lines = PrometheusText.Render([family]) + .Split('\n', StringSplitOptions.RemoveEmptyEntries) + .Where(l => !l.StartsWith('#')) + .ToArray(); + + Assert.Equal( + new[] { "pass", "block_engine", "block_operator", "geo_reject" }.OrderBy(x => x, StringComparer.Ordinal) + .Select(v => $"openwaf_requests_total{{verdict=\"{v}\"}} 1"), + lines); + } + + [Fact] + public void A_family_with_no_sample_renders_nothing_rather_than_a_header_and_no_answer() + { + Assert.Equal(string.Empty, PrometheusText.Render([MetricFamily.Counter("openwaf_empty_total", "Nothing yet.")])); + // And a body with nothing in it is still a valid body: an empty file is + // a successful scrape, which is what an edge that has served no traffic + // should answer. + Assert.Equal(string.Empty, PrometheusText.Render([])); + } + + [Fact] + public void Non_finite_values_are_dropped_because_a_gauge_that_is_NaN_is_a_number_this_edge_does_not_have() + { + var family = MetricFamily.Gauge("openwaf_test", "Help.") + .With(double.NaN) + .With(double.PositiveInfinity, ("state", "up")) + .With(7, ("state", "real")); + var body = PrometheusText.Render([family]); + + Assert.DoesNotContain("NaN", body); + Assert.DoesNotContain("Inf", body); + Assert.Contains("openwaf_test{state=\"real\"} 7", body); + // Two samples were dropped, so the body is the two header lines plus the + // one sample that is a number. + Assert.Equal(3, body.Split('\n').Length - 1); + } + + [Fact] + public void A_name_or_label_outside_the_alphabet_throws_here_rather_than_in_the_operators_alerting() + { + Assert.Throws(() => MetricFamily.Counter("openwaf requests total", "space")); + Assert.Throws(() => MetricFamily.Counter("9lives", "leading digit")); + Assert.Throws(() => MetricFamily.Counter("", "empty")); + // Colons are legal in metric names — recording rules write them — and + // this is the one place a reader might otherwise "fix" a working name. + Assert.NotNull(MetricFamily.Counter("openwaf:requests_total", "colon")); + + var family = MetricFamily.Gauge("openwaf_test", "Help."); + Assert.Throws(() => family.With(1, ("bad name", "x"))); + Assert.Throws(() => family.With(1, ("9bad", "x"))); + Assert.Throws(() => family.With(1, ("__internal", "x"))); + } + + [Fact] + public void Whole_numbers_stay_whole_because_a_count_is_not_a_measurement() + { + var body = PrometheusText.Render([ + MetricFamily.Counter("openwaf_requests_total", "Help.").With(3L).With(0L, ("verdict", "pass"))]); + Assert.Contains("openwaf_requests_total 3\n", body); + Assert.Contains("openwaf_requests_total{verdict=\"pass\"} 0\n", body); + } + + [Fact] + public void The_content_type_names_the_format_version_a_scraper_negotiates_on() + => Assert.Equal("text/plain; version=0.0.4; charset=utf-8", PrometheusText.ContentType); +} diff --git a/scripts/compose-smoke.sh b/scripts/compose-smoke.sh index 893711f..94870d6 100755 --- a/scripts/compose-smoke.sh +++ b/scripts/compose-smoke.sh @@ -1369,6 +1369,30 @@ OPEN55_RULE=$(admin "$EDGE/admin-api/rules" | jget "o['pattern']=='/upgrade-chec 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/$OPEN55_RULE")" +echo "- the edge's own numbers leave in Prometheus format" +# OPEN-58. The smoke gate proves the endpoint against a process built from this +# tree; this proves it against the shipped image, where the thing that could go +# wrong is the deployment: the always-pass prefix, the token, and the body +# staying aggregate on a stack that has real refusals and a real schema upgrade +# behind it. +check 'the metrics surface is closed without the token' '401' "$(code "$EDGE/metrics")" +OPEN58_TYPE=$(curl -s -m 10 -o /dev/null -w '%{content_type}' \ + -H "X-Admin-Token: $OPENWAF_ADMIN_TOKEN" "$EDGE/metrics") +check 'metrics answers in the Prometheus exposition format' 'text/plain; version=0.0.4; charset=utf-8' \ + "$OPEN58_TYPE" +OPEN58_BODY=$(admin "$EDGE/metrics") +msample() { printf '%s\n' "$OPEN58_BODY" | awk -v p="$1" 'index($0,p)==1 { print $NF; exit }'; } +check 'the verdict counter counts the rule refusal this stack just made' 'yes' \ + "$([ "$(msample 'openwaf_requests_total{verdict="block_rule"} ')" -gt 0 ] 2>/dev/null && echo yes || echo no)" +check 'the schema gauge says nothing the build needs is missing' '0' \ + "$(msample 'openwaf_schema_missing_tables ')" +check 'the write counters are published even on a healthy stack' '0' \ + "$(msample 'openwaf_write_failures_total{pillar="bans"} ')" +check 'the body names no address from the scene above' 'yes' \ + "$(printf '%s\n' "$OPEN58_BODY" | grep -qF "$OPEN55_IP" && echo no || echo yes)" +check 'and no per-source label exists anywhere in it' 'yes' \ + "$(printf '%s\n' "$OPEN58_BODY" | grep -Eq '(^|,)(ip|path|user_agent)=' && echo no || echo yes)" + 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 a4ec9c9..b60de30 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -125,6 +125,33 @@ check 'and the same refusal is still JSON for a client that parses it' blocked_b check 'the ban carries a Retry-After' yes \ "$(curl -s -D- -o /dev/null -H "X-Forwarded-For: $SCANNER" "$(from anything)" | grep -qi '^retry-after:' && echo yes || echo no)" +echo '- metrics (OPEN-58)' +# The pull surface. The integration tests hold the format; this holds the +# deployed shape — the content type a scraper negotiates on, the token that +# closes it, and the one property the whole feature exists for: an edge that is +# refusing a source can still be watched by that source's operator. +check 'the metrics surface is closed without the token' 401 \ + "$(code "http://127.0.0.1:$EDGE_PORT/metrics")" +check 'metrics answers in the Prometheus exposition format' 'text/plain; version=0.0.4; charset=utf-8' \ + "$(curl -s -o /dev/null -w '%{content_type}' -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/metrics")" +METRICS=$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/metrics") +msample() { printf '%s\n' "$METRICS" | awk -v p="$1" 'index($0,p)==1 { print $NF; exit }'; } +check 'the body declares a type for every family it samples' yes \ + "$([ "$(printf '%s\n' "$METRICS" | grep -c '^# TYPE ')" -ge 20 ] && echo yes || echo no)" +check 'no value in the body is NaN or Inf' yes \ + "$(printf '%s\n' "$METRICS" | grep -Eq 'NaN|Inf' && echo no || echo yes)" +BLOCK_ENGINE=$(msample 'openwaf_requests_total{verdict="block_engine"} ') +check 'the verdict counter counts the ban this scene just made' yes \ + "$([ "${BLOCK_ENGINE:-0}" -gt 0 ] 2>/dev/null && echo yes || echo no)" +check 'the live blocks gauge counts the engine ban' 1 \ + "$(msample 'openwaf_blocks_live{source="engine"} ')" +# The aggregate-only invariant, asserted over the whole body with the markers +# from the scene above actually in the database behind it. +check 'the body names no address, no path and no operator note' yes \ + "$(printf '%s\n' "$METRICS" | grep -Eq "$SCANNER|wp-admin|confirmed scraper" && echo no || echo yes)" +check 'a source the edge is refusing can still be watched' 200 \ + "$(code -H "X-Admin-Token: $TOKEN" -H "X-Forwarded-For: $SCANNER" "http://127.0.0.1:$EDGE_PORT/metrics")" + echo '- operator list' check 'add an operator block' 204 \ "$(code -X POST -H "X-Admin-Token: $TOKEN" -H 'Content-Type: application/json' \