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.
285 lines
17 KiB
C#
285 lines
17 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// 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
|
|
/// <c>/admin-api/state</c> 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:
|
|
///
|
|
/// <b>Aggregate only.</b> 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.
|
|
///
|
|
/// <b>No query per scrape.</b> 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.
|
|
///
|
|
/// <b>Behind the same token as the admin API.</b> 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.
|
|
/// </summary>
|
|
internal static class MetricsEndpoint
|
|
{
|
|
/// <param name="adminToken">The token that reads and writes.</param>
|
|
/// <param name="readOnlyToken">The read-only token (OPEN-62). It is allowed
|
|
/// here: /metrics is a read, and a scrape is the clearest case of a thing
|
|
/// that has to be able to look and must not be able to change anything.
|
|
/// It sits on an always-pass prefix for the same reason the numbers do.</param>
|
|
public static IEndpointRouteBuilder MapMetrics(this IEndpointRouteBuilder app, string? adminToken,
|
|
string? readOnlyToken)
|
|
{
|
|
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<MetricFamily>();
|
|
|
|
// 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);
|
|
|
|
// The queue behind the push (OPEN-60). Cached rather than queried:
|
|
// this endpoint's rule is that a scrape never leans on the database,
|
|
// so the gauge is at most five seconds behind the rows and says so.
|
|
var queue = notifier.Counts;
|
|
families.Add(MetricFamily.Gauge("openwaf_alert_push_pending",
|
|
"Deliveries this edge still owes the webhook, including the ones a "
|
|
+ "previous process left behind. Read at most five seconds stale.")
|
|
.With(queue.Pending));
|
|
families.Add(MetricFamily.Counter("openwaf_alert_push_delivered_total",
|
|
"Deliveries the endpoint accepted, counted as rows rather than as an "
|
|
+ "in-process counter, so the answer survives a restart.")
|
|
.With(queue.Delivered));
|
|
families.Add(MetricFamily.Counter("openwaf_alert_push_attempts_total",
|
|
"HTTP attempts the queue has made against the endpoint, over every row it has "
|
|
+ "ever held. Attempts per delivery is what separates an endpoint that refuses "
|
|
+ "everything from one that refuses occasionally.")
|
|
.With(queue.Attempts));
|
|
families.Add(MetricFamily.Counter("openwaf_alert_push_given_up_total",
|
|
"Deliveries that ran out of attempts. This is the number that says "
|
|
+ "'nobody was told', as distinct from 'we are still asking'.")
|
|
.With(queue.GivenUp));
|
|
if (queue.Pending > 0 && queue.OldestPendingAt is { } oldest)
|
|
{
|
|
families.Add(MetricFamily.Gauge("openwaf_alert_push_oldest_pending_age_seconds",
|
|
"How long the longest-owed delivery has been waiting. A webhook that "
|
|
+ "is down looks idle until this number moves.")
|
|
.With(Math.Round((now - oldest).TotalSeconds, 1)));
|
|
}
|
|
|
|
// 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, readOnlyToken, "metrics disabled: set OpenWaf__Admin__Token"));
|
|
|
|
return app;
|
|
}
|
|
}
|