Repository navigation
fix: Record Warning events for silent per-Certificate failures - #9199
Conversation
|
/label tide/merge-method-squash |
|
kindly /cc @wallrj for review |
There was a problem hiding this comment.
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.
b64b148 to
04bc8e9
Compare
wallrj
left a comment
There was a problem hiding this comment.
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:
- Two of the new events sit on branches the PR's own comments prove unreachable — I'd drop those two
Eventfcalls. - The CSR-encode event papers over a missing
PrivateKeyMatchesSpecguard that the issuing controller already has for the same race. - 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()) |
There was a problem hiding this comment.
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()) |
There was a problem hiding this comment.
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()) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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()) |
There was a problem hiding this comment.
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{ |
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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.
…y does not match spec Signed-off-by: Yuedong Wu <[email protected]>
…tificate failures Signed-off-by: Yuedong Wu <[email protected]>
… wait timeout and conflicts Signed-off-by: Yuedong Wu <[email protected]>
04bc8e9 to
5581adf
Compare
|
@wallrj Thanks for your detailed review. All suggestions have been incorporated. |
wallrj
left a comment
There was a problem hiding this comment.
Thanks @lunarwhite — this revision addresses everything from my review, and neatly:
- the
PrivateKeyMatchesSpecguard 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 plainreturn errwith the explanatory comment; - the single
SecretDataFailedevent at thesetValueschoke 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
TestIssuingControllertable; - the
RequestConflictevent 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
|
[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 DetailsNeeds approval from an approver in each of these files:
Approvers can indicate their approval by writing |
Pull Request Motivation
Fixes #9182
Note that the scope is a bit wider than reported. The original one mentioned
pki.EncodeCSRandpem.Encode, I sweptpkg/controller/certificates/for the same defect and fixed what turned up. For easy review they are in separate commits.requestmanager: the two paths No Warning event when CSR encoding fails in the requestmanager controller #9182 names are fixed structurally rather than evented. Adds thePrivateKeyMatchesSpecguard the issuing controller already has, so we wait for the keymanager instead of rebuilding a CSR that cannot be signed;pem.Encodebecomespem.EncodeToMemory, which has no error return. The remaining unreachable branch keeps its comment and records no event.issuing: one event at thesetValueschoke point rather than per-site ones insetKeystores, which also covers empty literal passwords, non-NotFound password Secret errors,additionalOutputFormatsand an undecodable issued cert — all previously silent. The temporary certificate event sits at the call site so it coversEncodePrivateKeytoo.requestmanager: thewaitForCertificateRequestToExisttimeout, andRequestConflicton thelen(requests) > 1branch. 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.goevents everySetuperror, thecertificaterequestsissuers go throughutil.Reporter, ACME usesStatus.Reason,cainjectorhas no recorder.Kind
/kind bug
Release Note