Skip to content

Add encryption config Secret generation with in-memory Key Secret in preflight controller - #2376

Closed
ardaguclu wants to merge 1 commit into
openshift:masterfrom
ardaguclu:preflight-config
Closed

Add encryption config Secret generation with in-memory Key Secret in preflight controller#2376
ardaguclu wants to merge 1 commit into
openshift:masterfrom
ardaguclu:preflight-config

Conversation

@ardaguclu

@ardaguclu ardaguclu commented Jul 24, 2026

Copy link
Copy Markdown
Member

This PR experiments the encryption controllers to find an elegant way for the preflight controller to reuse the encryption config Secret generation mechanism.

Summary by CodeRabbit

Summary

  • Improvements

    • KMS preflight checks now generate a fully computed encryption-config Secret and provide it to the preflight workload, including when no preflight pod exists.
    • Encryption state planning now accounts for an additional (simulated) key to ensure correct transition behavior.
    • Added stronger validation/error handling when the current encryption mode isn’t KMS or when encryption configuration can’t be computed.
  • Tests

    • Updated KMS preflight controller tests to cover the new computed Secret flow and the expanded deployer behavior.

@openshift-ci

openshift-ci Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

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

@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 24, 2026
@coderabbitai

coderabbitai Bot commented Jul 24, 2026

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Enterprise

Run ID: c776506d-219b-4474-8fd5-8c4c68724930

📥 Commits

Reviewing files that changed from the base of the PR and between b6631bb and fc7a4f3.

📒 Files selected for processing (4)
  • 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
🚧 Files skipped from review as they are similar to previous changes (3)
  • pkg/operator/encryption/statemachine/transition.go
  • pkg/operator/encryption/controllers/kms_preflight_controller_test.go
  • pkg/operator/encryption/controllers/kms_preflight_controller.go

Walkthrough

KMS preflight now computes an encryption-config Secret from the current KMS configuration and a simulated additional key before deploying the preflight workload. Encryption lookup uses explicit dependencies, and tests add matching deployer wiring.

Changes

KMS preflight encryption configuration

Layer / File(s) Summary
Additional-key desired-state computation
pkg/operator/encryption/statemachine/transition.go
Adds ComputeDesiredEncryptionStateWithAdditionalKey, combining deployed configuration, existing key Secrets, and a simulated additional key.
Preflight Secret generation and deployment
pkg/operator/encryption/controllers/key_controller.go, pkg/operator/encryption/controllers/kms_preflight_controller.go
Extracts encryption configuration helpers, extends controller dependencies, computes the KMS encryption-config Secret, and passes it to deployment when the preflight pod is absent.
Preflight test wiring
pkg/operator/encryption/controllers/kms_preflight_controller_test.go
Adds a fake encryption deployer and updates constructor arguments for the new dependencies.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant runPreflightChecks
  participant computeEncryptionConfigSecret
  participant ComputeDesiredEncryptionStateWithAdditionalKey
  participant encryptionDeployer
  runPreflightChecks->>computeEncryptionConfigSecret: compute encryption-config Secret
  computeEncryptionConfigSecret->>encryptionDeployer: read deployed encryption config
  computeEncryptionConfigSecret->>ComputeDesiredEncryptionStateWithAdditionalKey: provide simulated key Secret
  ComputeDesiredEncryptionStateWithAdditionalKey-->>computeEncryptionConfigSecret: desired encryption state
  computeEncryptionConfigSecret-->>runPreflightChecks: encryption-config Secret
  runPreflightChecks->>encryptionDeployer: deploy preflight workload with Secret
Loading

Possibly related PRs

Suggested reviewers: p0lyn0mial

