From a8f2b05340b918d4a196cd05465460d79ca83f6f Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Mon, 5 Oct 2026 05:17:42 +0200 Subject: [PATCH] an edge that refuses to start says so and then leaves Every bound this build refuses to run with - the refresh TTL, the two retention windows, the push-attempt and retry intervals, the webhook timeout, the token pair - was already refused with a sentence naming the key and the value. The sentence was right and the form was not. Measured on the shipped image: an unhandled exception during startup printed the reason and then the process sat at 100% CPU inside the runtime's crash path. The container stayed "Up (unhealthy)" forever with no exit code, so compose reported nothing, k8s restarted nothing, and the only symptom of a mistyped number was a spinning core. OPEN-62 caught this for one refusal; this is the convention for all of them. One way out: RefuseStartup writes the reason to stderr and returns 1, and every refusal goes through it, so the exit code is the same for all of them and a supervisor can tell "refused to start" from "an edge that died while serving". Most refusals are not raised in the entry point at all - the TTL and the retention windows surface during host start, when a hosted service resolves the service whose factory parsed the value - so app.Run is wrapped in a catch guarded by whether ApplicationStarted ever fired. Before that point an exception leaving app.Run is a configuration the operator can fix; after it, it is not, and it must not be reported as one. What the run caught, in order: (1) The app.Run guard does not reach the three alert bounds, which are parsed in the entry point before the host exists, so MaxPushAttempts=0 still took the crash path - they are now wrapped where they are parsed. (2) The refusal messages name the key in the appsettings spelling (OpenWaf:State:RefreshTtlSeconds), not the environment spelling the gate overrode it with, so the first version of the new assertions failed four times for a reason that was the gate's, not the product's. (3) The shape of the assertion matters as much as the code: a gate that waits on the process cannot tell a refusal from a hang, which is exactly why OPEN-62's original assertion passed on a container that never exited. Both suites now start the edge detached and poll for an exit, and "still running after the bound" is a failure. Gates on this tree: build 0 warnings / 0 errors, unit 307/307, integration 286/286 in 37s, smoke 113 passed / 0 failed (8 new: four bounds, each asserting the exit code and that the reason names the key), image 262 MB, compose-smoke 267 passed / 0 failed with 0 containers left behind (6 new, against the shipped image), console 90 assertions / 0 failed. Refs OPEN-63. --- README.md | 19 +++++-- dotnet/OpenWaf.Edge/Program.cs | 93 ++++++++++++++++++++++++++-------- scripts/compose-smoke.sh | 39 ++++++++++++-- scripts/smoke.sh | 55 ++++++++++++++++++++ 4 files changed, 177 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index fbc0179..c926bc6 100644 --- a/README.md +++ b/README.md @@ -269,6 +269,17 @@ process registers: | `OpenWaf:Alerts:PushRetrySeconds` | `30` | the base of the backoff between attempts: attempt *n* waits `base × 2^(n−1)`, capped at 30 minutes per step, because exponential growth from a 30-second base reaches a day in eight steps and a day is not a retry interval for a page meant to fire at 03:00. 1–3600 whole seconds, same startup refusal — a 0-second interval against a dead endpoint is a busy loop. | | `OpenWaf:Admin:ReadOnlyToken` (OPEN-62) | empty | a second token that can read every operator surface and change none of it. Unset means the level does not exist and the admin token is the only one there is. The level is decided by the request method — GET, HEAD and OPTIONS read, everything else writes — so a write endpoint added later is behind the rule without anyone remembering to mark it, and forgetting fails closed. `GET /admin-api/export` is the one read deliberately held to the admin token, because the document is a capability. A value equal to the admin token (compared after trimming, because env files add newlines) aborts startup naming both keys and never the secret, and it exits 1 rather than throwing: measured on the shipped image, an unhandled exception there printed the reason and then spun at 100% CPU with the container "Up (unhealthy)" forever, which is a failure no supervisor can see. | +A refused value ends the process. Every bound above is checked before the edge +serves a request, and a refusal is a written reason naming the key and the value +plus **exit code 1** — the same code for every one of them, so a supervisor can +tell "refused to start" from "an edge that died while serving". That form was a +bug, not a style: measured on the shipped image, an unhandled exception during +startup printed the reason and then the process sat at 100% CPU inside the +runtime's crash path, leaving the container `Up (unhealthy)` forever with no exit +code — compose reported nothing, k8s restarted nothing, and the only symptom was +a spinning core. The gates assert the process **leaves** (started detached, +polled for an exit), because waiting on it cannot tell a refusal from a hang. + Database: `Database:Provider` = `sqlite` (default) or `postgres`, `ConnectionStrings__OpenWaf`. GeoIP: `GEOIP_MAXMIND_DB_PATH`. @@ -1132,10 +1143,10 @@ 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-05 with the durable -alert-push queue, the config transfer and the second token on it: build 0 warnings / 0 errors, -unit **307/307**, integration **286/286 in 26 s**, console **90 assertions, 0 failed**, smoke -**passed 105, failed 0**, and compose **261 passed, 0 failed** against the built image at -262 MB, 0 containers left behind. The smoke count moved by more than its new scene: the edge was being +alert-push queue, the config transfer, the second token and the startup refusals on it: build +0 warnings / 0 errors, unit **307/307**, integration **286/286 in 37 s**, console **90 +assertions, 0 failed**, smoke **passed 113, failed 0**, and compose **267 passed, 0 failed** +against the built image at 262 MB, 0 containers left behind. 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 middleware pipeline without being handled by application code" for every request, diff --git a/dotnet/OpenWaf.Edge/Program.cs b/dotnet/OpenWaf.Edge/Program.cs index 0ab3614..ff552ad 100644 --- a/dotnet/OpenWaf.Edge/Program.cs +++ b/dotnet/OpenWaf.Edge/Program.cs @@ -86,16 +86,28 @@ builder.Services.AddSingleton(); var alertWebhookUrl = builder.Configuration["OpenWaf:Alerts:WebhookUrl"]; if (string.IsNullOrWhiteSpace(alertWebhookUrl)) alertWebhookUrl = Environment.GetEnvironmentVariable("OPENWAF_ALERT_WEBHOOK_URL"); -var alertWebhookTimeout = AlertNotifier.ParseTimeoutSeconds( - builder.Configuration["OpenWaf:Alerts:WebhookTimeoutSeconds"]); -// How hard to try, and how long to wait between tries (OPEN-60). Validated here -// rather than defaulted: MaxPushAttempts=0 means "never tell anybody" and a -// 0-second retry against a dead endpoint is a busy loop, and neither is what the -// operator meant when they wrote the number. -var alertPushAttempts = PushRetryPolicy.ParseMaxAttempts( - builder.Configuration["OpenWaf:Alerts:MaxPushAttempts"]); -var alertPushRetrySeconds = PushRetryPolicy.ParseRetrySeconds( - builder.Configuration["OpenWaf:Alerts:PushRetrySeconds"]); +// The three alert bounds are parsed here, before the host exists, so they need +// the same clean exit as the refusals that surface during host start (OPEN-63): +// an unhandled exception on the shipped image prints the reason and then spins +// at full CPU instead of leaving. +int alertWebhookTimeout, alertPushAttempts, alertPushRetrySeconds; +try +{ + alertWebhookTimeout = AlertNotifier.ParseTimeoutSeconds( + builder.Configuration["OpenWaf:Alerts:WebhookTimeoutSeconds"]); + // How hard to try, and how long to wait between tries (OPEN-60). Validated + // here rather than defaulted: MaxPushAttempts=0 means "never tell anybody" + // and a 0-second retry against a dead endpoint is a busy loop, and neither + // is what the operator meant when they wrote the number. + alertPushAttempts = PushRetryPolicy.ParseMaxAttempts( + builder.Configuration["OpenWaf:Alerts:MaxPushAttempts"]); + alertPushRetrySeconds = PushRetryPolicy.ParseRetrySeconds( + builder.Configuration["OpenWaf:Alerts:PushRetrySeconds"]); +} +catch (Exception ex) +{ + return RefuseStartup(ex.Message); +} builder.Services.AddSingleton(sp => new AlertNotifier( sp.GetRequiredService(), sp.GetRequiredService(), @@ -258,15 +270,8 @@ if (string.IsNullOrWhiteSpace(readOnlyToken)) // pipes startup output to. if (AdminTokenPolicy.ExplainConfigurationProblem(adminToken, readOnlyToken) is { } tokenProblem) { - // A clean exit, not a throw. Measured on the shipped image: an unhandled - // exception here prints the reason and then the process sits at 100% CPU - // inside the runtime's crash path instead of leaving - the container stays - // "Up (unhealthy)" forever, so the supervisor sees no failure, restarts - // nothing, and the operator has to notice a spinning process to learn the - // edge never started. Refusing to start is only useful if the process - // actually goes away and leaves a non-zero code behind. - Console.Error.WriteLine(tokenProblem); - return 1; + // A clean exit, not a throw - see RefuseStartup for the measurement. + return RefuseStartup(tokenProblem); } app.MapAdminApi(adminToken, readOnlyToken); @@ -283,8 +288,54 @@ if (!app.Environment.IsProduction()) app.MapReverseProxy(); -app.Run(); -return 0; +// Did this process ever reach the point of serving? It decides what an +// exception leaving app.Run means. +var startedServing = false; +app.Lifetime.ApplicationStarted.Register(() => startedServing = true); + +try +{ + app.Run(); + return 0; +} +catch (Exception ex) when (!startedServing) +{ + // A startup refusal. Most of them are not written here: the TTL, the two + // retention windows, the push-attempt and retry bounds and the webhook + // timeout are validated by the types that own them, and they surface during + // host start, when a hosted service resolves the service whose factory + // parsed the value. + // + // Catching it here rather than letting it go was measured, not guessed. On + // the shipped image an unhandled exception during host start prints the + // reason and then the process sits at 100% CPU inside the runtime's crash + // path: the container stays "Up (unhealthy)" forever, there is no exit code, + // and the supervisor - compose, k8s, a systemd unit - sees a running edge + // and restarts nothing. The refusal sentence itself was already correct; + // only its form was unreadable. + // + // The startedServing guard is what keeps "refused to start" and "an edge + // that died while serving" from collapsing into one exit code. After the + // application has started, an exception leaving app.Run is not a + // configuration the operator mistyped, and it must not be reported as one. + return RefuseStartup(ex.Message); +} + +/// +/// The one way this process says "I will not start": the reason on stderr and +/// exit code 1. Every startup refusal goes through here so the exit code is the +/// same for all of them, which is what lets a supervisor and a script tell +/// "refused to start" from "crashed later" - the crash path leaves a different +/// code and a stack trace, and a spinning container leaves neither. +/// +/// The reason is written as given. The validators own their sentences and each +/// one names the key and the offending value; none of them prints a secret. +/// +static int RefuseStartup(string reason) +{ + Console.Error.WriteLine($"the edge refused to start: {reason}"); + return 1; +} /// Marker for WebApplicationFactory in the integration tests. public partial class Program; diff --git a/scripts/compose-smoke.sh b/scripts/compose-smoke.sh index 80eac7e..59f1a9c 100755 --- a/scripts/compose-smoke.sh +++ b/scripts/compose-smoke.sh @@ -1526,10 +1526,9 @@ check 'and that row is removable again, so the volume stays clean' '200' \ check 'an unknown token is still 401 on the shipped image' '401' \ "$(code -H "X-Admin-Token: not-a-token" "$EDGE/admin-api/state")" -# The configuration the shipped image refuses to start with, run as a container: -# a read-only token that is also the admin token. Asserted against the image -# rather than only the source, because "refused at startup" is a claim about what -# an operator who configures this actually gets. +# The configuration the shipped image refuses to start with, run as a container. +# Asserted against the image rather than only the source, because "refused at +# startup" is a claim about what an operator who configures this actually gets. BAD_LOG=/tmp/openwaf-compose-bad-$$.log # Started detached and polled, not waited on: the assertion is that the process # LEAVES. A refusal that prints its reason and then keeps running is a container @@ -1554,6 +1553,38 @@ check 'it names both keys in the reason' 'yes' \ check 'and it never prints the secret' 'yes' \ "$(grep -q "$OPENWAF_ADMIN_TOKEN" "$BAD_LOG" && echo no || echo yes)" rm -f "$BAD_LOG" + +echo '- every startup refusal leaves the container, it does not sit there' +# The same claim as the scene above, over the bounds this build refuses to run +# with. Each is raised by the type that owns it - the TTL during host start, the +# retention window through the policy, the alert bounds in the entry point - so +# the gate is what keeps the convention from rotting back into a printed +# complaint and a container that burns a core forever. +for bad in 'OpenWaf__State__RefreshTtlSeconds=0' \ + 'OpenWaf__Policy__ObservationRetentionDays=0' \ + 'OpenWaf__Alerts__MaxPushAttempts=0'; do + key=${bad%%=*} + # The validators name the key in the appsettings spelling (OpenWaf:State:...), + # not the environment spelling, so the grep converts it before asking. + msg_key=${bad%%=*} + msg_key=${msg_key//__/:} + bad_name="openwaf-refused-$$" + docker compose run -d --name "$bad_name" -e "$bad" edge >/dev/null 2>&1 + bad_rc='' + for _ in $(seq 1 30); do + if [ "$(docker inspect -f '{{.State.Status}}' "$bad_name" 2>/dev/null)" = exited ]; then + bad_rc=$(docker inspect -f '{{.State.ExitCode}}' "$bad_name" 2>/dev/null) + break + fi + sleep 1 + done + docker logs "$bad_name" >"$BAD_LOG" 2>&1 + docker rm -f "$bad_name" >/dev/null 2>&1 + check "a bad $key leaves the shipped image with code 1" '1' "$bad_rc" + check " and the reason names the key" 'yes' \ + "$(grep -q "$msg_key" "$BAD_LOG" && echo yes || echo no)" +done +rm -f "$BAD_LOG" 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 2a407ef..e37f226 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -88,6 +88,39 @@ check() { } code() { curl -s -o /dev/null -w '%{http_code}' "$@"; } from() { printf 'http://127.0.0.1:%s/%s' "$EDGE_PORT" "$1"; } # usage: from path + -H "X-Forwarded-For: ip" +# A startup refusal has to leave a process that is GONE. Measured on the shipped +# image (OPEN-63): an unhandled exception at startup prints the reason and then +# the process sits at 100% CPU inside the runtime's crash path, so the container +# stays Up forever and the supervisor restarts nothing. This starts the edge with +# one bad value, waits for it to leave on its own, and answers its exit code - or +# "hung" if it is still there after 20 seconds. A gate that simply waited on the +# process could not tell the two apart. +refused_rc() { # $1 = KEY=VALUE to override, $2 = where to put the output + local override="$1" log="$2" + local db="/tmp/openwaf-smoke-refused-$$.db" + rm -f "$db" + env ASPNETCORE_URLS="http://127.0.0.1:$((EDGE_PORT+9))" \ + OPENWAF_ADMIN_TOKEN="$TOKEN" \ + ConnectionStrings__OpenWaf="Data Source=$db" \ + "$override" \ + dotnet "$BIN" --contentRoot "$BIN_DIR" >"$log" 2>&1 & + local pid=$! rc='' + for _ in $(seq 1 40); do + if ! kill -0 "$pid" 2>/dev/null; then + wait "$pid" 2>/dev/null + rc=$? + break + fi + sleep 0.5 + done + if [ -z "$rc" ]; then + kill "$pid" 2>/dev/null + wait "$pid" 2>/dev/null + rc=hung + fi + rm -f "$db" "$db-shm" "$db-wal" + printf '%s' "$rc" +} echo "edge :$EDGE_PORT upstream :$UP_PORT db $DB" @@ -380,6 +413,28 @@ check 'and it never prints the secret' yes \ "$(grep -q "$TOKEN" "$BAD_LOG" && echo no || echo yes)" rm -f "$BAD_DB" "$BAD_DB-shm" "$BAD_DB-wal" "$BAD_LOG" +echo '- a startup refusal leaves, it does not sit there' +# Every bound this build refuses to run with, asserted the same way: the process +# goes away by itself with code 1 and the reason names the key. These are the +# refusals that are NOT written in one place - each is raised by the type that +# owns the bound - so the assertion is what keeps the convention from rotting. +for bad in 'OpenWaf__State__RefreshTtlSeconds=0' \ + 'OpenWaf__Policy__ObservationRetentionDays=0' \ + 'OpenWaf__Alerts__MaxPushAttempts=0' \ + 'OpenWaf__Alerts__PushRetrySeconds=0'; do + key=${bad%%=*} + # The validators name the key in the appsettings spelling (OpenWaf:State:...), + # not the environment spelling, so the grep converts it before asking. + msg_key=${bad%%=*} + msg_key=${msg_key//__/:} + refused_log="/tmp/openwaf-smoke-refused-$$.log" + refused_code=$(refused_rc "$bad" "$refused_log") + check "a bad $key exits instead of spinning" 1 "$refused_code" + check " and the reason names the key" yes \ + "$(grep -q "$msg_key" "$refused_log" && echo yes || echo no)" +done +rm -f "$refused_log" + echo '- volume budget' STATE0_JSON="$(curl -s -H "X-Admin-Token: $TOKEN" "http://127.0.0.1:$EDGE_PORT/admin-api/state")" check 'the budget is off until an operator writes one' Off \