Repository navigation
fix: ServerSideApply field loss in certificate-shim and issuing controller - #8793
Conversation
|
@lunarwhite: The label(s) DetailsIn response to this:
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. |
|
/kind bug |
|
Copilot's reviews are somewhat useful. Not sure why they are not submitted directly on the PR. Hence response here:
This is left intentionally as out-of-scope. PR #8734 is going to solve it. (in my review queue)
Looks reasonable, I will incorporate it.
UT coverage for SSA is a pre-existing issue to be improved. Maybe we could address it later after some discussions. As of now I verified it manually: "E2E Verification" in the PR description. |
|
/cc @inteon I'd appreciate it if you could add this PR to your review queue. Context see #8793 (comment) and #8785 (comment). Thank you! |
| Conditions: conditions, | ||
| Revision: crt.Status.Revision, | ||
| LastFailureTime: crt.Status.LastFailureTime, | ||
| FailedIssuanceAttempts: crt.Status.FailedIssuanceAttempts, |
There was a problem hiding this comment.
This field might need some extra testing, we have to make sure it gets dropped when issuance is successful. If somehow this field becomes co-owned by two field managers, we might fail to remove the field from the object.
There was a problem hiding this comment.
I've added some more UTs along with a new integration test file: 6097803. Please let me know if I should expand/slim them.
Create with FieldManager records ownership as operation:Update. Use Apply when ServerSideApply is enabled so create ownership matches updates (operation:Apply). Add create/update Apply payload tests. Signed-off-by: Yuedong Wu <[email protected]>
Add issuing unit test that ApplyStatus includes the field on failure and omits it on success, and an integration test that scalar status fields clear by omission only when solely owned. Signed-off-by: Yuedong Wu <[email protected]>
|
Thank you for these improvements, all changes you made seem correct to me. This is a very complex piece of our operators, and we will probably need to fix a few more things in the future. PS: sorry for my review slowness /approve |
|
[APPROVALNOTIFIER] This PR is APPROVED This pull-request has been approved by: inteon 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 |
|
@inteon NP at all! Really appreciate your time and reivews. :) |
|
/cherry-pick release-1.21 with claude fable-5 |
|
@wallrj: new pull request created: #9233 DetailsIn response to this:
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. |
wallrj
left a comment
There was a problem hiding this comment.
Post-merge review, prompted by the pending cherry-pick in #9233. Two of the inline findings below are regressions introduced by this change. Both only manifest with the ServerSideApply feature gate enabled, which is why the new tests don't catch them; in my view they need fixing on master before this is backported, and I've closed #9233 accordingly.
Two further findings on lines outside this diff:
pkg/controller/certificates/issuing/issuing_controller.go:414 — failIssueCertificate mutates the informer-cached Certificate (LastFailureTime/FailedIssuanceAttempts, L414-L420) before the DeepCopy at L429. ProcessItem passes the lister object straight in — contrast issueCertificate, which copies first. If ApplyStatus fails and the item requeues before a watch event refreshes the cache, one failure is counted twice. These lines pre-date this PR, but adding failedIssuanceAttempts to the apply payload is what makes the inflated counter reach the API server. Moving the DeepCopy above the mutations fixes it.
pkg/controller/certificate-shim/sync.go:424 — pre-existing, adjacent to the touched code: buildCertificates deletes the applyset label from the live informer-cache labels map (the DeepCopy only happens at L449). Both shim controllers pass the lister object un-copied, so a user's applyset.kubernetes.io/part-of label is stripped from the cached Ingress process-wide, and a concurrent map read/write panic is possible. Worth a follow-up issue rather than anything to do here.
with claude fable-5
| Namespace: crt.Namespace, | ||
| Labels: crt.Labels, | ||
| OwnerReferences: crt.OwnerReferences, | ||
| Annotations: extraAnnotations, |
There was a problem hiding this comment.
This applies Annotations: extraAnnotations rather than crt.Annotations, dropping every annotation set by setIssuerSpecificConfig: acme.cert-manager.io/http01-override-ingress-name, cert-manager.io/issue-temporary-certificate (edit-in-place), and the http01-parent-ref-kind/-name annotations set unconditionally for Gateway/ListenerSet.
With the gate on and no --extra-certificate-annotations (the default), extractExtraAnnotations returns nil, setIssuerSpecificConfig allocates a fresh map on crt, and none of it reaches the API server — Gateway HTTP01 issuance hangs. When extras are configured, setIssuerSpecificConfig happens to write into the same map (aliasing), which is why the new test passes: it only covers the non-nil case.
The simplest fix also removes the trap: this block rebuilds, field by field, a Certificate identical to the crt it already holds, and duplicates the update branch below verbatim. serializeApply already strips Status and ManagedFields, so internalcertificates.Apply(ctx, cmClient, fieldManager, crt) is equivalent, shorter, and can't silently drop the next ObjectMeta field. The update branch has the same annotation drop — if filtering to extraAnnotations is intentional there, it deserves a comment saying so.
| _, err := cmClient.CertmanagerV1().Certificates(crt.Namespace).Create(ctx, crt, metav1.CreateOptions{FieldManager: fieldManager}) | ||
| // Create with FieldManager records ownership as operation:Update. | ||
| // Use Apply under SSA so create ownership matches updates (operation:Apply). | ||
| if utilfeature.DefaultFeatureGate.Enabled(feature.ServerSideApply) { |
There was a problem hiding this comment.
Replacing Create with a Force apply (Apply always sets Force: true) removes the AlreadyExists safety net. A Certificate lands in newCrts purely on a lister NotFound (L385), and the no-owner / not-controlled-by guards (L467-L475) only run on the cached-update path.
Previously, a same-named user-created Certificate not yet in the informer cache got a 409 here, and once cached the guard refused to touch it. Now it is silently adopted — spec and labels overwritten, controller ownerReference injected, a 'Successfully created' event emitted — and if the TLS entry is later removed, findCertificatesToBeRemoved deletes the user's Certificate. That's a data-loss path. The create path needs either to not force (and handle the conflict), or an explicit live-read ownership check before applying.
| IssuerRef: crt.Spec.IssuerRef, | ||
| Usages: crt.Spec.Usages, | ||
| }, | ||
| Spec: crt.Spec, |
There was a problem hiding this comment.
Force-applying the full built spec reverts user hand-edits to annotation-derived fields, and the trigger surface is inconsistent: certNeedsUpdate compares Duration/RenewBefore/RevisionHistoryLimit/CommonName/PrivateKey — edits to those are reverted on the next sync — but not Usages/IPAddresses/RenewBeforePercentage, which only revert when an unrelated change triggers an update. This is largely the intended fix for #8785, but the flip from partial field ownership to full Force ownership is a behaviour change that deserves a release note.
| Conditions: conditions, | ||
| Revision: crt.Status.Revision, | ||
| LastFailureTime: crt.Status.LastFailureTime, | ||
| FailedIssuanceAttempts: crt.Status.FailedIssuanceAttempts, |
There was a problem hiding this comment.
Clearing failedIssuanceAttempts/lastFailureTime by omission only prunes fields this Apply manager set last time. Values written before the gate was enabled belong to an operation:Update managedFields entry — managers are keyed by operation (BuildManagerIdentifier, apimachinery v0.36.1) — so after enabling ServerSideApply on an existing install, stale values survive indefinitely. The trigger controller then computes backoff from the frozen lastFailureTime, and the inflated attempt count jumps the next real failure straight to max backoff.
The new integration test proves the clearing mechanic for two Apply managers, but the Update→Apply migration path is unhandled — it needs a one-time explicit clear, or at least a release note telling gate-enablers to expect stale failure fields.
There was a problem hiding this comment.
Added to #9268 release-note, no migration code. a one-time clear means permanent managedFields introspection in ProcessItem + a second status write, and it cannot tell stale state from state written moments before a restart. shouldBackoffReissuingOnFailure returns false, 0 when durationSinceFailure >= delay, so a frozen old lastFailureTime skips backoff rather than extending it. The inflated count does push the next real failure toward max backoff, but only within maxDelay of the gate flip, and it self-heals at the first real failure once a forced apply claims the field. The new Test_StatusScalarApply subtest shows both halves against a real apiserver
| @@ -515,9 +515,10 @@ func (c *controller) updateOrApplyStatus(ctx context.Context, crt *cmapi.Certifi | |||
| return internalcertificates.ApplyStatus(ctx, c.client, c.fieldManager, &cmapi.Certificate{ | |||
There was a problem hiding this comment.
Bigger picture: this fix adds another entry to a hand-maintained whitelist of applied fields, and those copies demonstrably drift — the managedFields strip added to internal/controller/certificates/apply.go in this PR was already present in the certificaterequests copy.
We already generate apply configurations (pkg/client/applyconfigurations), and the typed ApplyStatus client is used by acmechallenges and certificatesigningrequests; ObjectMetaApplyConfiguration cannot even express managedFields, so the bug patched here is unrepresentable there. The readiness, trigger and keymanager controllers still carry hand-built status subsets — the next CertificateStatus field will reproduce #8785 a third time. Worth a follow-up to migrate to the typed builders, or a shared owned-fields helper.
|
|
||
| // matchRootCertificateApply validates a root-resource Certificate Apply patch | ||
| // (verb, patch type, options) and then runs check on the unmarshaled object. | ||
| func matchRootCertificateApply(check func(applied cmapi.Certificate) error) testpkg.ActionMatchFn { |
There was a problem hiding this comment.
Builder.AllActionsExecuted already pre-filters actions by namespace/resource/subresource/verb before calling the matchFn, so the verb and subresource checks in this matcher are dead code — and the patch bytes and options passed to NewPatchActionWithOptions are never compared (the matchFn ignores its first argument), which will mislead future readers into thinking the payload is asserted. issuing_controller_test.go repeats the same option-validation block statement for statement.
The established pattern is exact-bytes matching via testpkg.NewAction (e.g. acmechallenges/sync_test.go#L127) — or one shared apply-patch matcher in pkg/controller/test. The two ~100-line TestSync_ServerSideApplyCreate/Update functions would also collapse into this file's existing table pattern.
| require.NoError(t, err) | ||
| } | ||
|
|
||
| func applyCertificateStatus(t *testing.T, cmClient cmclient.Interface, fieldManager, namespace, name string, status cmapi.CertificateStatus) { |
There was a problem hiding this comment.
applyCertificateStatus re-implements internalcertificates.ApplyStatus byte for byte — same marshal shape, same patch options. Calling the production function would delete ~15 lines and make the test exercise the controller's real serialisation; a hand-rolled copy drifting from what the controller actually sends is precisely the failure mode this PR fixes elsewhere.
|
Thanks @wallrj for your review! Let me take a closer look and do a follow-up fix |
|
PR is up for review: #9268 |
|
We will not backport this PR to release-1.21. The fix for #7438 and #8785 ships in v1.22 only. Reasons:
[Claude Fable 5.1] |
The cherry-picked test calls applyCertificateStatus, which master gained in status_scalar_apply_test.go from cert-manager#8793. That PR is not on this branch, so the integration test package did not compile. Add the helper on its own, wrapping the existing ApplyStatus function in internal/controller/certificates, exactly as master defines it today. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Richard Wall <[email protected]>
The cherry-picked test calls applyCertificateStatus, which master gained in status_scalar_apply_test.go from cert-manager#8793. That PR is not on this branch, so the integration test package did not compile. Add the helper on its own, wrapping the existing ApplyStatus function in internal/controller/certificates, exactly as master defines it today. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Richard Wall <[email protected]>
Pull Request Motivation
Fixes #8785
Fixes #7438
When the
ServerSideApplyfeature gate is enabled, few controllers silently drop fields because their SSA apply payloads are incomplete:(1) Certificate shim: only 5 of 22+ CertificateSpec fields were included in SSA Apply, losing specs like
RevisionHistoryLimit.(2) Certificate issuing controller:
FailedIssuanceAttemptswas missing from theApplyStatuspayload, breaking issuance retry backoff.(3) Certificate shim: under SSA, Certificate create also uses Apply so field ownership matches updates (operation:Apply instead of operation:Update).
A secondary bug was exposed by fix (1):
serializeApplydeep-copied ObjectMeta includingManagedFieldsinto the SSA patch body, causing the API server to reject patches withmetadata.managedFields must be nil. This was latent because the old code constructed a fresh object with zero-value ObjectMeta.E2E Verification
certificate-shim 'spec.revisionHistoryLimit' should survives SSA Apply update
without the fix
with the fix
FailedIssuanceAttempts should persist via SSA ApplyStatus after an ACME failure
without the fix
with the fix
Kind
/kind bug
Release Note