🚥 Pre-merge checks | ✅ 15
✅ Passed checks (15 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: generating the encryption config Secret in the preflight controller using an in-memory key secret.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 The modified test file uses only static literal scenario names in t.Run; no dynamic or time-dependent test titles were added.
Test Structure And Quality ✅ Passed Table-driven t.Run cases are isolated, use only fake clients, include timeout-free logic, and assertions carry helpful failure messages.
Microshift Test Compatibility ✅ Passed No new Ginkgo e2e tests were added; the changed test file uses standard testing.T/t.Run and has no It/Describe/Context/When or MicroShift-unsafe APIs.
Single Node Openshift (Sno) Test Compatibility ✅ Passed No new Ginkgo e2e tests were added; the diff only changes controller logic and a unit test helper file.
Topology-Aware Scheduling Compatibility ✅ Passed The modified files only refactor encryption-secret generation and preflight secret computation; no new nodeSelector, affinity, toleration, spread, or replica logic was added.
Ote Binary Stdout Contract ✅ Passed No process-level stdout writes were added: the PR only touches controller/library code and test helpers; no main/init/TestMain/BeforeSuite or fmt.Print/klog stdout calls appear.
Ipv6 And Disconnected Network Test Compatibility ✅ Passed No new Ginkgo/e2e tests were added; the touched test file uses standard testing.T unit tests and shows no IPv4-only or external-connectivity assumptions.
No-Weak-Crypto ✅ Passed No weak algorithms, custom crypto, or secret/token comparisons were added in the touched files; the patch only reuses existing key/state plumbing.
Container-Privileges ✅ Passed PASS: PR only changes Go controller/statemachine code; no manifest changes or added privileged, hostNetwork/PID/IPC, SYS_ADMIN, or allowPrivilegeEscalation settings.
No-Sensitive-Data-In-Logs ✅ Passed No new sensitive logging was added in the touched code; the refactor only moves secret/config logic, and existing logs don’t print credentials or PII.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

@openshift-ci

openshift-ci Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: ardaguclu

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 24, 2026
return nil, fmt.Errorf("preflight is only supported in KMS mode, current mode is %q", currentMode)
}

providerCfg, err := newKMSProviderConfig(apiEncryptionConfiguration.KMS)

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.

We need to calculate the hash and compare it with what we have. If it doesn't match, we should requeue or return error.

@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

🧹 Nitpick comments (1)
pkg/operator/encryption/controllers/kms_preflight_controller_test.go (1)

864-875: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the encryption Secret passed to Deploy.

The fake deployer discards this argument, so the new no-pod path only proves it did not error. Capture and validate the generated Secret, including the candidate KMS plugin and referenced data; include an existing key to verify preservation.

🤖 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/kms_preflight_controller_test.go` around
lines 864 - 875, Update the test around NewKMSPreflightController and
fakeEncryptionDeployer so the Deploy call captures the encryption Secret instead
of discarding it. Assert the generated Secret contains the candidate KMS plugin
and its referenced data, and seed an existing key before reconciliation to
verify it remains preserved.
🤖 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/kms_preflight_controller.go`:
- Line 482: Update the generateKeySecret call in the preflight flow to use the
next unused KMS key ID instead of the hard-coded 0, ensuring the simulated
secret always sorts as newest. Determine that ID from existing keys and add
coverage for a case where keys already exist, verifying preflight validates the
newly simulated key’s plugin.

---

Nitpick comments:
In `@pkg/operator/encryption/controllers/kms_preflight_controller_test.go`:
- Around line 864-875: Update the test around NewKMSPreflightController and
fakeEncryptionDeployer so the Deploy call captures the encryption Secret instead
of discarding it. Assert the generated Secret contains the candidate KMS plugin
and its referenced data, and seed an existing key before reconciliation to
verify it remains preserved.
🪄 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: 20e22517-de2f-4e8f-b04f-3d63e16b2946

📥 Commits

Reviewing files that changed from the base of the PR and between d8f45c2 and f86d558.

📒 Files selected for processing (4)
  • 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

Comment thread pkg/operator/encryption/controllers/kms_preflight_controller.go Outdated

@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

