Skip to content

fix(issuing): do not fail issuance for a request built from a replaced key - #9116

Merged
cert-manager-prow[bot] merged 1 commit into
cert-manager:masterfrom
thc1006:fix-stale-cr-key-mismatch-failure
Aug 10, 2026
Merged

cert-manager-prow[bot] merged 1 commit into
cert-manager:masterfrom
thc1006:fix-stale-cr-key-mismatch-failure

Conversation

@thc1006

@thc1006 thc1006 commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Pull Request Motivation

Fixes #6331

That issue has been open since 2023 and people keep arriving on it with the same pair of log lines:

"next private key does not match CSR public key, waiting for requestmanager controller"
"Error generating certificate template" err="CSR not signed by referenced private key"

The two lines say opposite things about the same request, and that turns out to be the whole bug.

ProcessItem acts on a CertificateRequest's terminal state before it checks whether the request's CSR still matches the Certificate's current next private key. When the key is replaced while a request is in flight, the self-signed issuer marks that request Failed with ErrorKeyMatch, and this controller reads the failure first: it bumps the issuance attempts and drops the Issuing condition, so the certificate sits out a backoff for a request the requestmanager is about to delete and rebuild against the new key.

The mismatch check already exists a few lines below and already does the right thing by waiting. It was simply unreachable once the request had failed. This moves it above Denied, InvalidRequest and Failed, so the "is this request stale?" question is settled before any terminal state is acted on. The requestmanager deletes a mismatched request regardless of its condition, so none of those verdicts describe the current issuance.

There is a related guard a little earlier that catches a request which failed before the Issuing condition was last set, a leftover from a previous issuance. It does not help here, because in this race the request fails part way through the current issuance, so its FailureTime is newer than the Issuing transition.

Known limitation

The reports on #6331 describe certificates "never renewing again". The only concrete logs on the issue (a v1.13 cluster) show the certificate recovering automatically after the failed-issuance backoff, so that description is the bounded backoff (1h by default, up to the 32h cap) read as permanent, rather than a separate never-recovers stall. This PR removes that backoff.

One residual window remains. This controller reads the next private key through its secret informer, so if that cache still holds the old key when it reconciles the failed request, the mismatch check passes and issuance fails exactly as before. The race is narrowed, not eliminated.

Two behaviour changes worth stating:

  1. A genuine issuer failure that coincides with a key rotation is no longer counted towards failedIssuanceAttempts, so the rebuilt request is retried without backoff. That is the intended trade-off.
  2. A failed request whose CSR carries an unsupported public key type now makes PublicKeyMatchesCSR return an error and requeue, where previously issuance failed. It needs a hand-crafted request, and the requestmanager already errors on the same input, so I have left it alone.

What does not change

A request that fails for a real reason still fails. Its CSR matches the current key, so it reaches the failure branch exactly as before, which the existing "has failed for the first time / fifth time during this series of attempts" cases cover. If the underlying problem persists, the rebuilt request fails again with a matching key and issuance is marked failed then.

An undecodable CSR cannot reach the moved check either: RequestMatchesSpec decodes the request earlier in the same function and returns that error.

Testing

The new case carries a FailureTime set after the Certificate's Issuing transition, so it is not absorbed by the earlier "failed during a previous issuance" branch and matches the timing in the issue, where the request fails part way through the current issuance. It otherwise mirrors the existing "is ready, but the private key stored in the Secret does not match that creating the CSR" case, with the request failed instead of ready. That combination was the one gap in the table. Reverting only issuing_controller.go makes it fail with the symptom from the issue:

got unexpected events, exp='[]'
got='[Warning Failed The certificate request has failed to complete and will be retried:
      CSR not signed by referenced private key]'

along with the update status certificates call that bumps the failed issuance attempt, which is what users experience as the wait.

Kind

/kind bug

Release Note

Fixed an issue where rotating a Certificate's next private key while a CertificateRequest was in flight could mark the issuance as failed and delay it by a backoff, instead of waiting for the request to be rebuilt against the new key.

@cert-manager-prow cert-manager-prow Bot added release-note Denotes a PR that will be considered when it comes time to generate release notes. kind/bug Categorizes issue or PR as related to a bug. dco-signoff: yes Indicates that all commits in the pull request have the valid DCO sign-off message. needs-ok-to-test Indicates a PR that requires an org member to verify it is safe to test. labels Aug 10, 2026
@cert-manager-prow

Copy link
Copy Markdown
Contributor

Hi @thc1006. Thanks for your PR.

I'm waiting for a cert-manager member to verify that this patch is reasonable to test. If it is, they should reply with /ok-to-test on its own line. Until that is done, I will not automatically test new commits in this PR, but the usual testing commands by org members will still work.

