Repository navigation
feat(server): add a per-(cluster, source-subnet) connection limit - #1538
Merged
Merged
Conversation
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 25, 2026 20:02
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
force-pushed
the
feat/subnet-connection-limit
branch
from
September 25, 2026 21:59
17d3a20 to
fa325a6
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.
The bypass
The per-
(cluster, source-IP)limiter has no concept of a subnet. Someone on anIPv6
/64— the standard residential allocation — bypasses it entirely bytaking 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:
So this adds a second, independent counter rather than changing the first.
cluster_ip_at_limit,track_cluster_ip,effective_max_connections_per_ipandboth 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_ipalso drains the subnet slots (it is the single releasepoint 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:
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_subnetdefaults to0(disabled) and the prefixes defaultto
/32and/128, which mask nothing. An upgrade is inert until an operatoropts in.
/24and/56are 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.mdanddoc/rate-limit-design.md§7.1.1.Stronger than inert: while the cap is
0the subnet bookkeeping is not writtenat all, so a deployment that never enables the feature allocates nothing for it.
an_unset_subnet_cap_leaves_the_admission_path_untouchedasserts both maps stayempty. 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):max_connections_per_subnet0subnet_ipv4_prefix32subnet_ipv6_prefix128Plus a per-cluster
max_connections_per_subnetoverride with the sameNoneinherits /Some(0)explicit-unlimited /Some(n)overrides semantics asits per-IP twin. Out-of-range prefixes are rejected at config-load time
(
ConfigError::InvalidSubnetPrefix), never silently clamped.Additions to
command.proto, named explicitlyRequest.set_max_connections_per_subnet(uint64)Request.query_max_connections_per_subnetmessage QueryMaxConnectionsPerSubnet {}message MaxConnectionsPerSubnetLimit { limit, ipv4_prefix, ipv6_prefix }ResponseContent.max_connections_per_subnet_limitCluster.max_connections_per_subnet(optional uint64)ServerConfig.max_connections_per_subnetServerConfig.subnet_ipv4_prefixServerConfig.subnet_ipv6_prefixcommand/src/proto/command.rsis generated and was not edited.CLI
New
sozu subnet-connection-limit {set|remove|show}, mirroringsozu connection-limit.showreports 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/Ipv6Addrhave no standard masking method and no dependency wasadded. Both shift-overflowing bounds are branched explicitly —
u128::MAX << 128panics under
debug_assertionsand wraps silently in release, so a full-widthprefix must never reach the shift; a zero prefix is branched from the other end.
IPv4-mapped IPv6 sources are canonicalised first. A dual-stack
[::]listenerreports an IPv4 client as
::ffff:a.b.c.d; masking that with an IPv6 prefix wouldcollapse the entire IPv4 internet into one
::/56bucket, so it is converted toIPv4 and charged to
subnet_ipv4_prefix. The per-IP counter is deliberately leftun-canonicalised — part of what keeps its behaviour untouched.
To SEE THIS RED
Delete the
|| self.cluster_subnet_at_limit(...)disjunct fromSessionManager::cluster_connection_at_limitinlib/src/server.rs, leavingevery other piece — config keys, proto fields, masking, tracking — in place:
The test drives the real
plan_connect→consult_ip_gate→plan_connect_resumesequence for four distinct addresses in one
/24, under a per-IP cap of 10 thatno single address comes near — so only the subnet counter can refuse the fourth.
A fifth address in a different
/24is asserted admitted, so the refusal is thesubnet 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 toSome(0)after a session was tracked under a positive limit (AddClusteris an upsert and clears no counters; only the globalSetMaxConnectionsPerSubnet(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_tomlandan_out_of_range_subnet_prefix_is_rejected_not_clamped— the config plumbing and its validation.Known limitation
A subnet refusal currently surfaces as
BackendConnectionError::TooManyConnectionsPerIpand increments the shared
connections.rejected_per_cluster_ipcounter, so anoperator 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
mainat42ed1111(after #1537 and #1540 landed); CI is the verdict.
The rebase over #1537 conflicted only on line citations, in
doc/testing.mdandlib/src/protocol/mux/LIFECYCLE.md(13 hunks). Each was resolved by locating thetext 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.
cargo build --locked --no-default-features --features crypto-ring,opentelemetry,splice,simdcargo +nightly fmt --all -- --checkcargo clippy --all-targets --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd -- -D warningscargo test -p sozu-lib …cargo test -p sozu …cargo test -p sozu-command-lib --locked --no-default-featurescargo test -p sozu-e2e … -- --skip tests::fuzz_tests::RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --lockedRUSTFLAGS="--cfg tokio_unstable" cargo clippy -p sozu-sim --all-targets --locked -- -D warningscheck_doc_citations.py --self-test / --root . / --base / --audit --root .RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --lockedDocs 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. Linecitations displaced by the insertions were renumbered and each renumbered bound
verified against the text it named at the base.
Closes #1270
Signed-off-by: Florentin Dubois [email protected]