Skip to content

fix: Record Warning events for silent per-Certificate failures - #9199

Merged
cert-manager-prow[bot] merged 3 commits into
cert-manager:masterfrom
lunarwhite:fix-warn-event
Sep 1, 2026
Merged

cert-manager-prow[bot] merged 3 commits into
cert-manager:masterfrom
lunarwhite:fix-warn-event

Conversation

@lunarwhite

@lunarwhite lunarwhite commented Aug 25, 2026 •

Copy link
Copy Markdown
Member

Pull Request Motivation

Fixes #9182

Note that the scope is a bit wider than reported. The original one mentioned pki.EncodeCSR and pem.Encode, I swept pkg/controller/certificates/ for the same defect and fixed what turned up. For easy review they are in separate commits.

  1. requestmanager: the two paths No Warning event when CSR encoding fails in the requestmanager controller #9182 names are fixed structurally rather than evented. Adds the PrivateKeyMatchesSpec guard the issuing controller already has, so we wait for the keymanager instead of rebuilding a CSR that cannot be signed; pem.Encode becomes pem.EncodeToMemory, which has no error return. The remaining unreachable branch keeps its comment and records no event.
  2. issuing: one event at the setValues choke point rather than per-site ones in setKeystores, which also covers empty literal passwords, non-NotFound password Secret errors, additionalOutputFormats and an undecodable issued cert — all previously silent. The temporary certificate event sits at the call site so it covers EncodePrivateKey too.
  3. requestmanager: the waitForCertificateRequestToExist timeout, and RequestConflict on the len(requests) > 1 branch. That one is silent and terminal, it returns nil, so nothing requeues and issuance stops until a human deletes the extra CertificateRequests.

I used AI to scan outside pkg/controller/certificates/, it turns out that the category is already covered: issuers/sync.go events every Setup error, the certificaterequests issuers go through util.Reporter, ACME uses Status.Reason, cainjector has no recorder.

Kind

/kind bug

Release Note

Record Secret data failures, temporary certificate signing failures, and conflicting CertificateRequests as Warning events on the `Certificate` instead of only logging them. The certificates-request-manager controller now waits for the keymanager when the next private key does not match the Certificate spec, instead of repeatedly building a CSR that cannot be signed.

@cert-manager-prow cert-manager-prow Bot added kind/bug Categorizes issue or PR as related to a bug. release-note Denotes a PR that will be considered when it comes time to generate release notes. dco-signoff: yes Indicates that all commits in the pull request have the valid DCO sign-off message. size/L Denotes a PR that changes 100-499 lines, ignoring generated files. labels Aug 25, 2026
@lunarwhite

Copy link
Copy Markdown
Member Author

/label tide/merge-method-squash

@cert-manager-prow cert-manager-prow Bot added the tide/merge-method-squash Denotes a PR that should be squashed by tide when it merges. label Aug 25, 2026
@lunarwhite

Copy link
Copy Markdown
Member Author

kindly

/cc @wallrj

for review

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

This PR improves observability of per-Certificate failures in the certificates controllers by recording Kubernetes Warning events for several previously “log-only” (or silent) error paths, ensuring users can diagnose stuck Ready=False Certificates without relying on controller logs.

Changes:

  • Record Warning events for CSR encoding/PEM encoding/name computation failures during CertificateRequest creation, and for informer-staleness timeouts when waiting for a newly-created CertificateRequest to be observed.
  • Record Warning events for temporary certificate signing failures.
  • Record Warning events for keystore/truststore encoding failures and for password SecretRef key-missing scenarios, with accompanying unit tests.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
pkg/controller/certificates/requestmanager/requestmanager_controller.go Adds Warning events for CSR encode/PEM encode/name computation errors and for CertificateRequest lister-wait failure.
pkg/controller/certificates/requestmanager/requestmanager_controller_test.go Adds unit tests covering CSR encode failure and lister wait timeout event emission.
pkg/controller/certificates/issuing/temporary.go Records a Warning event when temporary certificate signing fails.
pkg/controller/certificates/issuing/temporary_test.go Adds a unit test asserting the Warning event is recorded on signer failure.
pkg/controller/certificates/issuing/issuing_controller.go Introduces event reason constant for temporary certificate failure.
pkg/controller/certificates/issuing/internal/secret.go Adds event reasons and records Warning events for missing password key data and keystore/truststore encoding failures.
pkg/controller/certificates/issuing/internal/secret_test.go Updates tests to use FakeRecorder and adds assertions for newly-recorded keystore-related events.

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

