Repository navigation
fix(router): anchor every branch of a hostname regex segment - #1363
Merged
Merged
Conversation
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 20, 2026 10:39
FlorentinDUBOIS
force-pushed
the
fix/anchor-hostname-regex
branch
from
September 20, 2026 11:01
b58a5ec to
085f9ea
Compare
A regex hostname segment was anchored by concatenating `\A` and `\z`
around the operator's pattern without grouping it. `|` is the
lowest-precedence regex operator, so `\Aa|b\z` parses as `(\Aa)|(b\z)`:
each branch keeps one anchor only, which re-opens the substring match the
anchoring exists to prevent. With three or more branches the middle ones
keep neither anchor and match as a bare substring anywhere at all.
Measured on the tree as it stood, `/a|b/.example.com` served
`axx.example.com` and `xxb.example.com`, `/a|b|c/.example.com` served
`zzbzz.example.com`, and `/api|admin/.example.com` served
`apifoo.example.com` and `xadmin.example.com` — none of which the
operator declared, and none visible in `sozu query frontends`.
Both hostname code paths carried it. `convert_regex_domain_rule` now
emits `(?:` … `)` around each slash-delimited segment of the whole-host
regex a Pre/Post rule matches against. `pattern_trie.rs`'s segment-insert
wrappers — the insert dedup scan, the insert create path,
`remove_recursive` and `lookup_mut` — are now one `anchored_segment`
helper building `\A(?:{segment})\z`; that
string is also a `regexps` entry's identity, compared through
`Regex::as_str()` by the insert dedup scan, `remove_recursive` and
`lookup_mut`, so a second spelling would make a stored segment
un-removable.
The literal-label arm of the same function carried the same defect, one
`else` away, and is closed with it. A label the operator did not wrap in
slashes was pushed into the assembly verbatim, so `/a/.x|y.com` assembled
to `\A(?:a)\.x|y\.com\z` and matched `a.xZZZ` and `ZZZy.com`. A literal
label is a literal, so the treatment is `regex::escape`, not a group:
grouping would confine the alternation while leaving `+`, `?`, `*`, `^`
and `$` live in the same arm, and `b+c` matching `bbbc` is the same
defect with a different operator. Escaping is a no-op in matching
behaviour for every label a real hostname can carry — an LDH label is
`[A-Za-z0-9-]`, of which `regex::escape` touches only `-`, and `\-` is
`-` outside a character class. Two deliberate behaviour changes fall out
for labels that are not valid hostname labels, both narrowing and both
measured: a literal `*` label was a quantifier over the preceding atom,
so `*./x/.example.com` assembled to `\A*\.(?:x)\.example\.com\z` whose
`\A*` repeats a zero-width assertion and matched empty at any offset,
taking `evil.attacker.x.example.com`; and a literal label carrying an
unbalanced `(` or `[` was rejected outright and is now accepted, matching
exactly the host that was typed.
That `*` change is scoped to Pre/Post, which is all this function feeds.
A trie-routed frontend keeps a `*` label in `TrieNode`'s wildcard slot and
is untouched, so one configured hostname now answers differently by
position: `*./x/.example.com` takes `zz.x.example.com` on the trie and no
longer on Pre/Post, while `*.x.example.com` routes on both.
`doc/configure.md` carries that table, and the remediation for Pre/Post is
to spell the label out as a regex segment, `/[^.]*/./x/.example.com`.
SNI route selection carried the defect too and is fixed with it:
`lib/src/protocol/tcp_preread` resolves the ClientHello SNI against this
very trie and its routes are operator-configured, so a route
`/a|b|c/.example.com` accepted the SNI `zzbzz.example.com`.
`lib/src/tls.rs` uses the same `TrieNode` type but keys it by certificate
SAN names, which cannot contain a `/`, so its regex arm is unreachable in
practice and no test is claimed for it.
Adding that SNI test surfaced a separate pre-existing defect, fixed here
because the test cannot pass without it. `tcp_preread`'s `decide` carried
a `debug_assert!` requiring `matched_sni_pattern` to be the SNI itself or
a `*.` wildcard. `TrieNode::domain_lookup` returns a third shape — a key
carrying `/regex/` segments — which the assertion did not admit, so a
debug build panicked the first time any regex-segment SNI route matched,
though routing itself was correct. It now admits that shape by checking
the literal tail after the rightmost `/`; the segments are not
re-derived, because the trie has already matched them.
The group is non-capturing, so `captures_len` and therefore every
`$HOST[n]` rewrite index are unchanged: `$HOST[1]` of
`/cdn([0-9]+)/.example.com` is still the operator's own group. Each regex
segment is compiled on its own before being wrapped, because the wrapper
supplies one `(` and one `)` and can balance an unbalanced segment:
`a)(b` is rejected by `Regex::new`, yet `\A(?:a)(b)\.example\.com\z`
compiles and matches `ab.example.com`.
This is the hostname half of the wrapper #1357 landed for path regexes,
and it narrows existing rules the same way: an operator relying on the
leaked hosts writes the wildcards out, `/api|admin/` becoming
`/api.*|.*admin/`. `doc/configure.md` now also names a pre-existing trap
that remediation walks into — a `.*` inside a segment does not stop at
the label boundary, and where it stops depends on the rule position, so
`[^.]*` is what a `Pre`/`Post` rule needs. The 1.x-to-2.0 upgrade note
and `CHANGELOG.md` are corrected in the same changeset.
`an_alternating_regex_hostname_segment_is_still_anchored_at_one_end_only`
pinned the defect and asked, in its own comment, to be inverted rather
than deleted when the fix landed. It is now
`an_alternating_regex_hostname_segment_is_anchored_on_every_branch`,
extended to the three-branch case: with exactly two branches "first and
last" is every branch there is, so two cannot express the claim.
Closes #1356.
Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
force-pushed
the
fix/anchor-hostname-regex
branch
from
September 20, 2026 11:14
085f9ea to
1841ab7
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #1356.
The defect
Hostname regex segments were anchored by concatenating
\Aand\zaround the operator's patternwithout grouping it.
|is the lowest-precedence regex operator, so\Aa|b\zparses as(\Aa)|(b\z)— each branch anchored at one end only, which re-opens exactly the substring match theanchoring was added to prevent.
A frontend written
/api|admin/.example.comalso servedapifoo.example.comandxadmin.example.com. The operator has no way to notice: the frontend loads,sozu query frontendsshows exactly what they typed, and the extra hosts appear only if someone sends them.
With three branches it is worse than "one end only": ungrouped
\Aa|b|c\zparses as(\Aa)|(b)|(c\z), so the middle branch keeps neither anchor and matches as a bare substringanywhere in the host.
The change
Five sites across two genuinely different code paths:
lib/src/router/mod.rsconvert_regex_domain_rulenow emits(?:…)around eachslash-delimited segment. Not around the whole result — the function assembles multiple segments,
so
\A(?:a|b\.example\.com)\zwould have broken the intended match.format!("\\A{s}\\z")sites inlib/src/router/pattern_trie.rsbecame oneanchored_segment()helper. That string is also aregexpsentry's identity (compared viaRegex::as_str()at three of the four sites), so a second spelling would make a stored segmentun-removable; the helper is the single source. It also removed a pre-existing duplicate
format!.Both paths compile the bare pattern first, so a malformed pattern such as
a)(bcannot be rescuedinto a valid
\A(?:a)(b)\z.Non-capturing is load-bearing.
$HOST[n]exists on the hostname side:capture_cap_hostisDomainRule::Regex::captures_len()and extraction iscaps.iter().skip(1). A capturing wrappershifts every index, silently rewriting wrong traffic. Pinned by assertions on
captures_lenand bya rewrite test checking
$HOST[1]→42and$HOST[0]→ the whole host across all three ofPre/Post/Tree, with
$HOST[2]still refused asRouterError::InvalidHostRewrite.Wider than the issue: the TCP pre-read SNI path carried the trie half
lib/src/protocol/tcp_preread/mod.rs:377doesdomain_lookup(sni, ..)against operator-configuredroutes, reaching the same
pattern_trie::TrieNoderegexpsentries. It does not useconvert_regex_domain_rule, so it was not covered by the issue's analysis — but it carried the triehalf of this defect and inherits the grouped wrapper.
lib/src/tls.rs:637walks that same trie — a separateTrieNodeinstance, not shared state —and it is reachable too, though by a narrower route. Its entries are inserted at
tls.rs:374fromcert_to_add.names, which is the operator'snamesoverride when supplied and the parsed SAN/CN setotherwise. A parsed DNS SAN cannot contain
/; an operator-supplied name is not validated for it—
add_certificate's dry-run (tls.rs:326-336) rejects only an over-long name and a hardInsertResult::Failed, neither of which a/x/label triggers. So a certificate registered with anoperator-supplied regex-shaped name does land in the
regexpslist and does inherit this fix.Nothing tests that path, and this changeset adds no test for it.
A repo-wide grep found no other
\Aanchoring construction outsidelib/src/router/.Tests
Four new behavioural tests, every one using a three-branch alternation, because a two-branch
alternation cannot express the clause: with two branches the first gets
\Aand the last gets\z,so "every branch is anchored" has nothing to bite on. Asserted non-routing:
zzbzz.example.com,bzz.example.com,zzb.example.com, plus hand-built ungrouped controls proving they used to route.An existing test that pinned the defect and asked in its own comment to be inverted was inverted,
not deleted:
an_alternating_regex_hostname_segment_is_still_anchored_at_one_end_onlyis nowan_alternating_regex_hostname_segment_is_anchored_on_every_branch, extended to three branches andciting its old name.
Six mutations were run individually. Full unfixed baseline:
Per-site, the two that matter most:
The production bodies contain zero test-input literals, so the fix is not test-shaped.
Docs
doc/configure.md§ "Regex hostname segments" claimed the segment "matches that whole segment andnothing else" — corrected, with the narrowing note and the remediation. Its
/api|admin/→apifoo/xadminexample and its/api.*|.*admin/remediation are each asserted as an 8-row table:every measured claim in the prose has an assertion behind it.
CHANGELOG.mdgains a Security entry, and one stale in-release cross-reference — the #1357 pathentry, which described the hostname sites as ungrouped — was corrected.
Validation
BUILD=0 CLIPPY=0 TEST=0 FMT=0,test result: ok. 868 passed; 0 failed.Also
-p sozu97 passed,-p sozu-command-lib153 passed, andtests::router_hostname_tests::test_malformed_hostnames_rejectedby exact name.Not reproduced against a live proxy; measured through the router's public surface, as the issue
states. The SNI inheritance is asserted by code reading — both call
TrieNode::domain_lookupon thesame trie — not by a new SNI-level test.