Repository navigation
feat: add per-cluster per-IP connection limiting - #1193
Merged
Merged
Conversation
llenotre
approved these changes
Mar 11, 2026
FlorentinDUBOIS
added a commit
that referenced
this pull request
Apr 29, 2026
…TP 429 + graceful TCP close Caps the number of simultaneous frontend connections one source IP may hold against a given cluster. Replaces the simpler per-source-IP variant the previous PR #1193 commits proposed (those did not survive the H2 mux unification). Closes #890, #1057. Wire shape (proto): - ServerConfig.max_connections_per_ip = 22 [optional, default 0] - ServerConfig.retry_after = 23 [optional, default 60] - Cluster.max_connections_per_ip = 13 [optional, override] - Cluster.retry_after = 14 [optional, override] - CustomHttpAnswers.answer_429 = 12 [optional, custom 429 template] - Request.set_max_connections_per_ip = 50 (uint64) - Request.query_max_connections_per_ip = 51 (QueryMaxConnectionsPerIp {}) - ResponseContent.max_connections_per_ip_limit = 14 (MaxConnectionsPerIpLimit { limit: u64 }) Override semantics: cluster `None` inherits the global default, `Some(0)` is explicit "unlimited for this cluster", `Some(n > 0)` overrides. Source IP is the parsed PROXY-protocol source when present, else `peer_addr`. Enforcement: - HTTP/HTTPS via the unified mux at protocol/mux/router.rs::connect: after cluster resolution, before backend selection. The check fires AFTER auth/redirect/SNI decisions so a 401/421/redirect frontend never trips the limit. On hit: stash the resolved Retry-After on the stream context and return BackendConnectionError::TooManyConnectionsPerIp, which the mux converts into a 429 default answer through the new set_default_answer_with_retry_after path. Covers H1 and H2 — the unified mux serves both protocols. - H2 multiplex semantics: SessionManager keeps a per-token HashSet<(cluster, ip)>. Multiple streams to the same (cluster, ip) from the same H2 connection share one slot — the limit governs distinct frontend connections, not requests. Decrement is wholesale on session close (untrack_all_cluster_ip). - TCP at tcp.rs::connect_to_backend: rejection produces a graceful FIN via SessionResult::Close (no SO_LINGER trick). Answer engine (lib/src/protocol/kawa_h1/answers.rs + lib/src/protocol/mux/answers.rs): - Answer429 variant on DefaultAnswer with retry_after: Option<u32>. - 429 template registered alongside 421/503/etc. - New %RETRY_AFTER variable with `or_elide_header = true`: when the resolved value is 0/None, the engine drops the entire `Retry-After:` line. `Retry-After: 0` would invite an immediate retry that defeats the limit, so we omit instead of rendering literal 0. - legacy_to_map flattens CustomHttpAnswers.answer_429 into the per-listener answers map. - default_answer_for_code(429, ...) builds the variant. - set_default_answer_with_retry_after threads the resolved retry value through to the rendered answer. Proxy-protocol fixes (lib/src/protocol/proxy_protocol/{expect,relay}.rs): - ExpectProxyProtocol::into_pipe and RelayProxyProtocol::into_pipe now use ProxyAddr::source() from the parsed v2 header instead of the raw TCP peer_addr. Without this fix the pipe phase records the upstream PROXY-emitter (an LB / edge proxy / health-check probe), not the originating client — which means the per-(cluster, source-IP) limit would have keyed on the LB's IP. Relay mode previously discarded the parsed addresses entirely; we now stash them on the struct. SessionManager (lib/src/server.rs): - max_connections_per_ip: u64 + retry_after: u32 fields. - connections_per_cluster_ip: HashMap<(String, IpAddr), usize> + cluster_ip_tracks: HashMap<Token, HashSet<(String, IpAddr)>>. - cluster_ip_at_limit (token-aware: a token already holding a slot is never at the limit), track_cluster_ip (idempotent within a token), untrack_all_cluster_ip (drains on session close), effective_max_connections_per_ip / effective_retry_after (override resolution), clear_cluster_ip_tracking (runtime disable). - HttpProxy / HttpsProxy / TcpSession close paths drain via untrack_all_cluster_ip on the frontend token before the slab slot is reused. ProxySession trait (lib/src/lib.rs): - New cluster_id() and session_address() default-implemented as None. - New L7Proxy::sessions() so the mux router can reach the SessionManager from a Rc<RefCell<dyn L7Proxy>>. - New BackendConnectionError::TooManyConnectionsPerIp variant with cluster_id payload. CLI (bin/src/{cli,ctl/mod,ctl/request_builder}.rs): - `sozu connection-limit set <N>` / `remove` / `show` patches the global limit at runtime. The setter is non-sticky (workers reset to the TOML-configured value on restart); operators must mirror the change in the config to make it durable. - `--answer-429 <path>` flag added to `sozu listener {http,https} update`. - New build_http_answers helper threads answer_429 through the existing CustomHttpAnswers builder. Config (command/src/config.rs): - DEFAULT_MAX_CONNECTIONS_PER_IP = 0 (disabled), DEFAULT_RETRY_AFTER = 60. - FileConfig + Config + ServerConfig From conversion threaded. - FileClusterConfig + HttpClusterConfig + TcpClusterConfig + ListenerBuilder + CustomHttpAnswers gain the new fields. Metric: connections.rejected_per_cluster_ip (counter, labelled by cluster_id, backend_id always empty — rejection happens before backend selection). Replaces the simpler `connections.rejected_per_ip` from the older PR #1193 commits — single name covers H1, H2, TCP. Tests: - e2e/src/tests/cluster_ip_limit_tests.rs covers H1 global limit (429 + Retry-After), H1 Retry-After: 0 elides the header, H1 per-cluster override (unlimited cluster coexists with capped), TCP graceful close on limit. All four pass `cargo test -p sozu-e2e cluster_ip_limit`. Validation: - cargo build --all-features --locked - cargo +nightly fmt --all -- --check - cargo clippy --all-features --all-targets --locked -- -D warnings - cargo test --workspace --locked Docs: bin/config.toml, doc/configure.md (parameters + metric), CHANGELOG.md. Co-authored implementation guidance from Codex on the H2 multiplex semantics, Retry-After: 0 elision, PROXY-protocol Relay-mode address stashing, and rolling-upgrade safety (optional proto fields, not required). Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
force-pushed
the
feat/per-ip-rate-limit
branch
from
April 29, 2026 07:46
ffa0e1c to
0e8e0cd
Compare
FlorentinDUBOIS
added a commit
that referenced
this pull request
Apr 29, 2026
…TP 429 + graceful TCP close Caps the number of simultaneous frontend connections one source IP may hold against a given cluster. Replaces the simpler per-source-IP variant the previous PR #1193 commits proposed (those did not survive the H2 mux unification). Closes #890, #1057. Wire shape (proto): - ServerConfig.max_connections_per_ip = 22 [optional, default 0] - ServerConfig.retry_after = 23 [optional, default 60] - Cluster.max_connections_per_ip = 13 [optional, override] - Cluster.retry_after = 14 [optional, override] - CustomHttpAnswers.answer_429 = 12 [optional, custom 429 template] - Request.set_max_connections_per_ip = 50 (uint64) - Request.query_max_connections_per_ip = 51 (QueryMaxConnectionsPerIp {}) - ResponseContent.max_connections_per_ip_limit = 14 (MaxConnectionsPerIpLimit { limit: u64 }) Override semantics: cluster `None` inherits the global default, `Some(0)` is explicit "unlimited for this cluster", `Some(n > 0)` overrides. Source IP is the parsed PROXY-protocol source when present, else `peer_addr`. Enforcement: - HTTP/HTTPS via the unified mux at protocol/mux/router.rs::connect: after cluster resolution, before backend selection. The check fires AFTER auth/redirect/SNI decisions so a 401/421/redirect frontend never trips the limit. On hit: stash the resolved Retry-After on the stream context and return BackendConnectionError::TooManyConnectionsPerIp, which the mux converts into a 429 default answer through the new set_default_answer_with_retry_after path. Covers H1 and H2 — the unified mux serves both protocols. - H2 multiplex semantics: SessionManager keeps a per-token HashSet<(cluster, ip)>. Multiple streams to the same (cluster, ip) from the same H2 connection share one slot — the limit governs distinct frontend connections, not requests. Decrement is wholesale on session close (untrack_all_cluster_ip). - TCP at tcp.rs::connect_to_backend: rejection produces a graceful FIN via SessionResult::Close (no SO_LINGER trick). Answer engine (lib/src/protocol/kawa_h1/answers.rs + lib/src/protocol/mux/answers.rs): - Answer429 variant on DefaultAnswer with retry_after: Option<u32>. - 429 template registered alongside 421/503/etc. - New %RETRY_AFTER variable with `or_elide_header = true`: when the resolved value is 0/None, the engine drops the entire `Retry-After:` line. `Retry-After: 0` would invite an immediate retry that defeats the limit, so we omit instead of rendering literal 0. - legacy_to_map flattens CustomHttpAnswers.answer_429 into the per-listener answers map. - default_answer_for_code(429, ...) builds the variant. - set_default_answer_with_retry_after threads the resolved retry value through to the rendered answer. Proxy-protocol fixes (lib/src/protocol/proxy_protocol/{expect,relay}.rs): - ExpectProxyProtocol::into_pipe and RelayProxyProtocol::into_pipe now use ProxyAddr::source() from the parsed v2 header instead of the raw TCP peer_addr. Without this fix the pipe phase records the upstream PROXY-emitter (an LB / edge proxy / health-check probe), not the originating client — which means the per-(cluster, source-IP) limit would have keyed on the LB's IP. Relay mode previously discarded the parsed addresses entirely; we now stash them on the struct. SessionManager (lib/src/server.rs): - max_connections_per_ip: u64 + retry_after: u32 fields. - connections_per_cluster_ip: HashMap<(String, IpAddr), usize> + cluster_ip_tracks: HashMap<Token, HashSet<(String, IpAddr)>>. - cluster_ip_at_limit (token-aware: a token already holding a slot is never at the limit), track_cluster_ip (idempotent within a token), untrack_all_cluster_ip (drains on session close), effective_max_connections_per_ip / effective_retry_after (override resolution), clear_cluster_ip_tracking (runtime disable). - HttpProxy / HttpsProxy / TcpSession close paths drain via untrack_all_cluster_ip on the frontend token before the slab slot is reused. ProxySession trait (lib/src/lib.rs): - New cluster_id() and session_address() default-implemented as None. - New L7Proxy::sessions() so the mux router can reach the SessionManager from a Rc<RefCell<dyn L7Proxy>>. - New BackendConnectionError::TooManyConnectionsPerIp variant with cluster_id payload. CLI (bin/src/{cli,ctl/mod,ctl/request_builder}.rs): - `sozu connection-limit set <N>` / `remove` / `show` patches the global limit at runtime. The setter is non-sticky (workers reset to the TOML-configured value on restart); operators must mirror the change in the config to make it durable. - `--answer-429 <path>` flag added to `sozu listener {http,https} update`. - New build_http_answers helper threads answer_429 through the existing CustomHttpAnswers builder. Config (command/src/config.rs): - DEFAULT_MAX_CONNECTIONS_PER_IP = 0 (disabled), DEFAULT_RETRY_AFTER = 60. - FileConfig + Config + ServerConfig From conversion threaded. - FileClusterConfig + HttpClusterConfig + TcpClusterConfig + ListenerBuilder + CustomHttpAnswers gain the new fields. Metric: connections.rejected_per_cluster_ip (counter, labelled by cluster_id, backend_id always empty — rejection happens before backend selection). Replaces the simpler `connections.rejected_per_ip` from the older PR #1193 commits — single name covers H1, H2, TCP. Tests: - e2e/src/tests/cluster_ip_limit_tests.rs covers H1 global limit (429 + Retry-After), H1 Retry-After: 0 elides the header, H1 per-cluster override (unlimited cluster coexists with capped), TCP graceful close on limit. All four pass `cargo test -p sozu-e2e cluster_ip_limit`. Validation: - cargo build --all-features --locked - cargo +nightly fmt --all -- --check - cargo clippy --all-features --all-targets --locked -- -D warnings - cargo test --workspace --locked Docs: bin/config.toml, doc/configure.md (parameters + metric), CHANGELOG.md. Co-authored implementation guidance from Codex on the H2 multiplex semantics, Retry-After: 0 elision, PROXY-protocol Relay-mode address stashing, and rolling-upgrade safety (optional proto fields, not required). Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
force-pushed
the
feat/per-ip-rate-limit
branch
from
April 29, 2026 07:51
0e8e0cd to
1d96722
Compare
…TP 429 + graceful TCP close Caps the number of simultaneous frontend connections one source IP may hold against a given cluster. Replaces the simpler per-source-IP variant the previous PR #1193 commits proposed (those did not survive the H2 mux unification). Closes #890, #1057. Wire shape (proto): - ServerConfig.max_connections_per_ip = 22 [optional, default 0] - ServerConfig.retry_after = 23 [optional, default 60] - Cluster.max_connections_per_ip = 13 [optional, override] - Cluster.retry_after = 14 [optional, override] - CustomHttpAnswers.answer_429 = 12 [optional, custom 429 template] - Request.set_max_connections_per_ip = 50 (uint64) - Request.query_max_connections_per_ip = 51 (QueryMaxConnectionsPerIp {}) - ResponseContent.max_connections_per_ip_limit = 14 (MaxConnectionsPerIpLimit { limit: u64 }) Override semantics: cluster `None` inherits the global default, `Some(0)` is explicit "unlimited for this cluster", `Some(n > 0)` overrides. Source IP is the parsed PROXY-protocol source when present, else `peer_addr`. Enforcement: - HTTP/HTTPS via the unified mux at protocol/mux/router.rs::connect: after cluster resolution, before backend selection. The check fires AFTER auth/redirect/SNI decisions so a 401/421/redirect frontend never trips the limit. On hit: stash the resolved Retry-After on the stream context and return BackendConnectionError::TooManyConnectionsPerIp, which the mux converts into a 429 default answer through the new set_default_answer_with_retry_after path. Covers H1 and H2 — the unified mux serves both protocols. - H2 multiplex semantics: SessionManager keeps a per-token HashSet<(cluster, ip)>. Multiple streams to the same (cluster, ip) from the same H2 connection share one slot — the limit governs distinct frontend connections, not requests. Decrement is wholesale on session close (untrack_all_cluster_ip). - TCP at tcp.rs::connect_to_backend: rejection produces a graceful FIN via SessionResult::Close (no SO_LINGER trick). Answer engine (lib/src/protocol/kawa_h1/answers.rs + lib/src/protocol/mux/answers.rs): - Answer429 variant on DefaultAnswer with retry_after: Option<u32>. - 429 template registered alongside 421/503/etc. - New %RETRY_AFTER variable with `or_elide_header = true`: when the resolved value is 0/None, the engine drops the entire `Retry-After:` line. `Retry-After: 0` would invite an immediate retry that defeats the limit, so we omit instead of rendering literal 0. - legacy_to_map flattens CustomHttpAnswers.answer_429 into the per-listener answers map. - default_answer_for_code(429, ...) builds the variant. - set_default_answer_with_retry_after threads the resolved retry value through to the rendered answer. Proxy-protocol fixes (lib/src/protocol/proxy_protocol/{expect,relay}.rs): - ExpectProxyProtocol::into_pipe and RelayProxyProtocol::into_pipe now use ProxyAddr::source() from the parsed v2 header instead of the raw TCP peer_addr. Without this fix the pipe phase records the upstream PROXY-emitter (an LB / edge proxy / health-check probe), not the originating client — which means the per-(cluster, source-IP) limit would have keyed on the LB's IP. Relay mode previously discarded the parsed addresses entirely; we now stash them on the struct. SessionManager (lib/src/server.rs): - max_connections_per_ip: u64 + retry_after: u32 fields. - connections_per_cluster_ip: HashMap<(String, IpAddr), usize> + cluster_ip_tracks: HashMap<Token, HashSet<(String, IpAddr)>>. - cluster_ip_at_limit (token-aware: a token already holding a slot is never at the limit), track_cluster_ip (idempotent within a token), untrack_all_cluster_ip (drains on session close), effective_max_connections_per_ip / effective_retry_after (override resolution), clear_cluster_ip_tracking (runtime disable). - HttpProxy / HttpsProxy / TcpSession close paths drain via untrack_all_cluster_ip on the frontend token before the slab slot is reused. ProxySession trait (lib/src/lib.rs): - New cluster_id() and session_address() default-implemented as None. - New L7Proxy::sessions() so the mux router can reach the SessionManager from a Rc<RefCell<dyn L7Proxy>>. - New BackendConnectionError::TooManyConnectionsPerIp variant with cluster_id payload. CLI (bin/src/{cli,ctl/mod,ctl/request_builder}.rs): - `sozu connection-limit set <N>` / `remove` / `show` patches the global limit at runtime. The setter is non-sticky (workers reset to the TOML-configured value on restart); operators must mirror the change in the config to make it durable. - `--answer-429 <path>` flag added to `sozu listener {http,https} update`. - New build_http_answers helper threads answer_429 through the existing CustomHttpAnswers builder. Config (command/src/config.rs): - DEFAULT_MAX_CONNECTIONS_PER_IP = 0 (disabled), DEFAULT_RETRY_AFTER = 60. - FileConfig + Config + ServerConfig From conversion threaded. - FileClusterConfig + HttpClusterConfig + TcpClusterConfig + ListenerBuilder + CustomHttpAnswers gain the new fields. Metric: connections.rejected_per_cluster_ip (counter, labelled by cluster_id, backend_id always empty — rejection happens before backend selection). Replaces the simpler `connections.rejected_per_ip` from the older PR #1193 commits — single name covers H1, H2, TCP. Tests: - e2e/src/tests/cluster_ip_limit_tests.rs covers H1 global limit (429 + Retry-After), H1 Retry-After: 0 elides the header, H1 per-cluster override (unlimited cluster coexists with capped), TCP graceful close on limit. All four pass `cargo test -p sozu-e2e cluster_ip_limit`. Validation: - cargo build --all-features --locked - cargo +nightly fmt --all -- --check - cargo clippy --all-features --all-targets --locked -- -D warnings - cargo test --workspace --locked Docs: bin/config.toml, doc/configure.md (parameters + metric), CHANGELOG.md. Co-authored implementation guidance from Codex on the H2 multiplex semantics, Retry-After: 0 elision, PROXY-protocol Relay-mode address stashing, and rolling-upgrade safety (optional proto fields, not required). Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
force-pushed
the
feat/per-ip-rate-limit
branch
from
April 29, 2026 09:10
1d96722 to
d481c19
Compare
FlorentinDUBOIS
added a commit
that referenced
this pull request
May 2, 2026
The CHANGELOG previously carried three concurrent Unreleased blocks — `## [Unreleased]` (main-scoped post-1.1.1 fixes from PRs #1162, #1191, #1192, #1193, #1194, #1196, #1202, #1223), `## feat/answer-templates-rewrite-auth - Unreleased` (answer templates, URL rewrite, basic auth), and `## feat/h2-mux - Unreleased` (the H2 multiplexer rewrite from PR #1209). All three feature stacks are on `main`; the per-branch dividers were release- engineering staging that no longer reflects current state. Changes: - Drop the `## feat/answer-templates-rewrite-auth - Unreleased` and `## feat/h2-mux - Unreleased` dividers; their bodies now appear under `## [Unreleased]` with provenance markers (`### Added — Answer templates / ...`, `### Added — H2 multiplexer (PR #1209)`). - Promote the breaking changes (proto-tag renumbers, dashboard metric renames, `http.errors` labelling, pattern-trie regex anchoring, empty-val del-header semantic, sub-16393 `buffer_size` rejection, cipher-list constant rename) to a top-level `### Breaking changes (v1.1.x → v2.0.0)` paragraph at the top of the section so operators see them first. - Drop emoji from top-level subheaders (🌟 → Added, 🔄 → Changed, ⛑️ → Fixed, ✍️ → Changed, 📚 → Documentation, 🤖 → CI,⚠️ → Behaviour-affecting). Per- commit-log subsection at depth ≥ 4 keeps minor emoji ornaments where they don't conflict with Keep-a-Changelog vocabulary. - Preserve historical release entries (`## 1.1.1`, `## 1.1.0`, …) verbatim; they are released and immutable. Net effect: a single `## [Unreleased]` block ready for the v2.0.0 release-cut in §3.4.c of `tasks/todo.md`. Future passes can de-duplicate the multiple `### Added`/`### Changed`/`### Fixed` sub-blocks into one each per Keep-a-Changelog strict shape; this commit is the structural collapse only. Refs: tasks/todo.md §3.1.a; codex M12 amendment (3-way not 2-way collapse). Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
May 2, 2026
…ite rate-limit design doc Two related changes folded into a single follow-up to Wave 2: 1. **Matrix coverage for 302 / 308 redirects** PR #1009's e2e tests so far only exercised the H1 frontend path (`try_redirect_found_h1_emits_302` + `try_redirect_permanent_redirect_h1_emits_308` in `redirect_rewrite_auth_tests.rs`). The H2 frontend cells, plus the h2c-backend cells, were not covered — even though the `protocol_pair_matrix` harness already exists for exactly this purpose. `e2e/src/tests/protocol_pair_matrix.rs` now ships: - `try_redirect_cell_inner(...)` — generalised redirect cell that takes `policy: RedirectPolicy` + `expected_status: u16`. Reuses the same listener / cluster / unbound-backend setup as the 301 cell. - `try_redirect_permanent_cell` (301), `try_redirect_found_cell` (302), `try_redirect_permanent_redirect_cell` (308) — thin wrappers each invoking the generalised cell with their respective policy + status. - Three `protocol_pair_matrix!` invocations, one per status, each emitting four `pub fn try_*_h{1,2}_h{1,2c}` wrappers and four `#[test] fn test_*` harnesses. Net: 4 cells × 3 statuses = 12 redirect tests pass in parallel (`cargo test -p sozu-e2e protocol_pair_matrix::test_redirect_`). 2. **Rate-limit design doc rewrite** `doc/rate-limit-design.md` previously described an unimplemented two-layer mechanism (token-bucket request-rate at L7 + per-IP TCP cap at L4). The actual mechanism that landed in PR #1193 (closing #890 + #1057) is a **single layer** — per-(cluster, source-IP) concurrent connection cap with a 429 response. The doc listed types like `RateLimitRule`, `trust_forwarded_for`, `rate_limit_check`, `max_connections_per_source_ip`, `nb_connections_per_source_ip` that do not exist in the codebase. Rewritten to describe what's on main: - `max_connections_per_ip: Option<u64>` global default + per-cluster override on `Cluster.max_connections_per_ip`. - Counter discipline at SessionManager (per-token set of `(cluster, ip)` pairs) — H2 multiplexing notes inline. - Enforcement points (`mux/router.rs` for HTTP/HTTPS, `tcp.rs` for TCP). - Reject behaviour (`Answer429` variant, `Retry-After` elision when `0`, `connections.rejected_per_cluster_ip` counter, custom template via `CustomHttpAnswers.answer_429`). - Source IP selection (PROXY-v2 → peer_addr fallback; both `ExpectHeader` and `RelayHeader` modes are address-aware). - CLI / runtime API surface (`sozu connection-limit set/show/remove`). - Test coverage pointer to `e2e/src/tests/cluster_ip_limit_tests.rs`. - Future work (token-bucket request-rate, cross-worker sync, adaptive quotas, ban-list integration, pre-TLS TCP-level cap) each captured as deferred. - Operator guidance (global default rule of thumb, per-cluster overrides, NAT / shared-egress notes, behind-another-LB notes). Signed-off-by: Florentin Dubois <[email protected]>
8 of 9 tasks
FlorentinDUBOIS
added a commit
that referenced
this pull request
May 2, 2026
…ite rate-limit design doc Two related changes folded into a single follow-up to Wave 2: 1. **Matrix coverage for 302 / 308 redirects** PR #1009's e2e tests so far only exercised the H1 frontend path (`try_redirect_found_h1_emits_302` + `try_redirect_permanent_redirect_h1_emits_308` in `redirect_rewrite_auth_tests.rs`). The H2 frontend cells, plus the h2c-backend cells, were not covered — even though the `protocol_pair_matrix` harness already exists for exactly this purpose. `e2e/src/tests/protocol_pair_matrix.rs` now ships: - `try_redirect_cell_inner(...)` — generalised redirect cell that takes `policy: RedirectPolicy` + `expected_status: u16`. Reuses the same listener / cluster / unbound-backend setup as the 301 cell. - `try_redirect_permanent_cell` (301), `try_redirect_found_cell` (302), `try_redirect_permanent_redirect_cell` (308) — thin wrappers each invoking the generalised cell with their respective policy + status. - Three `protocol_pair_matrix!` invocations, one per status, each emitting four `pub fn try_*_h{1,2}_h{1,2c}` wrappers and four `#[test] fn test_*` harnesses. Net: 4 cells × 3 statuses = 12 redirect tests pass in parallel (`cargo test -p sozu-e2e protocol_pair_matrix::test_redirect_`). 2. **Rate-limit design doc rewrite** `doc/rate-limit-design.md` previously described an unimplemented two-layer mechanism (token-bucket request-rate at L7 + per-IP TCP cap at L4). The actual mechanism that landed in PR #1193 (closing #890 + #1057) is a **single layer** — per-(cluster, source-IP) concurrent connection cap with a 429 response. The doc listed types like `RateLimitRule`, `trust_forwarded_for`, `rate_limit_check`, `max_connections_per_source_ip`, `nb_connections_per_source_ip` that do not exist in the codebase. Rewritten to describe what's on main: - `max_connections_per_ip: Option<u64>` global default + per-cluster override on `Cluster.max_connections_per_ip`. - Counter discipline at SessionManager (per-token set of `(cluster, ip)` pairs) — H2 multiplexing notes inline. - Enforcement points (`mux/router.rs` for HTTP/HTTPS, `tcp.rs` for TCP). - Reject behaviour (`Answer429` variant, `Retry-After` elision when `0`, `connections.rejected_per_cluster_ip` counter, custom template via `CustomHttpAnswers.answer_429`). - Source IP selection (PROXY-v2 → peer_addr fallback; both `ExpectHeader` and `RelayHeader` modes are address-aware). - CLI / runtime API surface (`sozu connection-limit set/show/remove`). - Test coverage pointer to `e2e/src/tests/cluster_ip_limit_tests.rs`. - Future work (token-bucket request-rate, cross-worker sync, adaptive quotas, ban-list integration, pre-TLS TCP-level cap) each captured as deferred. - Operator guidance (global default rule of thumb, per-cluster overrides, NAT / shared-egress notes, behind-another-LB notes). Signed-off-by: Florentin Dubois <[email protected]>
jrcribb
pushed a commit
to jrcribb/sozu
that referenced
this pull request
Aug 10, 2026
…TP 429 + graceful TCP close Caps the number of simultaneous frontend connections one source IP may hold against a given cluster. Replaces the simpler per-source-IP variant the previous PR sozu-proxy#1193 commits proposed (those did not survive the H2 mux unification). Closes sozu-proxy#890, sozu-proxy#1057. Wire shape (proto): - ServerConfig.max_connections_per_ip = 22 [optional, default 0] - ServerConfig.retry_after = 23 [optional, default 60] - Cluster.max_connections_per_ip = 13 [optional, override] - Cluster.retry_after = 14 [optional, override] - CustomHttpAnswers.answer_429 = 12 [optional, custom 429 template] - Request.set_max_connections_per_ip = 50 (uint64) - Request.query_max_connections_per_ip = 51 (QueryMaxConnectionsPerIp {}) - ResponseContent.max_connections_per_ip_limit = 14 (MaxConnectionsPerIpLimit { limit: u64 }) Override semantics: cluster `None` inherits the global default, `Some(0)` is explicit "unlimited for this cluster", `Some(n > 0)` overrides. Source IP is the parsed PROXY-protocol source when present, else `peer_addr`. Enforcement: - HTTP/HTTPS via the unified mux at protocol/mux/router.rs::connect: after cluster resolution, before backend selection. The check fires AFTER auth/redirect/SNI decisions so a 401/421/redirect frontend never trips the limit. On hit: stash the resolved Retry-After on the stream context and return BackendConnectionError::TooManyConnectionsPerIp, which the mux converts into a 429 default answer through the new set_default_answer_with_retry_after path. Covers H1 and H2 — the unified mux serves both protocols. - H2 multiplex semantics: SessionManager keeps a per-token HashSet<(cluster, ip)>. Multiple streams to the same (cluster, ip) from the same H2 connection share one slot — the limit governs distinct frontend connections, not requests. Decrement is wholesale on session close (untrack_all_cluster_ip). - TCP at tcp.rs::connect_to_backend: rejection produces a graceful FIN via SessionResult::Close (no SO_LINGER trick). Answer engine (lib/src/protocol/kawa_h1/answers.rs + lib/src/protocol/mux/answers.rs): - Answer429 variant on DefaultAnswer with retry_after: Option<u32>. - 429 template registered alongside 421/503/etc. - New %RETRY_AFTER variable with `or_elide_header = true`: when the resolved value is 0/None, the engine drops the entire `Retry-After:` line. `Retry-After: 0` would invite an immediate retry that defeats the limit, so we omit instead of rendering literal 0. - legacy_to_map flattens CustomHttpAnswers.answer_429 into the per-listener answers map. - default_answer_for_code(429, ...) builds the variant. - set_default_answer_with_retry_after threads the resolved retry value through to the rendered answer. Proxy-protocol fixes (lib/src/protocol/proxy_protocol/{expect,relay}.rs): - ExpectProxyProtocol::into_pipe and RelayProxyProtocol::into_pipe now use ProxyAddr::source() from the parsed v2 header instead of the raw TCP peer_addr. Without this fix the pipe phase records the upstream PROXY-emitter (an LB / edge proxy / health-check probe), not the originating client — which means the per-(cluster, source-IP) limit would have keyed on the LB's IP. Relay mode previously discarded the parsed addresses entirely; we now stash them on the struct. SessionManager (lib/src/server.rs): - max_connections_per_ip: u64 + retry_after: u32 fields. - connections_per_cluster_ip: HashMap<(String, IpAddr), usize> + cluster_ip_tracks: HashMap<Token, HashSet<(String, IpAddr)>>. - cluster_ip_at_limit (token-aware: a token already holding a slot is never at the limit), track_cluster_ip (idempotent within a token), untrack_all_cluster_ip (drains on session close), effective_max_connections_per_ip / effective_retry_after (override resolution), clear_cluster_ip_tracking (runtime disable). - HttpProxy / HttpsProxy / TcpSession close paths drain via untrack_all_cluster_ip on the frontend token before the slab slot is reused. ProxySession trait (lib/src/lib.rs): - New cluster_id() and session_address() default-implemented as None. - New L7Proxy::sessions() so the mux router can reach the SessionManager from a Rc<RefCell<dyn L7Proxy>>. - New BackendConnectionError::TooManyConnectionsPerIp variant with cluster_id payload. CLI (bin/src/{cli,ctl/mod,ctl/request_builder}.rs): - `sozu connection-limit set <N>` / `remove` / `show` patches the global limit at runtime. The setter is non-sticky (workers reset to the TOML-configured value on restart); operators must mirror the change in the config to make it durable. - `--answer-429 <path>` flag added to `sozu listener {http,https} update`. - New build_http_answers helper threads answer_429 through the existing CustomHttpAnswers builder. Config (command/src/config.rs): - DEFAULT_MAX_CONNECTIONS_PER_IP = 0 (disabled), DEFAULT_RETRY_AFTER = 60. - FileConfig + Config + ServerConfig From conversion threaded. - FileClusterConfig + HttpClusterConfig + TcpClusterConfig + ListenerBuilder + CustomHttpAnswers gain the new fields. Metric: connections.rejected_per_cluster_ip (counter, labelled by cluster_id, backend_id always empty — rejection happens before backend selection). Replaces the simpler `connections.rejected_per_ip` from the older PR sozu-proxy#1193 commits — single name covers H1, H2, TCP. Tests: - e2e/src/tests/cluster_ip_limit_tests.rs covers H1 global limit (429 + Retry-After), H1 Retry-After: 0 elides the header, H1 per-cluster override (unlimited cluster coexists with capped), TCP graceful close on limit. All four pass `cargo test -p sozu-e2e cluster_ip_limit`. Validation: - cargo build --all-features --locked - cargo +nightly fmt --all -- --check - cargo clippy --all-features --all-targets --locked -- -D warnings - cargo test --workspace --locked Docs: bin/config.toml, doc/configure.md (parameters + metric), CHANGELOG.md. Co-authored implementation guidance from Codex on the H2 multiplex semantics, Retry-After: 0 elision, PROXY-protocol Relay-mode address stashing, and rolling-upgrade safety (optional proto fields, not required). Signed-off-by: Florentin Dubois <[email protected]> Co-authored-by: Eloi Démolis <[email protected]> Co-authored-by: hcaumeil <[email protected]>
jrcribb
pushed a commit
to jrcribb/sozu
that referenced
this pull request
Aug 10, 2026
…imit feat: add per-cluster per-IP connection limiting
jrcribb
pushed a commit
to jrcribb/sozu
that referenced
this pull request
Aug 10, 2026
The CHANGELOG previously carried three concurrent Unreleased blocks — `## [Unreleased]` (main-scoped post-1.1.1 fixes from PRs sozu-proxy#1162, sozu-proxy#1191, sozu-proxy#1192, sozu-proxy#1193, sozu-proxy#1194, sozu-proxy#1196, sozu-proxy#1202, sozu-proxy#1223), `## feat/answer-templates-rewrite-auth - Unreleased` (answer templates, URL rewrite, basic auth), and `## feat/h2-mux - Unreleased` (the H2 multiplexer rewrite from PR sozu-proxy#1209). All three feature stacks are on `main`; the per-branch dividers were release- engineering staging that no longer reflects current state. Changes: - Drop the `## feat/answer-templates-rewrite-auth - Unreleased` and `## feat/h2-mux - Unreleased` dividers; their bodies now appear under `## [Unreleased]` with provenance markers (`### Added — Answer templates / ...`, `### Added — H2 multiplexer (PR sozu-proxy#1209)`). - Promote the breaking changes (proto-tag renumbers, dashboard metric renames, `http.errors` labelling, pattern-trie regex anchoring, empty-val del-header semantic, sub-16393 `buffer_size` rejection, cipher-list constant rename) to a top-level `### Breaking changes (v1.1.x → v2.0.0)` paragraph at the top of the section so operators see them first. - Drop emoji from top-level subheaders (🌟 → Added, 🔄 → Changed, ⛑️ → Fixed, ✍️ → Changed, 📚 → Documentation, 🤖 → CI,⚠️ → Behaviour-affecting). Per- commit-log subsection at depth ≥ 4 keeps minor emoji ornaments where they don't conflict with Keep-a-Changelog vocabulary. - Preserve historical release entries (`## 1.1.1`, `## 1.1.0`, …) verbatim; they are released and immutable. Net effect: a single `## [Unreleased]` block ready for the v2.0.0 release-cut in §3.4.c of `tasks/todo.md`. Future passes can de-duplicate the multiple `### Added`/`### Changed`/`### Fixed` sub-blocks into one each per Keep-a-Changelog strict shape; this commit is the structural collapse only. Refs: tasks/todo.md §3.1.a; codex M12 amendment (3-way not 2-way collapse). Signed-off-by: Florentin Dubois <[email protected]>
jrcribb
pushed a commit
to jrcribb/sozu
that referenced
this pull request
Aug 10, 2026
…ite rate-limit design doc Two related changes folded into a single follow-up to Wave 2: 1. **Matrix coverage for 302 / 308 redirects** PR sozu-proxy#1009's e2e tests so far only exercised the H1 frontend path (`try_redirect_found_h1_emits_302` + `try_redirect_permanent_redirect_h1_emits_308` in `redirect_rewrite_auth_tests.rs`). The H2 frontend cells, plus the h2c-backend cells, were not covered — even though the `protocol_pair_matrix` harness already exists for exactly this purpose. `e2e/src/tests/protocol_pair_matrix.rs` now ships: - `try_redirect_cell_inner(...)` — generalised redirect cell that takes `policy: RedirectPolicy` + `expected_status: u16`. Reuses the same listener / cluster / unbound-backend setup as the 301 cell. - `try_redirect_permanent_cell` (301), `try_redirect_found_cell` (302), `try_redirect_permanent_redirect_cell` (308) — thin wrappers each invoking the generalised cell with their respective policy + status. - Three `protocol_pair_matrix!` invocations, one per status, each emitting four `pub fn try_*_h{1,2}_h{1,2c}` wrappers and four `#[test] fn test_*` harnesses. Net: 4 cells × 3 statuses = 12 redirect tests pass in parallel (`cargo test -p sozu-e2e protocol_pair_matrix::test_redirect_`). 2. **Rate-limit design doc rewrite** `doc/rate-limit-design.md` previously described an unimplemented two-layer mechanism (token-bucket request-rate at L7 + per-IP TCP cap at L4). The actual mechanism that landed in PR sozu-proxy#1193 (closing sozu-proxy#890 + sozu-proxy#1057) is a **single layer** — per-(cluster, source-IP) concurrent connection cap with a 429 response. The doc listed types like `RateLimitRule`, `trust_forwarded_for`, `rate_limit_check`, `max_connections_per_source_ip`, `nb_connections_per_source_ip` that do not exist in the codebase. Rewritten to describe what's on main: - `max_connections_per_ip: Option<u64>` global default + per-cluster override on `Cluster.max_connections_per_ip`. - Counter discipline at SessionManager (per-token set of `(cluster, ip)` pairs) — H2 multiplexing notes inline. - Enforcement points (`mux/router.rs` for HTTP/HTTPS, `tcp.rs` for TCP). - Reject behaviour (`Answer429` variant, `Retry-After` elision when `0`, `connections.rejected_per_cluster_ip` counter, custom template via `CustomHttpAnswers.answer_429`). - Source IP selection (PROXY-v2 → peer_addr fallback; both `ExpectHeader` and `RelayHeader` modes are address-aware). - CLI / runtime API surface (`sozu connection-limit set/show/remove`). - Test coverage pointer to `e2e/src/tests/cluster_ip_limit_tests.rs`. - Future work (token-bucket request-rate, cross-worker sync, adaptive quotas, ban-list integration, pre-TLS TCP-level cap) each captured as deferred. - Operator guidance (global default rule of thumb, per-cluster overrides, NAT / shared-egress notes, behind-another-LB notes). 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.
Summary
Caps the number of simultaneous frontend connections one source IP may hold against a given cluster, with HTTP
429 Too Many Requests(H1 + H2) or graceful TCP close. Replaces the simpler per-source-IP variant of the original commits, which did not survive the unified H2 mux. Closes #890, closes #1057.Scope
protocol/mux/router.rs::connect. The unified Mux session inlib/src/http.rsandlib/src/https.rscarries both H1 and H2 traffic, so a single insertion point covers both protocols. Check fires AFTER cluster resolution and AFTER auth/redirect/SNI decisions, BEFORE backend selection — so a 401/421/redirect frontend never trips the limit and a rejection consumes neither a backend pool slot nor a retry budget.tcp.rs::connect_to_backend. Rejection produces a graceful TCP FIN viaSessionResult::Close(no SO_LINGER trick).(cluster, IP)pair, regardless of how many streams it multiplexes. SessionManager keeps a per-tokenHashSet<(cluster, ip)>; an H2 stream to a(cluster, ip)already in that token's set never trips the limit.ExpectProxyProtocol::into_pipeandRelayProxyProtocol::into_pipenow preferProxyAddr::source()from the parsed v2 header over the raw TCPpeer_addr. Without this, the pipe phase recorded the upstream PROXY-emitter (an LB / edge / health-check probe), not the originating client. Relay mode previously discarded the parsed addresses entirely.Override semantics
None)Some(0)Some(n > 0)max_connections_per_ipmax_connections_per_ipretry_afterRetry-Afterheaderretry_afterRetry-After: 0would invite an immediate retry that defeats the limit, so the answer engine elides the header line entirely when the resolved value is 0.Wire shape (proto)
ServerConfig.max_connections_per_ip = 23 [optional, default 0]ServerConfig.retry_after = 24 [optional, default 60]Cluster.max_connections_per_ip = 13 [optional]Cluster.retry_after = 14 [optional]CustomHttpAnswers.answer_429 = 12 [optional]Request.set_max_connections_per_ip = 50 (uint64)Request.query_max_connections_per_ip = 51 (QueryMaxConnectionsPerIp {})ResponseContent.max_connections_per_ip_limit = 14 (MaxConnectionsPerIpLimit { limit: u64 })All new fields are
optionalwith proto defaults — older worker managers / state-replay paths keep working without these knobs (rolling-upgrade safe).CLI
sozu connection-limit set <N>/remove/showpatches the global limit at runtime. The setter is non-sticky (workers reset to the TOML-configured value on restart); operators must mirror the change in the config to make it durable.sozu listener {http,https} update --answer-429 <path>to ship a custom 429 template.[clusters.<id>] max_connections_per_ip = Nandretry_after = Sfor cluster-scoped overrides.Metric
connections.rejected_per_cluster_ip(counter, labelled bycluster_id). Counts H1 + H2 + TCP rejections together. Pair with the existingclient.connect.per_source.bucket_*/24IPv4 //48IPv6 telemetry for SOC dashboards.Test plan
End-to-end coverage in
e2e/src/tests/cluster_ip_limit_tests.rs:Retry-After: 30; the slot frees on close so the next request admits.Retry-After: 0elides the header line entirely.Validation:
cargo build --all-features --lockedcargo +nightly fmt --all -- --checkcargo clippy --all-features --all-targets --locked -- -D warningscargo test --workspace --lockedNotes
Retry-After: 0ambiguity, PROXY Relay-mode addresses, rolling-upgrade proto-field optionality) are addressed above.git push --force-with-lease. The earlier per-source-IP variant could not survive the H2 mux unification merged onmain(2db90ae9 feat(server): per-source accept telemetryrewrote the accept path with a 5-tuple queue carryingOption<SocketAddr>); the new commit re-implements the feature on top of the unified mux + accept-path design.