Repository navigation
fix(router): reject a malformed frontend hostname instead of panicking the worker - #1312
Conversation
`TrieNode::insert` asserted that `insert_recursive` never reports
`InsertResult::Failed`:
let insert_result = self.insert_recursive(&key, &key, value);
assert_ne!(insert_result, InsertResult::Failed);
but `insert()` only guards the empty key and a bare `.`, while
`insert_recursive` rejects a much wider class of hostnames: a host ending
in `/` with no openable regex segment (`example.com/`), a regex segment
that is not `.`-anchored (`abc/[0-9]+/.example.com`), a segment that is
not a valid regex (`/[/.example.com`), and an empty label from a leading
or doubled `.` (`.example.com`, which trips the sibling
`assert_ne!(partial_key, &b""[..])` in `insert_recursive`).
Those hostnames arrive from the control plane -- an `AddHttpFrontend`
over the command socket, or a `LoadState` replay -- and the main process
fans the request out to every worker, so a single malformed frontend
panicked all of them at once, then panicked them again on each restart
state replay:
thread 'main' panicked at lib/src/router/pattern_trie.rs:106:9:
assertion `left != right` failed
left: Failed
right: Failed
Both asserts become graceful rejections. Every mutating step in
`insert_recursive` (`children.insert`, `regexps.push`) is already guarded
by an `Ok` from the level below, so a rejected key cannot leave a
half-built branch behind; that is now asserted as a post-condition
(value-count unchanged + `check_invariants()`) rather than assumed.
`add_tree_rule` checks the result and surfaces it as
`RouterError::AddRoute`, so the worker answers `Failure` and stays up --
the same shape `tcp.rs::insert_sni_route` already uses for SNI routes.
The rejection log follows the router's redaction convention (byte length,
not the hostname), on the canonical `log_module_context!()` envelope.
Tests: two unit tests in `pattern_trie` (every shape rejected, the trie
left untouched, existing entries intact), two in `router`
(`add_tree_rule` and `add_http_front`), and a new e2e suite
`router_hostname_tests.rs` that sends all eight malformed hostnames over
IPC, asserts `ResponseStatus::Failure` for each, then asserts a
well-formed frontend still installs and the worker soft-stops cleanly.
The e2e guard was verified by re-introducing the assert -- it fails, and
passes again once restored.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LZje41ASjwZ2dNNtPgtyYU
Signed-off-by: kannar <[email protected]>
…malformed hostnames Review follow-ups on the AddHttpFrontend hardening: - convert_regex_domain_rule indexed one byte past the end of a hostname whose last segment is followed by a bare trailing dot (/a/., a/b/., x./y/.): the dot arm of the loop tail advances the index to the key length and the next iteration panicked on the slice bounds check -- in release, through the unconditional DomainRule parse in add_http_front, upstream of every trie guard. The loop head now rejects the exhausted key. - Router::add_http_front_with_hsts_origin and Router::remove_http_front bound the hostname to MAX_HOSTNAME_LENGTH (4096 bytes) before any parse: the trie recurses once per label (a ~100k-label hostname aborted the worker with an uncatchable stack overflow) and a /-segment compiles a control-plane-supplied regex whose compilation time grows with the pattern size. - CertificateResolver::add_certificate dry-runs every certificate name against a scratch trie before mutating any state, and both re-insert sites keep a tcp.rs-style canary: with TrieNode::insert no longer panicking, a discarded InsertResult::Failed would have registered the certificate while the SNI trie never learned the name, silently failing every handshake for that SNI. Every rejection was seen red first: the DomainRule family panicked with the exact out-of-bounds the guard removes, the oversized hostname installed Ok, and the malformed certificate name returned Ok with an empty SNI trie. Redaction-test fixtures shrink below the new bound; the redaction properties they assert are length-independent. cargo test -p sozu-lib --lib: 778 passed. cargo test -p sozu-e2e --lib router_hostname: 1 passed. cargo clippy -p sozu-lib -p sozu-e2e --all-targets --locked -- -D warnings: clean. cargo +nightly fmt --all -- --check: clean. Signed-off-by: Florentin Dubois <[email protected]>
RUSTSEC-2026-0258: h2 0.4.15 accepts unbounded empty DATA frames; fixed in 0.4.16. Clears the cargo audit CI job, red since 2026-08-17 and unrelated to this branch. Cargo re-resolves the subtree's windows-sys edges to 0.52.0 as part of the same update; Linux builds are unaffected. cargo build --workspace --locked: clean. Signed-off-by: Florentin Dubois <[email protected]>
|
Cross-review done — fixes pushed to this branch. I ran an adversarial multi-lens review (correctness, security, tests, systemic) with independent red/green reproduction. The trie fix itself is correct and minimal: reverting the guards makes 4/70 router unit tests fail with the exact incident assertion and the e2e suite red; restoring them turns everything green. An adversarial probe over 16 malformed keys × Two verified findings were still in scope; both are fixed in d9a078b:
Also in d9a078b: hostnames are bounded to a8b5ada bumps h2 0.4.15 → 0.4.19 (RUSTSEC-2026-0258) to clear the Follow-ups deliberately left out (each worth its own issue):
CI note: the previous run's |
FlorentinDUBOIS
left a comment
There was a problem hiding this comment.
Adversarial cross-review done (full report in the review comment above): the trie fix is correct and was independently reproduced red/green; the residual panic/abort paths it left open are closed by the follow-up commits on this branch. CI is fully green on a8b5ada. Follow-ups tracked in #1313 / #1314 with PRs #1315 / #1316.
…ain-process state
`ConfigState` has no route-grammar check: `add_http_frontend` only reparses the
address and maps the position, so an `Add{Http,Https}Frontend` whose hostname
every worker's router refuses is still recorded by the main process. That state
is authoritative — `SaveState` re-serialises the malformed entry and every
replay re-injects it — and the replay path has no rollback at all, so the entry
survived a unanimous worker rejection and poisoned each subsequent restart.
The main process now runs the worker's OWN insertion path — the same
`Router::add_http_front`, against a disposable empty router — before
`ConfigState::dispatch`, on all three apply paths (`worker_request`,
`load_state`, `load_static_config`) through one shared `validate_request` entry
point that also keeps the #1301 listener check. A live frontend add is answered
with a failure and never fanned out; a malformed entry in a saved state file or
in the static configuration is skipped without entering the state, so it can
never be re-persisted nor re-injected.
Skipped entries — frontends and, as before, unbuildable listeners — are now
reported at `warn!` instead of `debug!`, because an entry silently dropped from
the state the operator saved must be visible at the default log level, and
`load_state` reports how many it skipped. The rejection strings are
`RouterError` / `RequestError` `Display` values, which carry byte lengths only,
never the operator-supplied hostname.
Based on #1312: the disposable-Router probe is only safe once
`Router::add_http_front` returns an error instead of aborting the process on
this hostname class, and once `convert_regex_domain_rule` no longer indexes out
of bounds. Without those the probe would panic the main process rather than a
worker.
The generic replay rollback — undoing entries the workers reject for reasons no
input validation can predict — stays out of scope and open in #1313: the probe
is the worker's own code, so an entry that passes it is not refused for
grammar, and the hostname class is now closed at the door on every path.
Refs #1313
Signed-off-by: Florentin Dubois <[email protected]>
Problem
A production worker crashed on a
AddHttpFrontendcarrying a malformed hostname:TrieNode::inserthard-asserts thatinsert_recursivenever reportsInsertResult::Failed:but
insert()only guards the empty key and a bare., whileinsert_recursiverejects a muchwider class of hostnames. The call path is entirely control-plane:
AddHttpFrontend->HttpProxy::add_http_frontend->Router::add_http_front->add_tree_rule->
TrieNode::domain_insert-> panic.The main process fans the request out to every worker, so one malformed frontend killed all
workers at once — and killed them again on every restart state replay, since the frontend stays in
ConfigState.Enumerating the trigger set with a probe over
insert/lookup/remove(onlyinsertisaffected;
lookupandremoveare panic-free for all of these):example.com/,www.example.com/,foo/,a/*/,/,///Failedabc/[0-9]+/.example.com(regex segment not.-anchored)Failed/[/.example.com(segment is not a valid regex)Failed.example.com,.a.b,..(empty label)assert_ne!(partial_key, ""))Failed*.example.com,/[0-9]+/.example.com,a.b.,www.example.com/pathOkOk(unchanged)The assert dates back to
e562299d(Oct 2023) and is unrelated to the H2 mux work.Fix
pattern_trie.rs::insert—assert_ne!becomes a gracefulFailedreturn. Every mutatingstep in
insert_recursive(children.insert,regexps.push) is already guarded by anOkfromthe level below, so a rejected key cannot leave a half-built branch behind; that is now asserted
as a post-condition (value count unchanged +
check_invariants()) rather than assumed.pattern_trie.rs::insert_recursive— an emptypartial_key(leading or doubled.) returnsFailedinstead ofassert_ne!.router/mod.rs::add_tree_rule— checksInsertResult::Failedand returnsfalse, soadd_http_frontsurfacesRouterError::AddRoute->ProxyError::AddFrontend. The worker answersResponseStatus::Failureand stays up.This is the same shape
lib/src/tcp.rs::insert_sni_routealready uses for SNI routes — that pathwas hardened against
InsertResult::Failed, the HTTP one never was.The rejection log follows the router's redaction convention (hostname byte length, not the value —
the hostname still reaches the control plane through
RouterError::AddRoute, whoseHttpFrontendDebugis itself redacting) on the canonicallog_module_context!()envelope.Protocol / security impact
No wire-protocol change. This is a control-plane availability fix: a malformed hostname pushed over
the command socket (or replayed from a state file) previously took down every worker in the process
group, repeatedly. It now costs one
Failureresponse and oneERRORline.Tests added
pattern_trie::tests::insert_rejects_malformed_keys_without_panicking— every shape isFailed,the trie is left
is_empty(), and the key is not resolvable with or without wildcards.pattern_trie::tests::a_rejected_insert_leaves_existing_entries_intact— a rejected insert on apopulated trie does not disturb the existing exact and wildcard entries.
router::tests::add_tree_rule_rejects_malformed_hostnames_without_panickingrouter::tests::add_http_front_surfaces_a_malformed_hostname_as_an_errore2e/src/tests/router_hostname_tests.rs(new suite) — sends all eight malformed hostnamesover IPC to a live worker, asserts
ResponseStatus::Failurefor each, then asserts a well-formedfrontend still installs on the same listener and the worker soft-stops cleanly. A panicking worker
fails this test by never answering.
The e2e guard was validated by re-introducing the
assert_ne!: the test fails, and passes againonce the fix is restored.
Commands run
Docs
CHANGELOG.md— entry under[Unreleased] / 🐛 Fixed.Known follow-up (not in this PR)
The main process runs
state.dispatchbefore the fan-out, so a malformed frontend is stillrecorded in
ConfigStateeven though every worker now rejects it: a phantom route shows insozu state, and each worker re-logs the rejection on every restart replay. That is the same classas #1301, which was fixed for listeners only. Closing it properly needs a main-process validator
that mirrors the trie grammar — including the legitimate
/regex/.hostsegment form — so it isdeliberately left out of this fix.
🤖 Generated with Claude Code
https://claude.ai/code/session_01LZje41ASjwZ2dNNtPgtyYU