Skip to content

WIP: compute encryption-config for preflight - #2373

Open
bertinatto wants to merge 3 commits into
openshift:masterfrom
bertinatto:kms-preflight-create-ec
Open

WIP: compute encryption-config for preflight#2373
bertinatto wants to merge 3 commits into
openshift:masterfrom
bertinatto:kms-preflight-create-ec

Conversation

@bertinatto

@bertinatto bertinatto commented Jul 22, 2026

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features

    • Improved encryption key rotation planning and generation across configured resources.
    • KMS preflight validation now deploys the correct upcoming encryption configuration, including credentials, endpoints, and plugin settings.
    • Added validation for referenced encryption resources and clearer handling of incomplete KMS configuration data.
  • Bug Fixes

    • Improved selection of the next encryption key when existing or invalid key secrets are present.
    • Added requeue behavior while encryption configuration changes are still converging.
  • Tests

    • Expanded coverage for key rotation, KMS configuration, credential handling, missing resources, error scenarios, and preflight deployment.

@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 Jul 22, 2026
@openshift-ci
openshift-ci Bot requested review from ardaguclu and p0lyn0mial July 22, 2026 13:33
@openshift-ci

openshift-ci Bot commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: bertinatto

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

@openshift-ci openshift-ci Bot added the approved Indicates a PR has been approved by an approver from all required OWNERS files. label Jul 22, 2026
@coderabbitai

coderabbitai Bot commented Jul 22, 2026

Copy link
Copy Markdown

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

The change centralizes encryption-key planning and Secret construction. Key creation uses these helpers. KMS preflight now computes and deploys the next-key encryption configuration. Desired encryption-state computation is exported, with expanded preflight tests.

Changes

Encryption rollout

Layer / File(s) Summary
Shared key planning and construction
pkg/operator/encryption/controllers/encryption_key_helpers.go, pkg/operator/encryption/controllers/encryption_key_helpers_test.go
Adds next-key planning, mode-specific key-state construction, referenced resource loading, Secret conversion, and validation tests.
Key controller integration
pkg/operator/encryption/controllers/key_controller.go
Uses shared planning and construction for key decisions, IDs, validation, event reasons, KMS resource reuse, and Secret conversion.
Desired encryption-state API
pkg/operator/encryption/statemachine/transition.go, pkg/operator/encryption/statemachine/transition_test.go
Exports GetDesiredEncryptionState and updates its call site and test.
KMS preflight computation
pkg/operator/encryption/controllers.go, pkg/operator/encryption/controllers/kms_preflight_controller.go, pkg/operator/encryption/controllers/kms_preflight_controller_test.go
Wires encryption deployment dependencies, waits for convergence, computes the next KMS configuration, deploys the resulting Secret, and tests success and error paths.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant KMSPreflightController
  participant EncryptionDeployer
  participant SecretInformer
  participant EncryptionKeyHelpers
  participant GetDesiredEncryptionState
  KMSPreflightController->>EncryptionDeployer: check encryption-state convergence
  EncryptionDeployer-->>KMSPreflightController: deployed encryption configuration
  KMSPreflightController->>SecretInformer: read existing key Secrets
  SecretInformer-->>KMSPreflightController: key Secret data
  KMSPreflightController->>EncryptionKeyHelpers: plan and build next KMS key
  EncryptionKeyHelpers-->>KMSPreflightController: simulated key Secret
  KMSPreflightController->>GetDesiredEncryptionState: derive desired encryption state
  GetDesiredEncryptionState-->>KMSPreflightController: desired encryption state
  KMSPreflightController->>EncryptionDeployer: deploy encryption-config Secret
Loading

Possibly related PRs

Suggested reviewers: ardaguclu, p0lyn0mial

