Skip to content

certrotation: require UserInfo on PeerRotation, add tests#2157

Open
sanchezl wants to merge 5 commits intoopenshift:masterfrom
sanchezl:peerrotation-userinfo-followup
Open

certrotation: require UserInfo on PeerRotation, add tests#2157
sanchezl wants to merge 5 commits intoopenshift:masterfrom
sanchezl:peerrotation-userinfo-followup

Conversation

@sanchezl
Copy link
Copy Markdown
Contributor

@sanchezl sanchezl commented Apr 9, 2026

Summary

Follow-up to #2145 addressing deferred review comments:

  • Require UserInfo unconditionally on PeerRotation — previously only validated when ConfigurablePKI was enabled. A caller converting ServingRotationPeerRotation without setting UserInfo would silently work on the legacy path but fail when ConfigurablePKI is enabled. On the legacy path, also validates that UserInfo.Name matches the sorted first hostname (used as CN by MakeServerCertForDuration).
  • Add PeerRotation NewCertificate tests — covers both happy paths (legacy RSA, ECDSA with ConfigurablePKI) and error paths (nil UserInfo, mismatched UserInfo name). Verifies dual ExtKeyUsage, Subject encoding, and hostname SANs.
  • Use t.Context() in certrotation tests — replaces context.Background()/context.TODO() across all test files.

Test plan

  • go test ./pkg/operator/certrotation/... passes
  • Verify CEO's PeerRotation usage still compiles (already sets UserInfo)

sanchezl added 3 commits April 9, 2026 15:31
Previously UserInfo was only validated when ConfigurablePKI was enabled
(keyGen != nil). A caller converting ServingRotation to PeerRotation
without setting UserInfo would silently work on the legacy path but
fail when ConfigurablePKI is enabled on the cluster.

Move the nil check before the keyGen branch so it fails early
regardless of path. On the legacy path, also validate that
UserInfo.Name matches the sorted first hostname, since
MakeServerCertForDuration uses that as the certificate CN.
Add TestPeerRotation_NewCertificate_WithKeyPairGenerator covering both
happy paths (legacy RSA, ECDSA with ConfigurablePKI) and error paths
(nil UserInfo, mismatched UserInfo name). Verifies dual ExtKeyUsage
(ClientAuth + ServerAuth), Subject encoding, and hostname SANs.
Replace context.Background() and context.TODO() with t.Context()
across all certrotation test files. Remove unused "context" imports.
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 9, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3d284392-689a-43a2-bd9b-838f92982ba0

📥 Commits

Reviewing files that changed from the base of the PR and between 9d7c515 and 27f907d.

📒 Files selected for processing (1)
  • pkg/operator/certrotation/target_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/operator/certrotation/target_test.go

Walkthrough

Switched tests to use per-test contexts (t.Context()), removed unused context imports, reworked key-generation branching in certificate rotation methods to prefer duration-based helpers when keyGen==nil and configurable-PKI constructors otherwise, moved PeerRotation UserInfo checks, and added PeerRotation unit tests.

Changes

Cohort / File(s) Summary
Test context updates
pkg/operator/certrotation/cabundle_test.go, pkg/operator/certrotation/client_cert_rotation_controller_test.go, pkg/operator/certrotation/signer_test.go, pkg/operator/certrotation/target_test.go
Replaced context.TODO() / context.Background() with t.Context() in tests and removed now-unused context imports.
Certificate-generation branching
pkg/operator/certrotation/target.go
Reordered keyGen branches: keyGen == nil now uses duration-based helpers (Make*ForDuration / MakeCAConfigForDuration); keyGen != nil uses configurable-PKI constructors (New*Certificate / NewSigningCertificate) with lifetime and extensions. Moved PeerRotation UserInfo requirement outside the keyGen branch and added legacy CN validation (sorted hostnames).
PeerRotation tests & coverage
pkg/operator/certrotation/target_test.go
Added TestPeerRotation_NewCertificate_WithKeyPairGenerator and extended key-algorithm coverage for client/serving rotation tests; validates public-key algorithm selection, UserInfo error cases, legacy CN conflict behavior, SAN/DNS contents, CN/organization fields, and both ClientAuth/ServerAuth extended usages.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands and usage tips.

@openshift-ci openshift-ci Bot requested review from deads2k and p0lyn0mial April 9, 2026 19:37
@sanchezl
Copy link
Copy Markdown
Contributor Author

sanchezl commented Apr 9, 2026

/cc @rh-roman

@openshift-ci openshift-ci Bot requested a review from rh-roman April 9, 2026 19:38
Copy link
Copy Markdown

@rh-roman rh-roman left a comment

Choose a reason for hiding this comment

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

Mostly cosmetic changes, the PR looks good!

