Skip to content

fix(router): let a leftmost-regex host be inserted after a deeper sibling - #1352

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
fix/trie-regex-segment-insert
Sep 19, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
fix/trie-regex-segment-insert

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

A 9-line production fix, and a documentation section that turned out to be wrong in six separate
dimensions. Completes #1330, which fixed remove_recursive and 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 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 (the create-path below built it via
TrieNode::new)". That premise is false when the entry was created by the pos > 0 branch, which
builds a valueless TrieNode::root().

So inserting the deeper domain first made the leftmost-regex host permanently un-insertable: the
second insert answered Existing and stored nothing.

build observable
debug worker panics from a control-plane AddHttpFrontend, on add_tree_rule's post-condition
release add_tree_rule returns true, sozu query frontends lists it, and it never routes

The 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 answers Ok, occupied
answers 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_certificate
validates 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.insert sites use disjoint key spaces, one keyed
by a dotless segment and one by a key that always starts with .. That undocumented accident is
precisely how the regex arm rotted.

The documentation, pinned by 14 tests

doc/configure.md claimed "Configuration order does not affect routing". It does. The rewritten
section states, each measured and each guarded by a test seen red under a production mutation:

  • PREFIX — longest match wins among rules whose method matches the request; an
    equal-length tie goes to the last declared.
  • REGEX / EQUALS — the scan returns on the first match, so the first declared wins, and
    neither type outranks the other.
  • a matching EQUALS/REGEX beats a longer PREFIX in either order — but only carrying 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.

Two facts recorded rather than fixed:

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 method value.

method is now a parameter with three named constants (GET, NO_METHOD, WRONG_METHOD) at every
call site, and the test file states which dimensions remain held constant, so the next claim that goes
wrong in one is at least findable.

cargo +nightly fmt --all -- --check                                              exit 0
cargo +1.93.1 clippy --workspace --all-targets --all-features --locked -D warn   exit 0
cargo +1.93.1 test -p sozu-lib --locked --all-features      843 passed, 0 failed

…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
FlorentinDUBOIS merged commit f74f56c into main Sep 19, 2026
23 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the fix/trie-regex-segment-insert branch September 19, 2026 07:02
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]>
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.

1 participant