Skip to content

feat(h2): HTTP/2 support via unified Mux session layer - #1209

Merged
FlorentinDUBOIS merged 433 commits into
mainfrom
feat/h2-mux
Apr 27, 2026
Merged

FlorentinDUBOIS merged 433 commits into
mainfrom
feat/h2-mux

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Mar 9, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds full HTTP/2 support to Sōzu through a unified Mux session layer that handles both HTTP/1.1 and HTTP/2 connections. The Mux layer replaces the old Http<Front> protocol and enables all four protocol combinations transparently.

This work builds on the mux_v1 architecture originally designed and implemented by @Edemolis (Eloi Demolis), with contributions from @hcaumeil (Helian Caumeil) on H2↔H2 SETTINGS handshake and H1→H2 upgrade path. The original mux_v1 branch established the core Mux session, Connection::H1/Connection::H2 enum, Stream abstraction, and the H2 frame state machine. This PR extracts, adapts, hardens, and completes that work for production readiness.

Architecture

                   ┌──────────────────────────┐
                   │        Mux<Front, L>      │
                   │                          │
   Client ──TLS──▶│  frontend: Connection     │     backend: Connection
                   │    ├─ H1(ConnectionH1)    │──▶    ├─ H1(ConnectionH1)
                   │    └─ H2(ConnectionH2)    │       └─ H2(ConnectionH2)
                   │                          │
                   │  streams: Vec<Stream>     │  ◀─ shared bidirectionally
                   │    ├─ front: Kawa<Checkout>│     between frontend
                   │    ├─ back:  Kawa<Checkout>│     and backend
                   │    └─ context: HttpContext │
                   └──────────────────────────┘

The Mux layer uses kawa as the unified HTTP representation (headers, body, trailers as Blocks), nom for H2 binary frame parsing, and loona-hpack for HPACK header compression. Buffer memory comes from poole (pooled slab allocator). The Position enum (Server for frontend, Client(cluster_id, backend, status) for backend) drives position-aware stream splitting.

Protocol support matrix

Frontend Backend Status
HTTP/1.1 HTTP/1.1 ✅ Existing (via Mux)
HTTP/1.1 HTTP/2 ✅ New
HTTP/2 HTTP/1.1 ✅ New
HTTP/2 HTTP/2 ✅ New

Key changes

Core Mux session (lib/src/protocol/mux/, ~14k lines)

File Lines Purpose
mod.rs 1477 Mux<Front, L> struct, Connection enum, Endpoint trait, session state machine, connect_to_backend, stream lifecycle
h2.rs 4962 Full H2 state machine: connection preface, SETTINGS, HEADERS/DATA/CONTINUATION/WINDOW_UPDATE/GOAWAY/RST_STREAM/PING/PRIORITY frame handling, flood detection, RFC 9218 priorities, flow control
parser.rs 1988 H2 binary frame parser (nom-based) with take(payload_len) symmetry across fixed-length frames
pkawa.rs 1758 HPACK→kawa bridge: decode H2 headers into kawa Blocks with full RFC 9113 validation, cookie splitting, Content-Length enforcement, RFC 9218 priority header parsing
converter.rs 863 kawa→H2 bridge: convert kawa blocks into H2 wire frames via H2BlockConverter with reusable cookie buffer
h1.rs 665 H1 connection within the mux layer (request/response proxying, keep-alive, upgrade, continue, early hints)
serializer.rs 552 H2 binary frame serializer with R-bit masking
router.rs 522 Backend routing with connect rollback on failure
connection.rs 502 Connection lifecycle and backend-token reverse index
stream.rs 271 Stream abstraction and state machine
answers.rs 226 Default answer generation for error responses
shared.rs 93 Shared types between H1 and H2
debug.rs 80 Debug history ring buffer

Supporting modules

File Lines Purpose
lib/src/pool.rs 408 Pooled slab allocator for stream buffers
lib/src/socket.rs +255 TLS vectored write path, ensure_tls_flushed(), signal_pending_write/read()
lib/src/splice.rs +247 Splice support for zero-copy forwarding

Integration (lib/src/http.rs, lib/src/https.rs)

  • HttpStateMachine::Http → HttpStateMachine::Mux(MuxClear)
  • HttpsStateMachine::Http → HttpsStateMachine::Mux(MuxTls)
  • ALPN preference set to ["h2", "http/1.1"] (H2 preferred)
  • H2 backend controlled by cluster.http2 config field

Configuration (command/src/config.rs, command/src/command.proto)

New per-listener protobuf fields with compile-time defaults:

Field Default Purpose
h2_initial_connection_window 1 MB Connection-level flow control window
h2_max_concurrent_streams 100 Maximum simultaneous streams per connection
h2_stream_shrink_ratio 2 Memory reclamation threshold
h2_max_rst_stream_per_window 50 Rapid Reset flood threshold
h2_max_ping_per_window 10 Ping flood threshold
h2_max_settings_per_window 10 SETTINGS flood threshold
h2_max_empty_data_per_window 50 Empty DATA flood threshold
h2_max_continuation_frames 50 CONTINUATION flood threshold
h2_max_glitch_count 10 Cumulative protocol abuse threshold
h2_max_header_table_size 4096 HPACK dynamic table size limit

CLI (bin/src/)

  • cluster h2 enable / cluster h2 disable commands
  • --http2 flag for runtime H2 toggling
  • SIMD feature exposed for kawa parser (--features simd)

Removed

  • Old lib/src/protocol/h2/ module (459 + 477 + 37 + 157 + 102 = 1232 lines)

RFC compliance

RFC 9113 (HTTP/2)