🚥 Pre-merge checks | ✅ 13 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Topology-Aware Scheduling Compatibility ⚠️ Warning The new controller path enables PodPreflightDeployer to create a pod whose template hard-codes node-role.kubernetes.io/master; no topology check supports HyperShift. Make preflight pod placement topology-aware. Do not require master labels on External/HyperShift; also exclude arbiter nodes where applicable.
✅ Passed checks (13 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the main change: computing the encryption configuration for KMS preflight.
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 Changed tests use standard testing.T; no Ginkgo titles exist. Added t.Run titles are static literals, and scenario-backed names come from static string tables.
Test Structure And Quality ✅ Passed The changed tests use Go testing.T subtests and fake clientsets, not Ginkgo; no Ginkgo imports, cluster waits, Eventually, or Consistently calls exist.
Microshift Test Compatibility ✅ Passed The PR adds only standard Go unit tests (func Test...); no new Ginkgo e2e tests (It, Describe, Context, or When) were added.
Single Node Openshift (Sno) Test Compatibility ✅ Passed The PR adds no Ginkgo e2e tests; changed tests use standard testing.T and fake clients, with no multi-node or HA assumptions.
Ote Binary Stdout Contract ✅ Passed The complete PR delta adds no stdout writes or suite setup code; no main/TestMain/RunSpecs/BeforeSuite/AfterSuite exists, and the klog call is inside controller logic.
Ipv6 And Disconnected Network Test Compatibility ✅ Passed Added coverage uses standard Go testing.T with fake clients, not Ginkgo e2e tests; it has no IPv4 literals and makes no external network connections.
No-Weak-Crypto ✅ Passed Added production code uses existing AES-256 key generation via crypto/rand and copies KMS data; no MD5, SHA-1, DES, RC4, Blowfish, ECB, custom crypto, or secret comparisons were added.
Container-Privileges ✅ Passed The PR adds no privilege-related fields and changes no YAML/YML/JSON manifests; the existing conditional hostNetwork setting is unchanged.
No-Sensitive-Data-In-Logs ✅ Passed The PR adds no new logging calls; event output contains only the key Secret name and reason strings, while referenced secret and ConfigMap values are never formatted for logs.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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 `@pkg/operator/encryption/controllers/key_controller.go`:
- Around line 214-216: Update the EncryptionKeyCreateFailed warning in the
createErr handling branch to log createErr instead of err, while preserving the
existing event message, return createErr behavior, and surrounding
generateKeySecret flow.
🪄 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: 3dabf247-0dc6-4ff5-9a83-9c4d3be9df94

📥 Commits

Reviewing files that changed from the base of the PR and between 050c1a9 and 97da54e.

📒 Files selected for processing (8)
  • pkg/operator/encryption/controllers/encryption_key_helpers.go
  • pkg/operator/encryption/controllers/encryption_key_helpers_test.go
  • pkg/operator/encryption/controllers/key_controller.go
  • pkg/operator/encryption/controllers/kms_preflight_controller.go
  • pkg/operator/encryption/controllers/kms_preflight_controller_test.go
  • pkg/operator/encryption/kms/constants.go
  • pkg/operator/encryption/statemachine/transition.go
  • pkg/operator/encryption/statemachine/transition_test.go

Comment on lines 214 to 216
if createErr != nil {
syncContext.Recorder().Warningf("EncryptionKeyCreateFailed", "Secret %q failed to create: %v", keySecret.Name, err)
return createErr

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Warning event logs err (nil) instead of createErr.

At this point err is the (nil) result from generateKeySecret that already passed the Line 207 guard, so the EncryptionKeyCreateFailed event will render <nil> instead of the real create failure. Return value is fine; only the diagnostic is lost.

🐛 Proposed fix
 	if createErr != nil {
-		syncContext.Recorder().Warningf("EncryptionKeyCreateFailed", "Secret %q failed to create: %v", keySecret.Name, err)
+		syncContext.Recorder().Warningf("EncryptionKeyCreateFailed", "Secret %q failed to create: %v", keySecret.Name, createErr)
 		return createErr
 	}
📝 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 createErr != nil {
syncContext.Recorder().Warningf("EncryptionKeyCreateFailed", "Secret %q failed to create: %v", keySecret.Name, err)
return createErr
if createErr != nil {
syncContext.Recorder().Warningf("EncryptionKeyCreateFailed", "Secret %q failed to create: %v", keySecret.Name, createErr)
return createErr
🤖 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 `@pkg/operator/encryption/controllers/key_controller.go` around lines 214 -
216, Update the EncryptionKeyCreateFailed warning in the createErr handling
branch to log createErr instead of err, while preserving the existing event
message, return createErr behavior, and surrounding generateKeySecret flow.

// requeue is true when the API server revisions have not converged yet (mirrors
// statemachine.GetEncryptionConfigAndState's "APIServerRevisionNotConverged" case);
// callers should requeue and retry later rather than treat this as an error.
func (c *kmsPreflightController) computeEncryptionConfigSecret(ctx context.Context) (requeue bool, secret *corev1.Secret, err 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.

I'm pretty sure this went past you, but I've added a small helper for testing the drift and preflight deployer:

https://github.com/openshift/library-go/blob/master/test/library/encryption/preflight_deploy.go#L147

do you mind to refactor a function that we can reuse there?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

oh, sorry, I missed this comment. Do you still need this?

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.

yes!

@bertinatto
bertinatto force-pushed the kms-preflight-create-ec branch from 97da54e to 3882161 Compare July 23, 2026 20:34

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
pkg/operator/encryption/kms/preflight/deployer_test.go (1)

430-432: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Report the failing action in the assertion diagnostic.

This assertion checks actions[10], but the failure message prints the type of actions[4], which can mislead debugging. Use actions[10] instead.

Proposed fix
-			t.Fatalf("expected CreateAction, got %T", actions[4])
+			t.Fatalf("expected CreateAction, got %T", actions[10])
🤖 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 `@pkg/operator/encryption/kms/preflight/deployer_test.go` around lines 430 -
432, Update the CreateAction type assertion diagnostic in the relevant test to
report the type of actions[10], matching the action being validated, instead of
actions[4].
🧹 Nitpick comments (2)
pkg/operator/encryption/controllers/encryption_key_helpers.go (2)

45-74: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Document the reason-collapsing rationale.

The logic that collapses per-resource reasons into a single shared reason when they all match (vs. keeping resource-prefixed reasons otherwise) is subtle and easy to break during future edits to this newly-shared helper. A short comment explaining the intent (e.g., "avoid repeating the same reason once per resource when it's the same event affecting all GRs") would help.

🤖 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 `@pkg/operator/encryption/controllers/encryption_key_helpers.go` around lines
45 - 74, Add a concise comment immediately above the reason-collapsing condition
in the shared helper, explaining that identical reasons are reduced to one
shared reason to avoid repeating the same event for every resource, while
differing reasons remain resource-prefixed.

82-191: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider bundling the trailing string params into a struct.

Both buildEncryptionKeyState and buildEncryptionKeySecret take 10 positional parameters, including three consecutive string args (internalReason, externalReason, kmsEndpointOverride). Since Go has no named arguments and all three are the same type, it's easy for a future call site to transpose them silently — the compiler won't catch it. These helpers are already called from at least two different controllers (key_controller.go and kms_preflight_controller.go per the provided context), so the risk compounds with each new caller.

♻️ Suggested direction
+type keySecretOptions struct {
+	InternalReason      string
+	ExternalReason      string
+	KMSEndpointOverride string
+}
+
 func buildEncryptionKeyState(
 	ctx context.Context,
 	keyID uint64,
 	currentMode state.Mode,
 	apiServerEncryption configv1.APIServerEncryption,
 	desiredProviderCfg kmsProviderConfig,
 	secretClient corev1client.SecretsGetter,
 	configMapClient corev1client.ConfigMapsGetter,
-	internalReason string,
-	externalReason string,
-	kmsEndpointOverride string,
+	opts keySecretOptions,
 ) (state.KeyState, error) {
🤖 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 `@pkg/operator/encryption/controllers/encryption_key_helpers.go` around lines
82 - 191, Bundle the trailing string parameters into a named options or metadata
struct and update both buildEncryptionKeyState and buildEncryptionKeySecret to
accept that struct instead of separate internalReason, externalReason, and
kmsEndpointOverride arguments. Update every caller, including the key and KMS
preflight controller paths, to populate the named fields explicitly while
preserving the existing values and behavior.
🤖 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 `@pkg/operator/encryption/controllers/encryption_key_helpers.go`:
- Around line 123-157: Wrap errors returned by
desiredProviderCfg.referencedSecretName() and referencedConfigMapName() with
context identifying the referenced secret or ConfigMap resolution, and wrap
failures from ks.KMS.PluginSecretData.Set and PluginConfigMapData.Set with the
corresponding resource name and key. Preserve the existing error propagation
while using %w so callers retain the underlying errors.

---

Outside diff comments:
In `@pkg/operator/encryption/kms/preflight/deployer_test.go`:
- Around line 430-432: Update the CreateAction type assertion diagnostic in the
relevant test to report the type of actions[10], matching the action being
validated, instead of actions[4].

---

Nitpick comments:
In `@pkg/operator/encryption/controllers/encryption_key_helpers.go`:
- Around line 45-74: Add a concise comment immediately above the
reason-collapsing condition in the shared helper, explaining that identical
reasons are reduced to one shared reason to avoid repeating the same event for
every resource, while differing reasons remain resource-prefixed.
- Around line 82-191: Bundle the trailing string parameters into a named options
or metadata struct and update both buildEncryptionKeyState and
buildEncryptionKeySecret to accept that struct instead of separate
internalReason, externalReason, and kmsEndpointOverride arguments. Update every
caller, including the key and KMS preflight controller paths, to populate the
named fields explicitly while preserving the existing values and behavior.
🪄 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: 17872bf1-c780-446c-a7e7-12cb9d5aecd3

📥 Commits

Reviewing files that changed from the base of the PR and between 97da54e and 3882161.

📒 Files selected for processing (9)
  • pkg/operator/encryption/controllers/encryption_key_helpers.go
  • pkg/operator/encryption/controllers/key_controller.go
  • pkg/operator/encryption/controllers/kms_preflight_controller.go
  • pkg/operator/encryption/controllers/kms_preflight_controller_test.go
  • pkg/operator/encryption/kms/preflight/cmd.go
  • pkg/operator/encryption/kms/preflight/deployer_test.go
  • pkg/operator/encryption/kms/preflight_endpoint.go
  • pkg/operator/encryption/statemachine/transition.go
  • pkg/operator/encryption/statemachine/transition_test.go
🚧 Files skipped from review as they are similar to previous changes (5)
  • pkg/operator/encryption/statemachine/transition_test.go
  • pkg/operator/encryption/statemachine/transition.go
  • pkg/operator/encryption/controllers/kms_preflight_controller.go
  • pkg/operator/encryption/controllers/kms_preflight_controller_test.go
  • pkg/operator/encryption/controllers/key_controller.go

Comment on lines +123 to +157
if secretName, expectedKeys, err := desiredProviderCfg.referencedSecretName(); err != nil {
return state.KeyState{}, err
} else if len(secretName) > 0 {
refSecret, err := secretClient.Secrets(openshiftConfigNS).Get(ctx, secretName, metav1.GetOptions{})
if err != nil {
return state.KeyState{}, fmt.Errorf("failed to get secret %s in %s: %w", secretName, openshiftConfigNS, err)
}
for _, key := range expectedKeys {
v, ok := refSecret.Data[key]
if !ok {
return state.KeyState{}, fmt.Errorf("secret %s in %s is missing required key %q", secretName, openshiftConfigNS, key)
}
if err := ks.KMS.PluginSecretData.Set(secretName, key, v); err != nil {
return state.KeyState{}, err
}
}
}

if cmName, expectedKeys, err := desiredProviderCfg.referencedConfigMapName(); err != nil {
return state.KeyState{}, err
} else if len(cmName) > 0 {
refCM, err := configMapClient.ConfigMaps(openshiftConfigNS).Get(ctx, cmName, metav1.GetOptions{})
if err != nil {
return state.KeyState{}, fmt.Errorf("failed to get configmap %s in %s: %w", cmName, openshiftConfigNS, err)
}
for _, key := range expectedKeys {
v, ok := refCM.Data[key]
if !ok {
return state.KeyState{}, fmt.Errorf("configmap %s in %s is missing required key %q", cmName, openshiftConfigNS, key)
}
if err := ks.KMS.PluginConfigMapData.Set(cmName, key, []byte(v)); err != nil {
return state.KeyState{}, 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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Add context to bubbled-up errors.

Errors from desiredProviderCfg.referencedSecretName()/referencedConfigMapName() (Lines 123-125, 141-143) and from PluginSecretData.Set/PluginConfigMapData.Set (Lines 135-137, 153-155) are returned bare, unlike the sibling Get() calls a few lines above/below that wrap errors with fmt.Errorf("failed to get secret %s in %s: %w", ...). This makes failures in these paths harder to diagnose in logs.

🐛 Proposed fix
-	if secretName, expectedKeys, err := desiredProviderCfg.referencedSecretName(); err != nil {
-		return state.KeyState{}, err
+	if secretName, expectedKeys, err := desiredProviderCfg.referencedSecretName(); err != nil {
+		return state.KeyState{}, fmt.Errorf("failed to resolve referenced secret name: %w", err)
	} else if len(secretName) > 0 {
		...
-			if err := ks.KMS.PluginSecretData.Set(secretName, key, v); err != nil {
-				return state.KeyState{}, err
+			if err := ks.KMS.PluginSecretData.Set(secretName, key, v); err != nil {
+				return state.KeyState{}, fmt.Errorf("failed to set plugin secret data %s/%s: %w", secretName, key, err)
			}

(similarly for the configmap branch)

🤖 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 `@pkg/operator/encryption/controllers/encryption_key_helpers.go` around lines
123 - 157, Wrap errors returned by desiredProviderCfg.referencedSecretName() and
referencedConfigMapName() with context identifying the referenced secret or
ConfigMap resolution, and wrap failures from ks.KMS.PluginSecretData.Set and
PluginConfigMapData.Set with the corresponding resource name and key. Preserve
the existing error propagation while using %w so callers retain the underlying
errors.

…hine

Export the desired encryption state helper so other encryption controllers can reuse the same state transition logic instead of reimplementing it.
@bertinatto
bertinatto force-pushed the kms-preflight-create-ec branch from 1d4924b to 51a718f Compare August 6, 2026 17:36
@coderabbitai

coderabbitai Bot commented Aug 6, 2026

Copy link
Copy Markdown

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

Move KMS key planning and key secret construction into reusable helpers so the key controller and preflight flow can build the same next-key shape from one implementation.
Build the candidate encryption config that would result from the next KMS
key before launching preflight so the checker validates the exact secret
and plugin data that rollout will use.
@bertinatto
bertinatto force-pushed the kms-preflight-create-ec branch from 51a718f to 96361f8 Compare August 6, 2026 17:59
@coderabbitai

coderabbitai Bot commented Aug 6, 2026

Copy link
Copy Markdown

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (3)
pkg/operator/encryption/controllers/encryption_key_helpers_test.go (2)

15-99: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for planNextEncryptionKey.

The new file adds planNextEncryptionKey, which aggregates per-resource reasons, collapses a common reason, and picks the maximum next key ID. No test in this file exercises it. Add cases for a single resource, multiple resources with the same reason, and multiple resources with different reasons and different latest key IDs.
Do you want me to draft these tests?

🤖 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 `@pkg/operator/encryption/controllers/encryption_key_helpers_test.go` around
lines 15 - 99, Add table-driven coverage for planNextEncryptionKey, covering one
resource, multiple resources sharing a reason, and multiple resources with
distinct reasons and latest key IDs. Assert the aggregated reason output,
common-reason collapse behavior, and selection of the maximum next key ID.

72-98: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Rename the test or split the success subtest.

TestBuildEncryptionKeyStateMissingRefs now contains a success-path subtest that asserts returned refs and the endpoint override. Move that subtest to a separate test function, for example TestBuildEncryptionKeyStateReturnsRefs, so the test name matches the behavior under test.

🤖 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 `@pkg/operator/encryption/controllers/encryption_key_helpers_test.go` around
lines 72 - 98, Move the “returns fetched refs for hasher reuse” success subtest
out of TestBuildEncryptionKeyStateMissingRefs into a separate test function such
as TestBuildEncryptionKeyStateReturnsRefs. Preserve its existing assertions for
refSecret, refCM, and the KMS endpoint override, while leaving only
missing-reference behavior in the original test.
pkg/operator/encryption/controllers/key_controller.go (1)

238-238: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Format the reasons list for the event message.

keyPlan.reasons is a []string. With %q the event message renders as ["a" "b"]. The previous message used a joined string. Use keyPlan.internalReason, or join the slice, to keep the message readable.

♻️ Proposed change
-	syncContext.Recorder().Eventf("EncryptionKeyCreated", "Secret %q successfully created: %q", keySecret.Name, keyPlan.reasons)
+	syncContext.Recorder().Eventf("EncryptionKeyCreated", "Secret %q successfully created: %q", keySecret.Name, keyPlan.internalReason)
🤖 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 `@pkg/operator/encryption/controllers/key_controller.go` at line 238, Update
the Eventf call in the key creation flow to format the reasons as a readable
string rather than passing the []string keyPlan.reasons with %q; use
keyPlan.internalReason or join keyPlan.reasons before interpolation, while
preserving the existing event message context.
🤖 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.

Nitpick comments:
In `@pkg/operator/encryption/controllers/encryption_key_helpers_test.go`:
- Around line 15-99: Add table-driven coverage for planNextEncryptionKey,
covering one resource, multiple resources sharing a reason, and multiple
resources with distinct reasons and latest key IDs. Assert the aggregated reason
output, common-reason collapse behavior, and selection of the maximum next key
ID.
- Around line 72-98: Move the “returns fetched refs for hasher reuse” success
subtest out of TestBuildEncryptionKeyStateMissingRefs into a separate test
function such as TestBuildEncryptionKeyStateReturnsRefs. Preserve its existing
assertions for refSecret, refCM, and the KMS endpoint override, while leaving
only missing-reference behavior in the original test.

In `@pkg/operator/encryption/controllers/key_controller.go`:
- Line 238: Update the Eventf call in the key creation flow to format the
reasons as a readable string rather than passing the []string keyPlan.reasons
with %q; use keyPlan.internalReason or join keyPlan.reasons before
interpolation, while preserving the existing event message context.

ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Enterprise

Run ID: acdfc66b-d5f8-4e43-b6eb-f75d957894c5

📥 Commits

Reviewing files that changed from the base of the PR and between 39539af and 96361f8.

📒 Files selected for processing (8)
  • pkg/operator/encryption/controllers.go
  • pkg/operator/encryption/controllers/encryption_key_helpers.go
  • pkg/operator/encryption/controllers/encryption_key_helpers_test.go
  • pkg/operator/encryption/controllers/key_controller.go
  • pkg/operator/encryption/controllers/kms_preflight_controller.go
  • pkg/operator/encryption/controllers/kms_preflight_controller_test.go
  • pkg/operator/encryption/statemachine/transition.go
  • pkg/operator/encryption/statemachine/transition_test.go
🚧 Files skipped from review as they are similar to previous changes (5)
  • pkg/operator/encryption/statemachine/transition.go
  • pkg/operator/encryption/statemachine/transition_test.go
  • pkg/operator/encryption/controllers.go
  • pkg/operator/encryption/controllers/kms_preflight_controller.go
  • pkg/operator/encryption/controllers/kms_preflight_controller_test.go

@openshift-ci

openshift-ci Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

@bertinatto: 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.

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. do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants