Skip to content

fix(command-state): order certificate mutations after their fallible steps, and assert no empty bucket - #1405

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
fix/state-replace-certificate-ordering
Sep 21, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
fix/state-replace-certificate-ordering

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

Three ordering bugs in ConfigState's certificate handling, all the same shape — a fallible step
sequenced 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_certificate removed the old fingerprint before computing the new one, and
computing it parses PEM and can fail:

.remove(&old_fingerprint);                                        // (1) old certificate gone
let new_fingerprint = Fingerprint(calculate_fingerprint(...)?);    // (2) can return Err

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_certificate in lib/src/tls.rs to add before removing, and never
mirrored 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_certificate removed the fingerprint without checking whether the bucket became empty,
    so removing an address's last certificate left the key mapped to {}. This is ordinary certificate
    removal, not an edge case. Fixed by evicting the address key, mirroring the name_fingerprint_idx
    cleanup lib/src/tls.rs received in fix: fix certificate lookup bugs in CertificateResolver #1202 for the identical leak shape.
  • add_certificate called entry(address).or_default() between two fallible steps, so a rejected
    add — 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_invariants carried 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:

  • In debug builds it already broke two pre-existing round-trip assertions — generate_requests'
    and diff's. Both normalise away empty backends and tcp_fronts collections explicitly, with a
    comment explaining that remove_backend/remove_tcp_frontend leave an empty Vec behind. No
    equivalent carve-out exists for certificates, so an empty bucket simply tripped them.
  • In release builds, where those assertions and check_invariants are compiled out, it causes
    silent certificate loss. generate_requests emits zero AddCertificate for an empty bucket,
    and it backs SaveState, worker bootstrap and the hot-upgrade replay legs — so the certificate
    quietly disappears on the next reload.

That release-build consequence is the reason these are one changeset and not three.

The invariant

for (address, certs) in &self.certificates {
    debug_assert!(!certs.is_empty(), "certificate bucket for address {address} must never be empty (sozu-proxy/sozu#1404)");
}

check_invariants runs on every dispatch, success or failure. Every mutator of self.certificates
was enumerated — add_certificate, remove_certificate, replace_certificate, and no other dispatch
arm 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: AddCertificate then RemoveCertificate of the only certificate,
and a single rejected AddCertificate. Both were reproduced at the dispatch level.

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's state_hash_before check would have caught #1404 in a debug build. That was
false and has been corrected in all three places. ConfigState::hash_state folds exactly clusters,
backends, tcp_fronts, http_fronts and https_fronts; certificates are not cluster-keyed and
never enter the hash. check_invariants had 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_rollback

No arm was added, deliberately, and the omission is now pinned by a test asserting it returns None.
A ReplaceCertificate carries only old_fingerprint, a one-way SHA-256, never the displaced
certificate's PEM or key — checked against command/src/command.proto — so no Request value can
express its inverse. That is the same structural reason AddCertificate and RemoveCertificate are
already 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_certificate against a
stale old_fingerprint for such an address silently succeeded and inserted rather than reporting
NotFound. It now correctly reports NotFound.

Tests

Four, three of them proven red by reverting each production hunk in isolation:

test red proof
replace_certificate_with_malformed_pem_keeps_old_certificate a failed replace must leave the original certificate in place, found []
remove_certificate_evicts_the_address_when_its_last_certificate_is_removed found Some({})
add_certificate_with_valid_pem_armor_but_invalid_x509_leaves_no_bucket found Some({})
replace_certificate_with_same_fingerprint_keeps_certificate not red — it passed on the buggy code too, by incidental re-insertion after removal. Kept as a pin under the new explicit short-circuit, and labelled as a pin rather than a regression test.

The production diff was grepped for literals shared with the test files; none, so the fix is general
rather than test-shaped.

Validation

cargo +1.93.1 build --all-features --locked                       -> exit 0
cargo +1.93.1 clippy --all-targets --all-features -- -D warnings  -> exit 0
cargo +nightly fmt --all -- --check                               -> exit 0
cargo +1.93.1 test -p sozu-command-lib --locked                   -> 158 passed, 0 failed
cargo +1.93.1 test -p sozu --locked                               -> 104 passed, 0 failed
python3 .github/scripts/check_doc_citations.py --base origin/main -> exit 0

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.state does a raw serde round-trip of the whole ConfigState for hot-upgrade re-exec,
bypassing dispatch and therefore check_invariants — unlike SaveState/LoadState, which replay
individual requests through dispatch and are covered. This is inert today because no remaining path
can 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 dispatch after the upgrade, not at the
upgrade itself.

Closes #1404.

…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
FlorentinDUBOIS merged commit 6dd569e into main Sep 21, 2026
24 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the fix/state-replace-certificate-ordering branch September 21, 2026 23:50
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.

command/state: ReplaceCertificate removes the old certificate before validating the new one, so a malformed PEM leaves the address with none

1 participant