Regular contributors should join the org to skip this step.

Once the patch is verified, the new status will be reflected by the ok-to-test label.

I understand the commands that are listed here.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@cert-manager-prow cert-manager-prow Bot added the size/M Denotes a PR that changes 30-99 lines, ignoring generated files. label Aug 10, 2026
@wallrj
wallrj requested a lite review from Copilot August 10, 2026 14:59
@wallrj

wallrj commented Aug 10, 2026

Copy link
Copy Markdown
Member

/ok-to-test

with claude fable-5

@cert-manager-prow cert-manager-prow Bot added ok-to-test and removed needs-ok-to-test Indicates a PR that requires an org member to verify it is safe to test. labels Aug 10, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Warning

Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.

Fixes a race where a CertificateRequest that becomes Failed due to a private key rotation is treated as stale (wait for rebuild) rather than counting as an issuance failure and triggering backoff.

Changes:

  • Reorders logic in ProcessItem to check CSR↔key mismatch before handling Failed CertificateRequests.
  • Adds a regression test covering the “failed request + replaced key” scenario to ensure no failure/backoff is triggered.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
pkg/controller/certificates/issuing/issuing_controller.go Moves the key-mismatch (stale request) check ahead of the failure branch so stale failures don’t count as issuance failures.
pkg/controller/certificates/issuing/issuing_controller_test.go Adds a table test case reproducing the stale-but-failed request scenario and asserting no actions/events occur.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@thc1006
thc1006 force-pushed the fix-stale-cr-key-mismatch-failure branch from 4aa2ae4 to fb6f6eb Compare August 10, 2026 15:25

