Skip to content

fix: harden the creation of private key secrets to avoid creating duplicates - #8579

Merged
cert-manager-prow[bot] merged 1 commit into
cert-manager:masterfrom
ThatsMrTalbot:fix/harden-private-key-secret-creation
Mar 10, 2026
Merged

cert-manager-prow[bot] merged 1 commit into
cert-manager:masterfrom
ThatsMrTalbot:fix/harden-private-key-secret-creation

Conversation

@ThatsMrTalbot

@ThatsMrTalbot ThatsMrTalbot commented Mar 5, 2026 •

Copy link
Copy Markdown
Contributor

Pull Request Motivation

This pull request improves the reliability of secret creation in the certificate key manager controller by addressing potential cache staleness issues. The main changes ensure that the latest certificate object is fetched directly from the API and that secret creation gracefully handles cases where the cache may be outdated.

Improvements to cache consistency and error handling:

  • In createNewPrivateKeySecret, the latest Certificate object is now fetched via a direct API call before proceeding, reducing the risk of operating on stale data.

    While the extra API call in createNewPrivateKeySecret bypasses the informer cache to get a fresh Certificate object, this code path is only actually reached when:

    1. The certificate has Issuing == True (an active issuance cycle), and
    2. Zero "next private key" secrets are visible in the cache — i.e. the very start of that cycle

    This means it fires at most once per renewal (e.g. every 60–90 days), and the single Get is far cheaper than the Create that immediately follows it on the same path. There is no meaningful performance impact.

  • After attempting to create a new secret, if an IsAlreadyExists error is encountered (indicating the cache was outdated and the secret already exists), the code now fetches and returns the existing secret instead of failing.

Kind

/kind bug

Release Note

NONE

@ThatsMrTalbot
ThatsMrTalbot requested a review from Copilot March 5, 2026 18:58
@cert-manager-prow cert-manager-prow Bot added release-note-none Denotes a PR that doesn't merit a release note. 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/S Denotes a PR that changes 10-29 lines, ignoring generated files. labels Mar 5, 2026

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 encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

@ThatsMrTalbot
ThatsMrTalbot force-pushed the fix/harden-private-key-secret-creation branch from 1e47ed8 to 8edc0e5 Compare March 5, 2026 19:27
@cert-manager-prow cert-manager-prow Bot added size/M Denotes a PR that changes 30-99 lines, ignoring generated files. and removed size/S Denotes a PR that changes 10-29 lines, ignoring generated files. labels Mar 5, 2026
@ThatsMrTalbot
ThatsMrTalbot force-pushed the fix/harden-private-key-secret-creation branch from 8edc0e5 to ca69438 Compare March 5, 2026 19:39
@ThatsMrTalbot
ThatsMrTalbot requested a review from Copilot March 5, 2026 19:56

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 2 out of 2 changed files in this pull request and generated 3 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@ThatsMrTalbot
ThatsMrTalbot force-pushed the fix/harden-private-key-secret-creation branch from ca69438 to 7e27be8 Compare March 5, 2026 20:09
@ThatsMrTalbot
ThatsMrTalbot requested a review from Copilot March 5, 2026 20:09

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 2 out of 2 changed files in this pull request and generated 1 comment.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@SgtCoDFish SgtCoDFish 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
/approve

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

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: SgtCoDFish

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 Mar 10, 2026
@cert-manager-prow
cert-manager-prow Bot merged commit 46f66d4 into cert-manager:master Mar 10, 2026
wallrj added a commit to wallrj/cert-manager that referenced this pull request Sep 14, 2026
… 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]>
cert-manager-prow Bot pushed a commit that referenced this pull request Sep 17, 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]>
Signed-off-by: Richard Wall <[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]>
Signed-off-by: Richard Wall <[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
Signed-off-by: Richard Wall <[email protected]>

---------

Signed-off-by: Richard Wall <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
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]>
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-none Denotes a PR that doesn't merit a release note. size/M Denotes a PR that changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants