Skip to content

fix: fix certificate lookup bugs in CertificateResolver - #1202

Merged
FlorentinDUBOIS merged 2 commits into
mainfrom
fix/certificate-lookup
Apr 28, 2026
Merged

FlorentinDUBOIS merged 2 commits into
mainfrom
fix/certificate-lookup

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Mar 8, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Two interacting bugs in lib/src/tls.rs causing wrong certificate selection and memory leaks. The third fix from the original PR (try_lock() → blocking lock()) was shipped independently on main during the h2-mux integration trail and is therefore dropped from this PR's scope after rebase.

  1. Remove-before-add in replace_certificate() — Old cert was removed before new cert was added. If the add failed, the old cert was already gone. Reversed order: add new first, remove old second.
  2. Memory leak in name_fingerprint_idx — Empty Vec entries were left in the HashMap after certificate removal. Added cleanup of empty entries. Replaced drain().filter().collect() with retain().

2 new unit tests added.

Closes #774

Test plan

  • cargo test -p sozu-lib --all-features --locked tls:: — 8/8 pass (including 2 new tests)
  • cargo build --all-features --locked clean
  • cargo clippy --all-targets --all-features --locked -- -D warnings clean (matches CI gate .github/workflows/ci.yml:47)
  • cargo +nightly fmt --all -- --check clean

Comment thread lib/src/tls.rs Resolved
Comment thread lib/src/tls.rs Resolved
The MutexCertificateResolver lock-acquisition fix (try_lock → blocking
lock with poisoned-mutex fallback) was already implemented on main in
its let-else form during the h2-mux integration. After rebase this
commit covers the remaining two issues:

  1. replace_certificate ordering: add the new certificate before
     removing the old one so a parse / sign-key failure does not drop
     a working certificate.
  2. name_fingerprint_idx empty-Vec leak in remove_certificate: when
     the last fingerprint for a name is removed, drop the (now-empty)
     index entry instead of leaving an orphan Vec behind.

Two unit tests added (replace_certificate_add_before_remove,
removal_cleans_up_empty_index_entries).

Closes #774

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the fix/certificate-lookup branch from a472708 to 4370358 Compare April 28, 2026 13:46
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 6f71fca into main Apr 28, 2026
28 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the fix/certificate-lookup branch April 28, 2026 15:20
FlorentinDUBOIS added a commit that referenced this pull request May 2, 2026
The CHANGELOG previously carried three concurrent Unreleased blocks —
`## [Unreleased]` (main-scoped post-1.1.1 fixes from PRs #1162, #1191, #1192,
#1193, #1194, #1196, #1202, #1223), `## feat/answer-templates-rewrite-auth -
Unreleased` (answer templates, URL rewrite, basic auth), and
`## feat/h2-mux - Unreleased` (the H2 multiplexer rewrite from PR #1209). All
three feature stacks are on `main`; the per-branch dividers were release-
engineering staging that no longer reflects current state.

Changes:
- Drop the `## feat/answer-templates-rewrite-auth - Unreleased` and
  `## feat/h2-mux - Unreleased` dividers; their bodies now appear under
  `## [Unreleased]` with provenance markers (`### Added — Answer templates / ...`,
  `### Added — H2 multiplexer (PR #1209)`).
- Promote the breaking changes (proto-tag renumbers, dashboard metric renames,
  `http.errors` labelling, pattern-trie regex anchoring, empty-val del-header
  semantic, sub-16393 `buffer_size` rejection, cipher-list constant rename) to
  a top-level `### Breaking changes (v1.1.x → v2.0.0)` paragraph at the top of
  the section so operators see them first.
- Drop emoji from top-level subheaders (🌟 → Added, 🔄 → Changed, ⛑️ → Fixed,
  ✍️ → Changed, 📚 → Documentation, 🤖 → CI, ⚠️ → Behaviour-affecting). Per-
  commit-log subsection at depth ≥ 4 keeps minor emoji ornaments where they
  don't conflict with Keep-a-Changelog vocabulary.
- Preserve historical release entries (`## 1.1.1`, `## 1.1.0`, …) verbatim;
  they are released and immutable.

Net effect: a single `## [Unreleased]` block ready for the v2.0.0 release-cut
in §3.4.c of `tasks/todo.md`. Future passes can de-duplicate the multiple
`### Added`/`### Changed`/`### Fixed` sub-blocks into one each per
Keep-a-Changelog strict shape; this commit is the structural collapse only.

Refs: tasks/todo.md §3.1.a; codex M12 amendment (3-way not 2-way collapse).
Signed-off-by: Florentin Dubois <[email protected]>
jrcribb pushed a commit to jrcribb/sozu that referenced this pull request Aug 10, 2026
jrcribb pushed a commit to jrcribb/sozu that referenced this pull request Aug 10, 2026
…okup

fix: fix certificate lookup bugs in CertificateResolver
jrcribb pushed a commit to jrcribb/sozu that referenced this pull request Aug 10, 2026
The CHANGELOG previously carried three concurrent Unreleased blocks —
`## [Unreleased]` (main-scoped post-1.1.1 fixes from PRs sozu-proxy#1162, sozu-proxy#1191, sozu-proxy#1192,
sozu-proxy#1193, sozu-proxy#1194, sozu-proxy#1196, sozu-proxy#1202, sozu-proxy#1223), `## feat/answer-templates-rewrite-auth -
Unreleased` (answer templates, URL rewrite, basic auth), and
`## feat/h2-mux - Unreleased` (the H2 multiplexer rewrite from PR sozu-proxy#1209). All
three feature stacks are on `main`; the per-branch dividers were release-
engineering staging that no longer reflects current state.

Changes:
- Drop the `## feat/answer-templates-rewrite-auth - Unreleased` and
  `## feat/h2-mux - Unreleased` dividers; their bodies now appear under
  `## [Unreleased]` with provenance markers (`### Added — Answer templates / ...`,
  `### Added — H2 multiplexer (PR sozu-proxy#1209)`).
- Promote the breaking changes (proto-tag renumbers, dashboard metric renames,
  `http.errors` labelling, pattern-trie regex anchoring, empty-val del-header
  semantic, sub-16393 `buffer_size` rejection, cipher-list constant rename) to
  a top-level `### Breaking changes (v1.1.x → v2.0.0)` paragraph at the top of
  the section so operators see them first.
- Drop emoji from top-level subheaders (🌟 → Added, 🔄 → Changed, ⛑️ → Fixed,
  ✍️ → Changed, 📚 → Documentation, 🤖 → CI, ⚠️ → Behaviour-affecting). Per-
  commit-log subsection at depth ≥ 4 keeps minor emoji ornaments where they
  don't conflict with Keep-a-Changelog vocabulary.
- Preserve historical release entries (`## 1.1.1`, `## 1.1.0`, …) verbatim;
  they are released and immutable.

Net effect: a single `## [Unreleased]` block ready for the v2.0.0 release-cut
in §3.4.c of `tasks/todo.md`. Future passes can de-duplicate the multiple
`### Added`/`### Changed`/`### Fixed` sub-blocks into one each per
Keep-a-Changelog strict shape; this commit is the structural collapse only.

Refs: tasks/todo.md §3.1.a; codex M12 amendment (3-way not 2-way collapse).
Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS added a commit that referenced this pull request Sep 21, 2026
…cate (#1405)

ConfigState::replace_certificate (command/src/state.rs) removed the old
fingerprint from the address's certificate map before computing the new
fingerprint, and computing it (calculate_fingerprint -> parse_pem) is
fallible. A malformed ReplaceCertificate.new_certificate.certificate made
the `?` propagate after the old entry was already gone, leaving the
address with zero certificates.

Nothing existing caught it. The two postcondition debug_assert!s at the
end of replace_certificate are debug-only and only run on the Ok path the
early return skipped. worker_request's (bin/src/command/requests.rs)
state_hash_before no-op check does not cover this either: ConfigState::
hash_state folds only self.clusters, self.backends, self.tcp_fronts,
self.http_fronts and self.https_fronts -- never self.certificates, as
verified by reading the function body directly. And ConfigState::
check_invariants, the debug-only postcondition run inside dispatch
itself, had no certificate coverage at all before this changeset: its
existing comment on the certificates block explicitly said an empty
inner map was "a benign no-op for diff/replay" and left it unchecked. No
invariant in debug or release builds covered self.certificates before
this changeset -- which is exactly why this bug could ship silently and
sit there.

This is #774 surviving in a second, independent
implementation of the same verb. CertificateResolver::replace_certificate
in lib/src/tls.rs was fixed for exactly this ordering in #1202 ("now adds
the new certificate before removing the old one"); that fix was never
mirrored into ConfigState's own copy.

replace_certificate now computes and inserts the new certificate first,
and only removes the old fingerprint once the insert is confirmed present
-- and, mirroring #1202's idempotent-replace guard, skips that removal
when old and new fingerprints are equal, so an operator or ACME retry
loop resubmitting the same PEM does not delete the entry it meant to
keep.

check_invariants now asserts every self.certificates[address] bucket is
non-empty, closing the actual coverage gap. Making that assertion sound
required investigating whether an empty bucket is ever legitimately
reachable, and it is -- twice, both found and fixed in this changeset:

- remove_certificate removed the fingerprint from the address's inner
  map but never evicted the address key itself, so removing an address's
  LAST certificate through the ordinary, successful AddCertificate +
  RemoveCertificate sequence left a dangling self.certificates[address]
  == {} entry. This already silently broke generate_requests's own
  round-trip replay debug_assert before this fix (an empty bucket
  contributes zero AddCertificate requests, so replaying them into a
  fresh ConfigState never recreates the entry) -- reproduced directly.
  Mirrors the name_fingerprint_idx empty-entry leak #1202 fixed in
  lib/src/tls.rs's sibling remove_certificate. Fixed by evicting the
  address key once its bucket empties.

- add_certificate called self.certificates.entry(address).or_default()
  -- unconditionally materialising a bucket for the address, including a
  brand-new one -- BEFORE apply_overriding_names, its second fallible
  step (it re-parses full X.509 when names is empty). Valid PEM armor
  wrapping invalid X.509 DER content therefore left a dangling empty
  bucket behind for a previously-absent address on a REJECTED add, the
  same "mutate before the fallible step" defect class as
  replace_certificate's own bug -- reproduced directly. Fixed by moving
  entry() after both fallible steps.

compute_rollback (bin/src/command/requests.rs) gets no new arm for
ReplaceCertificate. That function derives its inverse purely from the
request's own fields; every covered verb's Add request already carries
everything its Remove inverse needs. A ReplaceCertificate's only identity
for the certificate it displaces is old_fingerprint, a one-way SHA-256
hash, never the displaced certificate's PEM/key content -- so no Request
value can express "put the old certificate back" from the request alone.
This is the same reason AddCertificate/RemoveCertificate are absent from
compute_rollback today. The decision is pinned by a new assertion in
rollback_inverse_targets_the_same_listener_and_skips_uncovered_verbs.

Regression tests in command/src/state.rs:
- replace_certificate_with_malformed_pem_keeps_old_certificate (red on
  the prior ordering, green after the fix)
- replace_certificate_with_same_fingerprint_keeps_certificate (already
  green on prior code by incidental re-insert-after-remove; still pinned
  under the new explicit short-circuit)
- remove_certificate_evicts_the_address_when_its_last_certificate_is_removed
  (red on prior remove_certificate, green after the fix)
- add_certificate_with_valid_pem_armor_but_invalid_x509_leaves_no_bucket
  (red on prior add_certificate, green after the fix)

CHANGELOG.md gains a matching entry under Unreleased / Fixed.

Closes #1404

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.

Could not look up a certificate for server name 'domain'

2 participants