Repository navigation
Only consume next private key Secrets owned by the Certificate - #9224
cert-manager-prow[bot] merged 4 commits into
Conversation
|
Skipping CI for Draft Pull Request. |
457742c to
1ac68a5
Compare
1ac68a5 to
08c7d60
Compare
08c7d60 to
490e795
Compare
There was a problem hiding this comment.
🟡 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
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]>
490e795 to
9203cab
Compare
|
/test pull-cert-manager-master-e2e-v1-37 |
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]>
|
/retest |
| // 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) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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]
|
/approve |
|
[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 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: #9224 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. |
* 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]>
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]>
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]>
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]>
If you can write a Certificate's
statussubresource, you can obtain a private key you are not allowed to read.Point
status.nextPrivateKeySecretNameat 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'sspec.secretName. You chosespec.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-keylabel and a controller owner reference back to the Certificate. The two consumers bypass that invariant by trusting the status field.Writing
certificates/statusis a weaker permission than reading Secrets. You need read access to the Secret you name inspec.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: updatethrough the aggregatedcert-manager-editrole, and Kubernetes' ownsystem:aggregate-to-editalready grants full read and write onsecretsin 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 renewdoes. 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
IsNextPrivateKeySecretstates the invariant, and everything that relies on it now goes through that one function:GetNextPrivateKeySecretfor 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.
createNewPrivateKeySecretalways usesgenerateName. 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 aNotOwnedWarning event and is ignored.Creating under a free name from the status field was unsafe on its own. The name could be the
spec.secretNameof 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: Neverpath that cannot make a next private key now clears the field rather than leaving a stale or untrusted name in it.IsNextPrivateKeySecretalso rejects the Secret named byspec.secretName.spec.secretTemplate.labelscan put thenext-private-keylabel on it, and--enable-certificate-owner-refgives it the controller reference, after which the keymanager would delete the served certificate on every Ready transition. Reservingcert-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.GetNextPrivateKeySecretresolves the name with a label-selected LIST rather than a GET. WithSecretsFilteredCachingon, 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.IsControlledByremoved fromIsNextPrivateKeySecret, so that the label alone is checked, exactly these fail, and no others:TestGetNextPrivateKeySecret/rejects a Secret labeled but owned by a different Certificateand.../rejects a Secret whose owner reference is not a controller referenceTestProcessItem/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, withexpected secretUpdateData func to be called: false was called: true. That is the private key being copied intospec.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
[Claude Opus 5, Claude Fable 5.1]