@wallrj wallrj left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @thc1006 — this is a well-researched fix and the PR description made it easy to verify. I traced the race independently and your claims check out:

  • The self-signed issuer permanently fails a request with ErrorKeyMatch when the referenced key changes under it:
    ok, err = pki.PublicKeysEqual(publickey, template.PublicKey)
    if err != nil || !ok {
    if err == nil {
    err = errors.New("CSR not signed by referenced private key")
    }
    message := "Error generating certificate template"
    s.reporter.Failed(cr, err, "ErrorKeyMatch", message)
    log.Error(err, message)
    return nil, nil
    }
  • "Do nothing and wait" is safe: the requestmanager deletes an owned request whose CSR does not match the current next private key regardless of its Ready condition, then recreates it:
    requests, err = c.deleteRequestsNotMatchingSpec(ctx, crt, pk.Public(), requests...)
    and
    if !matches {
    log.V(logf.DebugLevel).Info("CertificateRequest contains a CSR that does not have the same public key as the stored next private key secret, deleting CertificateRequest")
    if err := c.client.CertmanagerV1().CertificateRequests(req.Namespace).Delete(ctx, req.Name, metav1.DeleteOptions{}); err != nil {
    return nil, err
    }
    continue
  • RequestMatchesSpec decodes the CSR first, so an undecodable CSR errors before reaching the moved check:
    func RequestMatchesSpec(req *cmapi.CertificateRequest, spec cmapi.CertificateSpec) ([]string, error) {
    x509req, err := DecodeX509CertificateRequestBytes(req.Spec.Request)

Thanks also for folding in the Copilot wording nit and adding FailureTime to the test in the force-push.

Two asks before this merges:

  1. Same bug, two more paths — the Denied and InvalidRequest branches still fail issuance for a stale-keyed request. See the inline comment.
  2. "Fixes #6331" may over-claim. The reports on that issue say certificates are "not being renewed ever again", but the behaviour this PR removes is a bounded backoff (the trigger controller retries), not a permanent stall. There is also a residual window: if this controller's secret informer cache still holds the old key when it reconciles the failed request, the mismatch check passes and we fail issuance exactly as before — the race is narrowed, not closed. I suggest non-closing wording ("Improves #6331") so the issue stays open to track the permanent-stall reports, plus a sentence in the description acknowledging the narrowed-not-closed window.

One pre-existing bug I spotted in the surrounding code — not caused by this PR, fine as a follow-up: the guard at

if req.Status.FailureTime != nil &&
req.Status.FailureTime.Before(certIssuingCond.LastTransitionTime) && crReadyCond.Reason == cmapi.CertificateRequestReasonFailed {
log.V(logf.InfoLevel).Info("Found a failed CertificateRequest from previous issuance, waiting for it to be deleted...")
return nil
}
dereferences crReadyCond.Reason, but the crReadyCond == nil check only happens later at
if crReadyCond == nil {
log.V(logf.DebugLevel).Info("CertificateRequest does not have Ready condition, waiting...")
return nil
}
, so a request with status.failureTime set and no Ready condition would panic the controller.

with claude fable-5

}

// If public key does not match, do nothing (requestmanager will handle this).
// Check this before handling a failed request, or a stale one is counted as an

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Denied and InvalidRequest branches above (L311 and L318) have the same problem this PR fixes for Failed: a stale-keyed request that is denied or marked invalid still calls failIssueCertificate before reaching this check, dropping Issuing and imposing backoff for a request the requestmanager is about to delete and recreate anyway (it deletes mismatched requests regardless of their Ready condition:

if !matches {
log.V(logf.DebugLevel).Info("CertificateRequest contains a CSR that does not have the same public key as the stored next private key secret, deleting CertificateRequest")
if err := c.client.CertmanagerV1().CertificateRequests(req.Namespace).Delete(ctx, req.Name, metav1.DeleteOptions{}); err != nil {
return nil, err
}
continue
).

Could you hoist this check above those two branches as well, so the "is this request stale?" question is settled before any terminal-state handling?

// If the certificate request has failed, set the last failure time to
// now, bump the issuance attempts and set the Issuing status condition
// to False.
if crReadyCond.Reason == cmapi.CertificateRequestReasonFailed {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two behaviour changes from the reorder worth noting; neither is blocking:

  1. A genuine issuer failure that coincides with a key rotation is no longer counted towards failedIssuanceAttempts, so the rebuilt request is retried immediately with no backoff. That is the intended trade-off, but worth a sentence in the PR description.
  2. Edge case: a Failed request whose CSR carries an unsupported public key type now makes PublicKeyMatchesCSR return an error and requeue forever, where previously we failed the issuance. It is contrived (requires a hand-crafted request) and the requestmanager already errors on the same request (
    matches, err := pki.PublicKeyMatchesCSR(publicKey, x509Req)
    if err != nil {
    return nil, err
    ), so I do not think it needs fixing here — just flagging the change.

gen.AddCertificateRequestAnnotations(map[string]string{
cmapi.CertificateRequestRevisionAnnotationKey: "2", // Current Certificate revision=1
}),
gen.SetCertificateRequestStatusCondition(cmapi.CertificateRequestCondition{

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: the sibling failed-request cases build on exampleBundle.CertificateRequestFailed (e.g. L228) rather than hand-rolling the Ready=Failed condition. Basing this case on that fixture — keeping your explicit FailureTime override — keeps the table consistent and picks up any future changes to how the fixture models failures.

…d key

The issuing controller acts on a CertificateRequest's terminal state before it
checks whether the request's CSR still matches the Certificate's current next
private key. When the key is replaced while a request is in flight, the
self-signed issuer marks that request Failed with ErrorKeyMatch, and this
controller reads the failure first: it bumps the issuance attempts and drops the
Issuing condition, so the certificate waits out a backoff for a request that the
requestmanager is about to delete and rebuild against the new key.

The mismatch check already existed further down and already did the right thing
by waiting, it was simply unreachable once the request had reached a terminal
state. It now runs before Denied, InvalidRequest and Failed are acted on, since
the requestmanager deletes a mismatched request regardless of its condition, so
none of those verdicts say anything about the current issuance.

A request that fails for a real reason still fails: its CSR matches the current
key, so it reaches the failure branch exactly as before. If the underlying problem
persists, the rebuilt request fails again with a matching key and issuance is
marked failed then.

An undecodable CSR cannot reach the moved check either, because RequestMatchesSpec
decodes the request earlier in the same function and returns that error.

The regressions carry a FailureTime after the Certificate's Issuing transition, so
they are not caught by the earlier "failed during a previous issuance" branch and
reproduce the timing from the issue.

Signed-off-by: thc1006 <[email protected]>
@thc1006
thc1006 force-pushed the fix-stale-cr-key-mismatch-failure branch from fb6f6eb to 3c15d43 Compare August 10, 2026 15:43
@thc1006

thc1006 commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for tracing it independently, and for the two extra paths. Both asks are in 3c15d43.

Denied and InvalidRequest. You are right that they have the same shape, and the requestmanager link settles it: a mismatched request is deleted whatever its condition, so none of the three verdicts describe the current issuance. The mismatch check now sits above all of them, right after RequestMatchesSpec, so staleness is settled before any terminal state is read. That also keeps it clear of the nil dereference you spotted, though it does not fix it. I added a Denied regression alongside the Failed one; reverting the reorder fails both.

Wording. Changed to "Improves #6331" so the issue stays open for the never-renews-again reports, and the description now says what is left: this removes a bounded backoff rather than a permanent stall, and if this controller's secret informer still holds the old key when it reconciles, the mismatch check passes and issuance fails as before. Narrowed, not closed.

I also noted your two behaviour observations in the description: a genuine failure coinciding with a rotation no longer counts towards failedIssuanceAttempts, and the unsupported-key-type case now requeues instead of failing.

The nil dereference. Confirmed: crReadyCond.Reason is read at L286 while the nil check is at L322, so a request with failureTime and no Ready condition panics the controller. Happy to send that as a separate PR with its own test, since it is reachable without any of this.

Test case rebased onto exampleBundle.CertificateRequestFailed as suggested, keeping the explicit FailureTime override.

@wallrj

wallrj commented Aug 10, 2026

Copy link
Copy Markdown
Member

Filed the pre-existing nil-deref I mentioned in my review as #9119 — reproduced it against clean master with a unit test, so it's not caused by this PR (which only moves code around that guard). Noting it here so it's not conflated with this change. A one-line reorder fixes it; happy to send that separately.

with claude fable-5

@wallrj wallrj left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both asks are addressed and it reads well now.

  • The mismatch check sits above Denied, InvalidRequest and Failed, right after RequestMatchesSpec, so staleness is settled before any terminal state is read. The new Denied regression pins that, and the description spells out why none of the three verdicts describe the current issuance.
  • "Improves #6331" with the "What this does not close" section is exactly right: the bounded-backoff-vs-permanent-stall distinction and the residual informer-cache window are both stated, so the issue stays open for the never-renews reports.
  • Test rebased onto CertificateRequestFailed with the explicit FailureTime override, and the two behaviour changes are noted.

The nil dereference is out of scope here as we agreed (#9119), reachable without any of this.

Presubmits are green. Thanks for the careful iteration.


One aside, since it puzzled me too: the comment above that block has said "If public key does not match, do nothing (requestmanager will handle this)" since 2020, so how did we ever reach a state where the controller fails the issuance on a mismatch? Short version: the check was never a gate in front of the failure branch — it began life inside the success path and a 2020 refactor hoisted it below the failure handling, comment and all. It has been latent since the controller's first day. Full archaeology (with commit permalinks): https://gist.github.com/wallrj/0d5b62deb7646e8ecaaa1e7604d6c665

with claude fable-5

@cert-manager-prow

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: wallrj

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@cert-manager-prow cert-manager-prow Bot added the approved Indicates a PR has been approved by an approver from all required OWNERS files. label Aug 10, 2026
@wallrj

wallrj commented Aug 10, 2026

Copy link
Copy Markdown
Member

I've edited the description: Improves #6331 → Fixes #6331, so GitHub links the two and the issue closes on merge.

Reason: I went back to the issue evidence. @dkoshkin's logs (the only concrete data there) show the certificate recovering automatically after the 1h failed-issuance backoff, not stalling forever — so the "never renews again" reports are that bounded backoff (up to the 32h cap) read as permanent, which is exactly what this PR removes. My earlier "Improves" nit leaned too much on taking that "never" at face value, and I don't think it holds up. I've written it up on #6331 and in this gist: https://gist.github.com/wallrj/0d5b62deb7646e8ecaaa1e7604d6c665

I also renamed your "What this does not close" section to "Known limitation" so it doesn't contradict Fixes, keeping your residual-informer-cache caveat intact. Please reword or revert if you'd rather phrase it yourself.

with claude fable-5

@wallrj

wallrj commented Aug 10, 2026

Copy link
Copy Markdown
Member

/lgtm

@cert-manager-prow cert-manager-prow Bot added the lgtm Indicates that a PR is ready to be merged. label Aug 10, 2026
@cert-manager-prow
cert-manager-prow Bot merged commit fadd523 into cert-manager:master Aug 10, 2026
6 checks passed
@thc1006
thc1006 deleted the fix-stale-cr-key-mismatch-failure branch August 10, 2026 17:22
cert-manager-prow Bot pushed a commit that referenced this pull request Nov 23, 2026
Manual cherry-pick of #9116 to release-1.21.

The two new test cases use nextPrivateKeySecretMeta, as master does since
#9224, because #9368 is already on this branch and the issuing controller
ignores a next private key Secret that the Certificate does not own.

(cherry picked from commit fadd523)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Richard Wall <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved Indicates a PR has been approved by an approver from all required OWNERS files. dco-signoff: yes Indicates that all commits in the pull request have the valid DCO sign-off message. kind/bug Categorizes issue or PR as related to a bug. lgtm Indicates that a PR is ready to be merged. ok-to-test release-note Denotes a PR that will be considered when it comes time to generate release notes. size/M Denotes a PR that changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CSR not signed by referenced private key

3 participants