Skip to content

NO-JIRA: add two more encryption rotation scenarios#2218

Open
tjungblu wants to merge 1 commit into
openshift:masterfrom
tjungblu:rotation_tests
Open

NO-JIRA: add two more encryption rotation scenarios#2218
tjungblu wants to merge 1 commit into
openshift:masterfrom
tjungblu:rotation_tests

Conversation

@tjungblu
Copy link
Copy Markdown
Contributor

@tjungblu tjungblu commented May 12, 2026

This adds two new encryption tests:

  • Forced rotation during first migration
  • Forced rotation during a rotation

Summary by CodeRabbit

Tests

  • Added operator condition-based detection for encryption migration progress with fallback polling support
  • Introduced new encryption rotation test scenarios to verify behavior during active migration phases
  • Added encryption stability verification and key rotation tracking helpers
  • Enhanced encryption type application with immediate APIServer specification updates

@openshift-ci-robot
Copy link
Copy Markdown

@tjungblu: This pull request explicitly references no jira issue.

Details

In response to this:

This adds two new encryption tests:

  • Forced rotation during first migration
  • Forced rotation during a rotation

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 openshift-eng/jira-lifecycle-plugin repository.

@openshift-ci-robot openshift-ci-robot added the jira/valid-reference Indicates that this PR references a valid Jira ticket of any type. label May 12, 2026
@openshift-ci openshift-ci Bot added the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label May 12, 2026
@openshift-ci
Copy link
Copy Markdown
Contributor

openshift-ci Bot commented May 12, 2026

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

Comment on lines +225 to +230
// TODO(thomas): wire up a hook to define this from a provider configuration
// TODO(thomas): when we're on KMS provider we can grab the keyId from an annotation
// TODO(thomas): a new rotation controller can update the annotation for KMS

// TODO(thomas): alternative, when we detect a new KeyId, we can also remove the migrated-* annotations,
// that way the controller will definitely try to reconcile it again.
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I'll remove that, sorry

@openshift-ci
Copy link
Copy Markdown
Contributor

openshift-ci Bot commented May 12, 2026

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: tjungblu
Once this PR has been reviewed and has the lgtm label, please assign p0lyn0mial 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

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 12, 2026

Walkthrough

This PR introduces encryption migration and rotation testing helpers for OpenShift's library-go. It consolidates operator condition polling into a shared callback type in helpers.go, adds encryption state polling and rotation tracking helpers, extends rotation test scenarios with operator-aware progress detection, and introduces two new test scenarios that exercise key rotation during encryption migration windows.

Changes

Encryption migration and rotation testing

Layer / File(s) Summary
Operator conditions callback type and foundation
test/library/encryption/helpers.go, test/library/encryption/perf_scenarios.go
GetOperatorConditionsFuncType is defined in helpers.go with operatorv1 import support; the duplicate type definition and import are removed from perf_scenarios.go to establish a shared contract.
Encryption state polling and rotation tracking
test/library/encryption/helpers.go
WaitUntilEncryptionStable, WaitForNRotations, EncryptionWriteKeySecretID, and WaitForEncryptionMigrationInProgressWindow are added to poll for encryption consistency, track key rotation progression by numeric suffix parsing, and detect active migration windows via operator conditions with fallback to secret metadata.
APIServer encryption application and key rotation cleanup
test/library/encryption/helpers.go
ApplyAPIServerEncryptionType applies encryption specs without waiting for migration; ClearForcedKeyRotationReason clears forced rotation state via unsupported-config overrides; SetAndWaitForEncryptionType is updated to apply the APIServer spec before waiting for key migration completion.
Rotation scenario extension with operator conditions and cleanup
test/library/encryption/scenarios.go
RotationScenario is extended with an optional GetOperatorConditionsFunc field; TestEncryptionRotation adds deferred cleanup calling ClearForcedKeyRotationReason to clear rotation state on test exit.
New rotation-during-migration test scenarios
test/library/encryption/scenarios.go
TestEncryptionRotationDuringFirstMigration exercises key rotation during initial encryption enablement; TestEncryptionRotationDuringOngoingRotation exercises overlapping rotations during active migration, both using operator-observed in-progress windows to validate convergence.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • openshift/library-go#2220: Both PRs update test/library/encryption/helpers.go around SetAndWaitForEncryptionType, changing it to take a full configv1.APIServerEncryption provider and adjusting the APIServer encryption spec update/wait flow accordingly.

Suggested reviewers

  • deads2k
  • dgrisonnet
