Repository navigation
fix(acme/ari): adding cert id to status - #9203
cert-manager-prow[bot] merged 2 commits into
Conversation
4b8a36e to
b7fee64
Compare
SgtCoDFish
left a comment
There was a problem hiding this comment.
Mostly AI assisted commentary here but I think at least the first suggestion is worth considering. What do you think?
| case curCR != nil && !windowStart.After(curCR.CreationTimestamp.Time): | ||
| log.V(logf.DebugLevel).Info("Ignoring ACME renewal window that was already open when the current certificate was issued", | ||
| "windowStart", windowStart, "issuedAt", curCR.CreationTimestamp.Time) | ||
| default: |
There was a problem hiding this comment.
suggestion: (found with AI) This default case can get hit if curCR is nil, which could happen if it was deleted or garbage collected. Usually people keep at least the last CR around - as I understand it - so I think this is a bit of an edge case, but it's still quite possible.
So in those clusters, the issue this PR addresses would persist, right?
Does it make sense to check the window against NotBefore in the default branch?
Could also be worth a test with curCR == nil but a matching CertID to surface that branch in tests. Some light unit testing in this package could be helpful, but it's not absolutely required.
There was a problem hiding this comment.
yeah this is an edge case for sure.. but I can see two ways to handle it
- We just add a nil check and return. This way we use the usual renewal info and not worry about ARI at all
- The other way to handle it would probably be where we basically compare if the renewed cert's time (I am not sure how to fetch this though) is within the stored window.. I dont think relying on NotBefore makes sense because that kind of introduces the same bug we are trying to fix
Given that I would probably do 1 since its easier 😛 but if you do prefer 2 we can do that
There was a problem hiding this comment.
1 sounds good, seems a safe way to go.
f4429c8 to
dd8c557
Compare
dd8c557 to
7602d8d
Compare
|
@SgtCoDFish as I was writing the nil check I realized that this is more complicated than it sounds.. specifically in the edge case of something like a mass revocation where the window start would be the current time. Tbh this is definitely better than what we have now where it goes into auto renewal loop because of staleness which this PR definitely fixes but it still doesn't fix the problem when something like a mass revocation happens. I did attempt to add a TODO to fix it but we can discuss the TODO in our meetings too to solve it in a better way. |
There was a problem hiding this comment.
Pull request overview
Adds ARI certificate IDs to detect stale renewal information after certificate replacement.
Changes:
- Persists and validates ARI CertIDs.
- Refetches ARI data when certificates change.
- Updates generated APIs, schemas, CRDs, and tests.
Reviewed changes
Copilot reviewed 8 out of 12 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
pkg/controller/certificates/readiness/readiness_controller.go |
Tracks CertIDs and refreshes ARI status. |
pkg/controller/certificates/readiness/readiness_controller_test.go |
Tests CertID-based staleness handling. |
pkg/client/applyconfigurations/internal/internal.go |
Adds CertID to apply schema. |
pkg/client/applyconfigurations/certmanager/v1/certificateacmearistatus.go |
Adds CertID apply configuration. |
pkg/apis/certmanager/v1/types_certificate.go |
Exposes CertID in the public API. |
internal/generated/openapi/zz_generated.openapi.go |
Adds CertID OpenAPI metadata. |
internal/controller/certificates/policies/gatherer.go |
Validates ARI data against the current certificate. |
internal/controller/certificates/policies/checks.go |
Relies on gatherer staleness validation. |
internal/apis/certmanager/v1/zz_generated.conversion.go |
Converts CertID between API types. |
internal/apis/certmanager/types_certificate.go |
Adds CertID to the internal API. |
deploy/crds/cert-manager.io_certificates.yaml |
Updates the packaged CRD. |
deploy/charts/cert-manager/templates/crd-cert-manager.io_certificates.yaml |
Updates the Helm CRD template. |
Files not reviewed (3)
- internal/apis/certmanager/v1/zz_generated.conversion.go: Generated file
- pkg/client/applyconfigurations/certmanager/v1/certificateacmearistatus.go: Generated file
- pkg/client/applyconfigurations/internal/internal.go: Generated file
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
|
|
||
| var staleForCurrentCert bool | ||
| if crt.Status.ACME != nil && crt.Status.ACME.ARI != nil { | ||
| staleForCurrentCert = currCertID != crt.Status.ACME.ARI.CertID |
| openedBeforeIssuance := !windowStart.After(leaf.NotBefore) | ||
| requestCreatedAt := "<no current CertificateRequest>" | ||
| if curCR != nil { | ||
| requestCreatedAt = curCR.CreationTimestamp.Time.String() | ||
| if !windowStart.After(curCR.CreationTimestamp.Time) { |
There was a problem hiding this comment.
This is not true I would say.. in fact its the opposite.. in our case say a mass revocation happens then window start is the current time.. current time would always be more than the notBefore and the current certificate request time.. so it honors the window and the renewal happens.. if anything this logic introduces a loop in that edge case where in after the first cert is renewed a re-fetch happens and then say it gets a window with now as start.. this will again get renewed even though it was just renewed.
This however is an edge case because the odds of a cert just renewed having window start as now is less; that might only happen if the CA is facing issues.
7602d8d to
f531ba2
Compare
bb899bc to
a0f0626
Compare
wallrj
left a comment
There was a problem hiding this comment.
Thanks for this. Persisting the certID is the right direction, but the rewritten trigger gate looks like a regression, and there are two loops worth closing before merge. Details inline.
Smaller things:
useARIForRenewalre-addskeyto the logger thatProcessItemalready added, so every line logskey=twice.- Decode leaf plus
CertificateARIIDis now done three ways (gatherer, readiness,resolveReplacesCertID), each with a different error policy. Everything the gatherer block needs is already in scope inCurrentCertificateNearingExpiry. mustLeafWithAKIduplicates the CA-signed fixture inacme_test.go, andmustLeafWithoutAKIre-implementsMustCreateCertWithNotBeforeAfter. One helper intest/unit/cryptowould serve both.
with claude fable-5
| input.ARIRenewalInfo.SuggestedWindow.Start.After(x509Cert.NotBefore) { | ||
| if c.Now().Before(input.ARIRenewalInfo.SuggestedWindow.Start) { | ||
| crt.Status.RenewalTime != nil { | ||
| if c.Now().Before(crt.Status.RenewalTime.Time) { |
There was a problem hiding this comment.
This no longer uses the ARI window. The readiness controller resets Status.RenewalTime to the renewBefore value on every reconcile where no fetch is needed (useARIForRenewal returns nil when nextCheck is in the future, and ProcessItem then runs the calculator without ARI). The status write from the fetch re-enqueues, so the second reconcile overwrites the ARI-derived time before this gate sees it. A revoked cert with an immediate window is then not replaced until the renewBefore time; the base code renewed as soon as the window opened.
I think you want to keep c.Now().Before(input.ARIRenewalInfo.SuggestedWindow.Start). That also stops SuggestedWindow being dead data on Input, and the comment above still describes comparing against the window start. There is no test for this gate in checks_test.go, which is why it slipped through.
There was a problem hiding this comment.
This makes sense but I am making changes to use the Status.RenewalTime. I feel that is the correct behavior since we don't want the .Start to be the renewal time. I am making changes to make the status time persist when ARI is enabled.
|
|
||
| var staleForCurrentCert bool | ||
| if crt.Status.ACME != nil && crt.Status.ACME.ARI != nil { | ||
| staleForCurrentCert = currCertID != crt.Status.ACME.ARI.CertID |
There was a problem hiding this comment.
When the stored CertID is empty this is always true and bypasses NextCheck. With a v1.21.x CRD the field is pruned on write, so every reconcile fetches, writes status, re-enqueues and fetches again, with no backoff against the CA. Even with the new CRD every existing ACME Certificate fetches immediately on upgrade. The old lastChecked.Before(NotBefore) check corrected itself after one fetch.
Suggest ari.CertID != "" && ari.CertID != currCertID. The nextCheck == nil case already handles first-time population.
| } | ||
|
|
||
| staleForCurrentCert := lastChecked != nil && lastChecked.Time.Before(x509cert.NotBefore) | ||
| currCertID, err := acmeapi.CertificateARIID(x509cert) |
There was a problem hiding this comment.
On error currCertID is "" but is still treated as a real ID: an ARI block is created, GetRenewalInfo (which needs the same ID) fails, "" is persisted as certID, and the cert is re-polled with a Warning event at every NextCheck. On the next reconcile "" == "" so it is not stale, and a later no-AKI cert is indistinguishable. Better to clear the ARI block and return nil here. The new "no usable CertID" test sets NextCheck in the future so it never reaches this path.
There was a problem hiding this comment.
This makes sense.. although its a very rare edge case since not able to fetch cert id is only possible if the details of cert itself is missing.
| // the certificate's lifetime (ignore a window opening within the first N% of | ||
| // it) would sharpen both ends, but picking N is a decision about how soon | ||
| // after issuance an ARI window may legitimately trigger renewal. | ||
| openedBeforeIssuance := !windowStart.After(leaf.NotBefore) |
There was a problem hiding this comment.
This discards the window the CA sends for a certificate it has just revoked. Boulder's immediate window for a cert issued 30 minutes ago has start=now-1h, which is after NotBefore but before the CR's creation timestamp, so it is dropped and renewal falls back to renewBefore. A CA reporting a fixed past start for a mass revocation is dropped on every reconcile and never acted on. The TODO admits this, and the PR description says staleness should no longer depend on NotBefore, yet this re-adds it one layer up.
It also diverges from the readiness controller, which still only checks After(NotBefore) when reusing Status.RenewalTime. Now that certID is in status, both could use !staleForCurrentCert from one shared predicate and this block could go.
There was a problem hiding this comment.
This is not needed anymore because in the latest changes we persist the ARI renewal time along with better checking in checks.go before trigger controller can act for renewal.
e82db70 to
6dbaf61
Compare
|
@wallrj after spending some time on the renewal logic, I tried to solve all the small TODOs that were present in the ARI logic which I was planning to come back to. So hopefully this should make it easier for things to be more deterministic in the ARI pathway. |
Signed-off-by: Hemant Joshi <[email protected]>
Signed-off-by: hjoshi123 <[email protected]>
6dbaf61 to
4e25fee
Compare
wallrj
left a comment
There was a problem hiding this comment.
/lgtm
/approve
Thanks. This fixes both problems in #8993: the certID match breaks the renewal loop, and the immediate refetch on mismatch keeps status.acme.ari consistent after renewal. All my earlier comments are addressed and CI is green.
Three follow-ups, none blocking. Happy for them to land in a separate PR.
Regression test for the certID match in the gatherer
The line that breaks the loop is id == crt.Status.ACME.ARI.CertID in DataForCertificate, and nothing tests it. The checks_test.go cases inject ARIRenewalInfo directly, so they bypass it. Two cases in TestDataForCertificate would cover it: one where the stored certID matches the Secret and the window is surfaced, one where it does not match and the window is dropped.
The CA-signed leaf fixture from readiness_controller_test.go (mustLeafWithAKI) is the same one acme_test.go builds inline. Promoting it to test/unit/crypto serves all three:
// test/unit/crypto/crypto.go
// MustCreateCASignedCert returns a PEM-encoded leaf signed by a throwaway CA.
// Unlike the self-signed helpers above it carries an AuthorityKeyId, which
// acmeapi.CertificateARIID needs.
func MustCreateCASignedCert(t *testing.T, notBefore, notAfter time.Time, serial int64) []byte {
t.Helper()
caPK, err := pki.GenerateECPrivateKey(256)
require.NoError(t, err)
caTmpl := &x509.Certificate{
SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "test-ca"},
NotBefore: notBefore.Add(-time.Hour), NotAfter: notAfter.Add(time.Hour),
KeyUsage: x509.KeyUsageCertSign, IsCA: true, BasicConstraintsValid: true,
}
_, caCert, err := pki.SignCertificate(caTmpl, caTmpl, caPK.Public(), caPK)
require.NoError(t, err)
leafPK, err := pki.GenerateECPrivateKey(256)
require.NoError(t, err)
leafTmpl := &x509.Certificate{
SerialNumber: big.NewInt(serial), Subject: pkix.Name{CommonName: "example.com"},
DNSNames: []string{"example.com"}, NotBefore: notBefore, NotAfter: notAfter,
}
leafPEM, _, err := pki.SignCertificate(leafTmpl, caCert, leafPK.Public(), caPK)
require.NoError(t, err)
return leafPEM
}Then in gatherer_test.go, enable the gate for the whole table and add kubeObjects and wantARI fields:
func TestDataForCertificate(t *testing.T) {
featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultMutableFeatureGate, feature.ACMEUseARI, true)
now := time.Now()
leafPEM := testcrypto.MustCreateCASignedCert(t, now.Add(-time.Hour), now.Add(24*time.Hour), 2)
leaf, err := pki.DecodeX509CertificateBytes(leafPEM)
require.NoError(t, err)
leafID, err := acmeapi.CertificateARIID(leaf)
require.NoError(t, err)
ariCert := func(certID string) *cmapi.Certificate {
crt := gen.Certificate("cert-1", gen.SetCertificateNamespace("ns-1"),
gen.SetCertificateSecretName("secret-1"), gen.SetCertificateUID("cert-1-uid"))
crt.Status.ACME = &cmapi.CertificateACMEStatus{ARI: &cmapi.CertificateACMEARIStatus{
CertID: certID,
SuggestedWindow: &cmapi.ACMERenewalWindow{
Start: &metav1.Time{Time: now.Add(-30 * time.Minute)},
End: &metav1.Time{Time: now.Add(30 * time.Minute)},
},
}}
return crt
}
secret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{Name: "secret-1", Namespace: "ns-1"},
Data: map[string][]byte{corev1.TLSCertKey: leafPEM},
}
tests := map[string]struct {
builder *testpkg.Builder
givenCert *cmapi.Certificate
wantCurCR *cmapi.CertificateRequest
wantNextCR *cmapi.CertificateRequest
wantSecret *corev1.Secret
wantARI *acmeapi.RenewalInfoResponse
wantErr string
}{
// ... existing cases ...
"ARI window is surfaced when the stored certID matches the certificate in the Secret": {
givenCert: ariCert(leafID),
builder: &testpkg.Builder{KubeObjects: []runtime.Object{secret}},
wantSecret: secret,
wantARI: &acmeapi.RenewalInfoResponse{SuggestedWindow: acmeapi.RenewalInfoWindow{
Start: now.Add(-30 * time.Minute), End: now.Add(30 * time.Minute),
}},
},
"ARI window is dropped when the stored certID belongs to a previous certificate": {
// The scenario from #8993: the Secret was just renewed and status
// still carries the previous certificate's window.
givenCert: ariCert("stale-cert-id"),
builder: &testpkg.Builder{KubeObjects: []runtime.Object{secret}},
wantSecret: secret,
wantARI: nil,
},
}
// ... in the runner, alongside the existing asserts:
// assert.Equal(t, test.wantARI, got.ARIRenewalInfo)The second case fails on the base branch and passes on this PR.
Event message reports the wrong time when the gate fires on the window
The side observation in #8993 still applies. When RenewalTime lies outside the window the gate fires on window.Start, but the message still prints Status.RenewalTime. The new test asserts exactly that: it renews now while reporting a time 72 hours out. Building the message from gateTime fixes it:
// internal/controller/certificates/policies/checks.go
if c.Now().Before(gateTime) {
return "", "", false
}
return reason, fmt.Sprintf("Renewing certificate as the ACME renewal window opened at %s", gateTime), trueand update the two message: expectations in checks_test.go to match.
The leaf is decoded and the certID computed in three places
DataForCertificate, useARIForRenewal and ariRenewalTimeFromStatus each decode the Secret and call CertificateARIID, and resolveReplacesCertID in the ACME issuer does it a fourth time. The readiness controller already has x509cert in hand, so useARIForRenewal could compute the ID once and pass it to ariRenewalTimeFromStatus:
func ariRenewalTimeFromStatus(crt *cmapi.Certificate, x509cert *x509.Certificate, currCertID string) *metav1.Time {
// ... drop the CertificateARIID call and compare against currCertIDCosmetic. Worth doing only if someone is in that file anyway.
[Claude Fable 5.1]
|
[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 |
|
/label tide/merge-method-squash |
|
/cherry-pick release-1.21 |
|
@wallrj: #9203 failed to apply on top of branch "release-1.21": 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. |
|
@hjoshi123 This change has been included in v1.21.3, which is now published. If you are able to install the release and verify that the change works as expected in your environment, that would be much appreciated. Thank you for the contribution. |
Pull Request Motivation
This PR basically fixes a subtle bug within ARI where-in due to stale information in ACME ARI window, the cert could not only have old suggested window but also get into a renewal loop as a result of it. The fix is simply to not rely on things like
notBeforeornotAfterto check staleness but to actually calculate the cert id. if the cert id changes that means that a new cert was issued and we need to refetch the ARI info regardless of whether or not the window is valid.Fixes #8993
Kind
/kind bug
Release Note