OPEN-58. The edge had one push surface — the alert webhook, at-most-once, for the four things it can alert about — and every other number it keeps was readable by a human on /admin-api/state and by nothing else. 'The ban writes have been failing for forty minutes' is a pull question with a threshold on it, so it belongs in Prometheus, where the operator already keeps their alerting. The exposition is a pure type in the domain project (PrometheusText) rather than a metrics library: the numbers already exist in one place, and the parts that break a scrape — label escaping, HELP on one line, the name alphabet, NaN, sample ordering — are testable as a string without a running edge. EdgeCounterLedger adds the one piece of new state, counted at the single place that may refuse a request, so the verdict totals add up to the requests answered. Three rules, each a decision: aggregate only (no source key, address, path, user agent or operator note anywhere in the body, and the only labels are bounded sets written in the code — a label per source is a cardinality explosion and an IP leak); no query per scrape (every number is already in memory, so a scrape cannot be what makes an unhealthy database unhealthy for the request path); and behind the same token as the admin API, on an always-pass prefix, so an edge that has blocked the operator's own address is still watchable. The token check moved out of the admin group into AdminAuth rather than being copied. Three things the run caught. The 'closed surface' assertion passed alone and failed under the gate: Program falls back to OPENWAF_ADMIN_TOKEN when the configured token is blank and the gate scripts export a throwaway value into the test process, so a blank token there is an OPEN surface — 401, not 404. The smoke and compose sample helpers grepped for the metric name and matched the '# HELP' line first, answering with the help text's last word; they now match the line prefix. And EndpointFilterDelegate is not what AddEndpointFilter accepts — the two have different arities, which only shows when the filter is a method rather than a lambda at the call site. Gates on this tree: build 0 warnings / 0 errors, unit 250/250, integration 236/236, smoke 60/0, compose 223/0 against the built image (261 MB), console 90/0.
287 lines
13 KiB
C#
287 lines
13 KiB
C#
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using System.Text.RegularExpressions;
|
|
|
|
namespace OpenWaf.Tests.Integration;
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
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<HttpResponseMessage> 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);
|
|
}
|
|
}
|
|
|
|
/// <summary>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.</summary>
|
|
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<string>();
|
|
var helped = new HashSet<string>();
|
|
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}\""));
|
|
}
|
|
}
|