🚥 Pre-merge checks | ✅ 10 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 78.57% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Test Structure And Quality ⚠️ Warning Test code lacks meaningful assertion messages and contains unaddressed review comments about critical validation logic. Add assertion messages to all require.NoError calls. Address review comments: validate expectedWriteKey in WaitForEncryptionMigrationInProgressWindow operator path and normalize empty expectedMode in WaitUntilEncryptionStable.
✅ Passed checks (10 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adding two new encryption rotation test scenarios during migration phases.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Stable And Deterministic Test Names ✅ Passed PR adds test library helper functions with static Go names. No Ginkgo test definitions (Describe, Context, It, When) exist. Dynamic values only in rotation reason configuration data, not test titles.
Microshift Test Compatibility ✅ Passed New functions are library helpers, not Ginkgo e2e tests. They contain no Ginkgo keywords and are meant to be called by consuming repositories' tests, making the check not applicable.
Single Node Openshift (Sno) Test Compatibility ✅ Passed Functions are library helpers in test/library/encryption/, not Ginkgo e2e tests. Test encryption via API config and metadata polling, not multi-node cluster topology.
Topology-Aware Scheduling Compatibility ✅ Passed This PR modifies only test helper libraries in test/library/encryption/, not deployment manifests, operator code, or controllers. The topology check explicitly applies only to those.
Ote Binary Stdout Contract ✅ Passed Test library helpers (not OTE binary). All new functions require testing.TB. No process-level code. All logging via t.Logf/e.Logf. No stdout writes. Check not applicable.
Ipv6 And Disconnected Network Test Compatibility ✅ Passed Not applicable. PR adds test library helper functions, not Ginkgo e2e tests. No Ginkgo patterns (It/Describe/Context) present. No IPv4 assumptions or external connectivity requirements detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

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

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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

@tjungblu tjungblu force-pushed the rotation_tests branch 2 times, most recently from 7e6ba8f to 9f815c4 Compare May 13, 2026 08:13
tjungblu added a commit to tjungblu/cluster-kube-apiserver-operator that referenced this pull request May 13, 2026
from library-go openshift/library-go#2218

Signed-off-by: Thomas Jungblut <tjungblu@redhat.com>
Copy link
Copy Markdown
Contributor

@p0lyn0mial p0lyn0mial left a comment

Choose a reason for hiding this comment

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

I did a first quick pass. I’d like to clarify the scope. Are we creating new cases that will support all providers, or just KMS?

t.Skipf("initial migration finished before an in-progress window was observed; set GetOperatorConditionsFunc or use a cluster where migration stays visible longer")
}

require.NoError(e, ForceKeyRotation(e, scenario.UnsupportedConfigFunc, fmt.Sprintf("test-rotation-during-first-migration-%s", rand.String(4))))
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.

ForceKeyRotation has no effect on KMS. What is out plan here ? Do we want to run the new scenarios for all encryption providers ?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

ForceKeyRotation will be implemented differently later on