🧹 Nitpick comments (2)
pkg/operator/encryption/controllers/kms_preflight_controller_test.go (1)

864-877: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

No test asserts on the computed encryption-config Secret content.

fakeDeployer.Deploy discards the *corev1.Secret argument, so none of these scenarios verify that computeEncryptionConfigSecret/buildSimulatedKeySecret actually produce a correct Secret (simulated key, KMS plugin config, referenced secret/configmap data). Given this is new, non-trivial logic, consider capturing the deployed Secret in fakeDeployer and adding assertions for at least one scenario (e.g. that it contains the expected KMS plugin config), plus a scenario where computeEncryptionConfigSecret itself fails (e.g. mode mismatch).

🤖 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/kms_preflight_controller_test.go` around
lines 864 - 877, Extend the preflight controller tests around
NewKMSPreflightController to have fakeDeployer capture the *corev1.Secret passed
to Deploy instead of discarding it. Add assertions for at least one successful
scenario covering the expected simulated key, KMS plugin configuration, and
referenced Secret/ConfigMap data, and add a failure scenario where
computeEncryptionConfigSecret returns an error such as a mode mismatch.
pkg/operator/encryption/statemachine/transition.go (1)

64-101: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract shared logic with GetEncryptionConfigAndState.

ComputeDesiredEncryptionStateWithAdditionalKey duplicates the "load deployed config → parse → list key secrets" sequence already implemented in GetEncryptionConfigAndState (Lines 38-58), differing only in the converged check and the extra key. Consider factoring the shared steps into a helper so future changes (e.g., error wrapping) don't need to be kept in sync across both call paths.

♻️ Sketch of a shared helper
func loadCurrentAndKeySecrets(ctx context.Context, deployer Deployer, secretClient corev1client.SecretsGetter, encryptionSecretSelector metav1.ListOptions) (*encryptiondata.Config, []*corev1.Secret, error) {
	encryptionConfigSecret, _, err := deployer.DeployedEncryptionConfigSecret(ctx)
	if err != nil {
		return nil, nil, err
	}
	var current *encryptiondata.Config
	if encryptionConfigSecret != nil {
		current, err = encryptiondata.FromSecret(encryptionConfigSecret)
		if err != nil {
			return nil, nil, fmt.Errorf("invalid encryption config %s/%s: %v", encryptionConfigSecret.Namespace, encryptionConfigSecret.Name, err)
		}
	}
	encryptionSecrets, err := secrets.ListKeySecrets(ctx, secretClient, encryptionSecretSelector)
	if err != nil {
		return nil, nil, err
	}
	return current, encryptionSecrets, nil
}
🤖 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/statemachine/transition.go` around lines 64 - 101,
Extract the shared deployed-config loading, parsing, and key-secret listing
logic from GetEncryptionConfigAndState and
ComputeDesiredEncryptionStateWithAdditionalKey into a helper such as
loadCurrentAndKeySecrets. Update both callers to use it, preserving
GetEncryptionConfigAndState’s converged check and appending additionalKeySecret
only in ComputeDesiredEncryptionStateWithAdditionalKey.
🤖 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/kms_preflight_controller.go`:
- Around line 472-505: Reuse the APIServer encryption configuration already
fetched by preflightRequired when generating the Secret, instead of calling
getCurrentModeReasonAndEncryptionConfig again inside
computeEncryptionConfigSecret. Thread the fetched configuration through
runPreflightChecks and computeEncryptionConfigSecret, while preserving the
existing KMS-mode validation and error handling.

---

Nitpick comments:
In `@pkg/operator/encryption/controllers/kms_preflight_controller_test.go`:
- Around line 864-877: Extend the preflight controller tests around
NewKMSPreflightController to have fakeDeployer capture the *corev1.Secret passed
to Deploy instead of discarding it. Add assertions for at least one successful
scenario covering the expected simulated key, KMS plugin configuration, and
referenced Secret/ConfigMap data, and add a failure scenario where
computeEncryptionConfigSecret returns an error such as a mode mismatch.

In `@pkg/operator/encryption/statemachine/transition.go`:
- Around line 64-101: Extract the shared deployed-config loading, parsing, and
key-secret listing logic from GetEncryptionConfigAndState and
ComputeDesiredEncryptionStateWithAdditionalKey into a helper such as
loadCurrentAndKeySecrets. Update both callers to use it, preserving
GetEncryptionConfigAndState’s converged check and appending additionalKeySecret
only in ComputeDesiredEncryptionStateWithAdditionalKey.
🪄 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: e5668c4a-241e-410f-b95a-25aff4b967c1

📥 Commits

Reviewing files that changed from the base of the PR and between d8f45c2 and b6631bb.

📒 Files selected for processing (4)
  • 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

Comment on lines +472 to +505
func (c *kmsPreflightController) computeEncryptionConfigSecret(ctx context.Context) (*corev1.Secret, error) {
currentMode, _, apiEncryptionConfiguration, err := getCurrentModeReasonAndEncryptionConfig(ctx, c.apiServerClient, c.operatorClient, c.unsupportedConfigPrefix)
if err != nil {
return nil, err
}
if currentMode != state.KMS {
return nil, fmt.Errorf("preflight is only supported in KMS mode, current mode is %q", currentMode)
}

providerCfg, err := newKMSProviderConfig(apiEncryptionConfiguration.KMS)
if err != nil {
return nil, fmt.Errorf("failed to create KMS provider config: %w", err)
}

simulatedKeySecret, err := c.buildSimulatedKeySecret(ctx, apiEncryptionConfiguration.KMS, providerCfg)
if err != nil {
return nil, fmt.Errorf("failed to build simulated key secret: %w", err)
}

desiredState, err := statemachine.ComputeDesiredEncryptionStateWithAdditionalKey(
ctx, c.encryptionDeployer, c.coreClient, c.encryptionSecretSelector,
c.provider.EncryptedGRs(), simulatedKeySecret,
)
if err != nil {
return nil, err
}

cfg, err := encryptiondata.FromEncryptionState(desiredState)
if err != nil {
return nil, fmt.Errorf("failed to build encryption config: %w", err)
}
secretName := fmt.Sprintf("%s-%s", encryptiondata.EncryptionConfSecretName, c.instanceName)
return encryptiondata.ToSecret("openshift-config-managed", secretName, cfg)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Duplicate APIServer fetch between preflightRequired and computeEncryptionConfigSecret.

preflightRequired (Line 673) and computeEncryptionConfigSecret (via getCurrentModeReasonAndEncryptionConfig, Line 473) independently re-fetch the "cluster" APIServer object within the same runPreflightChecks invocation. If the spec changes between the two fetches, the deployed encryption-config Secret could reflect a different plugin config than the one requiredHash was computed from — the pod's reported hash condition would no longer accurately describe the deployed Secret's content. This self-corrects on the next resync (stale-hash cleanup), but threading the already-fetched config from preflightRequired into computeEncryptionConfigSecret would remove the extra round trip and the inconsistency window.

🤖 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/kms_preflight_controller.go` around lines
472 - 505, Reuse the APIServer encryption configuration already fetched by
preflightRequired when generating the Secret, instead of calling
getCurrentModeReasonAndEncryptionConfig again inside
computeEncryptionConfigSecret. Thread the fetched configuration through
runPreflightChecks and computeEncryptionConfigSecret, while preserving the
existing KMS-mode validation and error handling.

@ardaguclu

Copy link
Copy Markdown
Member Author

This was experimentation, closing
/close

@openshift-ci openshift-ci Bot closed this Jul 27, 2026
@openshift-ci

openshift-ci Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

@ardaguclu: Closed this PR.

Details

In response to this:

This was experimentation, closing
/close

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.

@ardaguclu
ardaguclu deleted the preflight-config branch July 27, 2026 05:59
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.

1 participant