Repository navigation
fix(command-state): order certificate mutations after their fallible steps, and assert no empty bucket - #1405
Merged
Conversation
…cate 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]>
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 21, 2026 22:34
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.
Three ordering bugs in
ConfigState's certificate handling, all the same shape — a fallible stepsequenced after a mutation — plus the invariant that makes the shape impossible to reintroduce
silently. They ship together because the invariant cannot be true without all three fixes.
The reported bug (#1404)
ConfigState::replace_certificateremoved the old fingerprint before computing the new one, andcomputing it parses PEM and can fail:
A malformed PEM therefore left the address with zero certificates. This is issue
#774 surviving in the copy that
#1202's sweep did not reach: that PR fixed
CertificateResolver::replace_certificateinlib/src/tls.rsto add before removing, and nevermirrored it into
ConfigState, which is a second, independent implementation of the same verb.Fixed by computing and inserting the new certificate first, verifying it is present, and removing the
old one only when the fingerprints differ — the last clause also making the idempotent replace (an
ACME or operator retry resubmitting the same PEM) safe by construction rather than by accident.
Two more of the same shape, found while validating the invariant
Adding an invariant that an address never maps to an empty certificate bucket required checking
whether an empty bucket was legitimately reachable. It was, twice:
remove_certificateremoved the fingerprint without checking whether the bucket became empty,so removing an address's last certificate left the key mapped to
{}. This is ordinary certificateremoval, not an edge case. Fixed by evicting the address key, mirroring the
name_fingerprint_idxcleanup
lib/src/tls.rsreceived in fix: fix certificate lookup bugs in CertificateResolver #1202 for the identical leak shape.add_certificatecalledentry(address).or_default()between two fallible steps, so a rejectedadd — valid PEM armor, non-X.509 DER — left a dangling empty bucket on a previously-absent address.
Fixed by creating the entry after both fallible steps.
Why an empty bucket was never benign
check_invariantscarried a comment saying an empty inner map was "a benign no-op for diff/replay".That was wrong before this changeset, in two different ways:
generate_requests'and
diff's. Both normalise away emptybackendsandtcp_frontscollections explicitly, with acomment explaining that
remove_backend/remove_tcp_frontendleave an emptyVecbehind. Noequivalent carve-out exists for certificates, so an empty bucket simply tripped them.
check_invariantsare compiled out, it causessilent certificate loss.
generate_requestsemits zeroAddCertificatefor an empty bucket,and it backs
SaveState, worker bootstrap and the hot-upgrade replay legs — so the certificatequietly disappears on the next reload.
That release-build consequence is the reason these are one changeset and not three.
The invariant
check_invariantsruns on everydispatch, success or failure. Every mutator ofself.certificateswas enumerated —
add_certificate,remove_certificate,replace_certificate, and no other dispatcharm or bulk path touches it — and each is now unable to leave an empty bucket.
Shipping this assertion without the other two fixes was verified to panic an unmodified sozu on
ordinary control-plane sequences:
AddCertificatethenRemoveCertificateof the only certificate,and a single rejected
AddCertificate. Both were reproduced at thedispatchlevel.A correction to this changeset's own earlier claim
An earlier revision of this branch asserted in the commit message, the CHANGELOG and a doc comment
that
worker_request'sstate_hash_beforecheck would have caught #1404 in a debug build. That wasfalse and has been corrected in all three places.
ConfigState::hash_statefolds exactlyclusters,backends,tcp_fronts,http_frontsandhttps_fronts; certificates are not cluster-keyed andnever enter the hash.
check_invariantshad no certificate coverage either.The true statement is the more useful one: nothing covered this in either build profile, which is
why it could ship and sit there.
compute_rollbackNo arm was added, deliberately, and the omission is now pinned by a test asserting it returns
None.A
ReplaceCertificatecarries onlyold_fingerprint, a one-way SHA-256, never the displacedcertificate's PEM or key — checked against
command/src/command.proto— so noRequestvalue canexpress its inverse. That is the same structural reason
AddCertificateandRemoveCertificatearealready absent. The ordering fix closes the internal partial-failure hazard; the separate
"zero workers acknowledged" divergence hazard is pre-existing, shared with the other certificate
verbs, and would need the displaced certificate captured out-of-band before
dispatch.One behaviour improvement worth naming
Before the eviction fix an address could be known but empty, so a
replace_certificateagainst astale
old_fingerprintfor such an address silently succeeded and inserted rather than reportingNotFound. It now correctly reportsNotFound.Tests
Four, three of them proven red by reverting each production hunk in isolation:
replace_certificate_with_malformed_pem_keeps_old_certificatea failed replace must leave the original certificate in place, found []remove_certificate_evicts_the_address_when_its_last_certificate_is_removedfound Some({})add_certificate_with_valid_pem_armor_but_invalid_x509_leaves_no_bucketfound Some({})replace_certificate_with_same_fingerprint_keeps_certificateThe production diff was grepped for literals shared with the test files; none, so the fix is general
rather than test-shaped.
Validation
Suites were run in debug so the new
debug_assert!is live; nothing in the existing corpus trips it.Known gap, not addressed here
UpgradeData.statedoes a raw serde round-trip of the wholeConfigStatefor hot-upgrade re-exec,bypassing
dispatchand thereforecheck_invariants— unlikeSaveState/LoadState, which replayindividual requests through
dispatchand are covered. This is inert today because no remaining pathcan produce an empty bucket, but it means the invariant has no reach at the hot-upgrade boundary: a
future regression there would first surface on an unrelated
dispatchafter the upgrade, not at theupgrade itself.
Closes #1404.