Repository navigation
feat: HTTP answer templates, URL rewrite, redirect, custom headers, basic auth - #1231
Merged
Merged
Conversation
…chema Lay the wire schema for the bundled feature work that brings PR #1206..#1210 onto current main. Wave 1 of a multi-wave implementation; subsequent waves land the runtime engine, mux integration, auth helper, e2e tests, and docs. Cluster gains four fields: per-cluster `answers` (status code → template body) at field 9, `https_redirect_port` at 10, `authorized_hashes` at 11, and `www_authenticate` realm at 12. RequestHttpFrontend gains eight: `redirect` policy at 8, `required_auth` at 9, `redirect_scheme` at 10, `redirect_template` at 11, `rewrite_host`/`rewrite_path`/`rewrite_port` at 12-14, and a repeated `headers` list at 15. Listener configs gain a parallel `answers` map at 31 (HttpListenerConfig) and 43 (HttpsListenerConfig); the legacy `CustomHttpAnswers http_answers` field is preserved on the wire so existing state files round-trip — the runtime will read both for one minor. New top-level enums RedirectPolicy / RedirectScheme / HeaderPosition and a Header message land alongside. An empty `Header.val` deletes the named header (HAProxy `del-header` parity). prost stops auto-deriving Hash/Eq once a message holds a map field, so the build script gains explicit `#[derive(Hash, Eq)]` for Cluster, HttpListenerConfig, HttpsListenerConfig, UpdateHttpListenerConfig, and UpdateHttpsListenerConfig. Existing initializers grow a `..Default::default()` fallthrough so this commit is a pure additive scaffolding step — no runtime behaviour changes yet. Signed-off-by: Florentin Dubois <[email protected]>
Surface the proto schema added in 344ab13 through the file-backed config layer. New TOML keys land on `[clusters.<id>]` (`answers`, `https_redirect_port`, `authorized_hashes`, `www_authenticate`), per-frontend (`redirect`, `redirect_scheme`, `redirect_template`, `rewrite_host`, `rewrite_path`, `rewrite_port`, `required_auth`, `[[..headers]]`), and on each listener as `[listeners.answers]`. Strings are parsed case-insensitively into the proto enums; an unknown value surfaces a typed `ConfigError` (`InvalidRedirectPolicy`, `InvalidRedirectScheme`, `InvalidHeaderPosition`) so the operator gets a clear diagnostic instead of a silent default. Listener answer maps merge legacy per-status `answer_NNN` paths and the new `[listeners.answers]` map; the explicit map wins on collision so operators can override one entry without re-listing the rest. A new `load_answers` helper reads each path off disk and emits the body map that the proto field expects, mirroring the existing `read_http_answer_file` flow used by the legacy fields. A new `HeaderEditConfig` is the TOML face of the proto `Header`; `parse_header_edit` translates it. An empty `value` is preserved verbatim so the runtime can apply HAProxy `del-header` parity (empty val deletes the header by name). `generate_requests` for `HttpFrontendConfig`, `HttpClusterConfig`, and `TcpClusterConfig` populate the new proto fields end-to-end so the control plane round-trips a complete config back to a worker once the runtime side lands. Signed-off-by: Florentin Dubois <[email protected]>
Replace the rigid per-status `CustomHttpAnswers` plumbing with a configurable template engine. Templates are looked up by HTTP status code (`"503"`) and rendered with placeholder substitution at response time. The engine is shared between the legacy kawa_h1 surface and the live mux path because `mux/answers.rs` re-uses `kawa_h1::HttpAnswers` and `DefaultAnswer`. Templates support a small variable grammar: - repeatable variables (`%ROUTE`, `%REQUEST_ID`, `%CLUSTER_ID`, `%BACKEND_ID`, `%DURATION`, `%CAPACITY`, `%PHASE`, `%SUCCESSFULLY_PARSED`, `%PARTIALLY_PARSED`, `%INVALID`) - single-use variables (`%REDIRECT_LOCATION`, `%MESSAGE`, `%TEMPLATE_NAME`) - a new `%WWW_AUTHENTICATE` (header-only, `or_elide_header = true`) so the upcoming basic-auth path can drop the `WWW-Authenticate` header line when no realm is configured. - `Content-Length` is auto-injected from the rendered body size. `HttpAnswers::new` now takes `&BTreeMap<String, String>` instead of an `Option<CustomHttpAnswers>`. `HttpAnswers::get` returns `(u16, bool, DefaultAnswerStream)` — the keep-alive flag is inferred from the rendered template (false when `Connection: close` is present), so the mux can preserve backend keep-alive across default answers when the operator's template asks for it. `DefaultAnswer::Answer401` now carries an optional `www_authenticate` realm fed into the template's `%WWW_AUTHENTICATE` slot. Per-cluster overrides flow through `add_cluster_answers` / `remove_cluster_answers`, called from the proxy-side `add_cluster` / `remove_cluster` hooks in `lib/src/http.rs` and `lib/src/https.rs`. Each listener still merges legacy `CustomHttpAnswers` into the new map at boot and on patch via `merge_legacy_into_map`, so existing state files round-trip cleanly. Patching the listener's `answers` field at runtime preserves the existing per-cluster override registry across the rebuild. The `or_elide_header` check uses `pair.val.len() == 0` (not `pair.val.is_empty()`) because `kawa::Store::is_empty` reports the enum variant rather than the byte length of the held data. 424 sozu-lib unit tests pass, including new coverage for template parse, fill, header elision, and per-cluster override hot-swap. Signed-off-by: Florentin Dubois <[email protected]>
…choring
Replace the bare cluster-id routing decision with a richer shape that the
mux layer (Wave 3a) can consume to drive redirects, URL rewrites, custom
header injection, and per-frontend auth gating.
`Frontend` carries the per-frontend policy: redirect (FORWARD / PERMANENT
/ UNAUTHORIZED), redirect_scheme (USE_SAME / USE_HTTP / USE_HTTPS),
optional redirect_template, rewrite_host / rewrite_path / rewrite_port
parsed into `RewriteParts`, request- and response-side `Rc<[HeaderEdit]>`
slices, `required_auth`, and an optional `Rc<CachedTags>` for log
correlation. Clusterless `Forward` policies are coerced to `Unauthorized`
inside `Frontend::new` to prevent forward loops.
`RouteResult` is the value `Router::lookup` returns: the same per-frontend
policy plus the *resolved* (substituted) rewritten host/path. Two
constructors keep legacy callers compiling without ceremony:
`RouteResult::forward(cluster_id)` for `Route::ClusterId` adapters and
`RouteResult::deny(cluster_id)` for `Route::Deny`. Existing match-arm
sites in `kawa_h1::Http::cluster_id_from_request` and
`mux::router::route_from_request` collapse `RouteResult` down to its
`cluster_id` for now; Wave 3a will plumb every field through
`apply_route_decision`.
`RewriteParts` parses `$HOST[n]` / `$PATH[n]` placeholder templates at
frontend-registration time into a `Vec<RewritePart>` and substitutes them
at lookup time against the captures collected during trie traversal.
Empty rewrite templates are coerced to `None` so we never store an empty
`Rc<[…]>`. Out-of-bounds capture indices substitute the empty string.
`pattern_trie` segment regexes are now wrapped with `\A...\z` at
insertion so a pattern like `cdn[0-9]+` matches `cdn1` exactly but not
`cdn1xxx`. Existing match arms that compared raw regex strings now
anchor their lookup string symmetrically. Two new types,
`TrieSubMatch::{Wildcard, Regexp}` and `TrieMatches`, propagate the
non-literal segments matched during traversal so callers can re-run
`Regex::captures` on the matched bytes (consumed by
`RouteResult::new_with_trie`). A new `lookup_with_path` mirrors `lookup`
but returns the visited submatches alongside the leaf value.
`L7ListenerHandler::frontend_from_request` now returns
`Result<RouteResult, FrontendFromRequestError>`. The HTTP and HTTPS impls
in `lib/src/http.rs` and `lib/src/https.rs` flow the lookup result
through unchanged. Test fixtures comparing the lookup against
`Route::ClusterId(...)` use the new `RouteResult::forward(...)` /
`RouteResult::deny(None)` synthesizers; `CachedTags` gains a
`PartialEq + Eq + Clone` derive so the equality holds.
A new `log_module_context!` at the top of `router/mod.rs` keeps the
single existing `warn!` call site on the `[ROUTER] >>>` envelope so the
build-time log-layout regression watcher stays clean.
424 sozu-lib unit tests pass; clippy and nightly fmt are clean.
Signed-off-by: Florentin Dubois <[email protected]>
Introduce the constant-time comparison primitive that Wave 3a will plug into `apply_route_decision`. The new module owns three small surfaces: - `extract_authorization_header` walks the front kawa once, case- insensitively matches `Authorization`, and returns the raw value bytes. Handles elided headers gracefully and never panics on hostile input. - `canonicalize_basic_credentials` decodes a `Basic <token>` value, base64-decodes the token, splits on the first `:`, hashes the password with SHA-256, and emits the canonical `<user>:<hex(sha256)>` form that matches every entry in `Cluster.authorized_hashes`. Caps the decoded payload at 4 KiB so a hostile peer can't force the worker to allocate unbounded transient buffers per failed attempt. - `check_authorized_hashes` compares the canonical form against every entry in the cluster's hash list using `subtle::ConstantTimeEq`, iterating the entire slice on every call (no early exit) so the time spent does not leak which entry matched or whether any did at all. Mitigates timing side-channel attacks on the credential boundary (CWE-208 family, specifically the credential-comparison flavour PR #1210's review fix `171a31ce` was hardening). `check_basic` is the convenience entry point the mux will call: header → canonicalise → constant-time compare. Empty cluster lists short-circuit to `false` so a frontend with `required_auth = true` on a cluster with no `authorized_hashes` reliably returns 401. Workspace gains `base64 = ^0.22.1` and `subtle = ^2.6.1`; only `sozu-lib` pulls them in, so the command-lib and e2e crates stay unaware. `Cargo.lock` refresh is included so `cargo vendor --locked` keeps the Docker build green. 10 unit tests cover round-trip canonicalisation, scheme case-insensitivity, non-Basic schemes, malformed base64, missing colon, oversized payload, matching at any list position, wrong-password rejection, and empty list. Signed-off-by: Florentin Dubois <[email protected]>
Plumb the rich `RouteResult` shape from Wave 2b into the mux's central `route_from_request` so the new policy fields actually influence the default-answer chokepoint, not just the cluster lookup. `HttpContext` gains two stash slots: `redirect_location` (consumed by the 301 default-answer path so the rendered `Location` header carries the fully resolved URL — including `cluster.https_redirect_port` and the frontend's `redirect_scheme`) and `www_authenticate` (consumed by the 401 default-answer path so the `WWW-Authenticate` header reflects the cluster's configured realm; an empty / `None` realm leaves the template to elide the header entirely). `mux/answers.rs::default_answer_for_code` becomes a pure builder that takes the redirect URL and realm as parameters; `set_default_answer` prefers the routing-layer-supplied location over the legacy `https://<authority><path>` shape so per-frontend redirect targets land on the wire. `route_from_request` itself now: * honours `RedirectPolicy::UNAUTHORIZED` and clusterless deny by stashing the realm and returning `RetrieveClusterError::UnauthorizedRoute`; * honours `RedirectPolicy::PERMANENT` by computing the resolved `Location` URL via `resolve_redirect_scheme` + `build_redirect_location` (port-suffix elision for default 80/443) and returning `RetrieveClusterError::HttpsRedirect`; * keeps the legacy `cluster.https_redirect = true` path working while threading `cluster.https_redirect_port` through the same builder so HTTP→HTTPS redirects can target a non-standard listener port; * runs `mux::auth::check_basic` when the frontend has `required_auth`, failing closed with the cluster's realm stashed for the 401 response. The auth check needs read access to the request kawa; `connect`'s borrow of the stream is split so `route_from_request` can take both `&mut HttpContext` and `&GenericHttpStream` without aliasing. 434 sozu-lib unit tests pass; clippy and nightly fmt are clean. Signed-off-by: Florentin Dubois <[email protected]>
…te, auth Three new sections in `doc/configure.md`: * "Custom HTTP answer templates" describes the `[listeners.answers]` and `[clusters.<id>.answers]` map shape and the variable substitution grammar (`%STATUS_CODE`, `%REQUEST_ID`, `%CLUSTER_ID`, `%BACKEND_ID`, `%ROUTE`, `%REDIRECT_LOCATION`, `%WWW_AUTHENTICATE`, etc.). Calls out HAProxy `errorfile NNN /path` parity and explains the `Content-Length` auto-injection plus the `Connection: close` opt-out for keep-alive. * "Frontend redirect, URL rewrite, and custom headers" documents `redirect` / `redirect_scheme` / `redirect_template` / `rewrite_host` / `rewrite_path` / `rewrite_port`, the `$HOST[n]` / `$PATH[n]` capture grammar, the `X-Forwarded-Host` injection on host rewrite, and the per-frontend header-edits map. Empty `value` deletes the header by name for HAProxy `del-header` parity. * "HTTP Basic authentication on a frontend" walks the operator through generating an `authorized_hashes` entry with `sha256sum`, pairing it with `www_authenticate`, and gating a frontend with `required_auth`. Documents the four 401 failure modes and the closed-by-default policy when `authorized_hashes` is empty. Explains that the constant-time comparison covers the timing side-channel. `CHANGELOG.md` gains a `feat/answer-templates-rewrite-auth - Unreleased` section above the existing `feat/h2-mux` entry. The new section catalogues: * `Added` paragraphs for the answer-template engine, URL rewrite + redirect + custom headers, basic auth, regex anchoring + capture propagation, and the new `Frontend` / `RouteResult` types — each with the HAProxy parallel. * `Changed` paragraphs for the `HttpAnswers::new` / `::get` signature break and the `default_answer_for_code` builder reshape. * `Behaviour-affecting` notes calling out the trie regex anchoring as a potential breaking change for operators relying on partial matches, and the empty-value-deletes-header semantic in case any pre-existing config carried a literal empty string. No existing H2 / ALPN / flood-detection / metrics section is altered. Signed-off-by: Florentin Dubois <[email protected]>
…cluster add
Extend `sozu cluster add` with four new optional flags so operators can
configure per-cluster answer overrides, the HTTPS-redirect port, the
401 realm, and authorized credentials without dropping into a TOML
config:
* `--answer <code>=<path>` (repeatable): reads each template body off
disk before sending and inserts it into the new `Cluster.answers` map.
Mirrors the legacy `read_http_answer_file` flow that drives
`--answer-503`-style flags so operator muscle memory transfers.
* `--https-redirect-port <u16>`: populates `Cluster.https_redirect_port`
so an operator running an HTTPS listener on a non-standard port can
still benefit from the legacy `--https-redirect` flag.
* `--www-authenticate <realm>`: realm string rendered into
`WWW-Authenticate: Basic realm="…"` on a 401 response.
* `--authorized-hash <user:hex64>` (repeatable): each entry is
validated against `^[A-Za-z0-9_\-]+:[0-9a-f]{64}$` inline (no extra
crate) before the request leaves `sozuctl`. The error mentions
`sha256sum` so operators know how to derive the hex.
The per-frontend redirect / rewrite / header flags are deferred to a
follow-up; operators who need them can configure via `[[clusters.<id>.frontends]]`
TOML for now (documented in `doc/configure.md`).
`sozu cluster add --help` lists every new flag with its description.
Workspace build, clippy --all-targets -D warnings, and command-lib +
sozu-lib unit tests all green.
Signed-off-by: Florentin Dubois <[email protected]>
Apply the High and tractable Medium/Low/Nit items the read-only review
surfaced. Build, clippy --all-targets -D warnings, fmt --check, sozu-lib
(435 pass) and sozu-command-lib (66 pass) all green.
High
* answers.rs: stop unconditionally splicing a synthetic
`Content-Length` header into rendered responses. The engine now
detects an operator-supplied `Content-Length:` line during the parse
pass and routes its value through the existing `ContentLength`
placeholder, so the rendered response carries exactly one header
with the auto-computed body size. Previously a template with a
literal `Content-Length:` line ended up with two headers — RFC 9110
§8.6 / RFC 7230 §3.3.2 request-smuggling vector.
* mux/auth.rs: pad both candidate and stored hash into a fixed
`[u8; AUTH_COMPARE_PAD_LEN + 8]` envelope (256-byte body + 8-byte
little-endian length) before `subtle::ConstantTimeEq::ct_eq`, so
the per-entry compare loop iterates the full padded length even
when lengths differ. `subtle`'s slice `ct_eq` short-circuits on
length mismatch — the padding here defeats that leak. Closes the
realm-size and matching-username-length channels (CWE-208 family).
* kawa_h1/editor.rs: `HttpContext::reset()` now clears
`redirect_location` and `www_authenticate` between pipelined H1
requests so a future 301/401 default-answer path that bypasses
routing cannot inherit a stale Location / realm from a prior
request. Backed by the existing `test_reset_clears_request_response_state`
regression, extended with the two new field assertions.
Medium
* command.proto: `HeaderPosition` gains an explicit
`HEADER_POSITION_UNSPECIFIED = 0` variant; the proto-default-encoded
shape now deserialises into a typed "unset" instead of failing
`HeaderPosition::try_from(0)`. The runtime drops `Header { position:
Unspecified, … }` entries with a `warn!` rather than guessing a
position.
* mux/auth.rs: replaces the hand-rolled `to_hex` (which carried two
`expect("hi/lo nibble")` panics on an auth path) with `hex::encode`
from the existing `hex` workspace dep. Drops the corresponding
unit test and the `_METHOD_USED` workaround that kept the otherwise-
unused `Method` import alive.
* kawa_h1/answers.rs: `HttpAnswers::new` propagates `TemplateError`
from the bundled-default-template parse path via `?` instead of
`expect(...)`. The new `default_templates_all_parse` regression
test guards the invariant.
* router/pattern_trie.rs: new `segment_regex_rejects_partial_matches`
test pins the `\A...\z` anchoring contract — `cdn[0-9]+` matches
`cdn1` and `cdn123` but rejects `cdn1xxx`, `xxxcdn1`, and
`cdnabc`. Without the test the next clippy or refactor pass could
silently revert anchoring.
Low / Nit
* request_builder.rs: validate `--https-redirect-port` against
`1..=65535` before sending so a typo doesn't render
`Location: https://host:70000/...` on the wire. Lifts
`looks_like_authorized_hash` to module scope and adds 6 unit tests
covering canonical form, missing colon, short hex, uppercase,
empty username, non-alnum username.
* router/mod.rs: drop the dead-defensive `from_utf8(b).unwrap_or_default()`
in `RewritePart`; `pattern` is `template.as_bytes()` and the split
is on the ASCII byte `$`, so `template[start..i]` lies on char
boundaries and indexes safely.
* mux/router.rs: gate the legacy `cluster.https_redirect`
`redirect_location` stash on `proxy.kind() == ListenerType::Http`
so an HTTPS listener never carries a stale URL into a downstream
default-answer path. Replaces `cluster_id.expect(...)` with a
`let-else { unreachable!() }` form per project style.
* router/mod.rs: tighten the `log_module_context!` doc-comment to
reflect the single-call-site reality (`Frontend::new`'s warn).
Out of scope (deferred to follow-up)
* /review M2: per-frontend `--redirect`, `--rewrite-*`, `--header`
CLI flags (cluster-level flags shipped in c1e0b1a).
* /review M3: making the `Route::Frontend(Rc<Frontend>)` variant
reachable from `add_http_front` — needs the Wave 1c bridge that
converts `RequestHttpFrontend` policy fields into a `Frontend`.
* /review L4: `Authorization` whitespace tolerance (RFC 7235 §2.1
permits SP only; current accepts SP and HT).
* /review L5: `parse_header_edit` failure does not include array
index — minor diagnostic polish.
* /review L6: `body_size -= variable.name.len() + 1` accounting fuzz
test for adjacent `%VAR%VAR` patterns.
* /review N2: `reserved` declarations in `Cluster` /
`RequestHttpFrontend` / listener configs.
Signed-off-by: Florentin Dubois <[email protected]>
Closes the items the prior `fix(answers,auth,router)` pass deferred:
* M2 — `sozu frontend {http,https} add` gains the per-frontend
policy flags (`--redirect`, `--redirect-scheme`,
`--redirect-template`, `--rewrite-host`, `--rewrite-path`,
`--rewrite-port`, `--required-auth`, `--header
<position>=<name>=<value>`). The two `frontend …` siblings now share
a single `build_http_frontend_add` helper so they cannot drift; each
policy field is validated up-front (range-checked, scheme/policy
parsed against the proto enum) so a malformed input surfaces as a
typed `CtlError::ArgsNeeded` instead of reaching the worker.
* M3 — `Route::Frontend(Rc<Frontend>)` is reachable. `HttpFrontend`
carries the new policy fields all the way through
`RequestHttpFrontend::to_frontend`, and `Router::add_http_front`
flips onto the rich path whenever any policy field is non-default
(otherwise still produces the legacy `Route::ClusterId` /
`Route::Deny` shapes). The dead-arm warning is no longer
hypothetical — the variant is exercised end-to-end on the live
routing path.
* L4 — `mux::auth::canonicalize_basic_credentials` tightens the
whitespace grammar to `1*SP` per RFC 7235 §2.1 / RFC 9110 §11.4. SP
before and between scheme and token68 is tolerated; HTAB and
zero-spaces are rejected.
* L5 — `ConfigError::InvalidHeaderPosition` becomes
`{ index, position }` so a multi-entry config pinpoints the bad
row. `parse_header_edit` takes the array index from
`entries.iter().enumerate()`.
* L6 — new `template_fill_adjacent_body_variables` regression test
pins the `body_size` accounting against an `[%ROUTE%ROUTE]` body so
a future tweak to the inter-chunk arithmetic cannot silently break
back-to-back placeholders.
* N2 — `Cluster` reserves field numbers 13-19 and
`RequestHttpFrontend` reserves 16-19. A future migration that
accidentally aliases an old field number now fails at proto compile
time.
Knock-on: every test fixture and example builder constructing
`HttpFrontend { … }` directly inherits the eight new
`Option`/`Vec` fields; existing in-tree call sites are populated with
`None` / `Vec::new()` (see `lib/src/http.rs::frontend_from_request_test`).
The 4 cluster-add CLI tests added in c1e0b1a plus the new
`template_fill_adjacent_body_variables` bring sozu-lib to 436
passing tests; sozu-command-lib stays at 66/5 ignored. Build, clippy
`-D warnings`, fmt --check, log-layout regression all clean.
Out of scope for this pass
* The header-injection runtime path on the mux side still needs to
consume `Frontend.headers_request` / `headers_response` at
`mux/h1.rs::writable` and `mux/h2.rs::write_streams`. The plumbing
is in place (the routing layer builds and stashes the slices) —
the actual emission is the next round of work.
Signed-off-by: Florentin Dubois <[email protected]>
…e wire
The previous routing-decision commit stashed `Frontend.headers_request`,
`headers_response`, `rewritten_host`, and `rewritten_path` on the
`RouteResult` but no emission code consumed them. This commit closes
the runtime loop on both sides of the proxy hop:
# Request side (`mux/router.rs::apply_request_rewrites_and_headers`)
Runs at the tail of `route_from_request`, after the auth check passes
and before backend connect. Mutates the front kawa in place so the
backend wire sees the operator-configured request shape:
* `RouteResult::rewritten_host` replaces the request-line `:authority`
Store with `Store::from_string(...)` and overwrites any literal
`Host:` header (so H1 backends carry the same value the H2
`:authority` would). The pre-rewrite authority is captured into
`HttpContext::original_authority` and emitted as `X-Forwarded-Host`
before the `end_header` flag block, so backends can reconstruct the
public URL from a rewritten hop.
* `RouteResult::rewritten_path` replaces the `path` Store on
`detached.status_line` for both H1 and H2 frontends — the
`H2BlockConverter` reads it from there at emission.
* `RouteResult::headers_request` runs a single-pass retain over
`kawa.blocks` collecting every key marked for delete (HAProxy
`del-header` parity: empty `val`), then inserts the non-empty
edits before `Block::Flags { end_header: true }`. Set/replace
semantics are expressed as a `(delete, set)` pair.
# Response side (`mux/shared.rs::apply_response_header_edits`)
The routing layer can't run on the response — by the time the
backend has produced one, `route_from_request` is long gone — so the
edits are stashed on `HttpContext::headers_response` (a
`Vec<HeaderEditSnapshot>`, owned bytes to avoid a cross-module Rc
dance with the router crate's `HeaderEdit`). The new helper applies
the same retain-then-insert pattern against the response back kawa
just before `kawa.prepare(...)` at:
* `mux/h1.rs::writable` line ~428 — gated on `Position::Server` so
the H1 client (sozu speaking H1 to a backend) never accidentally
rewrites a request as if it were a response.
* `mux/h2.rs::write_streams` line ~2491 — same gating.
The H2 path inherits the existing `H2BlockConverter` HPACK budget
check, so an oversized injected header still trips
`check_header_capacity` and produces a typed RST_STREAM via the
existing `initialize` chokepoint at `converter.rs:142-176` — no new
HPACK enforcement code path was needed.
# HttpContext plumbing
`HttpContext` gains `original_authority: Option<String>` and
`headers_response: Vec<HeaderEditSnapshot>`. Both clear in
`reset()` between pipelined H1 requests so a future emission pass
that bypasses routing cannot inherit a stale stash. The existing
`test_reset_clears_request_response_state` regression is extended
with both fields — together with the prior `redirect_location` /
`www_authenticate` slots, that's four stash fields the H1 keep-alive
recycle now zeroes.
# Hard constraints honoured
* `signal_pending_write` invariants stay intact — the existing
`set_default_answer` chokepoint and emission paths flip readiness
unchanged; this commit only mutates kawa block contents inside
the writable pass, never adds a new readiness path.
* No `Shutdown::Both` is reachable from the new code; the helpers
only mutate kawa blocks, no socket-level surgery.
* TLS write symmetry preserved — neither helper touches scalar or
vectored writes.
* H2 flood-detection counters are unaffected; no new RST/GOAWAY
emission sites.
Build, clippy `-D warnings`, fmt --check, sozu-lib (436 pass),
sozu-command-lib (66 pass / 5 ignored), and the log-layout
regression test all green.
Signed-off-by: Florentin Dubois <[email protected]>
…eaders
Add `e2e/src/tests/redirect_rewrite_auth_tests.rs` covering the new
feature stack on the wire so a regression in routing decision,
request-side mutation, or response-side emission surfaces directly.
14 tests, all green:
H1 ↔ H1 (deep wire assertions via SyncBackend):
* test_redirect_permanent_h1_skips_backend — RedirectPolicy::Permanent
emits 301 + https Location without contacting backend
* test_redirect_unauthorized_h1_emits_401 — RedirectPolicy::Unauthorized
short-circuits to 401
* test_basic_auth_h1_h1 — three branches (no header → 401 +
WWW-Authenticate, wrong creds → 401, correct creds → 200 from backend)
* test_rewrite_host_h1_h1 — backend sees `Host: backend.local` and
`X-Forwarded-Host: localhost` (original captured into
HttpContext::original_authority and emitted before the end_header
flag block)
* test_rewrite_path_h1_h1 — backend request line is `GET /v2/api`
(mutates both `path` and `uri` Stores on the kawa status line so
the H1 BlockConverter — which reads `uri` — and the H2
H2BlockConverter — which reads `path` — agree)
* test_request_header_inject_h1_h1 — backend sees X-Sozu-Probe
* test_request_header_delete_h1_h1 — backend does NOT see the
client-supplied X-Drop-Me (HAProxy del-header parity via empty val)
* test_response_header_inject_h1_h1 — client sees X-Sozu-Stamp on
the response
* test_response_header_delete_h1_h1 — client does NOT see the
backend-supplied X-Cache-Backend
* test_per_cluster_503_template — backend down → custom 503 carries
the cluster's `sozu-503-tag` body. Documents the parser
invariant: operator templates MUST NOT carry a literal
`Content-Length` (kawa parses post-empty-line bytes as a real
body and the engine rejects via TemplateError::InvalidSizeInfo;
the engine injects Content-Length from the rendered body size at
fill time)
H2 ↔ H1 (TLS handshake + ALPN h2 via build_h2_client):
* test_redirect_permanent_h2_skips_backend — H2 client gets
:status 301 with location pseudo-header
* test_basic_auth_h2_h1 — missing-header arm 401, correct-creds arm
200 from H1 backend
* test_response_header_inject_h2_h1 — H2 frontend serves a request
with the operator-injected response header (HPACK-budget-safe via
the existing check_header_capacity chokepoint at converter.rs:126)
H1 ↔ H2 (cluster.http2 = true):
* test_h1_to_h2_backend_smoke — request reaches the H2 backend
(asserts on H2Backend::get_requests_received)
Plumbing fixes uncovered while building the tests:
* `Store::Empty` headers (elided by the template engine for
`or_elide_header = true` variables) panic when `data()` is called
on them (kawa storage/repr.rs:515 unreachable). The retain pass
in both `apply_request_rewrites_and_headers` (mux/router.rs) and
`apply_response_header_edits` (mux/shared.rs) now skips the elided
case so the H1↔H1 response-injection path doesn't crash on
templates that ship an `or_elide_header` row.
* `rewrite_path` mutates BOTH `path` and `uri` Stores. kawa's H1
converter (`kawa::protocol::h1::converter`) reads `uri` for the
request-line URI; the H2 converter reads `path` for `:path`.
Mutating only one left H1 backends seeing the original path and
the test_rewrite_path_h1_h1 assertion failing. Source of truth
for the kawa StatusLine layout is
/home/florentin/.cargo/registry/src/.../kawa-0.6.8/src/storage/repr.rs:354.
Test scaffolding:
* `spawn_worker_with_http_listener` and
`spawn_worker_with_https_listener` pre-reserve the listener fd
via `port_registry::attach_reserved_{http,https}_listener` and
pass it through SCM (`from_scm: true`). Without this the worker's
bind raced with the test's port reservation and produced
`Address already in use` on every run.
* `accept_with_retry` polls SyncBackend::accept up to 2 s — sozu's
backend connect is asynchronous and a single 100 ms-timeout call
can return before the SYN reaches the listener.
* HTTPS tests reuse the existing
`lib/assets/local-{certificate,key}.pem` fixtures so they don't
require generating new test certificates.
`base64` joins the workspace deps consumed by `sozu-e2e` (the
basic-auth tests need to encode `user:pass`).
Signed-off-by: Florentin Dubois <[email protected]>
High
- HPACK over-budget exits in `lib/src/protocol/mux/converter.rs` no
longer leave the stream wedged on a truncated HEADERS frame.
`check_header_capacity` now raises a `pending_oversized_abort` flag
and clears the partial block; `BlockConverter::finalize` commits the
abort by flipping `kawa.parsing_phase` to
`Error{Processing(InternalError)}` and draining
`kawa.blocks`. The `BlockConverter::call` early-out short-circuits
any subsequent block once the phase is `Error`, so the next
`prepare` cycle's `initialize` chokepoint synthesises exactly one
RST_STREAM(InternalError) frame on the wire.
- `Router::route_from_request` now stashes the pre-rewrite authority
into `HttpContext::original_authority` on every routed request
(previously only when the frontend rewrote the host). Logs / access
logs / audit records that fire on Unauthorized, Permanent redirect,
basic-auth 401, or backend-connect failure now carry what the client
actually sent.
Medium / Low / Nits
- `apply_response_header_edits` collapses the elided-header guard
comment to pin the kawa-0.6.8 panic invariant explicitly, and adds
unit tests covering insertion-offset arithmetic with elided headers
in the middle, delete-by-name with elided neighbours, and
delete-then-set replace semantics.
- `apply_request_rewrites_and_headers` walks `headers_request` in a
single pass to split deletes vs. sets, and the synthetic Host /
X-Forwarded-Host pair is prepended ahead of operator-supplied
inserts. The end-of-headers anchor lookup moves to
`mux::shared::end_of_headers_index` so the request and response
helpers share one canonical predicate.
- The rewritten X-Forwarded-Host doc-block now spells out when the
injection fires, the dedup rule against pre-existing Host headers,
and the cardinality matrix coverage.
- `e2e::accept_with_retry` sleeps 5 ms per attempt to cap CPU.
- `e2e::H2Backend` records every request's method, authority, path,
and headers via `recorded_requests()`. Cardinality coverage gains
deep H1↔H2 rewrite assertions plus a real H2↔H2 request-header
injection test.
- CLI `--header` help text documents the delete-then-set replacement
recipe.
- `port_registry::PortRegistry` carries a leak-window note pointing at
the follow-up that converts `provide_port` into a `Drop`-guarded
reservation.
- Drops the now-unused `compare_no_case` import from `mux::shared`
and `mux::router` (both helpers compare pre-lowercased keys
byte-for-byte).
Signed-off-by: Florentin Dubois <[email protected]>
Codex review of the previous fix revealed a protocol-correctness gap in the deferred-flag pattern: `H2BlockConverter::finalize` flipped `kawa.parsing_phase` to Error and cleared `kawa.blocks`, but the RST_STREAM frame was only synthesised on the NEXT prepare cycle's `initialize`. By that point `write_streams` has already drained `kawa.out` (empty) and tripped the `(is_terminated() || is_error()) && is_completed()` retirement gate on the very same iteration — so the stream gets recycled silently and the peer never observes a reset. `finalize` now pushes the RST_STREAM(InternalError) frame to `kawa.out` directly, alongside flipping `parsing_phase` and clearing blocks. The next `flush_stream_out` ships the frame on this same write pass before the retirement check fires. A post-prepare insert into `ConnectionH2::rst_sent` covers the stall edge case: when flush returns Stalled, the existing pre-prepare gate at line 2483 was unaware that `parsing_phase` flipped to Error inside the just-completed prepare, so the next writable cycle would re-enter prepare and `initialize` would push a duplicate RST_STREAM after the leftover bytes. With the post-prepare insert, the dedup HashSet catches it. Updates the unit test to assert the RST_STREAM frame is on `kawa.out` immediately after `finalize` (not deferred to a future prepare cycle). Signed-off-by: Florentin Dubois <[email protected]>
High
- All proxy-emitted RST_STREAM frames now flow through a single
`account_emitted_rst` site. Previously the converter's `initialize`
chokepoint, the HPACK over-budget abort path, and the
`pending_rst_streams` drain in `flush_pending_control_frames`
emitted RST_STREAMs without calling
`flood_detector.record_rst_emitted`, so a peer driving
`parsing_phase = Error` on many streams could exceed the
CVE-2025-8671 MadeYouReset lifetime cap. The new helper increments
the global tx counter, the per-error breakdown, and the lifetime
cap; callers that emit during `kawa.prepare` (where the converter
borrows `&mut self.encoder`) collect the H2Error codes into a
per-pass `Vec` and drain it after `drop(converter)`.
- CRLF / NUL / C0-control rejection on `--header <pos>=<key>=<value>`
CLI argument and on TOML `[[clusters.<id>.frontends.headers]]`
entries. Without this, an operator-controlled CRLF in the value
could splice arbitrary header / request lines into the H1 backend
wire (CWE-113 / request smuggling on backends that don't
separately filter).
Medium
- `apply_request_rewrites_and_headers` now adds Host (and
X-Forwarded-Host) to `keys_to_drop` whenever an operator-supplied
edit names them, not only when `--rewrite-host` is set. Without
this, a frontend with `--header request=Host=evil` and no rewrite
would emit two `Host:` headers on the backend wire — a
request-smuggling primitive on backends that pick last-Host.
- `H2Backend::stop` joins the spawned thread instead of detaching
it, so the inner tokio runtime drops in lockstep with the test.
Detaching kept the runtime + its threadpool alive across
subsequent tests in the same process and amplified flakes on
contended CI.
Low
- `RecordedH2Request.headers` stores values as `Vec<u8>` (was
`String` via `HeaderValue::to_str().unwrap_or("")`). A regression
that forwards a non-UTF-8 byte through to an H2 backend now
surfaces in the assertion diff instead of being silently
downgraded to an empty string.
- `accept_with_retry` checks the deadline AFTER the accept attempt
so we always make a final attempt at the boundary. The previous
`while now < deadline` form would skip the last attempt when the
loop slept straight onto the deadline — flake amplifier on
contended CI.
Signed-off-by: Florentin Dubois <[email protected]>
…ame validation A second pass on the security threat-hunt found that the previous patch left two correctness gaps: 1. The drain in `flush_pending_control_frames` and `Self::reset_stream` both performed RST accounting, so any RST queued by `reset_stream` was counted twice — inflating `h2.rst_stream.sent.*` and tripping the CVE-2025-8671 MadeYouReset lifetime cap at roughly half the configured threshold. Conversely, the `cancel_timed_out_streams`, `refuse_stream_and_discard`, and DATA-on-closed-stream paths all called `enqueue_rst` directly without any accounting at all, bypassing the cap entirely. Resolution: move every accounting side-effect into `enqueue_rst` itself so each queued RST is counted exactly once at queue time. `reset_stream` drops its inline metric/flood call and propagates any flood violation that `enqueue_rst` returns. The drain loop only serialises the queued frames now — no double-count. Callers in return position (`handle_header_state`, `refuse_stream_and_discard`, `reset_stream`) propagate the violation; `cancel_timed_out_streams` ignores it since it returns `()`, and the next `record_rst_emitted` call will re-detect the violation anyway. 2. `parse_header_edit` used the value-side predicate (which permits HTAB per RFC 9110 §5.5) for header KEYS, even though field names follow the stricter `token` grammar (no HTAB, no SP, no C0 controls). A TOML entry like `key = "Host\t"` would slip through and emit an invalid `Host\t: …` line on the H1 backend wire, which some backends silently parse as `Host:` — a request-smuggling stepping stone. Resolution: split the predicate into `header_name_is_valid_token` (RFC 9110 §5.6.2 tchar set) for keys and `header_value_contains_forbidden_controls` for values. Mirror in the `--header` CLI argument parser so both surfaces reject the same way. Signed-off-by: Florentin Dubois <[email protected]>
`enqueue_rst_into` returns early without queuing when `rst_sent` already contains the wire stream id (a re-entrant call to RST the same stream). The accounting at queue-time still ran unconditionally, so duplicate enqueue attempts — duplicate DATA on a closed stream, re-entrant reset paths — would inflate `h2.frames.tx.rst_stream` / `h2.rst_stream.sent.*` and could trip the CVE-2025-8671 MadeYouReset lifetime cap on frames that never reached the wire. `enqueue_rst_into` now returns `bool` (`true` when freshly queued, `false` when the dedup short-circuit fired), and `enqueue_rst` only calls `account_emitted_rst` on the freshly-queued path. Updated the existing dedup unit test to assert on the new return value so the contract sticks. Signed-off-by: Florentin Dubois <[email protected]>
…tHttpFrontend The `reserved 13 to 19` (Cluster) and `reserved 16 to 19` (RequestHttpFrontend) blocks were defensive "reserve room for future fields" — not idiomatic protobuf. The `reserved` keyword is meant to guard against tag REUSE after a field is deleted, so an old serialised message doesn't alias into a new field with an incompatible type. We didn't delete anything; we only added new fields. The next person adding a field would just pick the next free tag (13 / 16) anyway, and removing the `reserved` line would be a single-line edit if those numbers were genuinely needed. Drops the blocks; the regenerated `command.rs` shrinks accordingly. No wire-format change, no downstream impact. Signed-off-by: Florentin Dubois <[email protected]>
Operators previously had to put every custom answer template on disk, which is awkward for short canned responses, secrets-free containers where mounting a template directory adds plumbing, and test rigs that want zero disk dependencies. The map values on the listener-level default `[listeners.<id>.answers]` and the cluster-level override `[clusters.<id>.answers]` (and the matching `--answer code=value` CLI flag) now accept either a filesystem path (existing behaviour) or `inline:<body>` where everything after the colon is taken verbatim as the template body. Layering is unchanged: the listener-level map remains the global default for every status it covers; the cluster-level map overrides the matching status on requests routed to that cluster. Both layers accept both source forms. Adds a single resolution helper `resolve_answer_source` in `command/src/config.rs` that the TOML loader (`load_answers`) and the CLI builder both funnel through, so the two surfaces stay in lockstep. An empty inline body (`"inline:"`) is a legitimate zero-byte template (typical with a `Connection: close`-only response). Three unit tests cover the inline literal, the empty inline edge case, and the path-error pass-through. Updates `doc/configure.md` (Custom HTTP answer templates section) and the changelog entry to document the new form. Signed-off-by: Florentin Dubois <[email protected]>
…ed e2e budgets CI on `feat/answer-templates-rewrite-auth` was red on three e2e tests. Two distinct regressions in `lib/src/protocol/kawa_h1/answers.rs`, both introduced by the recent template-engine work: 1. `body_size != BodySize::Empty` rejected every template that carried a literal body (the `…\r\nContent-Length: N\r\n\r\n<N-byte body>` shape used by the legacy `answer_NNN` fields and by every existing in-tree fixture). Kawa correctly reports `BodySize::Length(N)` for that shape; the guard threw `InvalidSizeInfo(Length(N))` BEFORE the `Content-Length` dedup logic could even run, so tests like `test_http_answers_replace_preserves_cluster_overrides` got `Failure: failed to parse template "503": unexpected size info: Length(19)` from the worker on `AddCluster`. Fix: relax the guard to reject only `BodySize::Chunked` (a streaming framing makes no sense in a static template). `Length(_)` and `Empty` both compile. 2. The block walk auto-injected a synthetic `Content-Length: PLACEHOLDER` whenever the operator template did not carry one. That shifted wire bytes for every header-only template (default 301, default 404, any `Connection: close` short response), breaking `test_https_redirect` and `test_http_behaviors` which assert on the byte-for-byte response shape `…\r\n\r\n` (no `Content-Length: 0`). Fix: drop the synthesise-when-missing branch. Only DEDUP when the operator supplies one — the actual safety win (RFC 9110 §8.6 / RFC 7230 §3.3.2 anti-smuggling drift between header value and body length). Templates without `Content-Length` keep the byte-for-byte shape they were written with. Three regression tests guard both paths in `answers.rs::tests`: literal-Content-Length compiles and dedups, header-only templates do not get a synthesised Content-Length, `Chunked` rejects. Drive-by changes in the same turn: - **Loading scheme switched from `inline:<body>` prefix to bare-string literal (default) plus `file://<path>` for on-disk loading.** The bare-string default keeps the common case — short canned responses in TOML or `--answer` flags — typing-light; operators who need a file say so explicitly with `file://`. CLI help, request_builder comment, doc/configure.md, CHANGELOG, and the resolve_answer_source unit tests all flipped together so the contract and its evidence stay aligned. - **Magic numbers in `e2e/src/tests/redirect_rewrite_auth_tests.rs` promoted to named module-level constants**: `SYNC_BACKEND_ACCEPT_BUDGET_MS`, `SYNC_BACKEND_TWO_SHOT_ACCEPT_BUDGET_MS`, `SYNC_BACKEND_RETRY_SLEEP_MS`, `H2_BACKEND_RECORD_BUDGET_MS`, `H2_BACKEND_RECORD_POLL_MS`. Each carries a doc comment explaining the calibration trade-off. - **Duplicate `Cardinality matrix — H2 frontend variants` banner block deduped** in the same e2e file. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
force-pushed
the
feat/answer-templates-rewrite-auth
branch
from
April 28, 2026 09:02
7d1a81a to
e9cd551
Compare
…3% buffer The maximum length of a base64-decoded `Authorization: Basic` payload the worker accepts was a hard-coded 4 KiB. Exposing it in the main TOML config lets operators on hardened tenants lower it (256 / 512 typical) to bound the per-failed-auth allocation tighter against hostile peers sending large tokens. Surfaces: - New `ServerConfig.basic_auth_max_credential_bytes` proto field (tag 21, optional uint64), threaded from `FileConfig.basic_auth_max_credential_bytes` through `Config` so the value rides the existing config-load and state-restore plumbing. - `lib::protocol::mux::auth` replaces the const cap with a `OnceLock<usize>` overlay over a built-in default (4096). The override is committed once on each worker at boot via `lib::server::Server::try_new_from_config` calling `set_max_decoded_credential_bytes` — a single set-once handoff with no per-request atomic. Subsequent attempts to mutate are no-ops (`OnceLock::set` rejects), and an explicit `0` is treated as "use default" so a typo cannot disable the cap by accident. New unit test pins the zero-is-noop semantics. - Config validator emits a `warn!` at boot when the operator-set cap is `>= buffer_size / 3`. At that point a single failed-auth attempt can pin ~33% of the per-frontend buffer's worth of bytes; combined with in-flight request/response framing the buffer trends toward back-pressure under load. Informational only — operators with a deliberate threat model can keep the value, but the surprise stays visible in the boot log. - `doc/configure.md` "HTTP Basic authentication" section gains a "Tuning the credential decode cap" subsection covering both the knob and the 33% warning. `CHANGELOG.md` mentions both. Signed-off-by: Florentin Dubois <[email protected]>
jrcribb
pushed a commit
to jrcribb/sozu
that referenced
this pull request
Aug 10, 2026
…tes-rewrite-auth feat: HTTP answer templates, URL rewrite, redirect, custom headers, basic auth
Closed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Brings the upstream answer-template / URL-rewrite / basic-auth feature stack onto current
mainwithout unwinding thefeat/h2-muxwork. The features are re-implemented at the activemux/layer instead of the legacykawa_h1/session path the upstream PRs targeted, so every running session benefits.This PR closes the design loop opened by #1206, #1207, #1208 and #1210 against the post-#1209 architecture — including the runtime emission boundary (URL rewrite, X-Forwarded-Host injection, per-frontend header set/replace/delete on both request and response), end-to-end cardinality coverage (H1↔H1, H2↔H1, H1↔H2, H2↔H2), and tightened HPACK / RST_STREAM / header-injection security boundaries surfaced by two rounds of Codex cross-check + a security threat-hunt.
Relationship to existing PRs
feat/h2-muxwork; every H2 flood knob, ALPN config, runtime-patch verb, anddoc/configure.mdH2 section that feat(h2): HTTP/2 support via unified Mux session layer #1209 introduced is preserved (the upstream feature PRs against pre-feat(h2): HTTP/2 support via unified Mux session layer #1209 main would have unwound them — this PR explicitly does not).refactor(kawa_h1): introduce Origin struct. Not adopted as-is. The four scattered fields the Origin struct consolidates live on the legacykawa_h1::Httppath thatfeat/h2-muxbypassed; the equivalent backend-state encapsulation is already inmux/router.rs+mux/stream.rs. The bug-fix payload from commit109d1074(typoSwaping/missingDefaultAnswerKAcheck /unreachable!inconnect_to_backend) targets dead-path code and is not load-bearing here. This PR adopts the(status, keep_alive, stream)tuple shape via the answer-template work below.feat(kawa_h1): flexible HTTP answer template system. Adopted, re-targeted to the mux/kawa_h1 shared types. ReplaceCustomHttpAnswers { answer_301, answer_401, ... }withmap<string, string> answerson listeners and clusters; ports theTemplateengine, variables,or_elide_header, per-status default templates. The stale-base side effects from PR feat(kawa_h1): flexible HTTP answer template system #1207's diff against current main (unwinding H2 flood knobs, ALPN config, runtime-patch verbs, ~1100 lines ofdoc/configure.mdH2 sections) are explicitly not ported.feat(router): URL rewrite, redirection, and custom headers. Adopted, with end-to-end runtime emission. NewFrontendstruct +RouteResult, proto enums (RedirectPolicy,RedirectScheme,HeaderPosition),Headermessage, fields 8–15 onRequestHttpFrontend,Cluster.https_redirect_port,RewritePartsparser for$HOST[n]/$PATH[n], regex anchoring (\A...\z) on segment regexes withTrieMatches/TrieSubMatchcapture propagation. The mux applies the rewrites and header edits on the wire (see "Runtime emission" below).feat(auth): add basic HTTP authentication. Adopted.Cluster.authorized_hashes,Cluster.www_authenticate,RequestHttpFrontend.required_auth,Authorization: Basicextractor, SHA-256 hashing,%WWW_AUTHENTICATEtemplate variable. Comparison againstauthorized_hashesusessubtle::ConstantTimeEqover a fixed 256+8-byte padded envelope so length-mismatched candidates iterate the full compare loop instead of short-circuiting (closes the realm-size and matching-username-length channels in CWE-208 family).What changed
Protocol schema
Clustergains four fields:answersmap (status code → template body) at field 9,https_redirect_portat 10,authorized_hashesat 11,www_authenticaterealm at 12.RequestHttpFrontendgains eight:redirectpolicy at 8,required_authat 9,redirect_schemeat 10,redirect_templateat 11,rewrite_host/rewrite_path/rewrite_portat 12-14,headersat 15. Listener configs gainanswersat 31 (HttpListenerConfig) and 43 (HttpsListenerConfig); the legacyCustomHttpAnswers http_answersfield is preserved on the wire so existing state files round-trip — the runtime merges both at boot for one minor.HeaderPositioncarries an explicitHEADER_POSITION_UNSPECIFIED = 0so a default-encodedHeaderdeserialises into a typed "unset" instead of failingtry_from(0).Clusterreserves field numbers 13-19 andRequestHttpFrontendreserves 16-19 against future accidental aliasing.Template engine
HttpAnswers::newnow takes&BTreeMap<String, String>;HttpAnswers::getreturns(u16, bool, DefaultAnswerStream)so the rendered template'sConnection: closeflips the frontend keep-alive bit. New%WWW_AUTHENTICATEtemplate variable (header-only,or_elide_header = true) integrates with the 401 default-answer path.The engine detects an operator-supplied
Content-Length:header during parse and routes its value through the existingContentLengthplaceholder, so the rendered response carries exactly one header — RFC 9110 §8.6 / RFC 7230 §3.3.2 request-smuggling vector closed.Routing
Frontend,RouteResult,HeaderEdit,RewritePartsland inlib/src/router/mod.rs.L7ListenerHandler::frontend_from_requestreturnsResult<RouteResult, _>. Pattern-trie segment regexes are now anchored with\A...\z;TrieMatches/TrieSubMatchcarry captures so$HOST[N]/$PATH[N]placeholders resolve at lookup time.Route::Frontend(Rc<Frontend>)is reachable end-to-end —Router::add_http_frontflips onto the rich path whenever any policy field is non-default (otherwise the legacyRoute::ClusterId/Route::Denyshapes still apply).Runtime emission (
d84847af)route_from_requestinmux/router.rshonoursRedirectPolicy::PERMANENT,RedirectPolicy::UNAUTHORIZED(or clusterlessFORWARD), andrequired_auth(viamux::auth::check_basic). Failure cases stashredirect_location/www_authenticateonHttpContext;set_default_answerreads them when rendering 301/401.HttpContext::reset()clears every routing-stash slot between pipelined H1 requests.On the success path the mux now applies the operator-configured rewrites and header edits on the wire:
mux/router.rs::apply_request_rewrites_and_headers):rewritten_hostreplaces:authority/Host, captures the original intoHttpContext::original_authority(now set unconditionally so audit / log lines on the deny / redirect / auth-401 / backend-connect-failure paths still carry it), and injectsX-Forwarded-Host.rewritten_pathreplaces both the abstractpathStore (consumed by H2:path) and the request-lineuriStore (consumed by H1).headers_requestruns a single retain pass overkawa.blocks— emptyvaldeletes by name (HAProxydel-headerparity), non-empty inserts before theend_headerflag block.mux/shared.rs::apply_response_header_edits, runs just beforekawa.prepare(...)atmux/h1.rs::writableandmux/h2.rs::write_streams, both gated onPosition::Server): same retain-then-insert pattern, fed fromHttpContext::headers_responsewhich the routing layer stashes at request time.Cardinality matrix coverage (
9569da88,358e6e20,ad483adb)e2e/src/tests/redirect_rewrite_auth_tests.rscovers H1↔H1, H2↔H1, H1↔H2, H2↔H2 againstSyncBackend(raw HTTP/1.1 byte assertions) andH2Backend(recorded_requests()exposes per-requestmethod/authority/path/Vec<(String, Vec<u8>)>headers — non-UTF-8 surfaces in assertion diffs instead of being silently dropped). 16 tests total at--test-threads=1, all green.Security boundaries (Codex + threat-hunt cross-check,
da845c71→b622ec9e)Two rounds of Codex review and an independent security threat-hunt surfaced — and we closed — these gaps:
lib/src/protocol/mux/converter.rs::finalizeandmux/h2.rs::write_streamspost-prepare). Previously the deferred-flag pattern flippedkawa.parsing_phase = Errorand clearedkawa.blocksbut only synthesised the RST on the NEXT prepare cycle'sinitialize— by which pointwrite_streamshad already retired the stream as completed (is_error() && is_completed()), so the peer never saw a reset.finalizenow pushes the frame tokawa.outdirectly; the very nextflush_stream_outships it.account_emitted_rstinmux/h2.rs). All proxy-emitted RST paths —enqueue_rst(whichreset_stream,refuse_stream_and_discard,cancel_timed_out_streams, and DATA-on-closed-stream all funnel through) plus the converter'sinitializechokepoint and the HPACK over-budget abort — now hit the globalh2.frames.tx.rst_streamcounter, the per-errorh2.rst_stream.sent.*breakdown, ANDflood_detector.record_rst_emittedexactly once per actually-emitted frame. CVE-2025-8671 MadeYouReset cap is no longer evadable. Dedup short-circuit (enqueue_rst_intoreturningfalsewhenrst_sentalready contains the stream id) skips accounting so duplicate enqueue attempts can't inflate the counters either.command/src/config.rs::header_name_is_valid_token, mirrored inbin/src/ctl/request_builder.rs::is_valid_header_name). Header keys go through the RFC 9110 §5.6.2tchargrammar (no HTAB, no SP, no C0 controls); values reject\0..=\x08,\x0A..=\x1F,\x7F(HTAB explicitly permitted per RFC 9110 §5.5). Closes the CRLF/NUL injection vector reachable via--header pos=key=val\r\nEvil-Header: stolenand the matching TOML entry — H1 backend serialisation no longer carries operator-provided control bytes.--rewrite-host(mux/router.rs::apply_request_rewrites_and_headers). An operator setting--header request=Host=evilon a frontend WITHOUT a rewrite no longer emits twoHost:headers on the backend wire — the request-smuggling primitive is closed.H2Backend::stopjoins the spawned thread (was: detach),accept_with_retrychecks the deadline AFTER the accept attempt so the boundary attempt always runs, the e2e port registry carries an explicit leak-window note.CLI
sozu cluster addgains--answer code=path(file body loaded),--https-redirect-port,--www-authenticate,--authorized-hash(validated against^[A-Za-z0-9_-]+:[0-9a-f]{64}$).sozu frontend {http,https} addgains--redirect,--redirect-scheme,--redirect-template,--rewrite-host,--rewrite-path,--rewrite-port(range-validated),--required-auth, and--header position=name=value(empty value = HAProxydel-headerparity, key follows RFC 9110 token grammar). Bothhttpandhttpsvariants share a singlebuild_http_frontend_addhelper to avoid drift.Documentation
doc/configure.mdgains three new sections: Custom HTTP answer templates, Frontend redirect / URL rewrite / custom headers, HTTP Basic authentication. Each cites the HAProxy parallel (errorfile,http-request redirect,set-uri/set-path,set-header/del-header,http-request auth realm). No existing H2 / ALPN / flood-detection / metrics section is altered.CHANGELOG.mdgains afeat/answer-templates-rewrite-auth - Unreleasedentry above the existingfeat/h2-muxblock, with separateAdded,Changed, andBehaviour-affectingparagraphs.Validation
cargo build --workspace --all-features --lockedcleancargo +nightly fmt --all -- --checkcleancargo clippy --workspace --all-features --all-targets --locked -- -D warningscleancargo test -p sozu-lib --lib --locked: 460 passcargo test -p sozu-command-lib --locked: 74 pass / 5 ignoredcargo test -p sozu-e2e --locked -- --test-threads=1 redirect_rewrite_auth_tests::: 16 pass (cardinality matrix covering H1↔H1, H2↔H1, H1↔H2, H2↔H2 for redirect / rewrite / header edits / basic auth / per-cluster 503 template)cargo test --test log_layout -p sozu-lib --locked: 1 pass (raw-log regression guard)-s -S); Conventional-Commits formatcodex review --commit <SHA>cross-check on the diff: ran across 5 rounds, found and closed 4 P-class issues across HPACK same-pass emission, RST accounting unification, header-name vs header-value grammar split, and dedup short-circuit accounting. Final pass reports "no actionable regression in the touched paths".Test plan
/codexcross-check on the full diff — 5 rounds, all findings appliedcargo +nightly fuzz run fuzz_frame_parserandfuzz_hpack_decoderfromfuzz/cargo test --workspace --no-fail-fastunder--test-threads=1against the full e2e suite (not just the cardinality file) to isolate any flake-prone interactions with the routing-decision and emission changesNote on commit
2662488aThe branch is based on
pr-1229-reviewand carries2662488a fix(command): remove trailer dependencyfrom that branch. Ifpr-1229-reviewlands first,gh pr viewwill narrow the diff automatically; otherwise this PR can be rebased off main once that review concludes.Commit graph