Skip to content

feat: add per-cluster per-IP connection limiting - #1193

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
feat/per-ip-rate-limit
Apr 29, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
feat/per-ip-rate-limit

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Mar 8, 2026 •

Copy link
Copy Markdown
Collaborator

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

  • Unified H1 + H2 enforcement: implemented at protocol/mux/router.rs::connect. The unified Mux session in lib/src/http.rs and lib/src/https.rs carries 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 enforcement: tcp.rs::connect_to_backend. Rejection produces a graceful TCP FIN via SessionResult::Close (no SO_LINGER trick).
  • H2 multiplex semantics: each frontend session contributes at most 1 to the count for any (cluster, IP) pair, regardless of how many streams it multiplexes. SessionManager keeps a per-token HashSet<(cluster, ip)>; an H2 stream to a (cluster, ip) already in that token's set never trips the limit.
  • Proxy-protocol-aware source IP: ExpectProxyProtocol::into_pipe and RelayProxyProtocol::into_pipe now prefer ProxyAddr::source() from the parsed v2 header over the raw TCP peer_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

Setting Absent (None) Some(0) Some(n > 0)
Global max_connections_per_ip unlimited (default) unlimited limit
Cluster max_connections_per_ip inherit global explicitly unlimited override limit
Global retry_after 60s default omit Retry-After header header value
Cluster retry_after inherit global omit header override value

Retry-After: 0 would 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 optional with proto defaults — older worker managers / state-replay paths keep working without these knobs (rolling-upgrade safe).

CLI

  • 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.
  • sozu listener {http,https} update --answer-429 <path> to ship a custom 429 template.
  • [clusters.<id>] max_connections_per_ip = N and retry_after = S for cluster-scoped overrides.

Metric

  • connections.rejected_per_cluster_ip (counter, labelled by cluster_id). Counts H1 + H2 + TCP rejections together. Pair with the existing client.connect.per_source.bucket_* /24 IPv4 / /48 IPv6 telemetry for SOC dashboards.

Test plan

End-to-end coverage in e2e/src/tests/cluster_ip_limit_tests.rs:

  • H1 global limit returns 429 with Retry-After: 30; the slot frees on close so the next request admits.
  • H1 Retry-After: 0 elides the header line entirely.
  • H1 per-cluster override coexists with an unlimited cluster (two clusters, one capped, one explicit-unlimited).
  • TCP graceful close on limit (no SO_LINGER, no RST).

Validation:

  • cargo build --all-features --locked
  • cargo +nightly fmt --all -- --check
  • cargo clippy --all-features --all-targets --locked -- -D warnings
  • cargo test --workspace --locked

Notes

  • Cross-checked with Codex; flagged risks (H2 multiplex semantics, Retry-After: 0 ambiguity, PROXY Relay-mode addresses, rolling-upgrade proto-field optionality) are addressed above.
  • This branch replaces the original PR feat: add per-cluster per-IP connection limiting #1193 commits via git push --force-with-lease. The earlier per-source-IP variant could not survive the H2 mux unification merged on main (2db90ae9 feat(server): per-source accept telemetry rewrote the accept path with a 5-tuple queue carrying Option<SocketAddr>); the new commit re-implements the feature on top of the unified mux + accept-path design.

@FlorentinDUBOIS FlorentinDUBOIS changed the title feat: add per-IP connection limiting feat: add per-cluster per-IP connection limiting Mar 8, 2026
@FlorentinDUBOIS FlorentinDUBOIS self-assigned this Mar 9, 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
FlorentinDUBOIS force-pushed the feat/per-ip-rate-limit branch from ffa0e1c to 0e8e0cd Compare April 29, 2026 07:46
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
FlorentinDUBOIS force-pushed the feat/per-ip-rate-limit branch from 0e8e0cd to 1d96722 Compare April 29, 2026 07:51
…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
FlorentinDUBOIS force-pushed the feat/per-ip-rate-limit branch from 1d96722 to d481c19 Compare April 29, 2026 09:10
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 16812c7 into main Apr 29, 2026
28 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the feat/per-ip-rate-limit branch April 29, 2026 09:53
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]>
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]>
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.

Basic DoS protection Implements rate-limiting

2 participants