task(RHOAIENG-96269): harden KubeRay operand NPs for OCP compliance #246
<!-- coderabbit-ai-generated:v1 -->
<!-- This is an auto-generated comment: summarize by coderabbit.ai -->
<!-- This is an auto-generated comment: skip review by coderabbit.ai -->
[!IMPORTANT]
- [ ] <!-- {"checkboxId":"e9bb8d72-00e8-4f67-9cb2-caf3b22574fe"} --> 🔍 Trigger review
> This repository does not receive automatic reviews because it has fewer than 10 stars.
> <details>
<summary><strong><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</strong></summary>
<dl>
<dd>
> - Source mode: Auto
- Repository: Unavailable
- Branch: Unavailable
- File: No configuration file from this repository applied
- Commit: Unavailable
- Layers: Central YAML (base), Organization UI (inherited)
- Review profile: CHILL
- Plan: Advanced
- Run ID: 8872fa1c-f1fc-4d61-893c-1a4509575ccb> </dd>
</dl>
</details>
<!-- end of auto-generated comment: skip review by coderabbit.ai -->
<!-- tips_start -->
<sub>Comment @coderabbitai help to get the list of available commands.</sub>
<!-- tips_end -->
Can we either support custom ports end-to-end or explicitly disallow them for managed clusters?
the dashboard port is configurable so let's either keep this flexibility or use the default port and disable the configurable port
What happens when dashboard-port or metrics-export-port changes after the RayCluster is created?
EnsureOpenShiftRayClusterNetworkPolicy() only generates the default policy when spec.networkPolicy is nil. On subsequent updates, the existing rules are preserved, so they keep the old ports.
This rule has no From selector, so 8443 is reachable from any source allowed by the cluster network.
should we leave this unrestricted ? can we confirm the actual kube-rbac-proxy traffic path and restrict the rule to the required source?
The mutating webhook preserves any explicitly supplied spec.networkPolicy, and the validating webhook doesn't enforce a minimum policy for managed clusters.
That means a managed RayCluster can still supply overly permissive rules or select a mode that doesn't restrict ingress. We need a defined security baseline or an explicit supported exception.
These assertions check individual ports, but not the resulting policy selectors, peers, or reconciliation behavior.
Can we also test a port update on an existing RayCluster and assert the generated NetworkPolicy through the controller? We should verify that old ports are removed, not just that the new ports are present.
to meet the least privileges security source peers should we restrict ports open to all pods within the same namespace to specifically where the job came from or does that restrict the usability of the ray clusters?
Thanks @chipspeak for your PR.
There are few comments to address on this PR.
I believe what we need to do to complete this PR is
We already have coverage for the resulting policy structure:
The remaining gap is specifically the lifecycle behavior after changing dashboard-port or metrics-export-port on an existing RayCluster whose platform defaults have already been persisted. Before asserting that old ports must be removed, we need to define whether those rules remain native user configuration or are platform-owned defaults subject to reconciliation.
This also raises the CodeFlare SDK question: is it the central and mandatory entry point for RayClusters and RayJobs in RHOAI? It cannot be the sole security boundary because users or other clients may interact directly with the Kubernetes API. If RHOAI-managed clusters require a mandatory baseline, that needs to be enforced at admission or by a controller-level mechanism. Globally rejecting or rewriting explicit policies would preserve the platform contract at the cost of KubeRay functionality and a larger synch burden.
This rule is intentionally namespace-scoped because it uses a PodSelector without a NamespaceSelector. It allows only RayJob-originated Pods in the RayCluster namespace to reach the dashboard port. For clusterSelector RayJobs, KubeRay cannot safely restrict the rule to a particular RayJob because the submitter Pod is not owned by the selected RayCluster. Narrowing it further would require dynamically managing per-RayJob policy rules or a new cluster-specific label contract, which would change the current KubeRay ownership and reconciliation model.
Yes, agreed. I left this open until we defined the sensible platform baseline. We can preserve the mutating webhook’s behavior for explicit native configuration, while using the validating webhook to ensure that RHOAI-managed RayClusters do not fall below the approved default posture once that baseline is finalized. Generic or user-managed KubeRay clusters should retain their existing behaviour.
Agreed. We are intentionally leaving the existing 8443 rule unchanged until we confirm the actual kube-rbac-proxy traffic path and its legitimate callers. The current HTTPRoute targets the dashboard Service port, so we cannot safely infer that the gateway is the source for 8443. Removing or narrowing this rule without validating the path could break authentication. Once the caller is confirmed, we should replace the source-less rule with an explicit source peer and add a regression test. Until then, this remains a documented least-privilege gap rather than a completed hardening change.
Yeah this is another situation where we need to concede to tightening the default behaviour a good bit I think. The situation where this could occur would be updated RayStartParams. We'd need to unify the approach across codeflare and KubeRay for that. I think the validating webhook and sensible defaults might resolve this too. We could reject RayClusters that on update, deviate from our prescribed ports etc. Again, it technically drops logic from KubeRay but that's to be expected based on the compliance at this point. I think we'd just need to document it is all in case a user came from upstream KubeRay and expected the same functionality.
I think this will be another situation where we can use the validating webhook to keep our sensible defaults preserved. We'll just need to validate heavily with RHOAI 3.5.1 -> 3.6 upgrades etc to be safe.
run-kuberay-e2e
/run-kuberay-e2e
On updates, requireCurrentPlatformRules is false, so it looks like a user could remove the platform ingress rules and still pass validation. Could we keep requiring the current baseline on updates too, while handling port changes, and add a test for removing a required rule?
Could we add a test that changes the dashboard or metrics port on an existing cluster and checks the final policy? The controller adds rules for the new ports, but the old defaults are still in spec.networkPolicy, so it looks like the old ports stay open too. Can reconciliation replace the old platform rules?
This builds the Gateway selector, but do the Gateway data-plane Pods in both ODH and RHOAI actually have this label? Could we verify it in the rendered manifests or in a live test? Otherwise, this rule may block dashboard traffic.
Requested changes.
This appends the current platform rules but nothing ever removes the old-port rules: spec.networkPolicy.head retains them (the webhook update path explicitly whitelists them), so every dashboard/metrics port change permanently widens ingress. TestValidateManagedOpenShiftRayClusterNetworkPolicyAllowsPortUpdateForReconciliation currently cements this accumulation. Could reconciliation replace the prior platform rules instead of appending — e.g. strip rules matching the previously-effective platform set before adding the recomputed one, or track ownership via an annotation?
On updates requireCurrentPlatformRules is false and the allowed set includes the old spec rules, so a user can remove the platform ingress rules from spec and still pass admission. Refinement to what's already been noted: the live policy can't actually lose them (buildHeadNetworkPolicy re-appends recomputed platform rules unconditionally), so the controller repairs the NP — but the spec drifts permanently and silently, and create/update semantics are inconsistent (create demands the full baseline). Could updates also require the current baseline while handling the port-change window, plus a test for removing a required rule?
The route/NP/proxy now follow RayStartParams — but the head Service derives ports from container ports, not RayStartParams (common/service.go getPortsFromCluster, with upstream's own TODO to make RayStartParams the source of truth). A cluster with dashboard-port: 9365 and no matching declared containerPort gets a Service still exposing 8265 and an HttpRoute backendRef to 9365 matching no Service port → broken route. Since the managed profile is being enforced here anyway, could the webhook also require effective RayStartParams ports to match the declared head container ports?
Dashboard and metrics ports are now effective, but the client port stays hardcoded. If client-server-port is settable via RayStartParams it's the same staleness class; if it's deliberately fixed for the managed profile, a one-line comment here would prevent the question.
A transient discovery error here fails all RayCluster admissions — including non-OpenShift clusters that never needed the platform decision. Defensible given failurePolicy=fail (the webhook being down blocks everything anyway), but it converts discovery outages into a full CRD outage mode even with a healthy webhook. Consider failing hard only for requests that carry (or previously carried) the managed profile.
Review
Requesting changes — aligning with the two outstanding CHANGES_REQUESTED reviews. The core design here is genuinely good (EffectiveRayStartParamPort with bounds validation, fail-closed admission, the externally-managed managedBy rejection since KubeRay skips NP reconciliation for those, and a strong unit suite for the new validation). The gaps below are real; several are acknowledged in the code's own TODOs.
Blocking (inline)
1. Stale platform rules accumulate open — controller appends recomputed platform rules but nothing removes old-port rules, and the webhook update path whitelists the old spec rules. Every port change permanently widens ingress, in a least-privilege hardening PR.
2. Update path can silently drop the platform baseline from spec — create demands the full baseline, update doesn't. One refinement to what's already been noted: the live policy can't actually lose platform rules (buildHeadNetworkPolicy re-appends them unconditionally on OpenShift+legacy), so the controller repairs the NP — but the spec drifts permanently and silently, and create/update semantics are inconsistent.
3. Port-source consistency: the head Service is the broken joint. This PR ties the HttpRoute, NP, and proxy to RayStartParams — but the head Service derives ports from container ports (common/service.go getPortsFromCluster, with upstream's own TODO that RayStartParams should be the source of truth). A cluster with dashboard-port: 9365 and no matching declared containerPort gets a Service still exposing 8265 and an HttpRoute backendRef to 9365 that no Service port matches → broken route. The managed-profile webhook is the natural place to enforce consistency between effective RayStartParams ports and declared head container ports.
Non-blocking
failurePolicy=fail, but consider scoping the hard failure to requests that actually carry the managed profile (or did previously).validateManagedRules(..., requireAll ...bool) as a variadic-optional-flag is also unidiomatic.Suggestion
Consider splitting: the effective-port + HttpRoute/proxy/NP wiring is valuable standalone; the webhook managed-profile enforcement needs the controller's rule-replacement logic to land with it (they're currently co-dependent — the webhook's update semantics assume the controller cleans up, but it doesn't yet).
Thanks @ugiordan @sefroberg re the gateway question:
Validated on an active RHOAI OpenShift cluster:
data-science-gateway is Programmed=True.
gateway.networking.k8s.io/gateway-name=data-science-gateway.
The NetworkPolicy selector in openshift.go therefore matches the observed Gateway dataplane pod and should permit dashboard traffic. This validates the RHOAI deployment path; ODH-only deployment and live RayCluster traffic were not tested.
Additionally, the client port of 10001 is static in Ray. I've added a code comment to reflect that but a user can't supply it anyway via start params.
/run-kuberay-e2e
✅ Addressed in 954abf7d / e81d0e1 — networkpolicy_controller.go:257-262: the controller now skips the CR-retained head rules entirely on the managed profile (if instance.Spec.NetworkPolicy.Head != nil && (!r.isOpenShift || !utils.IsLegacySecurityEnabled(instance))) and regenerates the platform rules from the current contract. Old-port rules can no longer accumulate. Pinned by TestBuildHeadNetworkPolicyManagedOpenShiftReplacesStalePlatformPortRules (networkpolicy_controller_unit_test.go:458): port change 9365→9465 asserts the old port is absent and the new port present.
One behavior note for the description: during the transition window the webhook still whitelists old spec rules while the controller ignores them, so pre-profile custom rules stop applying when the profile activates. That's tightening and consistent with the managed contract — just worth a sentence so nobody is surprised.
✅ Addressed in 954abf7d — the create/update distinction is gone entirely. raycluster_validating_webhook.go:213-221 now separates requiredHeadRules (the current platform baseline, always required) from allowedHeadRules (current + old rules as a connectivity transition window). An update can no longer drop the baseline from spec, and stale-port changes are still rejected because only the current rules satisfy the required set. Bonus: the unidiomatic requireAll ...bool variadic I flagged is replaced by the explicit allowed/required parameters in validateManagedRules.
✅ Addressed in 954abf7d — new validateManagedOpenShiftRayPorts (raycluster_validating_webhook.go:113-159) closes the three-way port-source gap from both directions:
:140-158): a supplied dashboard-port/metrics-export-port must match a declared container port of the right name, else rejected with a clear message pointing at the container port.:124-138): custom effective ports are rejected outright (must declare a head container when overriding port), so the injected standard container can never disagree with the Ray endpoint.Pinned by TestValidateManagedOpenShiftRayPortsRequiresMatchingContainerPort, ...AcceptsMatchingContainerPort, and ...RejectsCustomPortWithoutHeadContainer (raycluster_validating_webhook_unit_test.go:205/228/251). This was the residual I was going to raise — already handled.
✅ Addressed in 3fd16f77 — openshift.go:120-121 now documents it: DefaultClientPort is fixed: KubeRay exposes the Ray client service on 10001, and users cannot configure this port through RayStartParams. Exactly what was needed.
✅ Addressed in e81d0e1 — raycluster_validating_webhook.go:69-76: discovery errors now fail closed only when the request carries (or the old cluster carried) the managed-profile annotation; unrelated clusters proceed with isOpenShift = false. The old-cluster check also closes the annotation-stripping bypass during an outage. This is the scoping I asked for.
Status update on my review
All five of my inline findings are addressed as of head 954abf7d — each thread has been replied to with the exact code and line references. Summary:
| Finding | Status | Where |
|---|---|---|
| Stale platform rules accumulate | ✅ Fixed | networkpolicy_controller.go:257-262 — CR-retained rules ignored on managed profile; networkpolicy_controller_unit_test.go:458 |
| Update path could drop the spec baseline | ✅ Fixed | raycluster_validating_webhook.go:213-221 — requiredHeadRules always enforced; old rules only a transition whitelist |
| Service/port-source mismatch (three-way) | ✅ Fixed | validateManagedOpenShiftRayPorts, raycluster_validating_webhook.go:113-159 — both with and without a declared head container |
| Client-port asymmetry | ✅ Documented | openshift.go:120-121 |
| Discovery outage blocked all admissions | ✅ Fixed | raycluster_validating_webhook.go:69-76 — fail-closed scoped to managed-profile requests |
| Gateway pod selector (from the body) | ✅ Validated live | issue comment 2026-10-28 17:38 — RHOAI cluster, dataplane pod label + Service selector + 3 HTTPRoutes confirmed (ODH-only deploy and live RayCluster traffic still untested) |
The 954abf7d refactor also replaced the requireAll ...bool variadic with explicit allowed/required parameters in validateManagedRules — cleaner than what I asked for.
Remaining (non-blocking, for the record)
raycluster_validating_webhook.go:243), pending validation of the gateway, kube-rbac-proxy, RayJob submitter, and workbench caller contracts — consistent with szaher's checklist.From my side the substantive blockers are resolved. Leaving the formal gate to @ugiordan's and @szaher's re-reviews.
Approved these changes.
/run-kuberay-e2e
/LGTM
/run-kuberay-e2e
<!-- pipeline: odh-pr-test-kuberay -->
@chipspeak: The following test has Succeeded:
OCI Artifact Browser URL
View in Artifact Browser
Inspecting Test Artifacts Manually
To inspect your test artifacts manually, follow these steps:
1. Install ORAS (see the ORAS installation guide).
2. Download artifacts with the following commands:
mkdir -p oras-artifacts
cd oras-artifacts
oras pull quay.io/opendatahub/odh-ci-artifacts:odh-pr-test-kuberay-8gncx
Thanks @chipspeak
I'll approve this PR but I have some comments so we hopefully we can address them in a follow up PR/ticket
1. There's a gap with the mutating webhook. If discovery fails, the mutator sets the security annotation to false, so the validator can treat a new RayCluster as unmanaged and allow it. Can we distinguish a genuine non-OpenShift environment from a discovery failure and add a test covering both webhooks?
2. I understand why we're regenerating the platform rules instead of using the persisted CR rules. One case I'd like to verify: an existing RayCluster created before this validation was introduced, with custom ingress rules. On upgrade, those rules would stop applying without the cluster going through admission. Is that an intended migration behavior? Could we cover it with an upgrade test?
for item number 2, if we want to skip it may we should at least document that behavior to let customers with old RayClusters and custom Ingress rules what will happen.
ugiordan
chipspeak
<!-- Thank you for your contribution! -->
<!-- Please add a reviewer to the assignee section when you create a PR. If you don't have the access to it, we will shortly find a reviewer and assign them to your PR. -->
Summary
Harden the managed OpenShift/RHOAI NetworkPolicy profile for RayCluster operands.
10001and cannot be configured throughRayStartParams.The Gateway selector was confirmed to match the
data-science-gatewaydataplane pod label.Related issue number
Jira Ticket
Labels
<!-- Please add the appropriate labels to this PR. -->
doc-updates-requiredlabel.breaking-changelabel.Checks
- [ ] Unit tests
- [ ] Manual tests
- [ ] This PR is not tested :(
Architecture