Files
Pavlo Ratushnyi 892cec172f the edge answers /metrics in the format the operator's alerting already reads
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.
2026-10-05 01:00:10 +02:00

143 lines
6.2 KiB
C#

using OpenWaf.Domain.Observability;
namespace OpenWaf.Tests.Unit;
/// <summary>
/// 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.
/// </summary>
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<ArgumentException>(() => MetricFamily.Counter("openwaf requests total", "space"));
Assert.Throws<ArgumentException>(() => MetricFamily.Counter("9lives", "leading digit"));
Assert.Throws<ArgumentException>(() => 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<ArgumentException>(() => family.With(1, ("bad name", "x")));
Assert.Throws<ArgumentException>(() => family.With(1, ("9bad", "x")));
Assert.Throws<ArgumentException>(() => 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);
}