Passes 127/145 h2spec 2.0 conformance tests (external h2spec binary; the 18 failing checks cluster in §5.3, §6.9, §8.2.2, §8.3, and §8.1.2.6 — tracked as #1209-h2spec-hardening):

Section Requirement Implementation
§5.1.2 MAX_CONCURRENT_STREAMS Enforced with start_stream() → bool, active_requests rollback, back-pressure on repeated REFUSED_STREAM
§6.5 SETTINGS handshake Full negotiation with ACK, timeout enforcement, 64-entry cap
§6.8 GOAWAY graceful drain draining flag, peer_last_stream_id, streams > last_stream_id retried on new connection, auto-close when drained, default-answer streams drained before close
§6.9 Flow control Connection + stream-level WINDOW_UPDATE, threshold at 50% initial window, coalescing capped at 2³¹−1
§6.9.2 Initial window update checked_add overflow handling per spec
§6.10 CONTINUATION Standalone CONTINUATION without preceding HEADERS → GOAWAY(PROTOCOL_ERROR), configurable frame cap
§7 RST_STREAM Sent with CANCEL on forceful backend stream termination
§8.1 1xx informational 100 Continue / 103 Early Hints forwarded as HEADERS without END_STREAM, back buffer reset for final response
§8.1 Trailers Reject pseudo-headers, uppercase names, CRLF/CTL characters in trailers; read-side state discriminates initial HEADERS from trailers
§8.1.1 Content-Length Validated on both request and response headers; DATA payload mismatch → RST_STREAM(PROTOCOL_ERROR)
§8.2 Header validation Reject uppercase names, connection-specific headers, empty names, CRLF/CTL injection
§8.2.2 TE header Only trailers value accepted
§8.2.3 Cookie splitting Combined cookie headers split into individual pairs with OWS trimming, reusable cookie buffer
§8.3.1 Pseudo-headers All four required, non-empty, before regular headers, no duplicates; :scheme/:path syntax enforced
§8.4 Server push PUSH_PROMISE from client → GOAWAY(PROTOCOL_ERROR)

RFC 7541 (HPACK)

  • HPACK decoder table size synchronization on SETTINGS ACK (§4.2)
  • Configurable max header table size via h2_max_header_table_size
  • Dynamic table shrink via converter_buf/lowercase_buf after large headers

RFC 9218 (Extensible Priorities)

  • Prioriser struct with HashMap<StreamId, (u8, bool)> for urgency + incremental flag
  • parse_rfc9218_priority() parses priority header (u=N, i format)
  • Stream scheduling sorted by urgency first (lower = higher priority), then stream ID for FIFO within same urgency
  • Priority entries cleaned up at 4 stream lifecycle sites (dead_streams, RST_STREAM, GoAway, reset_stream)
  • PRIORITY map capped to prevent memory exhaustion from adversarial PRIORITY frames

RFC 9110 (HTTP Semantics)

  • §5.1: Empty header names rejected via is_invalid_h2_header()
  • §8.6: Conflicting Content-Length values detected and rejected via set_content_length() helper
  • Host/:authority reconciliation in H2→H1 downgrade path

Security hardening

Crash safety — zero panic paths

Every error handling path in the mux module is graceful. No network input can crash the worker:

  • 0 unwrap() / expect() in production code
  • 0 unreachable!() / assert!() / assert_eq!() in production code
  • 0 todo!() / unimplemented!() / panic!()
  • All HPACK decode callbacks use fallible write_all() → invalid_headers flag pattern
  • All frame parsing errors → error!() + GoAway/RST_STREAM/CloseSession (never crash)

Request smuggling mitigations

  • CRLF and CTL characters rejected in H2 header names and values (including cookie values)
  • Connection-specific headers (transfer-encoding, connection, keep-alive, proxy-connection, upgrade) rejected in H2
  • Pseudo-header syntax enforcement: :scheme must be http/https, :path must start with / or be *
  • Host/:authority mismatch detected and rejected
  • SNI enforcement with strict_sni_binding (421 Misdirected Request + metric on mismatch)

Flood detection (configurable)

Per-window and lifetime flood thresholds protect against protocol abuse, all configurable per-listener:

Threshold Default Attack mitigated
h2_max_rst_stream_per_window 50 Rapid Reset (CVE-2023-44487)
h2_max_ping_per_window 10 Ping flood
h2_max_settings_per_window 10 Settings flood (SETTINGS 64-entry cap enforced)
h2_max_empty_data_per_window 50 Empty DATA flood
h2_max_continuation_frames 50 CONTINUATION flood (CVE-2024-27316)
h2_max_glitch_count 10 Cumulative protocol abuse (WINDOW_UPDATE-on-closed, etc.)
h2_max_rst_stream_lifetime 10000 Absolute lifetime cap on received RST_STREAM
h2_max_rst_stream_abusive_lifetime 50 Lifetime cap on "abusive" pre-response received RST_STREAM (Rapid Reset signature)
h2_max_rst_stream_emitted_lifetime 500 Absolute lifetime cap on server-emitted RST_STREAM (MadeYouReset, CVE-2025-8671)

When a threshold is exceeded, the connection is terminated with GOAWAY(ENHANCE_YOUR_CALM). The MadeYouReset counter (added in Round 10) closes the emission-direction-flipped sibling of Rapid Reset: an attacker sending legitimate-looking frames (Content-Length mismatch, header parse error, rejected priority, zero-increment WINDOW_UPDATE on an open stream) coerces the server into emitting RST_STREAM; graceful NoError cancels are exempt.

Pending RST_STREAM cap

  • MAX_PENDING_RST_STREAMS (200) with lifetime counter prevents memory exhaustion from accumulated RST_STREAM frames

Fuzz testing (fuzz/)

  • fuzz_frame_parser — H2 binary frame parser fuzzing with corpus (connection preface, all frame types)
  • fuzz_hpack_decoder — HPACK decoder fuzzing with corpus (Huffman, indexed, incremental, never-indexed)
  • Crash regression corpus: crash-d7a34a0d-padded-headers-underflow-regression captured and guarded

Performance

Optimization Commit Impact
IoSlice buffer reuse in write hot path 752e470a Eliminates per-writable() Vec allocation
Backend-token reverse index for stream lookup c5ffba04 O(1) stream lookup by backend token vs O(n) scan
Pending links queue replacing Link scan 0fe3591f O(1) dequeue vs O(n) scan for unlinked streams
HPACK Store::from_vec for output 4dd11bd2 Avoids copy from intermediate Vec into kawa Store
Cookie buffer reuse in H2BlockConverter fad019af Reuses buffer across cookie splitting iterations
Converter buffer reuse in ConnectionH2 earlier Avoids Vec::new() per writable() cycle
WINDOW_UPDATE coalescing earlier Merges increments for same stream_id
RFC 9218 urgency scheduling earlier Higher-priority streams (CSS/JS at u=0) written before lower-priority ones (images at u=5)
Proportional overhead distribution earlier Connection overhead distributed to streams by bytes transferred, not equally
SIMD parser exposure b486b700 --features simd enables kawa SIMD HTTP parser
IoSlice UB fix 9b850dbd Clears IoSlice refs before consume to prevent use-after-free

Benchmarks

  • lib/benches/h2_scheduling.rs — Priority scheduling sort strategy comparison (insertion sort vs stable sort vs unstable sort)
  • lib/benches/header_formatting.rs — Header formatting micro-benchmarks (expanded)

Observability

OpenTelemetry trace propagation

  • Behind #[cfg(feature = "opentelemetry")] feature flag
  • Extracts traceparent/tracestate headers from H2 frames during stream creation
  • Propagates SpanContext into access log entries for distributed tracing correlation

Metrics

  • Full parity with legacy H1/H2 handlers: http.active_requests, response time, request count, error rate
  • Backend metrics restored in mux layer
  • Gauge underflow protection (clamped to zero)
  • connections_per_backend gauge underflow fix
  • SNI mismatch counter metric

Session-context logging prefix (Round 10)

Every protocol-layer log line now carries a structured session prefix matching the RUSTLS convention:

MUX-H2  Session(peer=…, position=Server, state=Frames, streams=37, last_peer_id=489,
                window=983040, draining=false, readiness=…)   >>> <event>
  • Applied uniformly across seven log_context! macros: rustls, pipe, tcp, kawa_h1, mux/h2, mux/h1, mux/mod (plus a log_context_lite! for borrow-conflict sites).
  • Mux-level lines include a per-session ULID (session_ulid on Mux) so every event for one frontend connection is grep-correlatable.
  • Configurable ANSI colour scheme honours log_colored: bold accent protocol label, cyan Session keyword, gray attribute keys, bright-white values. ANSI codes are skipped when the sink is non-stdout.
  • New sozu_command::logging::is_logger_colored() public helper.
  • H2FloodDetector::check_flood() refactored to return Option<H2FloodViolation> so flood logs get emitted at the caller with full session context before GOAWAY.

Configuration knobs documented

  • log_colored, access_logs_colored, access_logs_format, automatic_state_save, disable_cluster_metrics, back_timeout, accept_queue_timeout, worker_timeout — previously accepted by the parser but missing from doc/configure.md and/or bin/config.toml; now fully documented.

Test coverage

E2E tests — 227 tests across 12 files (20,387 lines)

File Tests Coverage
h2_tests.rs 69 H2 basic, ALPN, POST, concurrent streams, large payload, header forwarding, H1 fallback, H2 backend, CONTINUATION, GoAway drain, RST_STREAM, malformed frames, Content-Length, WebSocket, 100-Continue, Proxy Protocol v2, stream-ID exhaustion, half-close, graceful GOAWAY
h2_security_tests.rs 47 Desync vectors, connection-specific headers, CL fuzzing, cookie splitting, HEAD, PING, RST/GOAWAY edges, PUSH_PROMISE, error responses, POST forwarding, multi-cluster, trailers, pseudo-header in trailers, half-closed streams, HPACK table size zero, connection reuse, Rapid Reset abusive-lifetime, SETTINGS 64-entry cap, PRIORITY map cap, WINDOW_UPDATE-on-closed glitch flood, stalled TLS peer starvation
h2_security_header_injection.rs 8 CRLF/CTL in header values, cookie values, pseudo-header syntax, Content-Length validation
h2_security_parser.rs 9 PADDED+PRIORITY underflow, GOAWAY length floor, strip_padding off-by-one, unknown frame types, R-bit masking, standalone CONTINUATION
h2_security_session.rs 5 Router-connect rollback leak, per-stream idle timeout, HTTP upgrade backend-drop, client FIN vs RST half-close, stream-ID exhaustion graceful disconnect
h2_security_sni.rs 5 SNI authority mismatch → 421, wildcard not expanded, plaintext listener skip, strict_sni_binding opt-out, multi-SAN certificate
mux_tests.rs 21 Mixed H1/H2 scenarios, multiplexed streams, request pipelining, WebSocket upgrades
tests.rs 42 Legacy H1 tests (regression)
h1_security_tests.rs 8 H1 security edge cases
tcp_tests.rs 5 TCP proxy tests
tls_tests.rs 6 TLS-specific tests
fuzz_tests.rs 2 Fuzz target integration (#[ignore]d — require nightly + cargo-fuzz)

Test infrastructure additions

  • e2e/src/mock/raw_h2_response_backend.rs — Raw-byte H2 response mock for adversarial :status testing
  • e2e/src/mock/h2_backend.rs — H2 backend mock for H2↔H2 scenarios
  • e2e/src/tests/h2_utils.rs — Shared H2 test utilities (frame builders, raw connection helpers, parameterized SNI)
  • e2e/src/port_registry.rs — Port allocation registry for parallel test execution
  • lib/assets/multi-sni-cert.pem + multi-sni-key.pem — Multi-SAN certificate for SNI E2E tests
  • lib/src/protocol/mux/ cfg(test) hooks for router leak and stream-ID exhaustion testing

Conformance

  • h2spec 2.0 (external binary): 145/145 pass (Round 13 — see below). The previously-failing 18 checks in RFC 9113 §5.3.1, §6.9/§6.9.1, §8.1.2, §8.1.2.1-3, §8.1.2.6 are closed by the eager-RST emission fix. test_h2spec_conformance is no longer gated #[ignore]; it gracefully skips when the h2spec binary is missing from PATH.

Crash safety

  • Zero panic paths verified (grep audit: 0 unwrap/expect/unreachable/assert in production code)

Code structure (h2.rs internals)

Sub-struct decomposition

ConnectionH2 fields are organized into logical groups for maintainability:

Sub-struct Fields Purpose
H2FlowControl window, peer_window, initial_window_size Connection-level flow control state
H2ByteAccounting overhead_bytes, zero_window_count Byte tracking for overhead distribution
H2DrainState goaway_sent, last_stream_id, pending_rst_streams Graceful shutdown lifecycle
H2FloodConfig 6 threshold fields Configurable flood detection limits
Prioriser HashMap<StreamId, (u8, bool)> RFC 9218 urgency + incremental tracking

Extracted methods

Large monolithic functions have been decomposed for readability:

Method Extracted from Purpose
handle_header_state() readable() HEADERS frame processing (~177 lines)
handle_continuation_header_state() readable() CONTINUATION processing (~52 lines)
write_streams() writable() Per-stream DATA/HEADERS serialization (~236 lines)
flush_pending_control_frames() writable() Control frame output (~100 lines)
flush_zero_to_socket() multiple sites Zero-copy flush helper (~45 lines)
handle_1xx_reset() write_streams() 1xx informational buffer reset (~20 lines)
ensure_tls_flushed() flush sites TLS buffer drain helper

Result: readable() ~213 lines (was ~420), writable() ~75 lines (was ~310).


Dependencies

Crate Version Purpose
loona-hpack 0.4.3 HPACK compression (replaces unmaintained hpack 0.3.0 which had panic vulnerabilities)
nom existing H2 binary frame parsing
kawa existing Zero-copy HTTP representation
poole existing Buffer pool

Documentation

File Change
doc/h2_mux_internals.md New — 649-line developer reference for the H2 multiplexer internals
doc/architecture.md +300 lines — Mux layer architecture, H2 state machine, flow control, stream lifecycle
doc/configure.md +568 lines — All new H2 config fields documented with examples and defaults
doc/configure_cli.md +18 lines — cluster h2 enable/disable CLI reference
doc/getting_started.md +70 lines — H2 getting started guide
CHANGELOG.md +101 lines — Full changelog for the release

Files changed (128 files, +47,207/−2,350)

Category Files
New: Mux module lib/src/protocol/mux/{mod,h1,h2,pkawa,converter,parser,serializer,router,connection,stream,answers,shared,debug}.rs
New: Pool lib/src/pool.rs
Removed: Old H2 lib/src/protocol/h2/{mod,parser,serializer,state,stream}.rs
Modified: Integration lib/src/{http,https,lib,socket,tcp,splice,timer,tls}.rs, lib/src/protocol/{mod,kawa_h1/editor,pipe}.rs
Modified: Config command/src/{config,command.proto,proto/display,state,channel}.rs
Modified: CLI bin/src/{cli,command/requests,command/server,command/sessions,command/upgrade,ctl/*,upgrade,util,worker}.rs
Modified: Metrics lib/src/metrics/local_drain.rs
New: E2E tests e2e/src/tests/{h2_tests,h2_security_tests,h2_security_header_injection,h2_security_parser,h2_security_session,h2_security_sni,mux_tests,h1_security_tests,tcp_tests,tls_tests,fuzz_tests,h2_utils}.rs
New: Test infra e2e/src/{port_registry,mock/h2_backend,mock/raw_h2_response_backend}.rs, lib/assets/{multi-sni-cert,multi-sni-key}.pem
New: Fuzz harness fuzz/{Cargo.toml,fuzz_targets/*.rs,corpus/**}
New: Benchmarks lib/benches/h2_scheduling.rs
Modified: E2E e2e/src/tests/{tests,mod}.rs, e2e/src/mock/{https_client,async_backend,sync_backend}.rs
Docs doc/{h2_mux_internals,architecture,configure,configure_cli,getting_started,README}.md, CHANGELOG.md
CI .github/workflows/{benchmark.yml,rsa-2048.cnf}

Related issues

Closes #1211 — Configurable flood detection thresholds
Closes #1212 — OTel trace propagation from H2 headers to access logs
Closes #1213 — Proportional overhead distribution by bytes transferred
Closes #1214 — ConnectionH2 sub-struct decomposition
Closes #1215 — RFC 9218 extensible priorities
Closes #1216 — Code structure improvements / readable+writable split


Review rounds

This PR went through 10 rounds of systematic review:

Round 1 (commit 025822cf)

  • GOAWAY sentinel token fix (Token(0) → Token(usize::MAX))
  • Compile-time usize assertion, rst_sent cleanup, WINDOW_UPDATE interest fix
  • glitch_count wired to 3 anomaly sites, MAX_PENDING_RST_STREAMS cap
  • 6 code simplifications (-130 lines), 25 new e2e security tests

Round 2 (commit 664bb659)

  • i32 overflow fix in stream creation, DebugHistory ring buffer cap (10k)
  • Shared connection-specific header list, buffer shrink after large headers
  • Display for H2Error, flag computation cleanup, dead code removal
  • Module-level documentation, 5 new e2e tests (30 total)

Round 3 (commit 21e7514d)

Round 4 (commits 7da4f580..fc606d23)

  • OTel trace propagation from H2 headers to access logs
  • RFC 9218 extensible priorities with urgency-based stream scheduling
  • Configurable flood detection thresholds via listener protobuf config
  • Proportional overhead distribution by bytes transferred
  • ConnectionH2 decomposed into sub-structs, readable()/writable() split

Round 5 (commit 9f414492)

  • 1xx informational response handling (100 Continue, 103 Early Hints)
  • Edge-triggered epoll TLS safety (ensure_tls_flushed(), signal_pending_write/read())
  • H1 pipelining validation, header validation consolidation
  • Proxy Protocol v2 E2E fix, PP → TLS readiness transfer fix

Round 6 — Protocol hardening (commits 4a798013..497cd256)

  • Reject standalone CONTINUATION not preceded by HEADERS
  • Back-pressure MAX_CONCURRENT_STREAMS on repeated REFUSED_STREAM
  • Symmetric take(payload_len) in parser for all fixed-length frames
  • cfg(test) hooks for router leak and stream-ID exhaustion testing
  • Trailer framing invariant documentation

Round 7 — Security E2E expansion (commits 7e0c02ff..3942f674)

  • 30+ new adversarial E2E tests across 4 new test files
  • SNI enforcement suite: authority mismatch → 421, wildcard handling, plaintext skip, strict binding opt-out
  • Parser adversarial suite: PADDED+PRIORITY underflow, GOAWAY floor, strip_padding, unknown frames, R-bit masking
  • Session lifecycle suite: router rollback leak, idle timeout, upgrade backend-drop, FIN vs RST half-close, stream-ID exhaustion
  • Header injection suite: CRLF/CTL rejection, pseudo-header syntax, host/:authority reconciliation
  • Raw H2 response mock backend, multi-SAN certificate, parameterized SNI helpers

Round 8 — Performance, correctness, and hardening (commits 0d8ea2fe..5dd49765)

  • Fixes: Trailer discrimination via read-side parse state, default-answer stream drain, connections_per_backend gauge underflow, CI benchmark certificate hostname
  • Performance: Cookie buffer reuse, HPACK Store::from_vec, pending_links queue (O(1) vs O(n)), backend-token reverse index (O(1) vs O(n)), IoSlice buffer reuse, IoSlice UB fix (clear refs before consume)
  • Features: SIMD parser feature exposure, h2_max_header_table_size config knob
  • Hardening: H2 header validation against request smuggling, SETTINGS/routing/WINDOW_UPDATE hardening
  • Benchmarks: Priority scheduling sort strategy comparison

Round 9 — Multi-phase security hardening (commits 7f0b8871..dcc1a701)

  • Phase 1 — TLS vectored write, stream recycling, teardown, Content-Length validation (7f0b8871): keeps socket_write and socket_write_vectored structurally symmetric, tightens teardown ordering, rejects CL mismatches on trailers.
  • Phase 2 — Per-stream idle timeout (2008ab3b): converts the per-stream timer from a lifetime cap to a true idle timeout — trickle DATA resets it, slow-multiplex Slowloris is cancelled per stream instead of pinning max_concurrent_streams slots for the full connection timeout.
  • Phase 3 — H2 header validation, shutdown, and converter security (080e43f2): strengthens header validation, graceful-shutdown edge cases, and converter output bounds.
  • Phase 4 — Port comparison, arithmetic, flood counters (b92ef8b7): port-equality semantics on :authority, overflow-safe arithmetic on flood counters, audit-driven hardening.
  • CI resilience (dcc1a701): widens the settings-flood test read window to absorb event-loop jitter.
  • Operational log-level (2ba95847): MessageClient response logs downgraded from info to debug to keep prod stderr readable.

Round 10 — Observability, documentation, and MadeYouReset (commits b4148751..67e78070)

  • Session-context logging prefix + ANSI colour (b4148751): rolls out the MUX-H2 Session(peer=…, streams=N, last_peer_id=X, window=W, draining=…) >>> prefix across all seven protocol macros (rustls/pipe/tcp/kawa_h1/mux h2/h1/mod). Adds per-Mux session_ulid, a log_context_lite! for borrow-conflict sites, and sozu_command::logging::is_logger_colored(). Refactors H2FloodDetector::check_flood to return Option<H2FloodViolation> so flood logs carry full context.
  • Log-prefix fix (9237f3ea): removes a duplicate log_context!(self) arg in handle_flood_violation and the GoAwayFrame serialize-error branch (flagged by the Lisa threat-hunt swarm audit).
  • MadeYouReset (CVE-2025-8671) mitigation (7953696d): caps server-emitted RST_STREAM with the total_rst_streams_emitted_lifetime counter inside H2FloodDetector::record_rst_emitted(); wired through reset_stream() on non-NoError resets (Content-Length mismatch, header parse error, priority rejection, zero-increment WINDOW_UPDATE on an open stream). Crossing the default 500 ceiling escalates to GOAWAY(EnhanceYourCalm). +3 new unit tests covering below-threshold, ceiling, and no-decay invariants. Privacy/retention note added to doc/configure.md covering the new per-line fields (peer IP, SNI, ULID).
  • Configuration documentation gap (91e56270): cross-audit of command/src/config.rs::FileConfig vs doc/configure.md + bin/config.toml surfaced eight undocumented global keys (log_colored, access_logs_colored, access_logs_format, automatic_state_save, disable_cluster_metrics, back_timeout, accept_queue_timeout, worker_timeout) — all now documented with examples.
  • MadeYouReset knob exposure (67e78070): promotes the CVE-2025-8671 cap from a compile-time default to a listener-level h2_max_rst_stream_emitted_lifetime knob. Touches the proto (field Make TLS options configurable #27 on HttpListenerConfig, add a timeout to reactivate the "readable" event for the config socket #39 on HttpsListenerConfig), ListenerBuilder, add_h2_flood_rows display helper, both get_h2_flood_config readers, doc/configure.md, and bin/config.toml.

Round 10b — RFC 9218 scheduler, audit-log enrichment, ergonomics, H2 polish (commits 7f8596c6..5e523ac0)

RFC 9218 priority scheduling — prerequisite work for Round 11's ET-rearm pass:

  • PRIORITY_UPDATE parsing and application (7ddf1f30): the H2 receiver accepts client-emitted PRIORITY_UPDATE frames (RFC 9218 §7.1) and reseats Prioriser entries mid-connection.
  • Urgency-scoped incremental counting (3f9f5e38): scope incremental_peer_count to the same urgency bucket plus ready peers, so a higher-urgency busy stream no longer forces an incremental yield.
  • Solo-bucket yield skip (f6c02912): skip the incremental yield when only one stream occupies the bucket — no peer to round-robin to.
  • Last-DATA yield suppression (8d226b88): suppress the incremental yield between the final DATA frame and the closing flags block, which would otherwise stall the trailing frame at stream close.
  • LIFECYCLE invariant 16 enforcement (164ba27a): finalize_write and has_pending_write now enforce the invariant so forward progress is guaranteed after a priority reordering pass.
  • E2E coverage: RED-state solo-bucket stall (465fb108) and mixed-urgency body-stall repro (5e523ac0).

Audit log enrichment (control plane) — the command-socket audit trail was restructured from a flat debug! stream into an operator-readable, MUX-aligned info! feed with full ucred attribution:

  • 2200fc2a — realign to the MUX Session(...) layout at debug level.
  • 0c2dc869 — promote to info! so the trail is visible without logs-debug.
  • 53b51e03 — enrich with full ucred, fanout list, and injection-defence cleaning.
  • 6b21c9c4 — dedicated audit sink, diff-before→after, request sha256, cert-replace fingerprint.
  • e7a5e29d — close-out: timestamp, actor_role, connect_ts, boot_generation, build_git_sha, JSON sink.

Mux stability & lifecycle:

  • 865ada38 — H2 stream idle timeout now inherits back_timeout instead of being capped at the old default.
  • f0874b9e — SETTINGS_TIMEOUT detection demoted from error! to warn! and stops re-firing on every loop tick.
  • 040e305f — close the H1→H2 wake gap, refresh the outbound idle counter, and correctly classify chunked-EOF at stream end. Round 11 Fix C mirrors this commit for the H2-backend → H2-frontend direction.
  • 4b762c21 — e2e large-asset repro suite with a new ChunkedFlushH1Backend mock that exposes flush boundaries.

Listener runtime-patch verb (operator ergonomics):

  • 77ad575f — sozu listener {http,https,tcp} update verb for patching listener config at runtime without a hot reload.
  • dc341565 — post-review follow-ups on the update verb.
  • abd1663b — reset active on give_back_listener plus repair of four e2e tests that depended on the old behaviour.

Access log / correlation header:

H2↔H1 trailer handling:

  • 9b8f3884 + 5610d3d4 — e2e lock-in for HTTP/1.1 chunked-trailer forwarding; the plumbing was already in place via kawa's ParsingPhase::Trailers. Closes Trailers in chunked frames #899.
  • 7f8596c6 — H2→H1 translation on fixed-Content-Length streams silently drops trailers (RFC 9110 §6.5). This commit adds a warn! and the h2.trailers_dropped_content_length counter so operators can detect the drop; peers that omit Content-Length get upgraded to chunked framing and their trailers pass through.

H2 protocol polish:

  • a585cea3 — emit HPACK dynamic-table-size-update on SETTINGS change (RFC 7541 §4.2).
  • 71d77d71 — e2e lock-in: response :status must be present and non-empty.
  • 8370b90f — raw-H2 assertion for 1xx informational forwarding (100 Continue / 103 Early Hints).
  • 9ff035d5 — 30-iteration backend-disconnect stress verifies no stream-state leak.
  • 11fcdc0a — document the negotiated max_frame_size caller contract.
  • 74e0edec — document the remove_dead_stream cache-eviction invariant.

Log severity & dead-code hygiene:

  • 07a83e92 — harmonise backend retry-budget-exhaustion log severity across H1 and H2 paths.
  • 9216e52a — gate the dead-code debug! arm on logs-debug so release builds no longer emit unused-variable warnings on this path.

Ping-flood diagnostic:

  • ebdef01f — instrument the ping-flood write path so future CI flakes carry enough context to diagnose from stderr.
  • defd17d7 — nightly fmt on the ping-flood diagnostic.

Rate-limit design (foundation; implementation pending, tracked in #890):

  • 0031aadb — per-tenant 429 + per-source-IP cap design recorded in doc/rate-limit-design.md. Reject response carries Retry-After and X-Sozu-RateLimit-Rule; counter family rate_limit.rejected.*.

Audit-findings task log (internal tracking under tasks/):

  • 4c35c10e, 8242c777, 5246c80b — running record of post-merge audit findings (buckets B3-c/d/f/g/j/o/p/q/v/w/x).

Round 11 — ET signal-pairing hygiene + invariant-15 canonical API (commits 66431dd1..40c9c2af)

  • Follow-up on a production HAR (Brave 147 / Chromium 147 on *.cleverapps.io; two concurrent priority: u=1, i XHRs stalled 180 s with sozu-emitted 504s). Dual-pass review converged on three latent interest.insert(Ready::WRITABLE) sites missing the paired signal_pending_write() — hardened in this round as defence-in-depth for LIFECYCLE invariant 15. The observed 180-s stall most likely traces to backend-side slowness (Spring Boot / Tomcat / MongoDB); the mux/mod.rs:1402-1423 16-iter synchronous drain loop was already flushing the 504 (confirmed by the sozu-id header visible in the HAR response).
  • New canonical API (66431dd1): Readiness::arm_writable() in lib/src/lib.rs pairs interest.insert(Ready::WRITABLE) with signal_pending_write() at a single call site. The existing H1 sites (mux/h1.rs:361-368) keep the open-coded pair to hold this refactor zero-churn — migration is opt-in, and signal_pending_write() stays pub so no caller is forced to move.
  • Fix A — set_default_answer rearm (41bc51f2): mux/answers.rs:210 now uses arm_writable() + incr!("h2.signal.writable.rearmed.default_answer"). Defence-in-depth for the backend-timeout path in mux/mod.rs:1378 that synthesises 504/500/400 responses.
  • Fix B — PRIORITY_UPDATE rearm (3269dd06): handle_priority_update_frame (mux/h2.rs:4349-4376) now rearms self.readiness after mutating self.prioriser, so a reprioritised stream does not need an unrelated event to run under ET epoll. Observed post-PU drain latency O(100 µs) on HEAD.
  • Fix C — H2-backend → H2-frontend peer rearm (fead8eb0): handle_data_frame (mux/h2.rs:4126-4131) and handle_headers_frame (mux/h2.rs:4258-4263) now pair the peer Ready::WRITABLE insert with signal_pending_write(), mirroring the H1-backend pattern landed in 040e305f. Forward-compat hardening — current Clever Cloud PaaS routing is frontal-H2/H1 ↔ backend-H1, but a cluster flipping to H2 upstream now has a working wake path.
  • Fix D — mid-pass incremental-count consistency (1de3faad): ready_incremental_by_urgency now decrements mid-pass at mux/h2.rs:2481 (inside the 'outer loop) when a stream becomes ineligible (rst_sent, retired). Saves one unnecessary voluntary yield per pass on same-urgency-bucket peers after a stream RSTs or completes. Structural regression guard added for the saturating_sub path.
  • Fix E — stale doc comments (e7920026): corrects the is_main_phase() / apply_incremental_rotation rationale in e2e/src/tests/h2_correctness_tests.rs:2346-2394 so a future agent doesn't chase a dead hypothesis (kawa 0.6.8 is_main_phase() returns true for Terminated; Round-4 apply_incremental_rotation no longer returns the total).
  • Telemetry (c0d03425): five new metric keys documented in doc/configure.md — h2.signal.writable.rearmed.{default_answer, priority_update, peer_data, peer_headers} (counters) and h2.streams.ready_incremental.by_urgency (gauge). Used as canary signals to verify rearm paths fire sanely in production.
  • E2E test module (28fe3422, 4e937df6, 40c9c2af): e2e/src/tests/h2_priority_rearm_tests.rs (~800 LOC) runs four always-on tests — test_h2_backend_silent_triggers_504_within_back_timeout, test_h2_priority_update_rearms_writable, test_h2_backend_silent_headers_data_peer_signal, test_h2_mid_pass_rst_does_not_force_yield. The Fix C test uses a new HEADERS-then-delay-then-DATA mode on RawH2ResponseBackend (~65 LOC extension, 4e937df6) to surface the H2-backend peer-rearm path deterministically.
  • Incidental (62747882): rustfmt wrap-break on single_read_h1_backend.

Round 12 — E2E regression guards (commits d60357fc..c1572502)

  • Un-ignore five of six previously gated e2e tests (d60357fc): fuzz_frame_parser and fuzz_hpack_decoder (10 s budget each; shell out to cargo +nightly fuzz run, require nightly + cargo-fuzz in PATH), e2e_session_stream_id_exhaustion_graceful (FIX-22 smoke), e2e_h2_flow_per_stream_idle_timeout (now deterministic after three fixes — split the TLS socket-read timeout, tighten the per-stream idle timeout below SETTINGS_ACK_TIMEOUT, drop an over-specified no_backend_requests assertion), and test_h2_large_response_1gb_stress (~14 s on reference hardware; sustained flow-control + TLS write retry on a 1 GB body). Only test_h2spec_conformance remains #[ignore]d — the test shells out to the external h2spec binary (h2spec 2.0), and 18 of 145 checks currently fail, clustered in RFC 9113 §5.3 (self-dependent HEADERS), §6.9 (WINDOW_UPDATE boundary), §8.2.2 (uppercase / connection-specific / TE), §8.3 (pseudo-header uniqueness / ordering / allow-list), and §8.1.2.6 (content-length vs DATA reconciliation); tracked as #1209-h2spec-hardening (e2e/src/tests/tests.rs:3145-3150).
  • 7.7 MB gzipped-truncation regression guard (c1572502): adds test_h2_large_gzipped_chunked_drains_fully (deterministic XorShift-128 seeded ~7.76 MB high-entropy payload, gzipped through the extended ChunkedFlushH1Backend with Content-Encoding: gzip, Chromium-146 SETTINGS profile — INITIAL_WINDOW_SIZE=6_291_456, HEADER_TABLE_SIZE=65_536, MAX_CONCURRENT_STREAMS=1000, MAX_HEADER_LIST_SIZE=262_144, ENABLE_PUSH=0, NO_RFC7540_PRIORITIES=1; one-shot stream-0 WINDOW_UPDATE(15_663_105), per-stream WINDOW_UPDATE(sid, 32 KiB) cadence, priority: u=3, i; sha256 byte-identity within 8 s) and test_h2_large_chunked_7mb_drains_fully (scale-only smoke, no gzip). Stream-0 WINDOW_UPDATE is issued once during the handshake only — H2FloodDetector caps stream-0 WUs at DEFAULT_MAX_WINDOW_UPDATE_STREAM0_PER_WINDOW = 100 per sliding window (lib/src/protocol/mux/h2.rs:259, enforcement at :856); refreshing the connection window frame-by-frame would GOAWAY the connection.

Round 13 — h2spec 145/145 (commits 8e07b311..50e01d2b)

Closes the 18 remaining h2spec 2.0 conformance failures clustered in RFC 9113 §5.3.1, §6.9 / §6.9.1, §8.1.2, §8.1.2.1-3, §8.1.2.6. test_h2spec_conformance un-ignored; live run 145 tests, 145 passed, 0 skipped, 0 failed in 0.95 s.

Two compounding gaps were masking every proxy-emitted RST_STREAM on malformed-stream rejections:

  1. forcefully_terminate_answer missed the event bit (lib/src/protocol/mux/answers.rs:216-227). Under edge-triggered epoll, filter_interest() = event & interest. Setting interest without raising event left the filter at zero, so writable() was never scheduled. Fix: migrate the final line from readiness.interest.insert(Ready::WRITABLE) to readiness.arm_writable() — the canonical invariant-15 pair defined at lib/src/lib.rs:1010.
  2. reset_stream's callers evicted the stream before write_streams could serialise the RST bytes. Every one of the eight reset_stream call sites is immediately followed by remove_dead_stream, which clears self.streams. write_streams iterates self.priorities_buf built from self.streams.keys(), and H2BlockConverter::initialize is the only path that serialises RST bytes into kawa.out. With the stream already evicted, kawa.prepare(&mut converter) was never called — the RST bytes never reached socket_write_vectored. Clients saw only the SETTINGS-handshake WINDOW_UPDATE before the ~6.8 s session timeout closed the TLS connection.

Fix — commit 8e07b311 (fix(h2): emit RST_STREAM eagerly from reset_stream):

  • Introduce ConnectionH2::enqueue_rst(wire_stream_id, error) on top of a free-function primitive enqueue_rst_into (unit-testable without a ConnectionH2<Front> fixture; five new tests cover the invariants in isolation). The helper is the single canonical entry point for proxy-emitted stream resets, and pins three co-invariants:
    • Dedupe via self.rst_sent: HashSet<StreamId> — at most one queued RST per wire id; HashSet::insert short-circuits on the already-present branch so the queue / counter / event bits stay in lock-step even under cascading error paths.
    • MadeYouReset queued cap via self.total_rst_streams_queued — counter bump per fresh enqueue, policed at MAX_PENDING_RST_STREAMS = 200 in flush_pending_control_frames (escalates to GOAWAY(ENHANCE_YOUR_CALM) on overflow). Orthogonal to the 500-emitted MadeYouReset lifetime cap at flood_detector.record_rst_emitted.
    • Invariant-15 arm via Readiness::arm_writable — both interest and event WRITABLE bits raised together for edge-triggered epoll.
  • Retrofit the three push sites to funnel through enqueue_rst: DATA-on-closed (h2.rs:1689 — StreamClosed), refuse_stream_and_discard (h2.rs:3488 — MCS / pool exhaustion), and the new call inside reset_stream itself.
  • Change reset_stream signature to accept the wire StreamId as a parameter. Every one of the eight callers already has it in scope (data.stream_id at the DATA/CL paths; bare stream_id at the HEADERS / WINDOW_UPDATE / PRIORITY paths), so the linear scan over self.streams the original scratch plan had in mind is unnecessary.
  • Migrate forcefully_terminate_answer to Readiness::arm_writable — closes Gap A for the mod.rs:1299-1303 timeout path that calls the helper directly, not through reset_stream. New metric h2.signal.writable.rearmed.forcefully_terminate_answer.
  • Guard finalize_write against dropping Ready::WRITABLE when pending_rst_streams or flow_control.pending_window_updates are still non-empty. flush_pending_control_frames is gated on expect_write.is_none(), so when a prior partial write deferred the Phase-3 flush the queues stay non-empty after expect_write drains — without this rearm the queued RST would stall until an unrelated event re-triggered writable. New metric h2.signal.writable.rearmed.control_queue.

Five unit tests cover the new invariants: test_enqueue_rst_into_populates_queue_and_dedupe, test_enqueue_rst_into_bumps_total_for_distinct_ids, test_enqueue_rst_into_arms_writable_in_invariant_15_form, test_enqueue_rst_into_dedupe_does_not_rearm_writable, test_forcefully_terminate_answer_arms_event_and_interest.

Test tighten — commit 2e977aba (test(e2e): un-ignore test_h2spec_conformance and tighten h2-security asserts):

  • Un-ignore test_h2spec_conformance; replace its .expect() on the h2spec binary with a graceful-skip so CI legs without the install step still finish the rest of the e2e suite.
  • Tighten 17 stream-scope permissive sites that had been hiding the emission gap — drop the || frames.is_empty() escape clause now that sozu emits RST_STREAM deterministically for every violation. Sites covered: h2_security_tests.rs:586, 664, 814, 883, 941, 1015, 1098, 2887, 2957 (kept !write_ok), 3025 (kept !write_ok), h2_security_header_injection.rs:115, 162, 238, 442, 535 (kept !wrote), 634, h2_correctness_tests.rs:96.
  • Keep 4 sites permissive with explanatory comments: h2_security_tests.rs:193 (HPACK bomb — flood), :503/:512 (connection preface corruption — connection-scope), :750 (authority/host normalized 200 is RFC-compliant acceptance), :3112 (DATA flood with padding).
  • Partial-tighten content_length_format_fuzzing (h2_security_tests.rs:1393): the three clearly dangerous CL values ("0,", "0,0", "-1") now require explicit rejection; silent close stays accepted for the whitespace/locale variants where rejection policy is still evolving.

Docs + CI — commit 8a984391 (docs(h2,ci): refresh LIFECYCLE RST path, CHANGELOG entry, install h2spec in CI):

  • lib/src/protocol/mux/LIFECYCLE.md §8.2 describes the unified enqueue_rst → pending_rst_streams → flush_pending_control_frames path, distinguishing rst_sent dedupe vs total_rst_streams_queued queued cap (200) vs record_rst_emitted MadeYouReset lifetime cap (500).
  • doc/h2_mux_internals.md mirrors the refresh on the flush_pending_control_frames Phase-3 flush.
  • CHANGELOG.md gains a ⛑️ Fixed entry under feat/h2-mux - Unreleased.
  • .github/workflows/ci.yml installs the prebuilt h2spec v2.6.0 binary from github.com/summerwind/h2spec/releases in every matrix leg before cargo test, so the now-un-ignored test_h2spec_conformance runs cleanly without a Go toolchain bootstrap (the test itself still gracefully skips on missing binary — belt-and-suspenders).

Validation:

  • test_h2spec_conformance → 145/145/0/0 in 0.95 s.
  • cargo test -p sozu-e2e --release h2_ → 189/189 in 308 s.
  • cargo test -p sozu-lib --lib -- protocol::mux → 416 pass (411 existing + 5 new).
  • cargo clippy --all-targets --locked -- -D warnings → 0 warnings.
  • cargo +nightly fmt --all -- --check → clean.
  • Fuzz targets (via cargo test -p sozu-e2e with -max_total_time=10): fuzz_frame_parser 195,135 runs and fuzz_hpack_decoder 20,720 runs, 0 crashes each.
  • Workspace-stress run (cargo test --workspace --locked) surfaced a single known H2 flood-family flake on test_h2_rapid_reset_triggers_goaway (Broken pipe race between the detector firing and the client's write loop finishing) — passes 5/5 in isolation on cargo test test_h2_rapid_reset_triggers_goaway, not a regression; tracked alongside the settings_flood / ping_flood siblings that share the same cause.

Net diff of Round 13: +437/-96 lines across 10 files (LIFECYCLE.md, h2_mux_internals.md, CHANGELOG.md, ci.yml, h2.rs, answers.rs, plus the four e2e test files).

Round 14 — CI flake stabilisation (commit 1f928981)

After Round 13 the feat/h2-mux CI matrix was still intermittently red — not because of the H2 mux changes but because of pre-existing test-harness race conditions that had been latent on the branch since Round 12. All affected tests passed reliably on local runs and the Codex cross-check reproduced the same local-pass / CI-fail split.

What CI actually showed (audit of failing runs 24896721675, 24896722873, 24897750687, 24897754034, 24905690253, 24909140723, 24909142701):

Test Flaked on runs Failure mode
test_h2_large_chunked_7mb_drains_fully 24897754034, 24897750687, 24909140723 panic at e2e/src/tests/h2_utils.rs:968 — Result::unwrap() on Err(BrokenPipe) during stream.flush() after a per-stream WINDOW_UPDATE write
test_h2_large_gzipped_chunked_drains_fully 24897754034, 24897750687, 24909140723, 24909142701 same panic point
test_h2_ping_flood_triggers_goaway 24905690253 returned State::Fail; write loop saw Broken pipe after ~N/200 frames, subsequent read picked up 0 frames
test_h2_settings_flood_triggers_goaway occasional across historical flood-family flakes (memory trail) same Broken pipe + zero-frame shape
test_h2_rapid_reset_triggers_goaway also observed during my cargo test --workspace --locked on 50e01d2 same
e2e_session_router_connect_failure_no_leak 24909140723 (nightly only) returned State::Fail — backend didn't reach expected state under load
e2e_session_stream_id_exhaustion_graceful 24909140723 (nightly only) returned State::Fail — third smoke request returned 503 instead of 200
fuzz_frame_parser / fuzz_hpack_decoder 24896721675, 24896722873, 24897750687, 24897754034 resolved in 024243e2 (CI nightly + cargo-fuzz install)

In parallel, the CI workers' stderr showed sustained ERROR MAXCONN: max number of session connection reached, flushing the accept queue, repeated ERROR 810-PANIC: error accepting TCPListen sockets: IoError, and ERROR H1-IDLE-ZOMBIE-METRICS — strong signals that the CI runner was near its file-descriptor limit and that some tests were accumulating slow-to-reap connections. That backdrop made the real root cause easier to see: whenever sozu legitimately decided to close a connection (end-of-response, flood detected, idle teardown), the test client's next write could race into BrokenPipe territory and either panic or break out of a loop too early to read the GOAWAY.

Codex cross-check (codex exec --sandbox read-only, gpt-5 default) independently identified the same two root causes and recommended the same structural fix direction: batched writes for the flood tests, and END_STREAM-before-WU ordering plus graceful BrokenPipe tolerance in the streaming drain helper. There is no production mux regression explaining either class.

Fix — commit 1f928981 (test(e2e): stabilise drain helper + flood tests against peer-close races):

  1. drain_h2_stream_streaming in e2e/src/tests/h2_utils.rs:

    • Check END_STREAM on each DATA frame before emitting the WINDOW_UPDATE refresh. The final frame carries END_STREAM by definition, so refreshing credit afterwards was always pointless and raced sozu's legitimate stream close.
    • Tolerate BrokenPipe / ConnectionReset / ConnectionAborted / NotConnected / UnexpectedEof on the WU flush: break the read loop gracefully and let the caller's body-integrity assertions (body_bytes, sha256) be the source of truth. Any other error still panics loudly.
  2. Flood tests in e2e/src/tests/h2_tests.rs (test_h2_ping_flood_triggers_goaway, test_h2_settings_flood_triggers_goaway, test_h2_rapid_reset_triggers_goaway): batch the entire flood payload into one write_all + flush, sized at threshold + 5 frames (105 pings vs threshold 100, 55 settings vs 50, 105 HEADERS+RST pairs vs 100). By the time the test switches to reading, sozu has seen the full flood — there is no per-frame write race left to lose.

test_h2_continuation_flood_triggers_goaway already used the batched pattern (pre-existing) and did not need a change.

No test was ignored, disabled, or loosened. The flood tests still assert contains_goaway_with_error(ENHANCE_YOUR_CALM); the large-body tests still assert body_bytes == gzipped_len and sha256 == expected_hex. The fix removes the race between the test's synthetic work and sozu's legitimate peer-close without affecting what we assert on the wire.

Local validation (release mode, 3 iterations each via repeat_until_error_or):

Test Result
test_h2_ping_flood_triggers_goaway ok 1 passed in 15.0 s
test_h2_settings_flood_triggers_goaway ok 1 passed in 3.5 s
test_h2_rapid_reset_triggers_goaway ok 1 passed in 15.0 s
test_h2_continuation_flood_triggers_goaway ok 1 passed in 17.6 s
test_h2_large_gzipped_chunked_drains_fully ok 1 passed in 8.8 s
test_h2_large_chunked_7mb_drains_fully ok 1 passed in 8.7 s

cargo +nightly fmt --all -- --check and cargo clippy --all-targets --locked -- -D warnings both clean. CI watch: run 24914367604.


Test plan

  • cargo test --workspace — all tests pass (222 mux unit tests, +3 new MadeYouReset cases in Round 10, +4 Readiness::arm_writable pair tests in Round 11; Round 10b and Round 12 add further unit + e2e coverage — see per-round bullets)
  • cargo clippy --workspace --all-features — no warnings
  • cargo +nightly fmt — formatted
  • h2spec 2.0 conformance: test_h2spec_conformance shells out to the external h2spec binary. Round 13 lands the fix; the test is now un-ignored and passes 145/145/0/0 in 0.95 s on the branch. CI installs the prebuilt h2spec v2.6.0 binary in each matrix leg; the test still gracefully skips when the binary is missing, so legs without the install step do not block the suite.
  • E2E: baseline grew from 227 → 231 through Round 11, further through Rounds 10b / 12 / 13 (Round 10b adds priority-stall repros, H1 chunked-trailer forwarding, raw-H2 :status/1xx assertions, backend-disconnect stress, large-asset + ChunkedFlushH1Backend; Round 12 un-ignores five previously gated tests and adds two 7.7 MB gzipped-truncation guards; Round 13 un-ignores test_h2spec_conformance and tightens 17 permissive stream-scope asserts + 2 partial). No e2e tests remain #[ignore]d on this branch.
  • CI flake stabilisation (Round 14): drain helper + flood family write-race eliminated. All six previously-flaky tests green locally in release mode, fmt --check clean, clippy -D warnings clean. No test ignored, disabled, or loosened — wire assertions (GOAWAY(ENHANCE_YOUR_CALM), body sha256, body_bytes == expected) preserved.
  • Zero panic paths verified (0 unwrap/expect/unreachable/assert in production code)
  • Manual H2 testing with curl --http2 against production-like config
  • Load testing with sustained H2 traffic
  • Verify WebSocket upgrade path through Mux layer
  • Lisa threat-hunt swarm (5 parallel angles + auditor) on the Round-10 logging refactor — findings folded into this round
  • Round 11 dual-pass review on a real production HAR; convergent file:line citations, zero CRITICAL/HIGH findings from the reviewer/auditor passes

Credits

Original mux architecture: @Edemolis (Eloi Demolis) — mux_v1 branch
H2↔H2 SETTINGS & H1→H2 upgrade: @hcaumeil (Helian Caumeil)
Earlier H2 prototype: Geoffroy Couprie (lib/src/protocol/h2/)

Closes

Closes #99, #540, #543, #858, #888, #899, #978, #979, #980, #1145, #1217

FlorentinDUBOIS added a commit that referenced this pull request Mar 9, 2026
- Use standard HTTP reason phrases in default answers (e.g., "Not Found"
  for 404, "Bad Gateway" for 502) instead of generic "Sozu Default Answer"
- Use HTTP/1.1 version in default answers instead of H2
- Remove extra Content-Length: 0 from error responses to match old behavior
- Fix cookie header matching in HPACK decoder: compare against "cookie"
  instead of debug artifact "cookie---", forward cookies as regular headers
- Add #[repr(u32)] with explicit RFC 7540 error codes to H2Error enum
- Remove stale commented-out nom macro parser code
- Fix typo "trat" -> "treat" in parser comment
- Document the http2 proto field on Cluster message

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS FlorentinDUBOIS changed the title feat(h2): HTTP/2 support via multiplexed Mux session feat(h2): HTTP/2 support via unified Mux session Mar 10, 2026
@FlorentinDUBOIS FlorentinDUBOIS changed the title feat(h2): HTTP/2 support via unified Mux session feat(h2): HTTP/2 support via unified Mux session layer Mar 10, 2026
@FlorentinDUBOIS FlorentinDUBOIS self-assigned this Mar 10, 2026
FlorentinDUBOIS added a commit that referenced this pull request Mar 10, 2026
- Use standard HTTP reason phrases in default answers (e.g., "Not Found"
  for 404, "Bad Gateway" for 502) instead of generic "Sozu Default Answer"
- Use HTTP/1.1 version in default answers instead of H2
- Remove extra Content-Length: 0 from error responses to match old behavior
- Fix cookie header matching in HPACK decoder: compare against "cookie"
  instead of debug artifact "cookie---", forward cookies as regular headers
- Add #[repr(u32)] with explicit RFC 7540 error codes to H2Error enum
- Remove stale commented-out nom macro parser code
- Fix typo "trat" -> "treat" in parser comment
- Document the http2 proto field on Cluster message

Signed-off-by: Florentin Dubois <[email protected]>
Co-authored-by: Eloi Demolis <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the feat/h2-mux branch 2 times, most recently from 9eab7f3 to 2a65aa7 Compare March 10, 2026 14:54
@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator Author

Works on cleverapps.io, everything seems fine, need more time in production, but this implementation seems promising

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator Author

It seems that there are some trick about the net I/O counters, but the other one are good, I also note that epoll and service time are on the same base between 1.0, 1.1 and the current branch, which is really nice

image

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator Author

Spike on services, are massive load state on restart

FlorentinDUBOIS added a commit that referenced this pull request Mar 13, 2026
Critical fixes:
- C-1: MAX_CONCURRENT_STREAMS now checks per-connection stream count
  (self.streams.len()) instead of global context.active_len()
- C-2: Parser rejects SETTINGS ACK with non-zero payload as
  FRAME_SIZE_ERROR (RFC 9113 §6.5 defense-in-depth)
- C-3: update_initial_window_size uses i64 intermediate math to
  prevent overflow on large deltas

High-priority fixes:
- H-1: RefusedStream sends RST_STREAM (stream error) instead of
  GOAWAY (connection error) per RFC 9113 §5.1.2
- H-3: Bounds check on storage.end before CONTINUATION header removal
- H-4: Use saturating_sub for active_requests decrement
- H-5: Buffer space checks before SETTINGS ACK and PING writes
- H-6: H1→H2 header name validation rejects control chars/high bytes
- H-7: Cap pending_window_updates at 202 entries

Medium-priority fixes:
- M-1: new_stream_id returns Option with exhaustion check
- M-2: Reuse lowercase_buf across converter calls
- M-3: Defensive .max(0) before casting window to usize
- M-5: Flood detector uses half-decay instead of full reset
- M-6: Skip pushing back zero-length chunks after split
- M-7: Skip Content-Length: 0 for 1xx/204/304 responses
- M-8: SETTINGS_ACK timeout checked in writable() too

Low-priority fixes:
- L-1: Replace Clone::clone() with to_owned() on strings
- L-3: H2FloodDetector fields now pub(super)
- L-4: Remove dead reuse_connecting variable

Tests:
- 12 unit tests for parser (SETTINGS ACK, WINDOW_UPDATE bounds,
  unknown frames, frame size validation)
- 3 e2e tests (max concurrent streams RST, window overflow,
  empty DATA flood CVE-2019-9518)

Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Mar 15, 2026
- Use standard HTTP reason phrases in default answers (e.g., "Not Found"
  for 404, "Bad Gateway" for 502) instead of generic "Sozu Default Answer"
- Use HTTP/1.1 version in default answers instead of H2
- Remove extra Content-Length: 0 from error responses to match old behavior
- Fix cookie header matching in HPACK decoder: compare against "cookie"
  instead of debug artifact "cookie---", forward cookies as regular headers
- Add #[repr(u32)] with explicit RFC 7540 error codes to H2Error enum
- Remove stale commented-out nom macro parser code
- Fix typo "trat" -> "treat" in parser comment
- Document the http2 proto field on Cluster message

Signed-off-by: Florentin Dubois <[email protected]>
Co-authored-by: Eloi Demolis <[email protected]>
Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Mar 15, 2026
Critical fixes:
- C-1: MAX_CONCURRENT_STREAMS now checks per-connection stream count
  (self.streams.len()) instead of global context.active_len()
- C-2: Parser rejects SETTINGS ACK with non-zero payload as
  FRAME_SIZE_ERROR (RFC 9113 §6.5 defense-in-depth)
- C-3: update_initial_window_size uses i64 intermediate math to
  prevent overflow on large deltas

High-priority fixes:
- H-1: RefusedStream sends RST_STREAM (stream error) instead of
  GOAWAY (connection error) per RFC 9113 §5.1.2
- H-3: Bounds check on storage.end before CONTINUATION header removal
- H-4: Use saturating_sub for active_requests decrement
- H-5: Buffer space checks before SETTINGS ACK and PING writes
- H-6: H1→H2 header name validation rejects control chars/high bytes
- H-7: Cap pending_window_updates at 202 entries

Medium-priority fixes:
- M-1: new_stream_id returns Option with exhaustion check
- M-2: Reuse lowercase_buf across converter calls
- M-3: Defensive .max(0) before casting window to usize
- M-5: Flood detector uses half-decay instead of full reset
- M-6: Skip pushing back zero-length chunks after split
- M-7: Skip Content-Length: 0 for 1xx/204/304 responses
- M-8: SETTINGS_ACK timeout checked in writable() too

Low-priority fixes:
- L-1: Replace Clone::clone() with to_owned() on strings
- L-3: H2FloodDetector fields now pub(super)
- L-4: Remove dead reuse_connecting variable

Tests:
- 12 unit tests for parser (SETTINGS ACK, WINDOW_UPDATE bounds,
  unknown frames, frame size validation)
- 3 e2e tests (max concurrent streams RST, window overflow,
  empty DATA flood CVE-2019-9518)

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator Author

So, it runs on cleverapps.io, we identified two main issues which are now fixed or in progress to be fixed.

  • Cookie header was malformed in the conversion from h2 to h1, as in h1, we must have one Cookie header and multiple values, have to be aggregate using '; '.
  • There is a stale buffer on close-delimited response from backend when payload are quite huge which was not properly read and transmit until the end.

FlorentinDUBOIS added a commit that referenced this pull request Mar 17, 2026
- Use standard HTTP reason phrases in default answers (e.g., "Not Found"
  for 404, "Bad Gateway" for 502) instead of generic "Sozu Default Answer"
- Use HTTP/1.1 version in default answers instead of H2
- Remove extra Content-Length: 0 from error responses to match old behavior
- Fix cookie header matching in HPACK decoder: compare against "cookie"
  instead of debug artifact "cookie---", forward cookies as regular headers
- Add #[repr(u32)] with explicit RFC 7540 error codes to H2Error enum
- Remove stale commented-out nom macro parser code
- Fix typo "trat" -> "treat" in parser comment
- Document the http2 proto field on Cluster message

Signed-off-by: Florentin Dubois <[email protected]>
Co-authored-by: Eloi Demolis <[email protected]>
Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Mar 17, 2026
Critical fixes:
- C-1: MAX_CONCURRENT_STREAMS now checks per-connection stream count
  (self.streams.len()) instead of global context.active_len()
- C-2: Parser rejects SETTINGS ACK with non-zero payload as
  FRAME_SIZE_ERROR (RFC 9113 §6.5 defense-in-depth)
- C-3: update_initial_window_size uses i64 intermediate math to
  prevent overflow on large deltas

High-priority fixes:
- H-1: RefusedStream sends RST_STREAM (stream error) instead of
  GOAWAY (connection error) per RFC 9113 §5.1.2
- H-3: Bounds check on storage.end before CONTINUATION header removal
- H-4: Use saturating_sub for active_requests decrement
- H-5: Buffer space checks before SETTINGS ACK and PING writes
- H-6: H1→H2 header name validation rejects control chars/high bytes
- H-7: Cap pending_window_updates at 202 entries

Medium-priority fixes:
- M-1: new_stream_id returns Option with exhaustion check
- M-2: Reuse lowercase_buf across converter calls
- M-3: Defensive .max(0) before casting window to usize
- M-5: Flood detector uses half-decay instead of full reset
- M-6: Skip pushing back zero-length chunks after split
- M-7: Skip Content-Length: 0 for 1xx/204/304 responses
- M-8: SETTINGS_ACK timeout checked in writable() too

Low-priority fixes:
- L-1: Replace Clone::clone() with to_owned() on strings
- L-3: H2FloodDetector fields now pub(super)
- L-4: Remove dead reuse_connecting variable

Tests:
- 12 unit tests for parser (SETTINGS ACK, WINDOW_UPDATE bounds,
  unknown frames, frame size validation)
- 3 e2e tests (max concurrent streams RST, window overflow,
  empty DATA flood CVE-2019-9518)

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the feat/h2-mux branch 2 times, most recently from 145847b to 219d6ee Compare March 17, 2026 14:37
@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator Author

I think the new 5s H2 shutdown timeout changes soft_stop from graceful drain to a hard deadline for in-flight requests.

In Mux::shutting_down(), Linked streams correctly keep can_stop = false, but once started_at.elapsed() > 5s the code still returns true and closes the session. The new test test_h2_graceful_shutdown_timeout_forces_close also codifies this by keeping a backend request active for 30s and asserting the worker exits within 8s.

That means a slow but healthy H2 upload/download/stream can now be truncated during soft_stop, which seems contrary to the intended semantics of graceful shutdown: stop accepting new streams, let existing ones finish, then close the connection cleanly.

The flush retry and quiesced-stream fixes make sense to me. The 5s forced close does not, unless soft_stop is intentionally being redefined as a bounded deadline rather than a graceful drain.

The `Crypto providers` matrix at lines 32-48 advertised three Cargo
features (`crypto-ring`, `crypto-aws-lc-rs`, `crypto-openssl`) that
do not exist in this workspace. `rustls` is wired to `ring` through
the workspace `Cargo.toml`; there is no pluggable provider surface
today. The "`--all-features` does not work" warning was also untrue
on this branch — `cargo build --all-features --locked` succeeds.

Replace the section with a `Cargo features` table that lists the
flags actually published (`tolerant-http1-parser`, `simd`, `splice`,
`opentelemetry`, `logs-debug`, `logs-trace`, `e2e-hooks`) and points
readers at the per-crate `Cargo.toml` for the authoritative source.
The 16393 buffer-size note in the `HTTP/2 support` section is left
untouched.

Signed-off-by: Florentin Dubois <[email protected]>
`sozuctl` was folded into the `sozu` CLI long ago; the audit-log
documentation still cited it as the actor `comm` value in two
example payloads (lines 223, 302) and in two prose bullets (lines
239, 242).

Rewrite the four sites: `actor_comm=sozuctl` and the JSON
`"comm": "sozuctl"` become `actor_comm=sozu` / `"comm": "sozu"` so
they match what `/proc/<pid>/comm` actually returns from the CLI
today, and the prose bullets describe the binary as the `sozu`
command-socket client (the `sozu` binary running with the
`command` sub-command) instead of `sozuctl`.

Signed-off-by: Florentin Dubois <[email protected]>
The mux module-layout table was frozen at the pre-rewrite shape
(7 modules, 11 178 lines). HEAD ships 13 modules totalling 18 666
lines (`wc -l lib/src/protocol/mux/*.rs`). Refresh the table to the
current per-file counts (mod 1818, h1 823, h2 7562, parser 2246,
serializer 557, converter 1410, pkawa 2229) and add the missing rows
for `connection.rs` (578), `router.rs` (678), `stream.rs` (290),
`answers.rs` (302), `shared.rs` (93), `debug.rs` (80).

Three permalinks pointed at long-stale SHAs
(`01a78be7…/lib/src/lib.rs#L527`, `3111e2db…/lib/src/logging.rs`,
`3111e2db…/lib/src/network/metrics`); the cited paths have moved
(`logging` lives under `command/src/logging`, `metrics` under
`lib/src/metrics`). Rewrite the three permalinks to point at the
current `main`-branch paths.

Add a single-line note under "Key design decisions" referencing the
on-branch `lib/src/protocol/mux/LIFECYCLE.md`, and clarify under
"H2 backend (h2c)" that `cluster.http2` is a backend-capability hint
and does NOT gate frontend H2 (frontend H2 is TLS-ALPN driven).

Signed-off-by: Florentin Dubois <[email protected]>
Drop the literal `TODO` under "Release Notes" and link the project
`CHANGELOG.md` instead. Add bullets for the seven previously-unlinked
docs (`configure_cli.md`, `debugging_strategies.md`, `lexicon.md`,
`observability.md`, `benchmark.md`, `rate-limit-design.md`,
`nightly-ci-notes.md`) and `configure_admin_ops.md` (planned for the
admin-ops narrative pass).

Reorganise into "Operating Sōzu" (config + admin + observability +
debugging + bench + rate-limit) and "Going deeper" (mux internals +
in-tree LIFECYCLE.md + lifetime-of-a-session). Add a link from
"Going deeper" to `lib/src/protocol/mux/LIFECYCLE.md` so readers can
cross-reference the in-tree state-machine notes that ship alongside
the code.

Signed-off-by: Florentin Dubois <[email protected]>
Part A — module-level //! headers across 34 files: mux (converter, h1,
h2, parser, pkawa, serializer), protocol/mod, kawa_h1 (mod, answers,
editor, parser, diagnostics), proxy_protocol (mod, expect, header,
parser, relay, send), pipe, rustls, https, socket, metrics/mod,
command (channel, scm_socket, buffer/{mod,fixed,growable}), bin
(upgrade, command/{mod, server, sessions, requests}), and the two
fuzz targets. Texts cite RFC sections, sibling modules, or the
canonical write-up they delegate to.

Part B — load-bearing invariant comments at six previously
undocumented sites:
- mux/mod.rs 16-iteration drain loop: explain the missing
  invariant-15 hop and cross-link mux/LIFECYCLE.md;
- mux/connection.rs //!: point at mux/h2.rs as the canonical home
  for the edge-trigger discipline;
- write-only shutdown invariant on the three undocumented call
  sites (mux/mod.rs backend ×2, http.rs frontend);
- FrontRustls::socket_write + socket_write_vectored symmetry
  contract with regression-test pointer (h2_correctness_tests +
  h2_tests::test_h2_large_*);
- command/src/config.rs H2_MIN_BUFFER_SIZE enforcement: cross-link
  mux/LIFECYCLE.md;
- e2e/src/tests/mod.rs //!: narrow serial_test::serial(force_h2_
  client_failure) discipline to e2e-hooks AtomicBool toggles only.

No behaviour changes. Validates: cargo +nightly fmt --check, cargo
build --all-features --locked, cargo clippy --all-targets --locked,
( cd fuzz && cargo +nightly check ).

Signed-off-by: Florentin Dubois <[email protected]>
Annotate the 63 previously-undocumented `unsafe { … }` blocks across the
worker, supervisor, and command-channel paths with explicit `// SAFETY:`
comments. Annotation only — no block body changes, no new or removed
`unsafe`. Each annotation states the precondition the block relies on and
points back to the upstream source of truth (call site, parser invariant,
sibling `Drop`).

Family breakdown: 14 `from_raw_fd` ownership transfers (server, scm,
upgrade, util, worker, command/server), 6 `from_utf8_unchecked` ASCII /
UTF-8 proofs (http, https, kawa_h1/parser, access_logs OpenTelemetry),
5 raw-pointer `DuplicateOwnership` impls + `into_binary_access_log` (with
the double-free obligation called out per type-level guidance at
`access_logs.rs:26`), 15 overlap-safe `ptr::copy` calls (buffer/fixed,
buffer/growable, pool), and 23 syscall / FFI sites (`getpid`, `fork`,
`getrlimit`/`setrlimit`, `sched_setaffinity`, `getsockopt`,
`sendmmsg`, `env::set_var`, `BorrowedFd::borrow_raw`, `from_raw_fd`
borrow-then-release).

Parity (dynamic): `unsafe_n=69`, `safety_n=69`. The expected delta is
`safety = unsafe + 1` because `kawa_h1/mod.rs:1211` carries a SAFETY
comment over a non-`unsafe` `Shutdown::Both` (the TLS-truncation
invariant). Counted via:

  unsafe_n=$(git grep -cE 'unsafe[[:space:]]*\{' lib/src command/src bin/src \
             | awk -F: '{s+=$2}END{print s}')
  safety_n=$(git grep -cE '// SAFETY' lib/src command/src bin/src \
             | awk -F: '{s+=$2}END{print s}')

Validation: `cargo +nightly fmt --check`, `cargo build --all-features
--locked`, `cargo clippy --all-targets --locked` (no new warnings),
`cargo test --all-features --locked` (805 passed, 9 ignored across 10
suites).

Signed-off-by: Florentin Dubois <[email protected]>
Sweep the last six in-source `sozuctl` references in the supervisor
surface so the renamed `sozu` CLI is consistent with the prose work
already done in C2 (`RELEASE.md`/`CONTRIBUTING.md`) and C6
(`doc/observability.md`):

- `bin/src/command/server.rs`: two doc comments on `peer_comm` (the
  per-accept `/proc/<pid>/comm` reader behind LISA-009).
- `bin/src/command/sessions.rs`: two field-doc comments on
  `ClientSession::session_ulid` and `actor_comm`.
- `bin/src/command/requests.rs`: one comment in the `audit_log_context!`
  macro doc and one test-fixture string in the audit-format tests.

`/proc/<pid>/comm` is capped at 15 chars by the kernel, so the
fixture stays short ("sozu"); prose uses "sozu CLI" or
"sozu command-socket client" depending on context. Pure comment +
test-fixture-string churn — no functional change.

Acceptance:
- `git grep -n 'sozuctl' bin/ doc/ command/ lib/ e2e/`: zero matches.
- `git grep -n '"sozuctl"' bin/ command/ lib/ e2e/`: zero matches.
- `cargo test -p sozu --all-features --locked`: 18 passed.

Signed-off-by: Florentin Dubois <[email protected]>
Add the maintainer-facing siblings to lib/src/protocol/mux/LIFECYCLE.md
plus an operator-facing admin-ops worked-examples doc and a fuzz
crate README that stays honest about the absent OSS-Fuzz wiring.

New files:

- lib/src/protocol/kawa_h1/LIFECYCLE.md (270 lines)
  H1 frontend / H1 backend lifecycle: per-stream accept → parse → route
  → backend connect → response stream → keep-alive → close, the
  HttpContext editor pass, the DefaultAnswer template machinery, the
  diagnostics envelope, and the load-bearing invariants (no panic on
  network input; write-only TLS shutdown; H1 readiness lifecycle owned
  by the editor; tolerant-http1-parser opt-in). Cross-links the mux
  LIFECYCLE for the H2 path.

- lib/src/protocol/proxy_protocol/LIFECYCLE.md (199 lines)
  Three-role narrative (expect ingress, relay forwarding, send synth)
  with v1 vs v2 wire-format reminder, the per-state machine, and the
  hardening rules (bounded 232-byte buffer, fast-close on bare-TCP
  healthchecks, MAX_LOOP_ITERATIONS ceiling, error counters on every
  reject, no panic on adversarial input).

- bin/src/command/LIFECYCLE.md (283 lines)
  Supervisor lifecycle: begin_main_process → main loop → shutdown /
  re-exec; the SO_PEERCRED accept envelope (ULID, actor_uid/gid/pid,
  PID-reuse-guarded actor_comm, cached actor_user, socket_path,
  connect_ts); verb dispatch and worker fan-out; hot-upgrade
  interaction. Recent additions subsection groups the post-feat/h2-mux
  hardening: command_allowed_uids admission, audit-log envelope (text
  + JSON sinks, sanitize_for_audit chokepoint), Lisa LISA-009
  PID-reuse guard, drop-on-register-fail.

- fuzz/README.md (225 lines)
  Crate layout, the two harnesses with bug classes (fuzz_frame_parser
  for the RFC 9113 length-confusion CVE family backing
  ensure_frame_size!; fuzz_hpack_decoder for RFC 7541 / loona-hpack
  oversize + incomplete-update flaws), local-run instructions,
  regression repro workflow, triage workflow that funnels findings to
  CODEOWNERS rather than directing readers to open issues, and an
  honest OSS-Fuzz section that records the absence of
  .clusterfuzzlite/ on this branch and outlines the integration steps
  per the ClusterFuzzLite docs.

- doc/configure_admin_ops.md (261 lines)
  Operator-facing worked-examples doc: patchable listener fields with
  preserve-on-omit semantics, tightening H2 flood thresholds under
  attack, toggling disable_http11 per listener, the
  cluster h2 enable|disable query-then-resubmit dance behind
  bin/src/ctl/request_builder.rs:214-238, plus an operational write-up
  (not a duplicate reference table) of the post-feat/h2-mux behaviours:
  per-connection stream-Vec shrink, channel message_len upper bound,
  drop-on-register-fail, SNI trailing-dot normalisation,
  https.alpn.rejected.unsupported counter, ensure_frame_size! macro.

Two patches to doc/configure.md:

- :65 — bump example buffer_size from 16384 to 16393 so the example
  matches the H2-enforced minimum already documented at :40.
- :939 — add a row for the https.alpn.rejected.unsupported counter
  alongside the existing https.alpn.rejected.http11_disabled, matching
  the SOC bucket noted in the operational write-up.

Validation:
- §2.5 grep on the six touched files: zero hits for tasks/ and zero
  hits for ~/.claude/, /home/florentin/.claude/, /tmp/.
- Markdown link sanity loop on all five new files: zero broken links.
- cargo build --all-features --locked: passes.

Signed-off-by: Florentin Dubois <[email protected]>
Replace the entire body of doc/lifetime_of_a_session.md (256 lines
from 2022-12, pinned to a removed-files SHA permalink and citing
modules that no longer exist on feat/h2-mux: lib/src/https_openssl.rs
and lib/src/protocol/http/mod.rs).

The new 500-line narrative covers the current architecture:
single-threaded mio worker, edge-triggered readiness contract, slab-
backed SessionManager, accept-queue + max_connections backpressure,
TLS handshake (rustls + ALPN dispatch with per-cause refusal metrics),
PROXY-protocol pre-flight, the three per-protocol session paths
(Kawa-backed H1, H2 mux with stream lifecycle + RFC 9218 priorities +
H2FloodDetector + GOAWAY draining, pipe pass-through), backend
routing + load balancing, edge-triggered forwarding pitfalls, the
TLS write-only shutdown invariant, hot reconfig + upgrades, and a
metrics sidebar.

Cross-links the four LIFECYCLE.md siblings introduced in C12
(mux/, kawa_h1/, proxy_protocol/, bin/src/command/). All cited
file:line references re-grepped at write time. No SHA-pinned
permalinks; legacy module names appear only in the §12
"Removed and migrated APIs" historical block.

Signed-off-by: Florentin Dubois <[email protected]>
Replace archived `actions-rs/*` actions with `dtolnay/rust-toolchain` +
direct cargo invocations, and add three new always-required jobs that
mirror the local validation baseline documented in CLAUDE.md "Build":

  * fmt     — `cargo +nightly fmt --all -- --check` (rustfmt.toml uses
              the unstable `ignore` key, so nightly is mandatory)
  * clippy  — `cargo clippy --all-targets --all-features --locked
              -- -D warnings` (option (a) chosen — see pre-flight below)
  * msrv    — `cargo build --all-features --locked` against
              `dtolnay/[email protected]`, advertising the MSRV
              declared in Cargo.toml `rust-version = "1.85.0"`. The
              `rust-toolchain` file still pins 1.88.0 for everyday
              development; this job verifies that 1.85.0 still builds.

The existing `test`, `doc`, and `dockerhub` jobs keep their semantics:
  * `test`: matrix stable/beta/nightly preserved; nightly stays
    `experimental: true`. The previously-undefined
    `${{ matrix.features }}` interpolation is replaced by an explicit
    `--all-features` flag, matching the rest of the workspace baseline.
    `protoc`, `cargo-fuzz`, and `h2spec` install steps are unchanged.
  * `doc`: same toolchain, same `cargo doc --verbose` output.
  * `dockerhub`: now carries an inline note that it tags `sozu:${SHA}`
    on every push and that release tagging lives in RELEASE.md.

Pre-flight clippy (option-decision per the C14 plan):
  cargo clippy --all-targets --all-features --locked -- -D warnings
  -> 0 warnings, 0 errors, exit 0.

The `clippy::if_same_then_else` warning that was historically present
in `e2e/src/tests/h2_correctness_tests.rs` is no longer reachable on
this branch (test file has been refactored repeatedly during the
H2 mux work), so option (a) — the strict `--all-features` clippy gate
— ships cleanly without any accompanying Rust source change. Option
(b) (drop `--all-features`) and option (c) (`#[allow]` directives)
were considered and rejected per the plan's safety ranking.

Local validation of the new gates:
  cargo +nightly fmt --all -- --check                                ok
  cargo build --all-features --locked                                 ok
  cargo clippy --all-targets --all-features --locked -- -D warnings   ok
  yamllint .github/workflows/ci.yml                                   no
                                                                      new
                                                                      findings
                                                                      vs.
                                                                      pre-existing
                                                                      baseline

No `actions-rs/*` remain (`grep -rn 'actions-rs' .github/` returns
zero hits).

Signed-off-by: Florentin Dubois <[email protected]>
Append two narrative sub-sections to the freshly regenerated
`feat/h2-mux - Unreleased` block summarising the documentation +
continuous-integration audit pass shipped in C1-C14:

- `### 📚 Documentation` (7 bullets) covers the README/RELEASE/CONTRIBUTING
  refresh, the `doc/` folder resync (crypto-providers section dropped,
  architecture line counts refreshed, observability audit examples
  rewritten, configure.md `buffer_size` example bumped, README index
  populated), the full rewrite of `doc/lifetime_of_a_session.md` cross-
  linking the new per-protocol LIFECYCLE.md siblings, the module-level
  `//!` doc headers across the previously-bare critical surfaces, the 63
  new `// SAFETY:` annotations (parity check `safety = unsafe + 1`), the
  load-bearing in-source invariant comments (16-iter drain loop,
  socket_write symmetry, write-only TLS-frontend shutdown rule, e2e
  serial_test discipline), the new narrative documents (kawa_h1 +
  proxy_protocol + bin/src/command LIFECYCLE.md, fuzz README with
  OSS-Fuzz roadmap, configure_admin_ops.md), and the comment-only
  sozuctl→sozu rename.

- `### 🤖 Continuous Integration` (4 bullets) covers the
  `actions-rs/*@v1` retirement (replaced by `dtolnay/rust-toolchain`),
  the new enforced `fmt` and `clippy` (`-D warnings`) jobs that were
  previously local-only conventions in CLAUDE.md, the new MSRV (1.85.0)
  build gate, and the noted clippy hygiene status (the
  `if_same_then_else` warning called out in CLAUDE.md is no longer
  reachable on this branch, so the `-D warnings` gate ships clean
  without a Rust-source change).

Validation:
- `git grep -nE '(^|[^/[:alnum:]])tasks/' -- CHANGELOG.md` → zero hits.
- `git grep -nE '(~/\.claude|/home/florentin/\.claude|/tmp)' -- CHANGELOG.md`
  → zero hits.
- All 7 relative `(...md)` links in the new bullets resolve to existing
  files: `doc/lifetime_of_a_session.md`, `doc/configure_admin_ops.md`,
  `fuzz/README.md`, `lib/src/protocol/{mux,kawa_h1,proxy_protocol}/LIFECYCLE.md`,
  `bin/src/command/LIFECYCLE.md`.
- `[Unreleased]: …compare/1.1.1...HEAD` Keep-a-Changelog footer line
  unchanged from C3.
- `cargo build --all-features --locked` succeeds (no Rust source changed).

Signed-off-by: Florentin Dubois <[email protected]>
The C14 GitHub Actions modernisation passed local validation but failed
in CI on the two new gates. Both failures were YAML config issues, not
warnings on the actual source code. Fix:

* fmt job — install `protobuf-compiler` and run `cargo +nightly check
  -p sozu-command-lib --locked` before `cargo +nightly fmt --all
  -- --check`. `command/build.rs` runs `prost-build`, which generates
  `command/src/proto/command.rs`. Without that file present, rustfmt
  fails to resolve `mod command;` while walking the module tree, even
  though `rustfmt.toml` lists the file in the `ignore` array.

* clippy job — switch the lint command from `cargo clippy ...` to
  `cargo +stable clippy ...`. The repo's `rust-toolchain` file pins
  `1.88.0`, which `cargo` honours by default and overrides the
  `dtolnay/rust-toolchain@stable` install. Stable does carry the
  `clippy` component installed alongside it; the explicit `+stable`
  toolchain selector points cargo at that toolchain.

Local toolchains pass without these steps because (a) prior workspace
builds leave the prost-generated file on disk, and (b) the local
`1.88.0` toolchain typically has clippy installed alongside it. CI's
fresh checkout reproduces neither.

The MSRV job (1.85.0 build) was already green; no change there.

Signed-off-by: Florentin Dubois <[email protected]>
The previous fix used `cargo +stable clippy` to bypass the
`rust-toolchain` pin, but stable 1.95 fires several lints that 1.88
does not (`clippy::derivable_impls` on `MetricDetailLevel` in
`command/src/config.rs`, `mismatched_lifetime_syntaxes` on five
parser/serializer functions in `lib/src/protocol/mux/`). CLAUDE.md
"Build" documents the workspace as warning-free under
`cargo clippy --all-targets --locked` (no `--all-features`); the
implicit baseline there is the pinned 1.88.0 toolchain.

Pin the CI clippy job to `dtolnay/[email protected]` with the
`clippy` component so the gate enforces the same baseline. Triaging
the newer-stable lints across the workspace is its own follow-up,
tracked alongside the eventual rust-toolchain bump.

Locally verified: `cargo clippy --all-targets --all-features --locked
-- -D warnings` on 1.88.0 → 0 issues.

Signed-off-by: Florentin Dubois <[email protected]>
Keep the router DebugEvent import behind debug_assertions so release all-feature bin builds do not warn while debug builds keep recording the route in DebugHistory.

Signed-off-by: Florentin Dubois <[email protected]>
Replace the stale post-1.1.1 generated index with current main..HEAD coverage for feat/h2-mux so reviewers can audit all 429 branch commits from one place.

Signed-off-by: Florentin Dubois <[email protected]>
Align the advertised MSRV of every workspace crate with the `1.88.0`
toolchain already pinned in `rust-toolchain`. The MSRV CI gate now
runs on `dtolnay/[email protected]`, the `rust-version` field is
bumped in `bin/`, `command/`, `e2e/`, and `lib/` manifests, and the
prose references in README.md and CLAUDE.md are updated in lockstep.

The corresponding "MSRV (1.88.0) build gate" line in CHANGELOG.md
was already refreshed under the unreleased feat/h2-mux section.

Signed-off-by: Florentin Dubois <[email protected]>
`cargo update --manifest-path fuzz/Cargo.toml` rolls the
out-of-workspace fuzz crate's `Cargo.lock` forward to the latest
patch / minor releases of transitive dependencies (icu_*,
hashbrown 0.16->0.17, indexmap 2.13->2.14, zerocopy 0.8.42->0.8.48,
rustls-pki-types 1.14.0->1.14.1, etc.). No direct dependency
versions or fuzz target behaviour changes; corpus + harness untouched.

The workspace `Cargo.lock` already tracks the same upstream
versions, so only the fuzz lockfile moves here.

Signed-off-by: Florentin Dubois <[email protected]>
Internal "Lisa LISA-XXX" tags from a private threat-modelling exercise
leaked into in-tree comments and the changelog. Drop the tokens while
preserving the technical rationale they prefixed: RFC citations, CWE
references, defense-in-depth notes, and PID-reuse / NSS-cache
mitigations now read on their own.

Touches comments and prose only — no code or behaviour change. Verified
with `cargo build --all-features --locked`, `cargo clippy
--all-features --all-targets --locked`, `cargo +nightly fmt --all --
--check`, and `cargo test --workspace --lib --bins` (781 passed).

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

2 participants