// ClearForcedKeyRotationReason clears encryption.reason under UnsupportedConfigOverrides (same merge path as
// ForceKeyRotation). Call when a test finishes so the next test in sequence does not inherit a non-empty
// reason and the key controller does not keep seeing an external rotation request.
func ClearForcedKeyRotationReason(t testing.TB, updateUnsupportedConfig UpdateUnsupportedConfigFunc) error {
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.

instead of a new fn why no to change teh ForceKeyRotation to register a cleanup routine via t.Cleanup ?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

why would I couple those two functionalities together? what if I just want to force a key rotation and not cleanup?

Comment thread test/library/encryption/scenarios.go Outdated

require.NoError(e, ForceKeyRotation(e, scenario.UnsupportedConfigFunc, fmt.Sprintf("test-rotation-during-first-migration-%s", rand.String(4))))
// n=2: one write-key revision from turning encryption on, one from ForceKeyRotation.
WaitForNRotations(e, clientSet.Kube, scenario.EncryptionProvider, scenario.TargetGRs, ns, labelSelector, prevMeta, 2)
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.

also for KMS, rotation will not create a new key.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

yep, so this would be implemented differently in KMS - I assume this would use this API that you and Ben cobbled together so far

@openshift-ci openshift-ci Bot added the needs-rebase Indicates a PR cannot be merged because it has merge conflicts with HEAD. label May 14, 2026
@tjungblu tjungblu marked this pull request as ready for review May 15, 2026 07:56
@tjungblu tjungblu force-pushed the rotation_tests branch 2 times, most recently from 20aff62 to 0cadc78 Compare May 15, 2026 08:06
This adds two new encryption tests:
* Forced rotation during first migration
* Forced rotation during a rotation

Signed-off-by: Thomas Jungblut <tjungblu@redhat.com>
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.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/library/encryption/helpers.go`:
- Around line 399-416: The operator-condition branch currently returns true for
any Migrating condition; change the loop that scans conds (inside the wait.Poll
using getOp) to also verify the expectedWriteKey is the target of that
migration: only treat a condition as success if c.Type ==
encryptionMigrationControllerProgressingType && c.Status ==
operatorv1.ConditionTrue && c.Reason == "Migrating" AND (expectedWriteKey == ""
OR the condition text contains expectedWriteKey). In practice, update the
condition check in the loop to inspect the condition's message/text (e.g.,
c.Message) for expectedWriteKey and only return true when it matches; keep the
existing fallback to secret metadata polling and the t.Logf call unchanged.
- Around line 339-355: WaitUntilEncryptionStable compares meta.Mode to the raw
expectedMode which can be the zero-value; normalize empty expectedMode to the
canonical defaultEncryptionMode before polling so callers passing "" don’t hang.
In WaitUntilEncryptionStable set wantMode := string(expectedMode) and if
wantMode == "" assign wantMode = defaultEncryptionMode (same mapping used by
WaitForEncryptionKeyBasedOn) so the meta.Mode comparison and
allTargetGRsMigrated checks use the normalized mode.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: openshift/coderabbit/.coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 62d417f5-06d3-4c1f-95cd-58e2149b95b8

📥 Commits

Reviewing files that changed from the base of the PR and between 9f815c4 and dc56c5c.

📒 Files selected for processing (3)
  • test/library/encryption/helpers.go
  • test/library/encryption/perf_scenarios.go
  • test/library/encryption/scenarios.go
💤 Files with no reviewable changes (1)
  • test/library/encryption/perf_scenarios.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/library/encryption/scenarios.go

Comment on lines +339 to +355
func WaitUntilEncryptionStable(t testing.TB, kube kubernetes.Interface, expectedMode configv1.EncryptionType, targetGRs []schema.GroupResource, namespace, labelSelector string) {
t.Helper()
wantMode := string(expectedMode)
err := wait.Poll(waitPollInterval, waitPollTimeout, func() (bool, error) {
meta, err := GetLastKeyMeta(t, kube, namespace, labelSelector)
if err != nil {
return false, err
}
if meta.Mode != wantMode {
return false, nil
}
if !allTargetGRsMigrated(meta, targetGRs) {
return false, nil
}
return true, nil
})
require.NoError(t, err)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Normalize empty expectedMode to identity before polling.

WaitForEncryptionKeyBasedOn already maps "" to defaultEncryptionMode, but this helper compares meta.Mode to "" directly. Any caller that passes the zero-value encryption type will sit here until timeout, and WaitForNRotations inherits that behavior.

Suggested fix
 func WaitUntilEncryptionStable(t testing.TB, kube kubernetes.Interface, expectedMode configv1.EncryptionType, targetGRs []schema.GroupResource, namespace, labelSelector string) {
 	t.Helper()
 	wantMode := string(expectedMode)
+	if wantMode == "" {
+		wantMode = defaultEncryptionMode
+	}
 	err := wait.Poll(waitPollInterval, waitPollTimeout, func() (bool, error) {
 		meta, err := GetLastKeyMeta(t, kube, namespace, labelSelector)
 		if err != nil {
 			return false, err
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func WaitUntilEncryptionStable(t testing.TB, kube kubernetes.Interface, expectedMode configv1.EncryptionType, targetGRs []schema.GroupResource, namespace, labelSelector string) {
t.Helper()
wantMode := string(expectedMode)
err := wait.Poll(waitPollInterval, waitPollTimeout, func() (bool, error) {
meta, err := GetLastKeyMeta(t, kube, namespace, labelSelector)
if err != nil {
return false, err
}
if meta.Mode != wantMode {
return false, nil
}
if !allTargetGRsMigrated(meta, targetGRs) {
return false, nil
}
return true, nil
})
require.NoError(t, err)
func WaitUntilEncryptionStable(t testing.TB, kube kubernetes.Interface, expectedMode configv1.EncryptionType, targetGRs []schema.GroupResource, namespace, labelSelector string) {
t.Helper()
wantMode := string(expectedMode)
if wantMode == "" {
wantMode = defaultEncryptionMode
}
err := wait.Poll(waitPollInterval, waitPollTimeout, func() (bool, error) {
meta, err := GetLastKeyMeta(t, kube, namespace, labelSelector)
if err != nil {
return false, err
}
if meta.Mode != wantMode {
return false, nil
}
if !allTargetGRsMigrated(meta, targetGRs) {
return false, nil
}
return true, nil
})
require.NoError(t, err)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/library/encryption/helpers.go` around lines 339 - 355,
WaitUntilEncryptionStable compares meta.Mode to the raw expectedMode which can
be the zero-value; normalize empty expectedMode to the canonical
defaultEncryptionMode before polling so callers passing "" don’t hang. In
WaitUntilEncryptionStable set wantMode := string(expectedMode) and if wantMode
== "" assign wantMode = defaultEncryptionMode (same mapping used by
WaitForEncryptionKeyBasedOn) so the meta.Mode comparison and
allTargetGRsMigrated checks use the normalized mode.

Comment on lines +399 to +416
if getOp != nil {
err := wait.Poll(2*time.Second, windowWait, func() (bool, error) {
conds, err := getOp(t)
if err != nil {
return false, err
}
for _, c := range conds {
if c.Type == encryptionMigrationControllerProgressingType && c.Status == operatorv1.ConditionTrue && c.Reason == "Migrating" {
return true, nil
}
}
return false, nil
})
if err == nil {
return true
}
t.Logf("encryption migration progressing condition not observed within %v, falling back to secret metadata polling: %v", windowWait, err)
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Gate the operator-condition path on expectedWriteKey.

This branch returns true on any Migrating condition, even if expectedWriteKey has not become the active write key yet. Since the metadata path is the only branch that validates the key and it does not run until after the full operator poll window, a stale/previous migration can satisfy this early and the next rotation gets stacked at the wrong time.

Suggested fix
 	if getOp != nil {
 		err := wait.Poll(2*time.Second, windowWait, func() (bool, error) {
+			meta, err := GetLastKeyMeta(t, kube, namespace, labelSelector)
+			if err != nil {
+				return false, err
+			}
+			if meta.Name != expectedWriteKey {
+				return false, nil
+			}
+			if allTargetGRsMigrated(meta, targetGRs) {
+				return false, nil
+			}
+
 			conds, err := getOp(t)
 			if err != nil {
 				return false, err
 			}
 			for _, c := range conds {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if getOp != nil {
err := wait.Poll(2*time.Second, windowWait, func() (bool, error) {
conds, err := getOp(t)
if err != nil {
return false, err
}
for _, c := range conds {
if c.Type == encryptionMigrationControllerProgressingType && c.Status == operatorv1.ConditionTrue && c.Reason == "Migrating" {
return true, nil
}
}
return false, nil
})
if err == nil {
return true
}
t.Logf("encryption migration progressing condition not observed within %v, falling back to secret metadata polling: %v", windowWait, err)
}
if getOp != nil {
err := wait.Poll(2*time.Second, windowWait, func() (bool, error) {
meta, err := GetLastKeyMeta(t, kube, namespace, labelSelector)
if err != nil {
return false, err
}
if meta.Name != expectedWriteKey {
return false, nil
}
if allTargetGRsMigrated(meta, targetGRs) {
return false, nil
}
conds, err := getOp(t)
if err != nil {
return false, err
}
for _, c := range conds {
if c.Type == encryptionMigrationControllerProgressingType && c.Status == operatorv1.ConditionTrue && c.Reason == "Migrating" {
return true, nil
}
}
return false, nil
})
if err == nil {
return true
}
t.Logf("encryption migration progressing condition not observed within %v, falling back to secret metadata polling: %v", windowWait, err)
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/library/encryption/helpers.go` around lines 399 - 416, The
operator-condition branch currently returns true for any Migrating condition;
change the loop that scans conds (inside the wait.Poll using getOp) to also
verify the expectedWriteKey is the target of that migration: only treat a
condition as success if c.Type == encryptionMigrationControllerProgressingType
&& c.Status == operatorv1.ConditionTrue && c.Reason == "Migrating" AND
(expectedWriteKey == "" OR the condition text contains expectedWriteKey). In
practice, update the condition check in the loop to inspect the condition's
message/text (e.g., c.Message) for expectedWriteKey and only return true when it
matches; keep the existing fallback to secret metadata polling and the t.Logf
call unchanged.

@openshift-ci openshift-ci Bot removed the needs-rebase Indicates a PR cannot be merged because it has merge conflicts with HEAD. label May 15, 2026
tjungblu added a commit to tjungblu/cluster-kube-apiserver-operator that referenced this pull request May 15, 2026
from library-go openshift/library-go#2218

Signed-off-by: Thomas Jungblut <tjungblu@redhat.com>
tjungblu added a commit to tjungblu/cluster-kube-apiserver-operator that referenced this pull request May 15, 2026
from library-go openshift/library-go#2218

Signed-off-by: Thomas Jungblut <tjungblu@redhat.com>
tjungblu added a commit to tjungblu/cluster-kube-apiserver-operator that referenced this pull request May 15, 2026
from library-go openshift/library-go#2218

Signed-off-by: Thomas Jungblut <tjungblu@redhat.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. jira/valid-reference Indicates that this PR references a valid Jira ticket of any type.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants