Skip to content

sd_notify, cert chain dedup, 302/308 redirects + matrix coverage - #1238

Merged
FlorentinDUBOIS merged 9 commits into
mainfrom
feat/v2-wave-2
May 2, 2026
Merged

FlorentinDUBOIS merged 9 commits into
mainfrom
feat/v2-wave-2

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

Summary

Wave 2 of the v2.0 follow-up batch. Four small, independently-reviewable
changes — three feature/fix items closing long-standing issues, plus a
test-coverage and documentation correction sweep.

Commit Closes Scope
e3ecd141 #228 systemd Type=notify + sd_notify (READY/STOPPING/MAINPID)
21ac9c24 #1135, #1148 TLS cert chain leaf-dedup + multi-PEM split
59376525 #1009 RedirectPolicy::Found (302) + PermanentRedirect (308)
0bcade31 — Migration guide entries for the three above
fcbf13b3 — 302/308 e2e matrix coverage (4×3 cells) + rate-limit doc rewrite

5 commits, ~1000 LoC, 22 files. Every commit is GPG-signed + signed-off
and self-contained: it builds, formats clean (cargo +nightly fmt),
clippy-clean, and ships its own regression tests.

Per-commit detail

feat(systemd): integrate sd_notify — closes #228

  • New helper command/src/sd_notify.rs (~60 LOC, std-only,
    UnixDatagram to $NOTIFY_SOCKET).
  • Master sends READY=1 after initial workers spawn + state replay,
    STOPPING=1 on graceful shutdown, MAINPID=<pid> + READY=1 after
    hot-upgrade re-exec.
  • Bundled units sozu.service / [email protected] flip to
    Type=notify + NotifyAccess=main (master-only).
  • Helper is a no-op when $NOTIFY_SOCKET is unset → custom unit
    files / non-systemd init keep working unchanged.
  • Two unit tests (notify_no_socket_set_is_noop,
    notify_writes_payload_to_socket); tempfile added as
    dev-dependency.
  • Watchdog ping scaffolded as STATE_WATCHDOG constant; periodic-timer
    wiring deferred to a follow-up.

fix(tls): dedup leaf in certificate chain — closes #1135 + #1148

  • TryFrom<&AddCertificate> in lib/src/tls.rs now (1) splits each
    chain entry through split_certificate_chain so concatenated
    multi-PEM strings no longer drop trailing CAs (silent parse_pem
    truncation), and (2) compares each split entry's DER bytes against
    the leaf, dropping on match.
  • info! log on dedup, gated behind the canonical TLS-RESOLVER log
    envelope.
  • Operators feeding fullchain.pem (Certbot/lego/acme.sh default)
    see the on-wire chain shrink to one copy of the leaf — fixes
    Node.js UNABLE_TO_VERIFY_LEAF_SIGNATURE.
  • Two regression tests:
    certificate_chain_dedup_drops_duplicate_leaf,
    certificate_chain_handles_multi_pem_single_entry.

feat(redirect): 302 + 308 — closes #1009

  • Proto: RedirectPolicy { FOUND = 3, PERMANENT_REDIRECT = 4 }. Tags
    0..2 unchanged → v1.x clients still decode FORWARD/PERMANENT/
    UNAUTHORIZED.
  • HttpContext::redirect_status: Option<u16> stashed by
    Router::route_from_request; the answer engine in mux/mod.rs
    reads it to dispatch to the right http.{301,302,308}.redirection
    template. Legacy cluster.https_redirect = true keeps its 301
    default (field is None).
  • DefaultAnswer gains Answer302 / Answer308;
    set_default_answer_with_retry_after dispatches all three through
    one redirect-shaped path.
  • Default templates default_302 / default_308 ship in-tree.
    Operator-supplied templates flow through the renamed
    HttpAnswers::render_inline_redirect(code, …); render_inline_301
    preserved as a thin wrapper.
  • New per-status counters http.302.redirection /
    http.308.redirection mirror the 301 emission path (cluster +
    backend labels).

docs(upgrade): Wave 2 sections

doc/upgrade/1.x-to-2.0.md gains operator-visible-behaviour entries
for the three above: Type=simple → Type=notify, the chain-dedup
log line + on-wire shape change, and the additive 302/308 variants
with their new metrics. Existing sections also picked up prettier --write paragraph-wrap cosmetic reformatting.

test(e2e) + docs(rate-limit): matrix + design-doc rewrite

Matrix. PR #1009's e2e tests only exercised the H1 frontend
path; the H2 / h2c-backend cells were not covered. The
protocol_pair_matrix.rs harness now ships a generalised
try_redirect_cell_inner(policy, expected_status) plus three
status-specific wrappers, and three protocol_pair_matrix!
invocations emitting 4 cells × 3 statuses = 12 redirect tests.
Filter: cargo test -p sozu-e2e protocol_pair_matrix::test_redirect_.

Rate-limit doc rewrite. doc/rate-limit-design.md previously
described an unimplemented two-layer mechanism (token-bucket
request-rate at L7 + per-IP TCP cap at L4). The actual mechanism
on main (PR #1193 closing #890 + #1057) is single-layer:
per-(cluster, source-IP) concurrent connection cap → 429.
Rewritten to reflect what's shipped: max_connections_per_ip: Option<u64> + per-cluster override, SessionManager counter
discipline, enforcement points, reject behaviour, source-IP
selection (PROXY-v2 → peer_addr fallback), CLI surface, test
coverage pointer, deferred future-work list, operator guidance
(NAT, behind-another-LB, etc.).

Test plan

  • cargo build --all-features --locked — clean
  • cargo +nightly fmt --all -- --check — clean
  • cargo clippy --all-targets --all-features --locked -- -D warnings — clean
  • cargo test --workspace --locked — full workspace pass
  • cargo test -p sozu-e2e protocol_pair_matrix::test_redirect_ — 12 cells pass
  • cargo test -p sozu-e2e -- redirect_rewrite_auth — 301/302/308 H1 baselines pass
  • cargo test -p sozu-command-lib sd_notify — both helper tests pass
  • cargo test -p sozu-lib certificate_chain — both dedup tests pass
  • CI push + pull_request runs — to be verified after open

Doc / API impact

  • New systemd unit semantics (Type=notify) — operators using bundled
    units get readiness gating for After=sozu.service peers; custom
    units unchanged.
  • New proto enum tags (3, 4) — additive; v1.x clients unchanged.
  • New default-answer templates (302, 308) — operator-overridable.
  • New metric labels (http.302.redirection, http.308.redirection)
    — documented in doc/configure.md follow-up if not already.
  • Migration guide doc/upgrade/1.x-to-2.0.md — updated.
  • doc/rate-limit-design.md — rewritten to match shipped behaviour.

Out of scope

  • Watchdog timer wiring (WATCHDOG=1 periodic ping) — deferred to a
    later commit; constants are present but no event-loop wiring.
  • v2 token-bucket request-rate, cross-worker rate-limit sync,
    pre-TLS TCP-level cap — captured as deferred items in the rewritten
    rate-limit design doc.

Closes #228.

The master process now sends `READY=1` to systemd via the
`$NOTIFY_SOCKET` unix datagram once its initial workers have spawned
and any saved state has been replayed — fixing the long-standing race
under `Type=simple` where `After=sozu.service` peers could start
hitting sozu before traffic was being accepted. Other lifecycle
transitions:

- Graceful shutdown sends `STOPPING=1` so systemd suppresses the
  abnormal-exit treatment.
- The hot-upgrade re-exec path (`bin/src/upgrade.rs::begin_new_main_process`)
  sends `MAINPID=<new-pid>` followed by `READY=1` so systemd tracks
  the post-exec master correctly.

Implementation is std-only — `std::os::unix::net::UnixDatagram`
connecting to `$NOTIFY_SOCKET`. No new dependency; the helper lives
at `command/src/sd_notify.rs` (~60 LOC) and exposes `notify(state)`
plus convenience constants (`STATE_READY`, `STATE_STOPPING`,
`STATE_RELOADING`, `STATE_WATCHDOG`) and `main_pid(pid)` /
`status(text)` helpers.

The helper is a no-op when `$NOTIFY_SOCKET` is unset (the operator
runs `sozu start` from a shell, the unit declares `Type=simple`,
non-systemd init system, etc.), so non-systemd deployments see no
behaviour change.

The shipped systemd units `os-build/systemd/sozu.service` and
`os-build/systemd/[email protected]` now declare:

  Type=notify
  NotifyAccess=main

`NotifyAccess=main` restricts which child PIDs systemd accepts
notifications from to the master only — matching sozu's master/worker
fork model (workers are forked children but should not signal the
unit's readiness).

Two unit tests cover the helper:

- `notify_no_socket_set_is_noop`: verifies `Ok(false)` when
  `$NOTIFY_SOCKET` is unset.
- `notify_writes_payload_to_socket`: spins up a `UnixDatagram::bind`
  on a temp path, points `$NOTIFY_SOCKET` at it, asserts the
  expected protocol bytes (`READY=1`) land on the socket.

`tempfile` is added as a dev-dependency on `sozu-command-lib` for
the second test.

Watchdog ping (periodic `WATCHDOG=1` when the unit declares
`WatchdogSec`) is scaffolded as `STATE_WATCHDOG` but not wired into
the master event loop in this commit — that needs a periodic timer
inside `CommandHub::run` and is left as a follow-up.

Signed-off-by: Florentin Dubois <[email protected]>
…tries

Closes #1135.
Closes #1148.

The TLS certificate resolver in `lib/src/tls.rs` previously built the
on-wire chain as `[leaf, ...cert.certificate_chain]` without checking
whether the supplied chain already contained the leaf. Many ACME
clients (Certbot's default `fullchain.pem`, lego, acme.sh) emit the
leaf at the START of the chain file, so the resolver stored
`[leaf, leaf, intermediate, root]`. Browsers accept this; stricter
validators reject it — Node.js raises
`UNABLE_TO_VERIFY_LEAF_SIGNATURE` (the symptom in #1148).

Two robustness passes are now applied to each chain entry:

1. **Split**. Each entry is fanned out through
   `split_certificate_chain` so a single string carrying multiple
   `-----BEGIN CERTIFICATE-----` blocks (operators concatenating
   fullchain contents into one chain entry, common via the runtime
   API path) is split into one entry per CA before parsing. Without
   this, `parse_pem` only consumes the FIRST PEM block in the string
   and silently drops the rest.

2. **Dedup**. Each split entry's DER bytes are compared against the
   leaf's DER and dropped on match. Robust against any chain shape
   that includes the leaf (start, end, repeated).

When at least one duplicate is dropped, an `info!` line fires (gated
behind the canonical `TLS-RESOLVER` log envelope so it shows up under
the standard log filter).

Two regression tests in `lib/src/tls.rs::tests`:

- `certificate_chain_dedup_drops_duplicate_leaf`: passes the leaf as
  both `certificate` AND the sole chain entry; asserts the stored
  chain length is `1`.
- `certificate_chain_handles_multi_pem_single_entry`: passes two
  concatenated PEM blocks as a single chain entry; asserts the split
  fans them out, dedup catches both as the leaf, stored chain length
  is `1`.

Signed-off-by: Florentin Dubois <[email protected]>
Closes #1009.

Sōzu's `RedirectPolicy` previously only supported `Permanent` (301) and
`Unauthorized` (401) at the frontend. Two new variants:

- `RedirectPolicy::Found` → 302 Found (RFC 9110 §15.4.3) — a temporary
  redirect; user agents MAY rewrite POST → GET on follow.
- `RedirectPolicy::PermanentRedirect` → 308 Permanent Redirect (RFC 9110
  §15.4.9) — like 301 but the HTTP method MUST be preserved on follow
  (no GET-rewrite on POST).

Wire-level changes:

- `command/src/command.proto::RedirectPolicy` gains `FOUND = 3` and
  `PERMANENT_REDIRECT = 4`. Tags 0..2 unchanged so v1.x clients still
  decode `FORWARD` / `PERMANENT` / `UNAUTHORIZED` correctly.
- `HttpContext` gains `redirect_status: Option<u16>` stashed by
  `Router::route_from_request` per resolved policy. The answer engine
  reads it in `mux/mod.rs` to pick the matching `http.{301,302,308}.redirection`
  template; the legacy `cluster.https_redirect = true` path keeps its
  301 default (the field is `None`).
- `DefaultAnswer` gains `Answer302` and `Answer308` variants alongside
  `Answer301`; `set_default_answer_with_retry_after` dispatches all
  three through one redirect-shaped path.
- Default templates `default_302` and `default_308` ship in-tree —
  `Connection: close`, `Sozu-Id: %REQUEST_ID`, single
  `Location: %REDIRECT_LOCATION`. Operator-supplied templates flow
  through the renamed `HttpAnswers::render_inline_redirect(code, …)`;
  `render_inline_301` is preserved as a thin wrapper for binary /
  source compatibility.
- Per-status counters `http.302.redirection` and `http.308.redirection`
  fire alongside the existing `http.301.redirection`, both labelled by
  cluster + backend, mirroring the 301 emission path.

Two e2e regression tests in `redirect_rewrite_auth_tests.rs`:

- `try_redirect_found_h1_emits_302`: H1 frontend with
  `RedirectPolicy::Found` must emit 302 + HTTPS Location, no backend
  contact.
- `try_redirect_permanent_redirect_h1_emits_308`: same but for 308.

H2 frontend cells, plus the inline-template H2 path, remain to be
backfilled in a follow-up; the H1 path covers the routing decision +
answer-engine plumbing end-to-end.

Signed-off-by: Florentin Dubois <[email protected]>
…/308 redirects

Document the operator-visible behaviour changes that landed in Wave 2:

- **systemd unit file: Type=simple → Type=notify** (#228). Bundled
  units flip; custom unit files keep working unchanged. Gives
  After=sozu.service peers a real readiness gate.
- **TLS certificate chain dedup** (#1135 / #1148). Operators using
  `fullchain.pem` (leaf at start) see a one-line `info!` log on
  every cert add and a shorter on-wire chain. No action required;
  Node.js / strict validators stop rejecting with
  `UNABLE_TO_VERIFY_LEAF_SIGNATURE`.
- **302 (Found) and 308 (Permanent Redirect) RedirectPolicy variants**
  (#1009). Additive — existing `redirect = permanent` unchanged.
  New metrics `http.302.redirection` and `http.308.redirection` ship.

Also picks up `prettier --write` cosmetic reformatting (paragraph
wrap at 80 cols) on the existing sections.

Signed-off-by: Florentin Dubois <[email protected]>
…ite rate-limit design doc

Two related changes folded into a single follow-up to Wave 2:

1. **Matrix coverage for 302 / 308 redirects**

   PR #1009's e2e tests so far only exercised the H1 frontend path
   (`try_redirect_found_h1_emits_302` +
   `try_redirect_permanent_redirect_h1_emits_308` in
   `redirect_rewrite_auth_tests.rs`). The H2 frontend cells, plus the
   h2c-backend cells, were not covered — even though the
   `protocol_pair_matrix` harness already exists for exactly this
   purpose.

   `e2e/src/tests/protocol_pair_matrix.rs` now ships:

   - `try_redirect_cell_inner(...)` — generalised redirect cell that
     takes `policy: RedirectPolicy` + `expected_status: u16`. Reuses
     the same listener / cluster / unbound-backend setup as the 301
     cell.
   - `try_redirect_permanent_cell` (301), `try_redirect_found_cell`
     (302), `try_redirect_permanent_redirect_cell` (308) — thin
     wrappers each invoking the generalised cell with their respective
     policy + status.
   - Three `protocol_pair_matrix!` invocations, one per status, each
     emitting four `pub fn try_*_h{1,2}_h{1,2c}` wrappers and four
     `#[test] fn test_*` harnesses.

   Net: 4 cells × 3 statuses = 12 redirect tests pass in parallel
   (`cargo test -p sozu-e2e protocol_pair_matrix::test_redirect_`).

2. **Rate-limit design doc rewrite**

   `doc/rate-limit-design.md` previously described an unimplemented
   two-layer mechanism (token-bucket request-rate at L7 + per-IP TCP
   cap at L4). The actual mechanism that landed in PR #1193
   (closing #890 + #1057) is a **single layer** — per-(cluster,
   source-IP) concurrent connection cap with a 429 response. The doc
   listed types like `RateLimitRule`, `trust_forwarded_for`,
   `rate_limit_check`, `max_connections_per_source_ip`,
   `nb_connections_per_source_ip` that do not exist in the codebase.

   Rewritten to describe what's on main:

   - `max_connections_per_ip: Option<u64>` global default + per-cluster
     override on `Cluster.max_connections_per_ip`.
   - Counter discipline at SessionManager (per-token set of
     `(cluster, ip)` pairs) — H2 multiplexing notes inline.
   - Enforcement points (`mux/router.rs` for HTTP/HTTPS, `tcp.rs` for
     TCP).
   - Reject behaviour (`Answer429` variant, `Retry-After` elision when
     `0`, `connections.rejected_per_cluster_ip` counter, custom
     template via `CustomHttpAnswers.answer_429`).
   - Source IP selection (PROXY-v2 → peer_addr fallback; both
     `ExpectHeader` and `RelayHeader` modes are address-aware).
   - CLI / runtime API surface (`sozu connection-limit set/show/remove`).
   - Test coverage pointer to `e2e/src/tests/cluster_ip_limit_tests.rs`.
   - Future work (token-bucket request-rate, cross-worker sync,
     adaptive quotas, ban-list integration, pre-TLS TCP-level cap)
     each captured as deferred.
   - Operator guidance (global default rule of thumb, per-cluster
     overrides, NAT / shared-egress notes, behind-another-LB notes).

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS FlorentinDUBOIS changed the title v2.0 Wave 2 — sd_notify, cert chain dedup, 302/308 redirects + matrix coverage sd_notify, cert chain dedup, 302/308 redirects + matrix coverage May 2, 2026
Three operational defects surfaced on PR #1238:

- **Abstract `$NOTIFY_SOCKET` silently failed** (`@/path` form,
  common in containers and namespace-gated hosts).
  `UnixDatagram::connect` resolved the value verbatim and returned
  `ENOENT`, so the master never sent `READY=1` — the unit hit
  `TimeoutStartSec` and was reported failed even though sozu was
  serving traffic. `command/src/sd_notify.rs::send_abstract` now
  routes `@` addresses through `libc::sendto` with `AF_UNIX` and a
  leading-NUL `sun_path`. New regression test
  `notify_writes_payload_to_abstract_socket` plus a `bind_abstract`
  helper that mirrors the send-side address layout.

- **Hot-upgrade `MAINPID=` / `STOPPING=1` race against systemd.**
  The old master previously emitted `STOPPING=1` after
  `command_hub.run()` returned, even on the upgrade-handoff path.
  Depending on scheduler ordering it could land before the new
  master's `MAINPID=`, prompting systemd to flip the unit to
  inactive while sozu was still serving traffic. The dispatcher now
  brackets every operator-issued mutation verb (LoadState /
  ReloadConfiguration / Add* / Remove* / Replace* / Update* /
  SetHealthCheck / SetMaxConnectionsPerIp / UpgradeMain /
  UpgradeWorker / SoftStop / HardStop) with `RELOADING=1` on entry
  and `READY=1` on exit so systemd is in `reloading` state across
  the handoff. `Server.upgrading` is set by `upgrade_main`;
  `CommandHub::run` returns it; `begin_main_process` skips
  `STOPPING=1` on the upgrade path. The new master keeps emitting
  `STOPPING=1` after its own graceful shutdown.

- **Signed-pid hardening.** `sd_notify::main_pid` now takes `u32`
  (`MAINPID=` is unsigned decimal per `sd_notify(3)`); call sites
  feed `std::process::id()` directly. The three previously-`unsafe
  { libc::getpid() }` sites in `bin/src/upgrade.rs` are replaced
  with safe equivalents.

Tests are now serialised through `#[serial_test::serial(notify_socket)]`
because they mutate the process-shared `NOTIFY_SOCKET` env var.
`serial_test` is added as a dev-dependency on `sozu-command-lib`.

Doc gap closed: `doc/upgrade/1.x-to-2.0.md` now records the
abstract-socket support, the `RELOADING=1` bracket around mutation
verbs, the upgrade-handoff `STOPPING=1` suppression, and an
explicit warning that operators MUST NOT add `WatchdogSec=` to
custom unit files until the periodic-timer follow-up lands.
`STATE_WATCHDOG` and `status()` are now `#[allow(dead_code)]`
explicitly until they grow callers.

Operator-visible logs: `notified systemd: READY=1` and
`notified systemd post-upgrade` drop from `info!` to `debug!`
(success-path lifecycle noise per CLAUDE.md tiers).

Signed-off-by: Florentin Dubois <[email protected]>
Three doc / code-hygiene gaps surfaced on PR #1238:

- **`doc/configure.md` redirect metrics**: the redirection table only
  carried `http.301.redirection`. Add the two new per-status
  counters (`http.302.redirection`, `http.308.redirection`) and the
  renamed `http.redirect_template.compile_error` (operator-supplied
  per-frontend `redirect_template` compile failures, now
  status-agnostic so 302/308 template failures surface under the
  same key as 301).

- **`doc/configure.md` redirect TOML key**: the inline comment on
  `redirect = "permanent"` only listed `forward / permanent /
  unauthorized`. Extend to include `found` and `permanent_redirect`
  with a paragraph explaining the 301 vs 302 vs 308 method-preservation
  semantics so operators can pick correctly.

- **`CHANGELOG.md` metric rename note**: PR #1238 silently renamed
  `http.301.redirect_template.compile_error` to
  `http.redirect_template.compile_error` (the per-status form would
  have left 302/308 template failures unmonitored). Document the
  rename in the "Breaking changes" section so dashboards scraping
  the old name get updated.

- **`mux/router.rs` redirect-status match**: the wildcard `_ => None`
  arm hid future `RedirectPolicy` variants. Replace with explicit
  `Forward | Unauthorized => None` so adding a new variant fails
  the build and forces a deliberate decision.

Signed-off-by: Florentin Dubois <[email protected]>
Three soft spots in PR #1238's e2e coverage:

- **`response.contains("302")` would false-positive** on a body or
  `Sozu-Id` header carrying the digits (M3). Switch to a status-line
  prefix check `HTTP/1.1 {expected_status} ` so a regression that
  emits the wrong status under a correct content body is caught.

- **`Box::leak(format!(...))` per call** — the helper was rebuilt on
  every `repeat_until_error_or` retry, leaking a fresh `&'static str`
  each time (M5). Replace with two `const &str` labels
  (`REDIR_302_CLIENT`, `REDIR_308_CLIENT`).

- **No Location-host assertion** (M8). A regression emitting
  `https://:443/...` (empty host) or cross-tenant bleed from a
  state-replay ordering bug would slip through a `starts_with("https://")`
  check. Both helpers now assert the Location host matches the
  frontend's request authority — `localhost` for the H1 helper
  (the `http_request(..., "localhost")` argument) and the matrix
  cell (the SAN baked into the test certs).

- **`client.receive()` is a single read** — under load it sees one
  TCP segment (M4 + repo CLAUDE.md "Always `loop_read_*`"). New
  helper `Client::receive_until_eof(deadline)` loops until the
  upstream half-closes (canonical EOF for `Connection: close`
  default-answer redirects) or the deadline elapses. The H1
  redirect helper switches to it.

The matrix cell helper picks up the same Location-host check and
gains a comment explaining the host-token choice.

`cargo test --locked -p sozu-e2e protocol_pair_matrix::test_redirect`
passes 12 cells; `cargo test --locked -p sozu-e2e -- redirect_rewrite_auth`
passes 20 cells (18 pre-existing + 2 H1 302/308 baselines).

Signed-off-by: Florentin Dubois <[email protected]>
Cosmetic follow-ups on the leaf-dedup landing in PR #1238:

- Drop `dropped_duplicates > 0` from `info!` to `debug!`. For
  operators feeding `fullchain.pem` (the dominant case the fix
  targets), this fires on every certificate add — signal-only on
  the first cert, noise after. Treat the count as a metric/log
  surface enabled by `log_level = "debug"` rather than a default
  emission. Migration guide cross-updated.

- Drop the `(closes #1135)` text from the runtime log line.
  Issue references belong in the doc comment / commit / PR text,
  not in operator-visible log envelopes that outlive the PR.

- Trim the 24-line in-function comment block to a 9-line summary.
  The same rationale already lives in the regression-test
  docstrings (`certificate_chain_dedup_drops_duplicate_leaf`,
  `certificate_chain_handles_multi_pem_single_entry`); keeping
  both copies in sync is unnecessary friction.

- `clone()` → `to_owned()` per user CLAUDE.md preferences for
  `&Vec<u8> → Vec<u8>` and `&String → String` ownership transitions
  — clearer ownership intent at the call site.

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 0af14ed into main May 2, 2026
38 checks passed
FlorentinDUBOIS added a commit that referenced this pull request May 2, 2026
Three operational defects surfaced on PR #1238:

- **Abstract `$NOTIFY_SOCKET` silently failed** (`@/path` form,
  common in containers and namespace-gated hosts).
  `UnixDatagram::connect` resolved the value verbatim and returned
  `ENOENT`, so the master never sent `READY=1` — the unit hit
  `TimeoutStartSec` and was reported failed even though sozu was
  serving traffic. `command/src/sd_notify.rs::send_abstract` now
  routes `@` addresses through `libc::sendto` with `AF_UNIX` and a
  leading-NUL `sun_path`. New regression test
  `notify_writes_payload_to_abstract_socket` plus a `bind_abstract`
  helper that mirrors the send-side address layout.

- **Hot-upgrade `MAINPID=` / `STOPPING=1` race against systemd.**
  The old master previously emitted `STOPPING=1` after
  `command_hub.run()` returned, even on the upgrade-handoff path.
  Depending on scheduler ordering it could land before the new
  master's `MAINPID=`, prompting systemd to flip the unit to
  inactive while sozu was still serving traffic. The dispatcher now
  brackets every operator-issued mutation verb (LoadState /
  ReloadConfiguration / Add* / Remove* / Replace* / Update* /
  SetHealthCheck / SetMaxConnectionsPerIp / UpgradeMain /
  UpgradeWorker / SoftStop / HardStop) with `RELOADING=1` on entry
  and `READY=1` on exit so systemd is in `reloading` state across
  the handoff. `Server.upgrading` is set by `upgrade_main`;
  `CommandHub::run` returns it; `begin_main_process` skips
  `STOPPING=1` on the upgrade path. The new master keeps emitting
  `STOPPING=1` after its own graceful shutdown.

- **Signed-pid hardening.** `sd_notify::main_pid` now takes `u32`
  (`MAINPID=` is unsigned decimal per `sd_notify(3)`); call sites
  feed `std::process::id()` directly. The three previously-`unsafe
  { libc::getpid() }` sites in `bin/src/upgrade.rs` are replaced
  with safe equivalents.

Tests are now serialised through `#[serial_test::serial(notify_socket)]`
because they mutate the process-shared `NOTIFY_SOCKET` env var.
`serial_test` is added as a dev-dependency on `sozu-command-lib`.

Doc gap closed: `doc/upgrade/1.x-to-2.0.md` now records the
abstract-socket support, the `RELOADING=1` bracket around mutation
verbs, the upgrade-handoff `STOPPING=1` suppression, and an
explicit warning that operators MUST NOT add `WatchdogSec=` to
custom unit files until the periodic-timer follow-up lands.
`STATE_WATCHDOG` and `status()` are now `#[allow(dead_code)]`
explicitly until they grow callers.

Operator-visible logs: `notified systemd: READY=1` and
`notified systemd post-upgrade` drop from `info!` to `debug!`
(success-path lifecycle noise per CLAUDE.md tiers).

Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request May 2, 2026
Three doc / code-hygiene gaps surfaced on PR #1238:

- **`doc/configure.md` redirect metrics**: the redirection table only
  carried `http.301.redirection`. Add the two new per-status
  counters (`http.302.redirection`, `http.308.redirection`) and the
  renamed `http.redirect_template.compile_error` (operator-supplied
  per-frontend `redirect_template` compile failures, now
  status-agnostic so 302/308 template failures surface under the
  same key as 301).

- **`doc/configure.md` redirect TOML key**: the inline comment on
  `redirect = "permanent"` only listed `forward / permanent /
  unauthorized`. Extend to include `found` and `permanent_redirect`
  with a paragraph explaining the 301 vs 302 vs 308 method-preservation
  semantics so operators can pick correctly.

- **`CHANGELOG.md` metric rename note**: PR #1238 silently renamed
  `http.301.redirect_template.compile_error` to
  `http.redirect_template.compile_error` (the per-status form would
  have left 302/308 template failures unmonitored). Document the
  rename in the "Breaking changes" section so dashboards scraping
  the old name get updated.

- **`mux/router.rs` redirect-status match**: the wildcard `_ => None`
  arm hid future `RedirectPolicy` variants. Replace with explicit
  `Forward | Unauthorized => None` so adding a new variant fails
  the build and forces a deliberate decision.

Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request May 2, 2026
Three soft spots in PR #1238's e2e coverage:

- **`response.contains("302")` would false-positive** on a body or
  `Sozu-Id` header carrying the digits (M3). Switch to a status-line
  prefix check `HTTP/1.1 {expected_status} ` so a regression that
  emits the wrong status under a correct content body is caught.

- **`Box::leak(format!(...))` per call** — the helper was rebuilt on
  every `repeat_until_error_or` retry, leaking a fresh `&'static str`
  each time (M5). Replace with two `const &str` labels
  (`REDIR_302_CLIENT`, `REDIR_308_CLIENT`).

- **No Location-host assertion** (M8). A regression emitting
  `https://:443/...` (empty host) or cross-tenant bleed from a
  state-replay ordering bug would slip through a `starts_with("https://")`
  check. Both helpers now assert the Location host matches the
  frontend's request authority — `localhost` for the H1 helper
  (the `http_request(..., "localhost")` argument) and the matrix
  cell (the SAN baked into the test certs).

- **`client.receive()` is a single read** — under load it sees one
  TCP segment (M4 + repo CLAUDE.md "Always `loop_read_*`"). New
  helper `Client::receive_until_eof(deadline)` loops until the
  upstream half-closes (canonical EOF for `Connection: close`
  default-answer redirects) or the deadline elapses. The H1
  redirect helper switches to it.

The matrix cell helper picks up the same Location-host check and
gains a comment explaining the host-token choice.

`cargo test --locked -p sozu-e2e protocol_pair_matrix::test_redirect`
passes 12 cells; `cargo test --locked -p sozu-e2e -- redirect_rewrite_auth`
passes 20 cells (18 pre-existing + 2 H1 302/308 baselines).

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS deleted the feat/v2-wave-2 branch May 2, 2026 17:22
jrcribb pushed a commit to jrcribb/sozu that referenced this pull request Aug 10, 2026
Three operational defects surfaced on PR sozu-proxy#1238:

- **Abstract `$NOTIFY_SOCKET` silently failed** (`@/path` form,
  common in containers and namespace-gated hosts).
  `UnixDatagram::connect` resolved the value verbatim and returned
  `ENOENT`, so the master never sent `READY=1` — the unit hit
  `TimeoutStartSec` and was reported failed even though sozu was
  serving traffic. `command/src/sd_notify.rs::send_abstract` now
  routes `@` addresses through `libc::sendto` with `AF_UNIX` and a
  leading-NUL `sun_path`. New regression test
  `notify_writes_payload_to_abstract_socket` plus a `bind_abstract`
  helper that mirrors the send-side address layout.

- **Hot-upgrade `MAINPID=` / `STOPPING=1` race against systemd.**
  The old master previously emitted `STOPPING=1` after
  `command_hub.run()` returned, even on the upgrade-handoff path.
  Depending on scheduler ordering it could land before the new
  master's `MAINPID=`, prompting systemd to flip the unit to
  inactive while sozu was still serving traffic. The dispatcher now
  brackets every operator-issued mutation verb (LoadState /
  ReloadConfiguration / Add* / Remove* / Replace* / Update* /
  SetHealthCheck / SetMaxConnectionsPerIp / UpgradeMain /
  UpgradeWorker / SoftStop / HardStop) with `RELOADING=1` on entry
  and `READY=1` on exit so systemd is in `reloading` state across
  the handoff. `Server.upgrading` is set by `upgrade_main`;
  `CommandHub::run` returns it; `begin_main_process` skips
  `STOPPING=1` on the upgrade path. The new master keeps emitting
  `STOPPING=1` after its own graceful shutdown.

- **Signed-pid hardening.** `sd_notify::main_pid` now takes `u32`
  (`MAINPID=` is unsigned decimal per `sd_notify(3)`); call sites
  feed `std::process::id()` directly. The three previously-`unsafe
  { libc::getpid() }` sites in `bin/src/upgrade.rs` are replaced
  with safe equivalents.

Tests are now serialised through `#[serial_test::serial(notify_socket)]`
because they mutate the process-shared `NOTIFY_SOCKET` env var.
`serial_test` is added as a dev-dependency on `sozu-command-lib`.

Doc gap closed: `doc/upgrade/1.x-to-2.0.md` now records the
abstract-socket support, the `RELOADING=1` bracket around mutation
verbs, the upgrade-handoff `STOPPING=1` suppression, and an
explicit warning that operators MUST NOT add `WatchdogSec=` to
custom unit files until the periodic-timer follow-up lands.
`STATE_WATCHDOG` and `status()` are now `#[allow(dead_code)]`
explicitly until they grow callers.

Operator-visible logs: `notified systemd: READY=1` and
`notified systemd post-upgrade` drop from `info!` to `debug!`
(success-path lifecycle noise per CLAUDE.md tiers).

Signed-off-by: Florentin Dubois <[email protected]>
jrcribb pushed a commit to jrcribb/sozu that referenced this pull request Aug 10, 2026
Three doc / code-hygiene gaps surfaced on PR sozu-proxy#1238:

- **`doc/configure.md` redirect metrics**: the redirection table only
  carried `http.301.redirection`. Add the two new per-status
  counters (`http.302.redirection`, `http.308.redirection`) and the
  renamed `http.redirect_template.compile_error` (operator-supplied
  per-frontend `redirect_template` compile failures, now
  status-agnostic so 302/308 template failures surface under the
  same key as 301).

- **`doc/configure.md` redirect TOML key**: the inline comment on
  `redirect = "permanent"` only listed `forward / permanent /
  unauthorized`. Extend to include `found` and `permanent_redirect`
  with a paragraph explaining the 301 vs 302 vs 308 method-preservation
  semantics so operators can pick correctly.

- **`CHANGELOG.md` metric rename note**: PR sozu-proxy#1238 silently renamed
  `http.301.redirect_template.compile_error` to
  `http.redirect_template.compile_error` (the per-status form would
  have left 302/308 template failures unmonitored). Document the
  rename in the "Breaking changes" section so dashboards scraping
  the old name get updated.

- **`mux/router.rs` redirect-status match**: the wildcard `_ => None`
  arm hid future `RedirectPolicy` variants. Replace with explicit
  `Forward | Unauthorized => None` so adding a new variant fails
  the build and forces a deliberate decision.

Signed-off-by: Florentin Dubois <[email protected]>
jrcribb pushed a commit to jrcribb/sozu that referenced this pull request Aug 10, 2026
Three soft spots in PR sozu-proxy#1238's e2e coverage:

- **`response.contains("302")` would false-positive** on a body or
  `Sozu-Id` header carrying the digits (M3). Switch to a status-line
  prefix check `HTTP/1.1 {expected_status} ` so a regression that
  emits the wrong status under a correct content body is caught.

- **`Box::leak(format!(...))` per call** — the helper was rebuilt on
  every `repeat_until_error_or` retry, leaking a fresh `&'static str`
  each time (M5). Replace with two `const &str` labels
  (`REDIR_302_CLIENT`, `REDIR_308_CLIENT`).

- **No Location-host assertion** (M8). A regression emitting
  `https://:443/...` (empty host) or cross-tenant bleed from a
  state-replay ordering bug would slip through a `starts_with("https://")`
  check. Both helpers now assert the Location host matches the
  frontend's request authority — `localhost` for the H1 helper
  (the `http_request(..., "localhost")` argument) and the matrix
  cell (the SAN baked into the test certs).

- **`client.receive()` is a single read** — under load it sees one
  TCP segment (M4 + repo CLAUDE.md "Always `loop_read_*`"). New
  helper `Client::receive_until_eof(deadline)` loops until the
  upstream half-closes (canonical EOF for `Connection: close`
  default-answer redirects) or the deadline elapses. The H1
  redirect helper switches to it.

The matrix cell helper picks up the same Location-host check and
gains a comment explaining the host-token choice.

`cargo test --locked -p sozu-e2e protocol_pair_matrix::test_redirect`
passes 12 cells; `cargo test --locked -p sozu-e2e -- redirect_rewrite_auth`
passes 20 cells (18 pre-existing + 2 H1 302/308 baselines).

Signed-off-by: Florentin Dubois <[email protected]>
jrcribb pushed a commit to jrcribb/sozu that referenced this pull request Aug 10, 2026
Cosmetic follow-ups on the leaf-dedup landing in PR sozu-proxy#1238:

- Drop `dropped_duplicates > 0` from `info!` to `debug!`. For
  operators feeding `fullchain.pem` (the dominant case the fix
  targets), this fires on every certificate add — signal-only on
  the first cert, noise after. Treat the count as a metric/log
  surface enabled by `log_level = "debug"` rather than a default
  emission. Migration guide cross-updated.

- Drop the `(closes sozu-proxy#1135)` text from the runtime log line.
  Issue references belong in the doc comment / commit / PR text,
  not in operator-visible log envelopes that outlive the PR.

- Trim the 24-line in-function comment block to a 9-line summary.
  The same rationale already lives in the regression-test
  docstrings (`certificate_chain_dedup_drops_duplicate_leaf`,
  `certificate_chain_handles_multi_pem_single_entry`); keeping
  both copies in sync is unnecessary friction.

- `clone()` → `to_owned()` per user CLAUDE.md preferences for
  `&Vec<u8> → Vec<u8>` and `&String → String` ownership transitions
  — clearer ownership intent at the call site.

Signed-off-by: Florentin Dubois <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Remove duplicate certificate if certificate chain is a full chain file Redirect 301, 302, 308 integration with systemd's sd_notify

1 participant