Repository navigation
fix(router): let a leftmost-regex host be inserted after a deeper sibling - #1352
Merged
Merged
Conversation
…ling In the pattern trie a domain whose leftmost label is a regex (`/test[0-9]/.example.com`) and a deeper domain sharing that segment (`foo./test[0-9]/.example.com`) live in the same `(regex, subtree)` entry: the first as the subtree's own value, the second as a child of it. `insert_recursive`'s `pos == 0` arm returned `InsertResult::Existing` unconditionally, justified by a comment claiming the subtree was already a value-bearing leaf built by `TrieNode::new`. That premise is false when the entry was created by the `pos > 0` branch, which builds a valueless `TrieNode::root()`. Inserting the deeper domain first therefore made the leftmost-regex host permanently un-insertable: the second insert answered `Existing` and stored nothing. Debug builds panicked the worker from a control-plane `AddHttpFrontend`, on `add_tree_rule`'s post-condition. Release builds reported success, listed the frontend in `sozu query frontends`, and never routed it — the main process recorded a frontend the data plane did not have. Pre-existing; PR #1330 fixed `remove_recursive` and left this path untouched. The arm now asks the slot through a new `insert_own_value`: free answers `Ok`, occupied answers `Existing`. The empty-key arm is deliberately not reused, because on the remove side it is a query and on the insert side it is validation — routing an insert through it would make every leading-dot hostname insertable, including as a TLS certificate name, which `CertificateResolver::add_certificate` rejects by dry-running the same trie. Three comments resting on the same false premise are corrected, and the no-dot arm's soundness is documented: it is safe only because the two `children.insert` sites use disjoint key spaces, one keyed by a dotless segment and one by a key that always starts with a dot. `doc/configure.md` claimed configuration order does not affect routing. It does, in ways the manual had wrong in six separate dimensions, so the precedence section is rewritten and pinned by fourteen tests: - `PREFIX` rules: longest match wins among rules whose method matches, with an equal-length tie going to the last declared. - `REGEX` and `EQUALS`: the scan returns on the first match, so the first declared wins, and neither type outranks the other. - a matching `EQUALS` or `REGEX` beats a longer `PREFIX` in either order, but only when it carries a method the request matches. - without a method the scan does not short-circuit, so the last declared wins and only a prefix spanning the whole request path displaces a regex. - a rule whose method is set but does not match is skipped entirely, whatever its path type. - the request path is the request-target including any query string, which inverts the whole-path case and stops `EQUALS` matching at all. Path regexes are documented as unanchored, which they are: the `\A...\z` work of 2.0.0 applies to hostname segments only. Whether they should be anchored is sozu#1350. Hostname overlap is stated as not resolved by declaration order, without describing what does resolve it: that behaviour attaches an exact-host rule to a matching regex segment's leaf and is sozu#1351. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 18, 2026 23:33
pull Bot
pushed a commit
to jrcribb/sozu
that referenced
this pull request
Sep 19, 2026
BREAKING. A `path_type = "REGEX"` rule now matches only when it spans the
whole request path. `doc/configure.md` has stated since v2.0.0 that `REGEX`
rules are anchored `\A...\z`; that was true of hostname segments and false of
path rules, because `PathRule::from_config` built a bare `Regex::new` and
`is_match` is unanchored. A rule written `/admin` matched `/foo/admin/bar`.
`Route::Deny` shares the same `PathRule::matches` scan, so deny rules narrow
identically: a `REGEX` deny of `/admin` still denies `/admin`, but
`/admin/secret` and `/administrator` now reach a backend. Audit deny-shaped
regex frontends before upgrading.
The two shapes an operator must rewrite:
- substring or prefix-shaped — `/api` matched `/api/v1`; write `/api.*`.
- suffix-shaped — `\.js$` matched every path ENDING in `.js`; a trailing
`.*` does NOT fix it (`\.js.*` does not match `/static/app.js`). Write a
LEADING `.*`: `.*\.js$`.
The second is the destructive direction and the easier one to miss. A
hand-written `^/abc` gains the end it lacked and merely narrows; a
hand-written `\.js$` gains a START it never wanted and stops matching
anything a client can send.
Anchoring also makes `REGEX` inherit the `EQUALS` query-string behaviour,
since the request path is the request-target: `/abc` no longer matches
`GET /abc?x=1`. Extend on the side the pattern is open on — a rule closed at
both ends needs the query spelled out, e.g. `.*\.js([?].*)?`.
The value is wrapped verbatim in a non-capturing group, `\A(?:{value})\z`.
The group is load-bearing rather than cosmetic: `|` binds looser than
concatenation, so the ungrouped form the hostname sites use would leave each
branch of an alternation anchored at one end only. Non-capturing keeps
`captures_len()` unchanged, so `$PATH[n]` rewrite indices are untouched —
they come from `caps.iter().skip(1)`, and a capturing wrapper would have
shifted every one.
Hand-written anchors are kept, not stripped. `^` and `$` are `\A` and `\z` in
this crate's default mode, so the assertions collapse and `\A(?:^/abc$)\z`
behaves as `/abc` does. Stripping them textually is unsound — `^` occurs
non-initially, inside groups, under `(?m)` and in classes.
The pattern is validated before it is wrapped, because wrapping can rescue an
invalid one: `a)(b` does not compile, but `\A(?:a)(b)\z` does, the wrapper's
own parentheses balancing it. Without that check an operator's typo would
become a silently accepted rule matching something they never wrote.
Wrapping can also reject a pattern that compiled bare — `(?x)` with a
trailing `#` comment swallows the closing `)\z`, and a pattern nested 249
deep exceeds the 250 limit once wrapped. That surfaces as
`RouterError::InvalidPathRule` when the frontend is registered, and the main
process validates through the same `Router::add_http_front`, so it is refused
at the control plane with no main/worker divergence.
The test PR sozu-proxy#1352 added to pin the unanchored behaviour,
`a_path_regex_is_unanchored_and_matches_anywhere_in_the_request_path`, is
inverted by this change and renamed to
`a_path_regex_is_anchored_at_both_ends_and_must_match_the_whole_request_path`.
It asserted that `bc` matches `/abcd`; it now asserts the same example does
not, plus the whole-path hit, both end rejections and both query-string
cases. That test existed so this change would be deliberate rather than
silent, and it did its job: it turned red and forced this entry.
Signed-off-by: Florentin Dubois <[email protected]>
Every behavioural claim the documentation above makes is asserted, including
the "used to match" column describing the pre-anchoring 2.2.1 behaviour. The
suffix family, the query-string family, the alternation cases, the two
wrapped-rejection shapes and both clusterless deny paths each have a test, and
each was seen red under a named mutation before it was allowed to pass.
Two of those deserve naming. The non-capturing group is pinned three ways,
because a capturing wrapper would shift every `$PATH[n]` rewrite index by one
and corrupt traffic silently rather than loudly: with a capturing wrapper a
`$PATH[1]` rewrite yields `/api/v2/users` where it must yield `v2`. And the
alternation claim is asserted with THREE branches, not two: with two branches
"every branch is anchored, not just the first and last" has nothing to bite
on, while ungrouped with three the middle branch keeps neither anchor and
matches as a bare substring.
Signed-off-by: Florentin Dubois <[email protected]>
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.
A 9-line production fix, and a documentation section that turned out to be wrong in six separate
dimensions. Completes #1330, which fixed
remove_recursiveand left the insert path untouched.The defect
In the pattern trie, a domain whose leftmost label is a regex (
/test[0-9]/.example.com) and adeeper domain sharing that segment (
foo./test[0-9]/.example.com) live in the same(regex, subtree)entry — the first as the subtree's own value, the second as a child of it.insert_recursive'spos == 0arm returnedInsertResult::Existingunconditionally, justified by acomment claiming the subtree was "already a value-bearing leaf (the create-path below built it via
TrieNode::new)". That premise is false when the entry was created by thepos > 0branch, whichbuilds a valueless
TrieNode::root().So inserting the deeper domain first made the leftmost-regex host permanently un-insertable: the
second insert answered
Existingand stored nothing.AddHttpFrontend, onadd_tree_rule's post-conditionadd_tree_rulereturnstrue,sozu query frontendslists it, and it never routesThe reverse insertion order works — which is the order #1330's own new test used, and why this stayed
invisible.
The fix — 9 lines
The arm now asks the slot, through a new private
insert_own_value: free answersOk, occupiedanswers
Existing.The empty-key arm is deliberately not reused. On the remove side it is a query; on the insert
side it is validation. Routing an insert through it would make every leading-dot hostname
insertable —
.example.com,..— and not only for routing:CertificateResolver::add_certificatevalidates TLS certificate names by dry-running the same trie, so a leading-dot certificate name
would be admitted too.
Three comments resting on the same false premise are corrected, and the no-dot arm's soundness is now
documented: it is safe only because the two
children.insertsites use disjoint key spaces, one keyedby a dotless segment and one by a key that always starts with
.. That undocumented accident isprecisely how the regex arm rotted.
The documentation, pinned by 14 tests
doc/configure.mdclaimed "Configuration order does not affect routing". It does. The rewrittensection states, each measured and each guarded by a test seen red under a production mutation:
PREFIX— longest match wins among rules whosemethodmatches the request; anequal-length tie goes to the last declared.
REGEX/EQUALS— the scan returns on the first match, so the first declared wins, andneither type outranks the other.
EQUALS/REGEXbeats a longerPREFIXin either order — but only carrying a methodthe request matches.
prefix spanning the whole request path displaces a regex.
path_type.case and stops
EQUALSmatching at all.Two facts recorded rather than fixed:
REGEXrules are unanchored. The manual said they were anchored\A...\zsince v2.0.0;that work was hostname-segment only, and
from_configis a bareRegex::new. Sobcmatches/abcd. Whether they should be anchored is docs/router: path REGEX rules are documented as anchored but are not #1350 — a behaviour change needing a decision.what does resolve it. That behaviour attaches an exact-host rule to a matching regex segment's leaf,
leaking it to every host the regex matches: router: an exact-hostname rule added after a matching regex segment attaches to the regex leaf and leaks to every host it matches #1351. Documenting the precedence would bless it.
Why this took seven review rounds
Every wrong draft was wrong in a dimension nothing tested — hostname regexes, then path regexes, then
a pre-existing precedence list carried forward, then method-less rules, then last-declared-wins, then
query strings. The tests could not catch the docs because they shared the docs' blind spot: the
helpers hard-coded one
methodvalue.methodis now a parameter with three named constants (GET,NO_METHOD,WRONG_METHOD) at everycall site, and the test file states which dimensions remain held constant, so the next claim that goes
wrong in one is at least findable.