Skip to content

fix(router): reject a malformed frontend hostname instead of panicking the worker - #1312

Merged
FlorentinDUBOIS merged 3 commits into
mainfrom
fix/router-trie-insert-panic
Aug 27, 2026
Merged

FlorentinDUBOIS merged 3 commits into
mainfrom
fix/router-trie-insert-panic

Conversation

@KannarFr

Copy link
Copy Markdown
Member

Problem

A production worker crashed on a AddHttpFrontend carrying a malformed hostname:

thread 'main' panicked at lib/src/router/pattern_trie.rs:106:9:
assertion `left != right` failed
  left: Failed
 right: Failed

TrieNode::insert hard-asserts that insert_recursive never reports InsertResult::Failed:

let insert_result = self.insert_recursive(&key, &key, value);
assert_ne!(insert_result, InsertResult::Failed);   // plain assert -> compiled into release

but insert() only guards the empty key and a bare ., while insert_recursive rejects a much
wider 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 (only insert is
affected; lookup and remove are panic-free for all of these):

hostname before after
example.com/, www.example.com/, foo/, a/*/, /, /// PANIC Failed
abc/[0-9]+/.example.com (regex segment not .-anchored) PANIC Failed
/[/.example.com (segment is not a valid regex) PANIC Failed
.example.com, .a.b, .. (empty label) PANIC (sibling assert_ne!(partial_key, "")) Failed
*.example.com, /[0-9]+/.example.com, a.b., www.example.com/path Ok Ok (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 graceful Failed return. 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.
  • pattern_trie.rs::insert_recursive — an empty partial_key (leading or doubled .) returns
    Failed instead of assert_ne!.
  • router/mod.rs::add_tree_rule — checks InsertResult::Failed and returns false, so
    add_http_front surfaces RouterError::AddRoute -> ProxyError::AddFrontend. The worker answers
    ResponseStatus::Failure and stays up.

This is the same shape lib/src/tcp.rs::insert_sni_route already uses for SNI routes — that path
was 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, whose HttpFrontend
Debug is itself redacting) on the canonical log_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 Failure response and one ERROR line.

Tests added

  • pattern_trie::tests::insert_rejects_malformed_keys_without_panicking — every shape is Failed,
    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 a
    populated trie does not disturb the existing exact and wildcard entries.
  • router::tests::add_tree_rule_rejects_malformed_hostnames_without_panicking
  • router::tests::add_http_front_surfaces_a_malformed_hostname_as_an_error
  • e2e/src/tests/router_hostname_tests.rs (new suite) — sends all eight malformed hostnames
    over IPC to a live worker, asserts ResponseStatus::Failure for each, then asserts a well-formed
    frontend 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 again
once the fix is restored.

Commands run

cargo test -p sozu-lib --lib router::          # 70 passed
cargo test -p sozu-e2e --locked router_hostname # 1 passed
cargo test --workspace --locked                 # green
cargo clippy --all-targets --locked -- -D warnings
cargo +nightly fmt --all -- --check

Docs

CHANGELOG.md — entry under [Unreleased] / 🐛 Fixed.

Known follow-up (not in this PR)

The main process runs state.dispatch before the fan-out, so a malformed frontend is still
recorded in ConfigState even though every worker now rejects it: a phantom route shows in
sozu state, and each worker re-logs the rejection on every restart replay. That is the same class
as #1301, which was fixed for listeners only. Closing it properly needs a main-process validator
that mirrors the trie grammar — including the legitimate /regex/.host segment form — so it is
deliberately left out of this fix.

🤖 Generated with Claude Code

https://claude.ai/code/session_01LZje41ASjwZ2dNNtPgtyYU

`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]>
@CLAassistant

CLAassistant commented Aug 27, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

…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]>
@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

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 × insert/lookup/remove on both branches confirms zero panics remain on this branch, and that lookup/remove never panicked on either branch — the exposure was, and stays, control-plane only.

Two verified findings were still in scope; both are fixed in d9a078b:

  1. convert_regex_domain_rule still release-panicked (index out of bounds) on a /-carrying hostname with a bare trailing . (/a/., a/b/., x./y/.): the . arm of the loop tail advances index to s.len() and the next iteration indexes past the end — reached through the unconditional DomainRule parse in add_http_front, upstream of every trie guard, so the CHANGELOG's "the worker answers Failure and stays up" was not yet true for that class. The loop head now rejects the exhausted key; the family is covered in the unit tests and the e2e suite, seen red first (index out of bounds: the len is 4 but the index is 4).
  2. CertificateResolver silently discarded the now-reachable InsertResult::Failed (add_certificate / remove_certificate re-insert): a malformed certificate name went from panic to Ok(fingerprint) — certificate registered, SNI trie never learns the name, every handshake for it fails with zero diagnostic in release and debug. Names are now dry-run validated against a scratch trie before any state mutation, and both re-insert sites keep a tcp.rs::insert_sni_route-style canary.

Also in d9a078b: hostnames are bounded to MAX_HOSTNAME_LENGTH (4096 bytes) before any parse — the trie recurses once per label and a ~100k-label hostname aborts the worker with an uncatchable stack overflow (confirmed by execution; no unwind, so even the panic-hook metrics flush never runs), and a /-segment compiles a control-plane-supplied regex whose compile time grows with the pattern. CHANGELOG rescoped accordingly (including the real benefit this PR unlocks: workers answering Failure makes the #1301 unanimous-rejection rollback reachable on the live fan-out path).

a8b5ada bumps h2 0.4.15 → 0.4.19 (RUSTSEC-2026-0258) to clear the cargo audit job, red since 2026-08-17 and unrelated to this branch.

Follow-ups deliberately left out (each worth its own issue):

  • LoadState replay has no rollback (LoadStateTask carries none — a poisoned saved state re-injects the entry and SaveState re-persists it), and the Invalid HTTPS listener config is committed to master state before the worker rejects it, blocking a corrected reload #1301 rollback is skipped on scatter timeout: one unpatched worker panicking during a rolling upgrade times the request out and commits the malformed entry permanently.
  • No fuzz target for the router: fuzz/ covers H2 frames, HPACK, ClientHello and UDP; a fuzz_router_hostname target feeding Router::add_http_front would have found the trailing-dot OOB in seconds.
  • e2e Worker::read_proxy_response can never return None (.expect() on channel error), so the else fallbacks in this suite are defensive-only; making it return None on channel error would make those branches real.

CI note: the previous run's crypto-openssl failure (test_tcp_sni_large_payload_coalesced_with_hello_delivered_intact) is unrelated to this diff and passed on the three prior runs of that workflow — watching the re-run triggered by this push.

@FlorentinDUBOIS FlorentinDUBOIS left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@FlorentinDUBOIS
FlorentinDUBOIS merged commit bfde514 into main Aug 27, 2026
22 checks passed
FlorentinDUBOIS added a commit that referenced this pull request Aug 27, 2026
…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]>
@FlorentinDUBOIS
FlorentinDUBOIS deleted the fix/router-trie-insert-panic branch August 28, 2026 06:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants