Skip to content

Only consume next private key Secrets owned by the Certificate - #9224

Merged
cert-manager-prow[bot] merged 4 commits into
cert-manager:masterfrom
wallrj:fix-nextprivatekey-secret-ownership
Sep 17, 2026
Merged

cert-manager-prow[bot] merged 4 commits into
cert-manager:masterfrom
wallrj:fix-nextprivatekey-secret-ownership

Conversation

@wallrj

@wallrj wallrj commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

If you can write a Certificate's status subresource, you can obtain a private key you are not allowed to read.

Point status.nextPrivateKeySecretName at any TLS Secret in the namespace. cert-manager signs a CSR with that Secret's private key, has the issuer sign it, and writes the key and the new certificate into the Certificate's spec.secretName. You chose spec.secretName, so you can read it. You now hold a working certificate and key pair built on a key that was never yours.

The requestmanager and issuing controllers use the private key from the Secret named by that field without checking that the Secret belongs to the Certificate. The keymanager controller, which creates those Secrets, only ever considers Secrets carrying the cert-manager.io/next-private-key label and a controller owner reference back to the Certificate. The two consumers bypass that invariant by trusting the status field.

Writing certificates/status is a weaker permission than reading Secrets. You need read access to the Secret you name in spec.secretName, and none at all to the Secret you steal from.

In a default install this is not a privilege escalation

The chart grants certificates/status: update through the aggregated cert-manager-edit role, and Kubernetes' own system:aggregate-to-edit already grants full read and write on secrets in the namespace. Anyone reaching that rule can read the Secret directly. The exposure is for hand-built Roles that grant Certificate and Certificate status write without Secret read.

The grant is deliberate. f6d8c4f (#4954) added it so namespace admins can trigger a manual renewal, which is what cmctl renew does. The fix therefore belongs in the controllers rather than in the chart.

This also stops a corrupted or hand-edited status from making cert-manager consume an unrelated Secret. The behaviour dates from 9e2d6a5 (July 2020), first released in v0.16.0.

What changed

IsNextPrivateKeySecret states the invariant, and everything that relies on it now goes through that one function: GetNextPrivateKeySecret for the two consumers, and the keymanager's own list of candidate Secrets. A Secret that exists but fails the check is reported as not found, so callers wait for the keymanager to repoint the field at a Secret it owns. That is what they already do when the Secret is absent, so there are no new error paths.

Recovery needs a keymanager change, which this PR also makes. The keymanager used to create its Secret under the name already in the status field, and adopt whatever Secret occupied that name. Both trusted the field. It now never creates under a name taken from the status field. createNewPrivateKeySecret always uses generateName. Before creating, it checks whether the named Secret is one it created on an earlier reconcile whose status write has not reached the cache yet, which is the duplicate-Secret race that #8579 guarded against. A named Secret that is not ours gets a NotOwned Warning event and is ignored.

Creating under a free name from the status field was unsafe on its own. The name could be the spec.secretName of a Certificate that has not issued yet. This Certificate would then own that Secret, and later delete it or sign with its key.

When the keymanager already owns a Secret but the status field names something else, it now repoints the field at the Secret it owns instead of deleting the Secret. Deleting it let a status writer force a key rotation on demand, and raced the Secret informer after the keymanager's own status write. The rotationPolicy: Never path that cannot make a next private key now clears the field rather than leaving a stale or untrusted name in it.

IsNextPrivateKeySecret also rejects the Secret named by spec.secretName. spec.secretTemplate.labels can put the next-private-key label on it, and --enable-certificate-owner-ref gives it the controller reference, after which the keymanager would delete the served certificate on every Ready transition. Reserving cert-manager.io/* label keys in validation would be the cleaner fix, but that is a breaking change, so I have left it for a follow-up.

GetNextPrivateKeySecret resolves the name with a label-selected LIST rather than a GET. With SecretsFilteredCaching on, a GET for an unlabeled Secret is answered by a live API request that returns the whole Secret, private key included, only for the ownership check to discard it.

The test fixtures built next private key Secrets with neither the label nor the owner reference, so they did not match what the keymanager produces in a real cluster. They now go through helpers that set both, which is most of the diff. The integration tests create the Secret after the Certificate, because the owner reference needs the Certificate's UID.

How I checked the tests actually catch the bug

With metav1.IsControlledBy removed from IsNextPrivateKeySecret, so that the label alone is checked, exactly these fail, and no others:

  • TestGetNextPrivateKeySecret/rejects a Secret labeled but owned by a different Certificate and .../rejects a Secret whose owner reference is not a controller reference
  • TestProcessItem/create a secret under a generated name if status.nextPrivateKeySecretName names a Secret not owned by the Certificate (keymanager)
  • TestProcessItem/do nothing if status.nextPrivateKeySecretName names a Secret not owned by the Certificate (requestmanager)
  • TestIssuingController/if certificate is in Issuing state but NextPrivateKeySecretName names a Secret it does not own, do nothing, with expected secretUpdateData func to be called: false was called: true. That is the private key being copied into spec.secretName.

The controller fixtures give the Certificate a UID and give the foreign Secret the label plus a controller reference to a Certificate with a different UID, so the owner UID comparison is the only thing rejecting it.

Reported by @the-vibe-dev.

Kind

/kind bug

Release Note

The `requestmanager` and `issuing` controllers now only consume the Secret named by `status.nextPrivateKeySecretName` when it carries the `cert-manager.io/next-private-key` label and is owned by the Certificate, matching the invariant the `keymanager` controller already enforces. Previously a principal able to write the `certificates/status` subresource, but not to read Secrets, could name any Secret in the namespace and have its private key copied into `spec.secretName`. The `keymanager` controller no longer creates the next private key Secret under the name in `status.nextPrivateKeySecretName`. It always uses a generated name, records a `NotOwned` Warning event when the field names a Secret it does not own, and repoints the field at the Secret it owns rather than deleting that Secret when the two disagree. The Secret named by `spec.secretName` is never treated as a next private key Secret, even if `spec.secretTemplate` labels it as one.

[Claude Opus 5, Claude Fable 5.1]

@cert-manager-prow

Copy link
Copy Markdown
Contributor

Skipping CI for Draft Pull Request.
If you want CI signal for your change, please convert it to an actual PR.
You can still manually trigger a test run with /test all

@cert-manager-prow cert-manager-prow Bot added do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. 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. size/L Denotes a PR that changes 100-499 lines, ignoring generated files. labels Aug 31, 2026
@wallrj
wallrj requested a lite review from Copilot August 31, 2026 08:25

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

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

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

Comment thread pkg/controller/certificates/secrets.go Resolved
@cert-manager-prow cert-manager-prow Bot added the needs-rebase Indicates a PR cannot be merged because it has merge conflicts with HEAD. label Sep 5, 2026
@wallrj
wallrj force-pushed the fix-nextprivatekey-secret-ownership branch from 457742c to 1ac68a5 Compare September 5, 2026 05:53
@cert-manager-prow cert-manager-prow Bot added size/XL Denotes a PR that changes 500-999 lines, ignoring generated files. and removed needs-rebase Indicates a PR cannot be merged because it has merge conflicts with HEAD. size/L Denotes a PR that changes 100-499 lines, ignoring generated files. labels Sep 5, 2026
@wallrj
wallrj force-pushed the fix-nextprivatekey-secret-ownership branch from 1ac68a5 to 08c7d60 Compare September 5, 2026 06:05
@cert-manager-prow cert-manager-prow Bot added the area/testing Issues relating to testing label Sep 5, 2026
@wallrj
wallrj marked this pull request as ready for review September 5, 2026 06:21
@cert-manager-prow cert-manager-prow Bot removed the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Sep 5, 2026
@wallrj
wallrj force-pushed the fix-nextprivatekey-secret-ownership branch from 08c7d60 to 490e795 Compare September 5, 2026 06:32
@wallrj
wallrj requested a balanced review from Copilot September 5, 2026 07:29

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.

🟡 Changes recommended

Keymanager recovery must prevent issuance stalls, and the affected requestmanager fixtures must retain intended test coverage.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details
  • Files reviewed: 8/8 changed files
  • Comments generated: 3
  • Review effort level: Balanced

Comment thread pkg/controller/certificates/secrets.go Resolved
The requestmanager and issuing controllers read the Secret named by
status.nextPrivateKeySecretName and use its private key without checking
that the Secret belongs to the Certificate. The keymanager controller,
which creates those Secrets, only ever considers Secrets carrying the
cert-manager.io/next-private-key label and a controller owner reference
back to the Certificate.

status.nextPrivateKeySecretName is writable by any principal with access
to the certificates/status subresource, which is a weaker permission than
reading Secrets in the namespace. Without an ownership check, such a
principal can name any Secret in the namespace and have its private key
copied into spec.secretName.

Add IsNextPrivateKeySecret, which states that invariant once, and
GetNextPrivateKeySecret, which applies it when reading the field. Both
consumers now go through it. A Secret that fails the check is reported as
not found, so callers wait for the keymanager to reconcile the field back
to a Secret it owns, exactly as they already do when the Secret is absent.

Recovery needs a keymanager change to work. createNewPrivateKeySecret
reuses the name already in the status field, so when that name belongs to
a Secret we do not own, the create fails with AlreadyExists and the
existing code adopted the foreign Secret and left the status unchanged.
The consumers would then reject it on every reconcile and issuance would
never progress. The keymanager now creates the Secret under a generated
name instead, and writes that name back to the status field. This is the
graceful recovery the TODO in the tests asked for.

The unit and integration test fixtures built next private key Secrets
with neither the label nor the owner reference, so they did not match
what the keymanager produces in a real cluster. They now go through
helpers that set both. The integration tests create the Secret after the
Certificate, because the owner reference needs the Certificate's UID.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Richard Wall <[email protected]>
@wallrj
wallrj force-pushed the fix-nextprivatekey-secret-ownership branch from 490e795 to 9203cab Compare September 5, 2026 08:00
@wallrj
wallrj requested a balanced review from Copilot September 5, 2026 08:46

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.

🟢 Approval recommended

No unresolved issues were identified, and the changes include appropriate recovery and test coverage.

Review details
  • Files reviewed: 11/11 changed files
  • Comments generated: 0 new
  • Review effort level: Balanced

@wallrj

wallrj commented Sep 13, 2026

Copy link
Copy Markdown
Member Author

/test pull-cert-manager-master-e2e-v1-37
/test pull-cert-manager-master-e2e-v1-37-upgrade

The previous commit replaced the label selector on the keymanager's Secret
LIST with labels.Everything(), and moved the label test into the predicate,
on the grounds that it cost nothing. That was wrong, and it stopped
certificates issuing at all.

The claim was checked against client-go's ListAllByNamespace, which indexes
only on namespace and then calls selector.Matches per item. That is the
wrong lister. With the SecretsFilteredCaching feature, which is on by
default, the Secret lister is the one in internal/informers. It serves a
LIST from two caches: a typed cache of cert-manager's own Secrets, which
carry the controller.cert-manager.io/fao label, and a metadata-only cache
of every other Secret in the namespace. The metadata cache stores no
labels, because partialMetadataRemoveAll strips them. Every Secret the
metadata cache returns costs one live GET against the API server.

A selector requiring the next-private-key label therefore matches nothing
in the metadata cache, and the LIST is served entirely from the typed
cache. labels.Everything() matches every entry in it, so the keymanager
issued one GET per unrelated Secret in the namespace on every reconcile of
every Certificate. In the end-to-end tests no Certificate reached Ready and
the setup timed out.

Restore the selector. Keep IsNextPrivateKeySecret as the predicate, so
there is still one statement of what a next private key Secret is, and
document why the label test has to appear in the selector as well. Build
the selector with labels.SelectorFromSet rather than the init function and
panic that the previous commit deleted.

Add a test that the selector rejects a Secret with no labels. It fails if
the selector is widened back to labels.Everything().

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Richard Wall <[email protected]>
… field

The keymanager still created its Secret under whatever name
status.nextPrivateKeySecretName held, as long as that name was free. Only
the taken-name case went through the ownership check added in the previous
commits. A principal able to write the certificates/status subresource
could therefore name the spec.secretName of a sibling Certificate that has
not issued yet. The keymanager would create that Secret with its own owner
reference and next-private-key label, the sibling's issuing controller
would apply its certificate and key into it, and the keymanager would then
delete it on the next spec mismatch or Issuing transition, or sign its own
CSR with the sibling's key.

Always create with generateName. Before creating, read the Certificate
live and check whether the Secret it names is one we created on an earlier
reconcile whose status write has not reached the cache yet. That keeps the
duplicate-Secret guard from cert-manager#8579. A named Secret that is not ours now
records a NotOwned Warning event, so a tampered status field leaves a
trace in kubectl describe rather than only a routine Generated event.

When the keymanager already owns one Secret but the status field names
something else, repoint the field at the Secret it owns instead of
deleting the Secret. The delete raced the Secret informer after the
keymanager's own status write, so the Secret created on one reconcile
could be deleted on the next, and it let a status writer force a key
rotation, a Secret delete and create, and a CertificateRequest delete and
create on demand. The rotationPolicy Never path that cannot make a next
private key now clears the field rather than leaving a stale or untrusted
name in it.

IsNextPrivateKeySecret also rejects the Secret named by spec.secretName.
spec.secretTemplate.labels can put the next-private-key label on it, and
--enable-certificate-owner-ref gives it the controller reference, after
which the keymanager would delete the served certificate on every Ready
transition. Reserving cert-manager.io label keys in validation is the
cleaner fix but is a breaking change, so it is left for a follow-up.

Move the label selector into the certificates package and resolve
status.nextPrivateKeySecretName with a label-selected LIST rather than a
GET. With SecretsFilteredCaching on, a GET for an unlabeled Secret is
answered by a live API request that returns the whole Secret, private key
included, only for the ownership check to discard it.

The controller test fixtures for the not-owned case carried neither the
label nor an owner reference, so the label check alone rejected them and
the owner UID comparison was untested outside secrets_test.go. They now
carry the label and a controller reference to a Certificate with a
different UID. With metav1.IsControlledBy removed, the not-owned case in
each of the three controllers fails, together with two cases in
secrets_test.go.

Spell labeled the US way in code comments and test names, to match the
rest of the code base.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_017WD7zqUuwxGXT2ZTNQSyFz
Signed-off-by: Richard Wall <[email protected]>
@wallrj

wallrj commented Sep 14, 2026

Copy link
Copy Markdown
Member Author

/retest

@lunarwhite lunarwhite 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.

/lgtm

Thanks @wallrj!

// live GET against the API server for every Secret it returns. A selector such
// as labels.Everything() matches every entry in that cache, so the keymanager
// would GET every Secret in the namespace on every reconcile.
func TestNextPrivateKeySecretSelectorRejectsUnlabeledSecret(t *testing.T) {

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.

Just nitpick: This test is load-bearing on its own. I mutated NextPrivateKeySecretSelector to labels.Everything() and re-ran the package: it fails, but TestGetNextPrivateKeySecret still passes all 9 subtests, because the name-and-ownership predicate masks the widening. So this is the only thing guarding the selector, not a duplicate of the table test below.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Thank you, and thank you for the review. I reproduced that: with the selector set to labels.Everything() only this test fails, and all nine TestGetNextPrivateKeySecret cases pass, because the predicate checks name and ownership and so hides the widening. That is why the test exists.

The widening is a cost bug rather than a correctness bug. With SecretsFilteredCaching on, the LIST would make one live GET per unlabelled Secret in the namespace on every reconcile. An earlier commit on this branch made that mistake and it stopped issuance in e2e; 7a0fe09 has the full account.

I have left the comment as it is rather than push a wording change and drop the lgtm.

[Claude Fable 5.1]

@cert-manager-prow cert-manager-prow Bot added the lgtm Indicates that a PR is ready to be merged. label Sep 16, 2026
@wallrj

wallrj commented Sep 16, 2026

Copy link
Copy Markdown
Member Author

/approve

@cert-manager-prow

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: lunarwhite, 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 16, 2026
@lunarwhite

Copy link
Copy Markdown
Member

/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 Sep 17, 2026
@cert-manager-prow
cert-manager-prow Bot merged commit 7e4ff4d into cert-manager:master Sep 17, 2026
6 checks passed
@wallrj

wallrj commented Sep 18, 2026

Copy link
Copy Markdown
Member Author

/cherry-pick release-1.21

@cert-manager-bot

Copy link
Copy Markdown
Contributor

@wallrj: #9224 failed to apply on top of branch "release-1.21":

Applying: Only consume next private key Secrets owned by the Certificate
Using index info to reconstruct a base tree...
M	pkg/controller/certificates/issuing/issuing_controller.go
M	pkg/controller/certificates/issuing/issuing_controller_test.go
M	pkg/controller/certificates/requestmanager/requestmanager_controller.go
M	pkg/controller/certificates/requestmanager/requestmanager_controller_test.go
Falling back to patching base and 3-way merge...
Auto-merging pkg/controller/certificates/requestmanager/requestmanager_controller_test.go
CONFLICT (content): Merge conflict in pkg/controller/certificates/requestmanager/requestmanager_controller_test.go
Auto-merging pkg/controller/certificates/requestmanager/requestmanager_controller.go
Auto-merging pkg/controller/certificates/issuing/issuing_controller_test.go
CONFLICT (content): Merge conflict in pkg/controller/certificates/issuing/issuing_controller_test.go
Auto-merging pkg/controller/certificates/issuing/issuing_controller.go
error: Failed to merge in the changes.
hint: Use 'git am --show-current-patch=diff' to see the failed patch
hint: When you have resolved this problem, run "git am --continue".
hint: If you prefer to skip this patch, run "git am --skip" instead.
hint: To restore the original branch and stop patching, run "git am --abort".
hint: Disable this message with "git config set advice.mergeConflict false"
Patch failed at 0001 Only consume next private key Secrets owned by the Certificate

Details

In response to this:

/cherry-pick release-1.21

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 Bot pushed a commit that referenced this pull request Sep 20, 2026
* Only consume next private key Secrets owned by the Certificate

The requestmanager and issuing controllers read the Secret named by
status.nextPrivateKeySecretName and use its private key without checking
that the Secret belongs to the Certificate. The keymanager controller,
which creates those Secrets, only ever considers Secrets carrying the
cert-manager.io/next-private-key label and a controller owner reference
back to the Certificate.

status.nextPrivateKeySecretName is writable by any principal with access
to the certificates/status subresource, which is a weaker permission than
reading Secrets in the namespace. Without an ownership check, such a
principal can name any Secret in the namespace and have its private key
copied into spec.secretName.

Add IsNextPrivateKeySecret, which states that invariant once, and
GetNextPrivateKeySecret, which applies it when reading the field. Both
consumers now go through it. A Secret that fails the check is reported as
not found, so callers wait for the keymanager to reconcile the field back
to a Secret it owns, exactly as they already do when the Secret is absent.

Recovery needs a keymanager change to work. createNewPrivateKeySecret
reuses the name already in the status field, so when that name belongs to
a Secret we do not own, the create fails with AlreadyExists and the
existing code adopted the foreign Secret and left the status unchanged.
The consumers would then reject it on every reconcile and issuance would
never progress. The keymanager now creates the Secret under a generated
name instead, and writes that name back to the status field. This is the
graceful recovery the TODO in the tests asked for.

The unit and integration test fixtures built next private key Secrets
with neither the label nor the owner reference, so they did not match
what the keymanager produces in a real cluster. They now go through
helpers that set both. The integration tests create the Secret after the
Certificate, because the owner reference needs the Certificate's UID.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: Richard Wall <[email protected]>

* State the next private key Secret invariant in one place

The previous commit added IsNextPrivateKeySecret and claimed in its doc
comment that the invariant lives in one place. It did not. The keymanager
controller still expressed the same rule separately, as a package-level
label selector built in an init function and ANDed with
predicate.ResourceOwnedBy. Route that list through IsNextPrivateKeySecret
so there is one statement of what a next private key Secret is, and delete
the selector and its init function.

Moving the label test out of the lister selector costs nothing.
ListAllByNamespace indexes only on namespace and then calls
selector.Matches per item, so a label selector and a predicate do the same
work.

Drop the nil and empty checks on status.nextPrivateKeySecretName from both
consumers. GetNextPrivateKeySecret already reports an unset name as not
found, and both callers already return on a not found error. The two copies
had drifted: the issuing controller rejected an empty string, the
requestmanager controller only rejected nil.

The test fixtures set only the next-private-key label, but the keymanager
sets cert-manager.io/part-of-cert-manager-controller as well, so fixtures
that claim to mirror what it creates now set both.

Also drop a fake clientset from the secrets test that seeded nothing, since
the informer factory is never started and the indexer is written directly,
and collapse a comment repeated at four integration test call sites into
the helper's own doc comment.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* Keep the next private key Secret LIST off the metadata cache

The previous commit replaced the label selector on the keymanager's Secret
LIST with labels.Everything(), and moved the label test into the predicate,
on the grounds that it cost nothing. That was wrong, and it stopped
certificates issuing at all.

The claim was checked against client-go's ListAllByNamespace, which indexes
only on namespace and then calls selector.Matches per item. That is the
wrong lister. With the SecretsFilteredCaching feature, which is on by
default, the Secret lister is the one in internal/informers. It serves a
LIST from two caches: a typed cache of cert-manager's own Secrets, which
carry the controller.cert-manager.io/fao label, and a metadata-only cache
of every other Secret in the namespace. The metadata cache stores no
labels, because partialMetadataRemoveAll strips them. Every Secret the
metadata cache returns costs one live GET against the API server.

A selector requiring the next-private-key label therefore matches nothing
in the metadata cache, and the LIST is served entirely from the typed
cache. labels.Everything() matches every entry in it, so the keymanager
issued one GET per unrelated Secret in the namespace on every reconcile of
every Certificate. In the end-to-end tests no Certificate reached Ready and
the setup timed out.

Restore the selector. Keep IsNextPrivateKeySecret as the predicate, so
there is still one statement of what a next private key Secret is, and
document why the label test has to appear in the selector as well. Build
the selector with labels.SelectorFromSet rather than the init function and
panic that the previous commit deleted.

Add a test that the selector rejects a Secret with no labels. It fails if
the selector is widened back to labels.Everything().

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* Never create the next private key Secret under a name from the status field

The keymanager still created its Secret under whatever name
status.nextPrivateKeySecretName held, as long as that name was free. Only
the taken-name case went through the ownership check added in the previous
commits. A principal able to write the certificates/status subresource
could therefore name the spec.secretName of a sibling Certificate that has
not issued yet. The keymanager would create that Secret with its own owner
reference and next-private-key label, the sibling's issuing controller
would apply its certificate and key into it, and the keymanager would then
delete it on the next spec mismatch or Issuing transition, or sign its own
CSR with the sibling's key.

Always create with generateName. Before creating, read the Certificate
live and check whether the Secret it names is one we created on an earlier
reconcile whose status write has not reached the cache yet. That keeps the
duplicate-Secret guard from #8579. A named Secret that is not ours now
records a NotOwned Warning event, so a tampered status field leaves a
trace in kubectl describe rather than only a routine Generated event.

When the keymanager already owns one Secret but the status field names
something else, repoint the field at the Secret it owns instead of
deleting the Secret. The delete raced the Secret informer after the
keymanager's own status write, so the Secret created on one reconcile
could be deleted on the next, and it let a status writer force a key
rotation, a Secret delete and create, and a CertificateRequest delete and
create on demand. The rotationPolicy Never path that cannot make a next
private key now clears the field rather than leaving a stale or untrusted
name in it.

IsNextPrivateKeySecret also rejects the Secret named by spec.secretName.
spec.secretTemplate.labels can put the next-private-key label on it, and
--enable-certificate-owner-ref gives it the controller reference, after
which the keymanager would delete the served certificate on every Ready
transition. Reserving cert-manager.io label keys in validation is the
cleaner fix but is a breaking change, so it is left for a follow-up.

Move the label selector into the certificates package and resolve
status.nextPrivateKeySecretName with a label-selected LIST rather than a
GET. With SecretsFilteredCaching on, a GET for an unlabeled Secret is
answered by a live API request that returns the whole Secret, private key
included, only for the ownership check to discard it.

The controller test fixtures for the not-owned case carried neither the
label nor an owner reference, so the label check alone rejected them and
the owner UID comparison was untested outside secrets_test.go. They now
carry the label and a controller reference to a Certificate with a
different UID. With metav1.IsControlledBy removed, the not-owned case in
each of the three controllers fails, together with two cases in
secrets_test.go.

Spell labeled the US way in code comments and test names, to match the
rest of the code base.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_017WD7zqUuwxGXT2ZTNQSyFz

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
(cherry picked from commit 7e4ff4d)
Signed-off-by: Richard Wall <[email protected]>
kokhlo added a commit to kokhlo/cert-manager that referenced this pull request Oct 1, 2026
secretNamespaceLister.List fetched every metadata-cache match with an
individual live GET, so a selector matching unlabelled Secrets cost one
API request per Secret in the namespace on every call (cert-manager#9347, observed
in cert-manager#9224). Fetch all matches with a single live LIST instead and
re-filter it by the caller's selector, keeping the duplicates-keep-the-
apiserver-copy contract. A typed-cache hit now costs no live request,
and the worst case is one LIST per call regardless of namespace size.

Signed-off-by: kokhlo <[email protected]>
kokhlo added a commit to kokhlo/cert-manager that referenced this pull request Oct 5, 2026
wallrj asked which direction the predicate should take on a request whose
Ready condition carries Reason=Failed with a status other than False, and
picked the loose reading. Taking it.

The status check went from the predicate, the issuing controller's new
branch that emitted a Stalled event and returned nil went with it, and the
master branch that counts Reason=Failed as a failure is back untouched. A
request reporting that reason has failed whatever else its status says, so
it is counted once by the issuing controller and replaced on the retry. The
old shape left a Certificate in Issuing=True for good: nothing counted it,
the requestmanager never deleted it, and the only signal was a Warning
event per sync.

The requestmanager now deletes such a request when it predates the Issuing
transition. That is the behaviour change, and it is the right one: the
request had failed before this issuance, so replacing it is what the
controller is for.

The three controller-level scenarios dropped in 1a63ece are restored. They
were not order-dependent. Their Secret fixtures had stopped carrying the
next-private-key label and the controller owner reference that
GetNextPrivateKeySecret has required since cert-manager#9224, so ProcessItem returned
before the predicate was ever reached and the test passed by doing nothing.
With nextPrivateKeySecretMeta(...) they pass alone and in the full tables,
on repeated runs. The shared *metav1.Time in
failedCRConditionPreviousIssuance was not the cause either, so that
condition value is shared again rather than rebuilt per scenario.

The requestmanager suite gains a second cert-manager#9327 case, the outermost one: a
failed request with neither failureTime nor a Ready lastTransitionTime,
where creationTimestamp is the only date left.

Local serial suite (-p 1 -short): issuing 132s PASS, requestmanager 37s
PASS, internal/controller/certificates 2s PASS. Reverting the predicate
change fails the new issuing case and the new predicate case, so both bite.

Signed-off-by: kokhlo <[email protected]>
@wallrj-cyberark wallrj-cyberark mentioned this pull request Oct 23, 2026
19 tasks done
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. area/testing Issues relating to testing 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/XL Denotes a PR that changes 500-999 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.

4 participants