Repository navigation
fix(router): anchor path REGEX rules, as the manual has always said - #1357
Merged
Merged
Conversation
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 #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]>
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 19, 2026 10:33
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 20, 2026
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`.
Five sites 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 four segment-insert wrappers
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.
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
added a commit
that referenced
this pull request
Sep 20, 2026
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]>
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 #1350.
doc/configure.mdhas stated since v2.0.0 thatREGEXrules are anchored at both ends (\A...\z). That was true of hostname segments and false of path rules:PathRule::from_configcompiled the operator's value with a bareRegex::new, andregex::bytes::Regex::is_matchis a substring search. A rule written/adminmatched/foo/admin/bar.#1350 offered two ways out — correct the manual, or anchor the code. This anchors the code: 2.x is not yet broadly in production, path regexes are not an exposed feature, and the documented behaviour is the one operators expect, so a minor break now is cheaper than a permanently false documented guarantee.
BREAKING — read this before upgrading
Two rule shapes change, and they change in opposite directions.
bc(substring)/abcdbc.*bc.*/api(prefix-shaped)/api/v1/api/api.*, orpath_type = "PREFIX"\.js$(suffix-shaped)/static/app.js.*\.js$The third row is the one that breaks silently, and a trailing
.*does not fix it. Extension routing is open at the start, so it needs a leading.*. Measured:\.js$no longer matches/static/app.js, and\.js.*does not rescue it —.*\.js$does. An end-anchored pattern with nothing before it can only match a path that is its own suffix, and an origin-form request-target always begins with/.This narrows
Route::Deny, which is the dangerous edge. A frontend with nocluster_idand one carryingredirect = "unauthorized"both answer 401 through this samePathRulematching. AREGEXdeny of/adminstill denies/admin, but no longer denies/admin/secretor/administrator— those fall through to whatever else matches. Audit deny-shapedREGEXfrontends before upgrading and widen the ones meant as a subtree (/admin.*).Anchoring also makes
REGEXinherit the query-string behaviourEQUALSalready had, since the matched path is the request-target:/abcno longer matchesGET /abc?x=1.Two details that are load-bearing, not cosmetic
The group is non-capturing on purpose.
|binds looser than concatenation, so an ungrouped\A/a|/b\zparses as(\A/a)|(/b\z)and leaves each branch anchored at one end only. With three or more branches the middle ones are anchored at neither end and match as plain substrings. And it is(?:)rather than()because$PATH[n]indices come fromcaps.iter().skip(1)with the buffer sized bycaptures_len()— a capturing wrapper would shift every operator's rewrite index by one.The value is compiled before it is wrapped, because the wrapper supplies one
(and one)and can therefore balance an unbalanced pattern:a)(bis rejected byRegex::new, yet\A(?:a)(b)\zcompiles and matchesab. Without that first compile, anchoring would promote a typo the router rejects today into a live rule matching something the operator never wrote.The reverse direction is real and is not claimed to be closed: a pattern that compiles bare can be rejected once wrapped, because the appended
)\zhas to survive whatever the pattern left open. Measured,(?x)/api/v1 # v1 onlyfails wrapped withunclosed group(the)lands inside the#comment), and a 249-deep nest exceeds the 250 limit. Both surface asRouterError::InvalidPathRuleat registration, and the main process validates through the sameRouter::add_http_front, so the cost is a loudly rejected frontend, never a silent mis-route.Tests
a_path_regex_is_unanchored_and_matches_anywhere_in_the_request_path, added by #1352 to pin the old behaviour so that anchoring it later would be "a deliberate change, not a silent one", is red under this change. It is inverted and renamed rather than deleted, cites its predecessor by name, and itsTo SEE THIS RED:block is rewritten for the new mutation. It did its job.Every behavioural claim the documentation above makes is asserted by a test — including the "used to match" column, which describes 2.2.1 behaviour and is pinned against the bare unwrapped regex. 16 new tests; each was seen red under a named mutation before it was allowed to pass, verified by running all six mutations and checking that every new test fails under the one its own comment names, and that no pre-existing test moves under any of them.
Two are worth naming:
\A({value})\za$PATH[1]rewrite yields/api/v2/userswhere it must yieldv2. The three legs —captures_len()parity, the end-to-end rewrite, and the out-of-range$PATH[2]still being refused — were each confirmed load-bearing by deleting the others and re-running.\A/a|/b|/c\zmatcheszzz/bzzz,/xx/b/yyandxx/byy.Nothing was weakened to reach green: no deleted test, no ignored test, no loosened assertion, no lint escape.