Comment thread pkg/operator/certrotation/target.go Outdated
Comment on lines +460 to +476
if r.UserInfo == nil {
return nil, fmt.Errorf("PeerRotation requires UserInfo for configurable PKI certificates")
}
return signer.NewPeerCertificate(
sets.New(hostnames...), r.UserInfo, keyGen,
crypto.WithLifetime(validity),
crypto.WithExtensions(r.CertificateExtensionFn...),
)
}
// Legacy path: use server cert template with extension fn to add both ExtKeyUsages.
// The subject CN comes from the first hostname (preserves current behavior).
// MakeServerCertForDuration sorts hostnames and uses the first sorted value as CN.
sortedHostnames := sets.List(sets.New(hostnames...))
if cn := sortedHostnames[0]; r.UserInfo.GetName() != cn {
return nil, fmt.Errorf("PeerRotation legacy path uses sorted first hostname %q as CN; UserInfo.Name %q conflicts — set UserInfo.Name to match or enable ConfigurablePKI", cn, r.UserInfo.GetName())
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

What do you think of flipping the keyGen check and putting legacy code inside. Then happy path will be the default return and removing the legacy path will be a smaller diff (eventually).

Comment on lines +856 to +864
if tc.wantErr != "" {
if err == nil {
t.Fatalf("expected error containing %q, got nil", tc.wantErr)
}
if !strings.Contains(err.Error(), tc.wantErr) {
t.Fatalf("expected error containing %q, got %q", tc.wantErr, err.Error())
}
return
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This project imports testify, you could shorten the test to

Suggested change
if tc.wantErr != "" {
if err == nil {
t.Fatalf("expected error containing %q, got nil", tc.wantErr)
}
if !strings.Contains(err.Error(), tc.wantErr) {
t.Fatalf("expected error containing %q, got %q", tc.wantErr, err.Error())
}
return
}
if tc.wantErr != "" {
if assert.Error(t, err) {
assert.ErrorContains(t, err, tc.wantErrText)
}
return
}

Comment on lines +874 to +890
// Verify both ExtKeyUsages are present
hasClientAuth := false
hasServerAuth := false
for _, usage := range cert.ExtKeyUsage {
if usage == x509.ExtKeyUsageClientAuth {
hasClientAuth = true
}
if usage == x509.ExtKeyUsageServerAuth {
hasServerAuth = true
}
}
if !hasClientAuth {
t.Error("missing ExtKeyUsageClientAuth")
}
if !hasServerAuth {
t.Error("missing ExtKeyUsageServerAuth")
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

If you pull these out into a helper you can also add them to Client and Serving tests, which don't already have them.

Flip the keyGen nil check in all rotation types so the legacy path
is handled first and returns early, with the configurable PKI path
as the clean fall-through.
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
pkg/operator/certrotation/target_test.go (1)

898-901: Strengthen SAN assertions to validate requested hostnames/IPs explicitly.

len(cert.DNSNames) > 0 can pass even when some required SAN entries are missing (especially IP SANs). Assert each tc.hostnames entry exists in DNS SANs or IP SANs.

Proposed test hardening
 import (
 	"crypto/x509"
 	"crypto/x509/pkix"
+	"net"
 	"slices"
 	"strings"
 	"testing"
 	"time"
@@
-			// Verify hostnames in SANs
-			if len(cert.DNSNames) == 0 {
-				t.Error("expected DNS SANs")
-			}
+			// Verify all requested hostnames/IPs are present in SANs
+			for _, h := range tc.hostnames {
+				if ip := net.ParseIP(h); ip != nil {
+					found := false
+					for _, certIP := range cert.IPAddresses {
+						if certIP.Equal(ip) {
+							found = true
+							break
+						}
+					}
+					if !found {
+						t.Errorf("missing IP SAN %q", h)
+					}
+					continue
+				}
+				if !slices.Contains(cert.DNSNames, h) {
+					t.Errorf("missing DNS SAN %q", h)
+				}
+			}

As per coding guidelines, "Focus on major issues impacting performance, readability, maintainability and security. Avoid nitpicks and avoid verbosity."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/operator/certrotation/target_test.go` around lines 898 - 901, The test
currently only asserts that cert.DNSNames is non-empty which can miss missing
SAN entries; update the test to iterate over each tc.hostnames entry and assert
it appears either in cert.DNSNames or in cert.IPAddresses (by comparing the
string form of net.IP entries or parsing tc.hostnames with net.ParseIP), and
fail with a clear t.Errorf when a specific hostname/IP from tc.hostnames is not
found; reference cert.DNSNames, cert.IPAddresses and tc.hostnames in the check
and use net.ParseIP to distinguish IP vs DNS entries.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@pkg/operator/certrotation/target_test.go`:
- Around line 898-901: The test currently only asserts that cert.DNSNames is
non-empty which can miss missing SAN entries; update the test to iterate over
each tc.hostnames entry and assert it appears either in cert.DNSNames or in
cert.IPAddresses (by comparing the string form of net.IP entries or parsing
tc.hostnames with net.ParseIP), and fail with a clear t.Errorf when a specific
hostname/IP from tc.hostnames is not found; reference cert.DNSNames,
cert.IPAddresses and tc.hostnames in the check and use net.ParseIP to
distinguish IP vs DNS entries.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 5813a957-0892-433a-9c50-14d563ed9a22

📥 Commits

Reviewing files that changed from the base of the PR and between 08ccb6a and 9d7c515.

📒 Files selected for processing (1)
  • pkg/operator/certrotation/target_test.go

Use slices.Contains for ExtKeyUsage checks in PeerRotation tests.
Add RSA-4096, ECDSA-P256, and ECDSA-P384 test cases to Client,
Serving, and Signer rotation tests for broader key generator coverage.

Co-authored-by: Roman Feldman <rofeldma@redhat.com>
@sanchezl sanchezl force-pushed the peerrotation-userinfo-followup branch from 9d7c515 to 27f907d Compare April 10, 2026 00:18
@openshift-ci
Copy link
Copy Markdown
Contributor

openshift-ci Bot commented Apr 10, 2026

@sanchezl: all tests passed!

Full PR test history. Your PR dashboard.

Details

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. I understand the commands that are listed here.

@rh-roman
Copy link
Copy Markdown

/lgtm

@openshift-ci openshift-ci Bot added the lgtm Indicates that a PR is ready to be merged. label Apr 10, 2026
@openshift-ci
Copy link
Copy Markdown
Contributor

openshift-ci Bot commented Apr 10, 2026

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: rh-roman, sanchezl
Once this PR has been reviewed and has the lgtm label, please assign jsafrane for approval. For more information see the Code Review Process.

The full list of commands accepted by this bot can be found 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

lgtm Indicates that a PR is ready to be merged.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants