Skip to content

feat(server): add a per-(cluster, source-subnet) connection limit - #1538

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
feat/subnet-connection-limit
Sep 25, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
feat/subnet-connection-limit

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Sep 25, 2026 •

Copy link
Copy Markdown
Collaborator

The bypass

The per-(cluster, source-IP) limiter has no concept of a subnet. Someone on an
IPv6 /64 — the standard residential allocation — bypasses it entirely by
taking a fresh address for every connection: the per-address counter never
reaches 2. Reported by @jpds in #1270 from reading the release notes and the
limiter code.

The shape: two independent limiters

Per @FlorentinDUBOIS in the issue:

I think we need both as the current rate limit is for handling rate limit by
ip as an api gateway, and the subnet aware will be there for ddos purposes.

So this adds a second, independent counter rather than changing the first.
cluster_ip_at_limit, track_cluster_ip, effective_max_connections_per_ip and
both per-IP maps are untouched — same fields, same semantics, same bodies. What
did change around them: the two call sites now go through a combined gate, and
untrack_all_cluster_ip also drains the subnet slots (it is the single release
point all three protocols already call on close, and a second entry point would
be one more thing each could forget). Both gates are consulted on every admission
and both must admit, which is what makes "10 per IP and 100 per /64"
expressible:

max_connections_per_ip     = 10     # existing, untouched
max_connections_per_subnet = 100    # new
subnet_ipv4_prefix         = 24
subnet_ipv6_prefix         = 56

The conjunction lives in exactly one place, SessionManager::cluster_connection_at_limit,
so the H1+H2 mux and raw TCP cannot drift on what "admitted" means.

The defaults leave current behaviour intact

max_connections_per_subnet defaults to 0 (disabled) and the prefixes default
to /32 and /128, which mask nothing. An upgrade is inert until an operator
opts in. /24 and /56 are documented recommendations, not defaults —
matching what the reporter did in the equivalent Caddy module (default left at
single IPs, those prefixes highly recommended in the docs). They are written up
in doc/configure.md and doc/rate-limit-design.md §7.1.1.

Stronger than inert: while the cap is 0 the subnet bookkeeping is not written
at all
, so a deployment that never enables the feature allocates nothing for it.
an_unset_subnet_cap_leaves_the_admission_path_untouched asserts both maps stay
empty. This is a deliberate divergence from the per-IP twin, which tracks
unconditionally — flagging it explicitly as the point where you may want to
decide otherwise. The cost is that enabling the cap at runtime does not
retroactively count sessions already in flight; the counter converges as they
close.

New configuration surface

Global TOML keys (command/src/config.rs):

Key Type Default
max_connections_per_subnet integer, 0 = unlimited 0
subnet_ipv4_prefix integer 0-32 32
subnet_ipv6_prefix integer 0-128 128

Plus a per-cluster max_connections_per_subnet override with the same
None inherits / Some(0) explicit-unlimited / Some(n) overrides semantics as
its per-IP twin. Out-of-range prefixes are rejected at config-load time
(ConfigError::InvalidSubnetPrefix), never silently clamped.

Additions to command.proto, named explicitly

Message / field Tag
Request.set_max_connections_per_subnet (uint64) 60
Request.query_max_connections_per_subnet 61
message QueryMaxConnectionsPerSubnet {} —
message MaxConnectionsPerSubnetLimit { limit, ipv4_prefix, ipv6_prefix } —
ResponseContent.max_connections_per_subnet_limit 18
Cluster.max_connections_per_subnet (optional uint64) 17
ServerConfig.max_connections_per_subnet 26
ServerConfig.subnet_ipv4_prefix 27
ServerConfig.subnet_ipv6_prefix 28

command/src/proto/command.rs is generated and was not edited.

CLI

New sozu subnet-connection-limit {set|remove|show}, mirroring
sozu connection-limit. show reports the two prefixes alongside the limit:
they are boot-time only, so that reply is the only runtime surface that can tell
an operator what the live cap is a cap on. Like its twin the setter is
non-sticky — workers reset to the TOML value on restart.

The prefixes have no runtime setter on purpose: the mask is part of the counter
key, so patching it live would re-key every counter in flight.

Masking

Ipv4Addr / Ipv6Addr have no standard masking method and no dependency was
added. Both shift-overflowing bounds are branched explicitly — u128::MAX << 128
panics under debug_assertions and wraps silently in release, so a full-width
prefix must never reach the shift; a zero prefix is branched from the other end.