@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 @lunarwhite — the goal is right and the tests are unusually careful. I've consolidated this review with the Copilot one: its point about the hard-coded timeout diagnosis is fixed by your latest push (I've replied on that thread with two follow-ups), and its grammar nit is a false positive (see reply there).

The themes below:

  1. Two of the new events sit on branches the PR's own comments prove unreachable — I'd drop those two Eventf calls.
  2. The CSR-encode event papers over a missing PrivateKeyMatchesSpec guard that the issuing controller already has for the same race.
  3. In setKeystores, one event at the choke point covers strictly more failure paths with less code — and the permanent misconfigurations arguably want a condition, not just a repeating event.

with claude fable-5

// request is retried with backoff instead of being treated as terminal.
csrDER, err := pki.EncodeCSR(x509CSR, pk)
if err != nil {
c.recorder.Eventf(crt, corev1.EventTypeWarning, reasonRequestFailed, "Failed to encode CSR: %s", err.Error())

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 issuing controller handles this same race structurally rather than by eventing: it calls utilpki.PrivateKeyMatchesSpec and returns silently to wait for the keymanager (issuing_controller.go#L234-L239). requestmanager has no such guard, so during the repair window every reconcile builds a CSR, fails EncodeCSR, requeues rate-limited, and now emits a Warning on each pass — and the window is unbounded if the keymanager is wedged or its Secret delete is denied by RBAC.

For the persistent form (rotationPolicy unset/Never with a mismatched stored key) the keymanager already records an actionable Warning naming the exact field to change (keymanager_controller.go#L268-L271), so the user would see both that and this newer, unactionable one.

Suggest adding the same PrivateKeyMatchesSpec guard here (log and return nil, as the issuing controller does) instead of the event — that removes both the event repetition and the wasted CSR work.

// bytes.Buffer never fails.
err = pem.Encode(csrPEM, &pem.Block{Type: "CERTIFICATE REQUEST", Bytes: csrDER})
if err != nil {
c.recorder.Eventf(crt, corev1.EventTypeWarning, reasonRequestFailed, "Failed to PEM encode CSR: %s", err.Error())

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.

Here and at L442 the new comments prove the branch can never execute, which makes these the only two new events in the PR that are untestable (and untested). I'd drop both Eventf calls and keep the comments.

For this one you can go further: pem.EncodeToMemory has no error return (already the pattern in pkg/util/pki/generate.go#L151), which deletes the branch, the buffer and the comment in one edit. And ComputeSecureUniqueDeterministicNameFromData only errors when maxNameLength < 64 (names.go#L58-L62), confirming your comment at L436-L438.


keystoreData, err := encodePKCS12Keystore(profile, string(pw), data.PrivateKey, data.Certificate, data.CA)
if err != nil {
s.recorder.Eventf(crt, corev1.EventTypeWarning, reasonKeystoreEncodeFailed, "Failed to encode PKCS12 keystore: %s", err.Error())

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.

Six Eventf+return pairs in setKeystores, while sibling failures of exactly the class this PR targets stay silent: empty literal passwords (L285, L343), non-NotFound password-Secret fetch errors (L273, L331), and setAdditionalOutputFormats (L155) — a bad additionalOutputFormats entry still fails silently forever.

All of these funnel through the single wrap in setValues (L151), so one Eventf at that choke point (or on UpdateData's error return) covers strictly more with a smaller diff — and the next error return someone adds inside setKeystores can't silently reintroduce the bug this PR fixes.

}

if pwSecret.Data == nil || len(pwSecret.Data[ref.Key]) == 0 {
s.recorder.Eventf(crt, corev1.EventTypeWarning, reasonKeystorePasswordSecretKeyNotFound, "PKCS12 keystore password Secret %q contains no data for key %q", ref.Name, ref.Key)

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.

A missing password key is permanent until a human fixes it, and setKeystores is also on the steady-state path (ensureSecretData → secretsUpdateData → UpdateData), so this Warning repeats on every rate-limited requeue for as long as the misconfiguration exists.

client-go bounds the write rate — burst of 25, then ~1 per 5 minutes (events_cache.go#L47-L48) — but the spam-filter key is source+object+type, not reason (events_cache.go#L70-L82), so a stuck Certificate's repeating keystore Warnings share one budget with every other Warning this controller records for that Certificate, and can crowd them out. And since Events are GC'd (1 h default TTL), the morning-after view is a stuck Certificate with no explanation again.

For a permanent, user-fixable state the stronger fix is pairing the event with a condition (as failIssueCertificate does) or emitting only when the reason changes. Fine as a follow-up, but worth deciding deliberately.

}
certData, err := c.localTemporarySigner(crt, pkData)
if err != nil {
c.recorder.Eventf(crt, corev1.EventTypeWarning, reasonTemporaryCertificateFailed, "Failed to generate temporary certificate: %s", err.Error())

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.

utilpki.EncodePrivateKey at L62 is the same class of failure — a rejected spec.privateKey.encoding loops forever with only a log line, the exact symptom this PR is fixing — and stays silent.

One Eventf at the call site in the issuing controller (issuing_controller.go#L402) would cover all three error returns of ensureTemporaryCertificate, and avoid defining reasonTemporaryCertificateFailed in a different file from its only use.

)

recorder := new(testpkg.FakeRecorder)
c := &controller{

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.

This is the only hand-built controller literal in the package; the existing tests go through testpkg.Builder + Register, which wires the real controller. TestIssuingController's runner already overrides localTemporarySigner (issuing_controller_test.go#L1577) and asserts events via ExpectedEvents, so a failing-signer table case there would exercise the real wiring — whereas this 3-field literal keeps passing even if NewController stops wiring the recorder or the signer.

client := cmfake.NewSimpleClientset()
// The fake clientset does not honour generateName, so fill in a stable name
// the way the shared test builder does.
client.PrependReactor("create", "certificaterequests", func(action coretesting.Action) (bool, runtime.Object, error) {

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.

This reactor is a narrower copy of testpkg.Builder.generateNameReactor, which Init() already installs on the fake cert-manager client (context_builder.go#L96, #L142-L145) — and "notrandom" is the string this file already passes as the builder's StringGenerator.

Using the builder, and simply not calling Start() — which leaves the lister empty, exactly the lagging-informer condition this test wants — replaces the copied reactor, the 4-of-8-fields controller literal, and the reflect.DeepEqual/cmp.Diff assertion with the ExpectedEvents mechanism the rest of the file uses.

@lunarwhite

Copy link
Copy Markdown
Member Author

@wallrj Thanks for your detailed review. All suggestions have been incorporated.

@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 @lunarwhite — this revision addresses everything from my review, and neatly:

  • the PrivateKeyMatchesSpec guard in requestmanager mirrors the issuing controller, and the mismatched-key test proves the wait-for-keymanager behaviour;
  • the two unreachable branches are gone (pem.EncodeToMemory) or left as a plain return err with the explanatory comment;
  • the single SecretDataFailed event at the setValues choke point now also covers the previously silent paths (additional output formats, the empty/unset password cases), with the non-BMP PKCS#12 password test being a nice find;
  • the temporary-certificate event moved to the caller and its test into the TestIssuingController table;
  • the RequestConflict event surfaces the genuinely terminal multiple-CertificateRequests state, with sorted names for determinism;
  • the wait-timeout error and event now agree, and the test is builder-based.

Local run of the three affected packages passes.

/approve
/lgtm

with claude fable-5

@cert-manager-prow cert-manager-prow Bot added the lgtm Indicates that a PR is ready to be merged. label Sep 1, 2026
@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 Sep 1, 2026
@cert-manager-prow
cert-manager-prow Bot merged commit 24b0afa into cert-manager:master Sep 1, 2026
6 checks passed
@lunarwhite
lunarwhite deleted the fix-warn-event branch September 1, 2026 05:57
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. release-note Denotes a PR that will be considered when it comes time to generate release notes. size/L Denotes a PR that changes 100-499 lines, ignoring generated files. tide/merge-method-squash Denotes a PR that should be squashed by tide when it merges.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

No Warning event when CSR encoding fails in the requestmanager controller

3 participants