IPv4-mapped IPv6 sources are canonicalised first. A dual-stack [::] listener
reports an IPv4 client as ::ffff:a.b.c.d; masking that with an IPv6 prefix would
collapse the entire IPv4 internet into one ::/56 bucket, so it is converted to
IPv4 and charged to subnet_ipv4_prefix. The per-IP counter is deliberately left
un-canonicalised — part of what keeps its behaviour untouched.

To SEE THIS RED

Delete the || self.cluster_subnet_at_limit(...) disjunct from
SessionManager::cluster_connection_at_limit in lib/src/server.rs, leaving
every other piece — config keys, proto fields, masking, tracking — in place:

cargo test -p sozu-lib --locked --no-default-features \
  --features crypto-ring,opentelemetry,splice,simd subnet
test ...::a_subnet_cap_refuses_a_fresh_address_from_an_already_counted_subnet ... FAILED
panicked at lib/src/protocol/mux/router.rs:
a fresh address from an already-counted /24 must be refused — an Admitted
verdict here is the #1270 bypass: a new address per connection defeats the cap

The test drives the real plan_connect → consult_ip_gate → plan_connect_resume
sequence for four distinct addresses in one /24, under a per-IP cap of 10 that
no single address comes near — so only the subnet counter can refuse the fourth.
A fifth address in a different /24 is asserted admitted, so the refusal is the
subnet key and not a blanket cap on new addresses.

Restoring the disjunct returns it to green; the cycle was run twice.

Tests added

  • a_subnet_cap_refuses_a_fresh_address_from_an_already_counted_subnet — the regression above.
  • an_unset_subnet_cap_leaves_the_admission_path_untouched — the default changes nothing, and allocates nothing.
  • a_cluster_override_dropping_to_zero_after_a_track_is_a_no_op — a cluster override can drop to Some(0) after a session was tracked under a positive limit (AddCluster is an upsert and clears no counters; only the global SetMaxConnectionsPerSubnet(0) drains). An earlier revision asserted that could not happen and panicked on it.
  • masking_handles_both_shift_overflowing_prefix_bounds — prefixes 0, full width, and over-wide.
  • masking_groups_addresses_at_the_recommended_prefixes — /24 and /56, including the issue's own /64-holder scenario.
  • an_ipv4_mapped_source_is_charged_to_the_ipv4_prefix — including the negative case where two mapped /24s must not collide.
  • subnet_connection_limit_keys_round_trip_from_toml and an_out_of_range_subnet_prefix_is_rejected_not_clamped — the config plumbing and its validation.

Known limitation

A subnet refusal currently surfaces as BackendConnectionError::TooManyConnectionsPerIp
and increments the shared connections.rejected_per_cluster_ip counter, so an
operator cannot tell the two caps apart in metrics. Kept shared to hold this
changeset to the feature; a distinct error variant and counter are a reasonable
follow-up.

Validation

All run locally at the tip of this branch, rebased onto main at 42ed1111
(after #1537 and #1540 landed); CI is the verdict.

The rebase over #1537 conflicted only on line citations, in doc/testing.md and
lib/src/protocol/mux/LIFECYCLE.md (13 hunks). Each was resolved by locating the
text the citation named at the merge base inside the merged tree, never by
arithmetic; the resulting diff on those two files is citations only — every
removed line has an identical added counterpart once the digits are stripped, so
none of #1537's prose was altered.

Command Result
cargo build --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd pass
cargo +nightly fmt --all -- --check pass
cargo clippy --all-targets --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd -- -D warnings pass
cargo test -p sozu-lib … 1147 passed, 0 failed
cargo test -p sozu … pass
cargo test -p sozu-command-lib --locked --no-default-features 171 passed, 0 failed
cargo test -p sozu-e2e … -- --skip tests::fuzz_tests:: 449 passed, 0 failed
RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked pass
RUSTFLAGS="--cfg tokio_unstable" cargo clippy -p sozu-sim --all-targets --locked -- -D warnings pass
check_doc_citations.py --self-test / --root . / --base / --audit --root . all pass
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked pass

Note on the two config tests — resolved since this PR was opened.
subnet_connection_limit_keys_round_trip_from_toml and
an_out_of_range_subnet_prefix_is_rejected_not_clamped live in
command/src/config.rs. When this PR was first pushed, CI ran cargo test for
sozu-lib, sozu, sozu-e2e and sozu-sim but never for
sozu-command-lib, and there was no workspace-wide cargo test anywhere — so
these two would have landed without ever running. That gap was reported as
#1539, and
#1540 landed the step that shut it;
it is now in main.
This branch is rebased on top of it, so CI does exercise both tests.

Docs updated in the same changeset: doc/configure.md, doc/rate-limit-design.md
(§3.1, §3.2, §3.3, §3.7, §3.8, §7.1.1), bin/config.toml, CHANGELOG.md. Line
citations displaced by the insertions were renumbered and each renumbered bound
verified against the text it named at the base.

On the renumbering, for check_doc_citations.py's own record. The first
automated pass produced three wrong ranges on lines whose text is ambiguous
(a bare }), two of them inverted. The checker caught two. The third —
lib/src/server.rs:1060-1068, which should have been 1056-1064 — passed
silently, because a citation this changeset re-anchored is exempt from the
base comparison and is never checked at all
(the run reports this honestly:
"39 re-anchored spans were exempt from the comparison"). It was only found by
auditing all 29 renumbered bounds content-against-content, resolving each one
through the text it named at the base. Another agent hit the same mechanism on
a different changeset today, so this is an independent confirmation that the
re-anchoring exemption is a real hole, not a theoretical one: the rule cannot
guard precisely the citations a changeset touches, which are the ones most
likely to be wrong.

Closes #1270

Signed-off-by: Florentin Dubois [email protected]

FlorentinDUBOIS added a commit that referenced this pull request Sep 25, 2026
## What was not running

`.github/workflows/ci.yml` tests exactly four packages — `-p sozu-lib`, `-p sozu`,
`-p sozu-e2e`, `-p sozu-sim` — and `simulation-sweep.yml` adds two more `-p sozu-sim`
invocations. There is no `cargo test --workspace` anywhere in the workflows, and
`sozu-command-lib` is named in none of them except a licence line in `release.yml`.

So `command/`'s **170 `#[test]` functions across 13 files** have never run in CI.

They pass. On `aaf2a6aa`:

```
$ cargo test -p sozu-command-lib --locked
test result: ok. 169 passed; 0 failed; 0 ignored   # unittests src/lib.rs
test result: ok. 4 passed; 0 failed; 0 ignored     # tests/state_compat_v1_1_1.rs
test result: ok. 2 passed; 0 failed; 3 ignored     # doctests
```

The 3 `ignored` are illustrative `proto` doc blocks, not skipped tests.

This was never a quarantine anyone chose — the package was simply never added, and
nothing reported its absence. A test that never runs is indistinguishable from a test
that always passes.

## It has been closed twice before, package by package

`ci.yml`'s own comments record both rounds:

> the rollback, response accounting and channel backpressure guarantees of
> sozu#1301/#1313/#1314 live there and **were never exercised by CI**

> They stay `#[ignore]`d so a contributor's `cargo test` stays fast, and this step is
> what runs them; **before it existed they never ran anywhere**

Each fix added the one package it was about. `sozu-command-lib` was in scope neither
time, so it survived both.

## What was unguarded

`command/` holds the configuration parser and validator, the protobuf request/response
types, `Channel`, the logging macros, and the state model that `sozu-lib` and `sozu` are
both built on. A regression in any of it reached CI only if some *other* package's test
happened to exercise it sideways.

It also holds **`command/tests/state_compat_v1_1_1.rs`**, which is not an internal unit
test at all: it pins the `SaveState` / `LoadState` JSON contract that `proxy-manager` and
other tools pinned to `sozu-command-lib = "1.1.1"` still write. Its own header describes
the failure it guards — a new `repeated`/`map` field without `#[serde(default)]` makes
`parse_several_requests` leave the payload unconsumed and `load_state` report
`"Error consuming load state message"`. That is a cross-project compatibility guarantee
that has been unenforced.

## The two decisions, measured rather than assumed

### Where: one cell, not the crypto matrix

`command/src/` contains **zero `cfg(feature)`**:

```
$ grep -rc 'cfg(feature' command/src/ --include='*.rs' | awk -F: '{s+=$2} END{print s}'
0
```

Its only features are `unstable`, `logs-debug` and `logs-trace`, all declared as empty
markers (`command/Cargo.toml`), and it has **no crypto-provider feature at all**. Nothing
in the package varies by matrix cell, so the four crypto cells would re-run one identical
result four times for a single verdict.

The step is therefore gated `if: matrix.cell == 'msrv-full'` — the guard `ci.yml` already
uses for its other workspace-wide steps (`Format check`, `Build documentation`). That cell
is non-experimental and pins the 1.93.1 MSRV, so the step also confirms `command/` builds
at the declared minimum. It reuses the cell's existing toolchain, cache and baked-in
`protoc`, so it adds no job, no runner and no new setup.

### Flags: none, because they are rejected

Not a judgement call — the flags do not apply:

```
$ cargo test -p sozu-command-lib --locked --no-default-features \
    --features crypto-ring,opentelemetry,splice,simd
error: the package 'sozu-command-lib' does not contain these features:
       crypto-ring, opentelemetry, simd, splice
help: packages with the missing features: sozu-lib, sozu, sozu-e2e
```

Passing `${{ matrix.flags }}` would fail the step outright on six of the nine cells. So the
command is `cargo test -p sozu-command-lib --locked --verbose`: `--locked` and `--verbose`
match the neighbouring test steps, so a dependency drift fails here exactly as it fails
there.

## Result

Green on the current tree — the step verified locally with the exact command it runs:

```
$ cargo test -p sozu-command-lib --locked --verbose
EXIT=0    169 + 4 + 2 passed, 0 failed
```

Had it been red, that failure would have been the point of the issue and is reported, not
skipped. It is not.

The changeset touches no Rust file, no manifest and no lockfile — `ci.yml` and
`CHANGELOG.md` only — so it cannot change what the other steps compile. The four
`check_doc_citations.py` rules (`--self-test`, `--root .`, `--base`, `--audit --root .`)
all pass.

## Note for review order

The `CHANGELOG.md` entry is appended at the **end** of the `### ✨ Added` section rather
than the top, deliberately: #1538 adds its entry at the top of the same section, and
keeping the two hunks ~240 lines apart lets both merge without a textual conflict. No
other file overlaps between the two branches.

Closes #1539

Signed-off-by: Florentin Dubois <[email protected]>
The per-(cluster, source-IP) limit has no concept of a subnet, and that
is a hole rather than a simplification. Someone on an IPv6 /64 — the
standard residential allocation — bypasses it entirely by taking a
fresh address for every connection: the per-address counter never
reaches 2.

Add a SECOND, independent counter rather than changing the first. The
two serve different cases and both need to be expressible at once: the
per-IP cap is the API-gateway case (one client, one address), the
per-subnet cap is the denial-of-service case (one actor, a routed
prefix). Both gates are consulted on every admission and both must
admit, so "10 per IP AND 100 per /64" is expressible.

The default changes nothing. max_connections_per_subnet defaults to 0
(disabled) and the prefixes default to /32 and /128, which mask
nothing, so an upgrade is inert until an operator opts in. /24 and /56
are documented recommendations, not defaults. While the cap is 0 the
subnet bookkeeping is not written at all, so a deployment that never
enables the feature allocates nothing for it.

New global TOML keys max_connections_per_subnet, subnet_ipv4_prefix and
subnet_ipv6_prefix, plus a per-cluster max_connections_per_subnet
override with the same None-inherits / Some(0)-unlimited / Some(n)
semantics as its per-IP twin. Out-of-range prefixes are rejected at
config-load time, never silently clamped.

New command.proto surface mirroring the per-IP verbs:
Request.set_max_connections_per_subnet (60),
Request.query_max_connections_per_subnet (61) with message
QueryMaxConnectionsPerSubnet, response MaxConnectionsPerSubnetLimit
(ResponseContent 18) carrying the limit and both prefixes,
Cluster.max_connections_per_subnet (17), and ServerConfig fields 26-28.
New CLI `sozu subnet-connection-limit {set|remove|show}`; show reports
the prefixes because they are boot-time only and would otherwise be
unreadable at runtime.

Enforced for HTTP/HTTPS and raw TCP through a single combined gate,
SessionManager::cluster_connection_at_limit, so the two protocols
cannot drift on what "admitted" means. Both counters are released from
the single existing teardown call.

Masking is written here: Ipv4Addr and Ipv6Addr have no standard masking
method, and the existing per_source_bucket masks at hard-coded /24 and
/48 by whole octets, which an arbitrary prefix cannot reuse. Both
shift-overflowing prefix bounds are branched explicitly, since
u128::MAX << 128 panics under debug_assertions and wraps silently in
release. An IPv4-mapped IPv6 source, what a dual-stack [::] listener
reports for an IPv4 client, is canonicalised to IPv4 and charged to
subnet_ipv4_prefix, so IPv4 clients are not all collapsed into one
::/56 bucket; the per-IP counter is deliberately left
un-canonicalised.

The disabled-limiter early return asserts nothing about what is already
recorded for the token: that is not an invariant. A cluster override can
drop to Some(0) after a session was tracked under a positive limit —
AddCluster is an upsert and clears no counters, and only the global
SetMaxConnectionsPerSubnet(0) drains the bookkeeping. The stale slot is
harmless and is released normally on close.

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the feat/subnet-connection-limit branch from 17d3a20 to fa325a6 Compare September 25, 2026 21:59
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 274268a into main Sep 25, 2026
28 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the feat/subnet-connection-limit branch September 25, 2026 23:23
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.

Per-IP rate-limiter needs subnet-level reasoning

1 participant