← Back to Pull requests

task(RHOAIENG-96269): harden KubeRay operand NPs for OCP compliance #246

Merged
chipspeak merged 10 files (794 lines) on Oct 29, 2026 23:04 UTC
View on GitHub
chipspeak chipspeak commented on Oct 16, 2026 12:39 UTC
Author

<!-- 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.

  • Enforce the current platform NetworkPolicy baseline on create and update.

  • Prevent removal of required managed ingress rules.

  • Regenerate managed platform rules during reconciliation so stale dashboard/metrics ports are removed.

  • Validate custom dashboard and metrics ports against declared head-container ports.

  • Scope transient OpenShift discovery failures to managed-profile requests.

  • Document that the Ray client port is fixed at 10001 and cannot be configured through RayStartParams.

  • Add regression coverage for baseline validation, port updates, and stale-rule removal.

  • Verify the Gateway dataplane selector against an active RHOAI OpenShift cluster.
  • The Gateway selector was confirmed to match the data-science-gateway dataplane pod label.

    Related issue number

    Jira Ticket

    Labels

    <!-- Please add the appropriate labels to this PR. -->

  • If this PR has user-facing changes that require documentation updates at release time, I have added the doc-updates-required label.

  • If this PR contains breaking changes, I have added the breaking-change label.
  • Checks

  • I've made sure the tests are passing.

  • Testing Strategy

  • - [ ] Unit tests
    - [ ] Manual tests
    - [ ] This PR is not tested :(

    Architecture

  • This PR does not change component boundaries or API contracts

  • OR: I have updated the relevant design doc / DEVELOPMENT.md
  • Diff: 794 lines (+771 / -23) across 10 files Reviewer: ugiordan Review duration: 19345m
    All Vouch review confidence checks passed
    Residual risk 0.23 = Change Risk (0.79) × (1 − Review Confidence (0.71)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.79 · 794 lines diff across 10 files
    0.79
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.52 · 5 substantive comment(s)
    0.52
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    71%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Sensitive Paths sensitive_paths
    0.079
    Real PR Conversation Timeline
    41 items
    coderabbitai[bot] coderabbitai[bot] commented on Oct 16, 2026 12:39 UTC
    Bot

    <!-- 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 -->

    szaher szaher commented on code on Oct 22, 2026 16:01 UTC
    Code Review
    ray-operator/controllers/ray/utils/openshift.go:1
    @@ -93,6 +94,8 @@ func ensureOpenShiftNetworkPolicy(spec *rayv1.RayClusterSpec) {
     	mode := rayv1.NetworkPolicyDenyAllIngress
     	spec.NetworkPolicy = &rayv1.NetworkPolicyConfig{Mode: &mode, Head: &rayv1.NetworkPolicyRules{}}
     	tcp := corev1.ProtocolTCP
    +	dashboardPort := effectiveHeadPort(spec, "dashboard-port", DefaultDashboardPort)

    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

    szaher szaher commented on code on Oct 22, 2026 16:02 UTC
    Code Review
    ray-operator/controllers/ray/utils/openshift.go:1
    @@ -162,6 +176,19 @@ func ensureOpenShiftNetworkPolicy(spec *rayv1.RayClusterSpec) {
     	})
     }
     
    +// effectiveHeadPort returns a valid integer Ray start parameter or its default.
    +// RayCluster pod construction applies the same fallback behavior when it builds
    +// the Ray command, so NetworkPolicy ports stay aligned with the effective head
    +// configuration.
    +func effectiveHeadPort(spec *rayv1.RayClusterSpec, key string, defaultPort int32) int32 {

    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.

    szaher szaher commented on code on Oct 22, 2026 16:04 UTC
    Code Review
    ray-operator/controllers/ray/utils/openshift.go:1
    @@ -105,19 +108,28 @@ func ensureOpenShiftNetworkPolicy(spec *rayv1.RayClusterSpec) {
     		}
     		return append(rules, rule)
     	}
    +	// TODO(ODH NetworkPolicy): The same-namespace 10001 allowance is retained
    +	// while the platform client-source contract is unresolved. Users may install
    +	// Jupyter workbenches in arbitrary namespaces, so this rule must not be
    +	// broadened to all namespaces. A future cross-namespace rule requires a
    +	// protected namespace label contract or explicit per-RayCluster source rules.
     	spec.NetworkPolicy.Head.IngressRules = appendIngress(spec.NetworkPolicy.Head.IngressRules, networkingv1.NetworkPolicyIngressRule{
     		From:  []networkingv1.NetworkPolicyPeer{{PodSelector: &metav1.LabelSelector{}}},
    -		Ports: []networkingv1.NetworkPolicyPort{port(8265), port(10001)},
    +		Ports: []networkingv1.NetworkPolicyPort{port(dashboardPort), port(DefaultClientPort)},
     	})
     	spec.NetworkPolicy.Head.IngressRules = appendIngress(spec.NetworkPolicy.Head.IngressRules, networkingv1.NetworkPolicyIngressRule{
     		From: []networkingv1.NetworkPolicyPeer{{PodSelector: &metav1.LabelSelector{
     			MatchLabels: map[string]string{
     				RayOriginatedFromCRDLabelKey: RayOriginatedFromCRDLabelValue(RayJobCRD),
     			},
     		}}},
    -		Ports: []networkingv1.NetworkPolicyPort{port(8265)},
    +		Ports: []networkingv1.NetworkPolicyPort{port(dashboardPort)},
     	})
     	spec.NetworkPolicy.Head.IngressRules = appendIngress(spec.NetworkPolicy.Head.IngressRules, networkingv1.NetworkPolicyIngressRule{
    +		// TODO(ODH NetworkPolicy): The supported caller for the kube-rbac-proxy
    +		// port is not yet established. The Gateway HTTPRoute currently targets
    +		// the dashboard service port, so do not guess a gateway peer here until
    +		// the 8443 data path is confirmed; changing this rule may break auth.
     		Ports: []networkingv1.NetworkPolicyPort{port(8443)},

    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?

    szaher szaher commented on code on Oct 22, 2026 16:07 UTC
    Code Review
    ray-operator/pkg/webhooks/v1/raycluster_validating_webhook.go:1
    @@ -49,6 +49,11 @@ func (w *RayClusterWebhook) ValidateDelete(_ context.Context, _ *rayv1.RayCluste
     func (w *RayClusterWebhook) validateRayCluster(rayCluster *rayv1.RayCluster) error {
     	var allErrs field.ErrorList
     
    +	// TODO(ODH NetworkPolicy): Define whether explicitly supplied managed

    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.

    szaher szaher commented on code on Oct 22, 2026 16:08 UTC
    Code Review
    ray-operator/controllers/ray/utils/openshift_test.go:1
    @@ -59,6 +59,57 @@ func TestOpenShiftMonitoringPreservesExplicitPolicy(t *testing.T) {
     	assert.Equal(t, want, cluster.Spec.NetworkPolicy, "explicit policies must not acquire platform default rules")
     }
     
    +func TestOpenShiftNetworkPolicyUsesEffectiveRayPorts(t *testing.T) {
    +	t.Setenv("MONITORING_NAMESPACE", "monitoring")
    +	cluster := &rayv1.RayCluster{
    +		Spec: rayv1.RayClusterSpec{
    +			HeadGroupSpec: rayv1.HeadGroupSpec{
    +				RayStartParams: map[string]string{
    +					"dashboard-port":      "9365",
    +					"metrics-export-port": "9090",
    +				},
    +			},
    +		},
    +	}
    +
    +	EnsureOpenShiftRayClusterSecurity(cluster)
    +	rules := cluster.Spec.NetworkPolicy.Head.IngressRules
    +
    +	assert.Contains(t, rulePorts(rules[0]), int32(9365), "dashboard access should use the configured dashboard port")
    +	assert.Contains(t, rulePorts(rules[0]), int32(DefaultClientPort), "client access should retain the client port")
    +	assert.Contains(t, rulePorts(rules[1]), int32(9365), "RayJob submission should use the configured dashboard port")
    +	assert.Contains(t, rulePorts(rules[4]), int32(9090), "monitoring should use the configured metrics port")

    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.

    szaher szaher commented on code on Oct 22, 2026 16:10 UTC
    Code Review
    ray-operator/controllers/ray/utils/openshift.go:1
    @@ -105,19 +108,28 @@ func ensureOpenShiftNetworkPolicy(spec *rayv1.RayClusterSpec) {
     		}
     		return append(rules, rule)
     	}
    +	// TODO(ODH NetworkPolicy): The same-namespace 10001 allowance is retained
    +	// while the platform client-source contract is unresolved. Users may install
    +	// Jupyter workbenches in arbitrary namespaces, so this rule must not be
    +	// broadened to all namespaces. A future cross-namespace rule requires a
    +	// protected namespace label contract or explicit per-RayCluster source rules.
     	spec.NetworkPolicy.Head.IngressRules = appendIngress(spec.NetworkPolicy.Head.IngressRules, networkingv1.NetworkPolicyIngressRule{
     		From:  []networkingv1.NetworkPolicyPeer{{PodSelector: &metav1.LabelSelector{}}},
    -		Ports: []networkingv1.NetworkPolicyPort{port(8265), port(10001)},
    +		Ports: []networkingv1.NetworkPolicyPort{port(dashboardPort), port(DefaultClientPort)},
     	})
     	spec.NetworkPolicy.Head.IngressRules = appendIngress(spec.NetworkPolicy.Head.IngressRules, networkingv1.NetworkPolicyIngressRule{
     		From: []networkingv1.NetworkPolicyPeer{{PodSelector: &metav1.LabelSelector{
     			MatchLabels: map[string]string{
     				RayOriginatedFromCRDLabelKey: RayOriginatedFromCRDLabelValue(RayJobCRD),

    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?

    szaher szaher requested changes on Oct 22, 2026 16:12 UTC
    Changes Requested Reviewer

    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

  • Resolve custom dashboard/metrics port handling across Ray, Services, authentication and NetworkPolicies

  • Make platform-managed NetworkPolicy rules update correctly when RayCluster ports change

  • Replace unrestricted 8443 and broad dashboard/client source allowances

  • Define how explicitly supplied policies interact with mandatory RHOAI security defaults

  • Verify worker policies, monitoring access, and RayJob-specific peer permissions

  • Add controller-level and live connectivity tests for authorized and denied traffic

  • Validate policy recreation, ODH/RHOAI manifest rendering, and deployed RBAC
  • chipspeak chipspeak commented on code on Oct 23, 2026 08:16 UTC
    Code Review
    ray-operator/controllers/ray/utils/openshift_test.go:1
    @@ -59,6 +59,57 @@ func TestOpenShiftMonitoringPreservesExplicitPolicy(t *testing.T) {
     	assert.Equal(t, want, cluster.Spec.NetworkPolicy, "explicit policies must not acquire platform default rules")
     }
     
    +func TestOpenShiftNetworkPolicyUsesEffectiveRayPorts(t *testing.T) {
    +	t.Setenv("MONITORING_NAMESPACE", "monitoring")
    +	cluster := &rayv1.RayCluster{
    +		Spec: rayv1.RayClusterSpec{
    +			HeadGroupSpec: rayv1.HeadGroupSpec{
    +				RayStartParams: map[string]string{
    +					"dashboard-port":      "9365",
    +					"metrics-export-port": "9090",
    +				},
    +			},
    +		},
    +	}
    +
    +	EnsureOpenShiftRayClusterSecurity(cluster)
    +	rules := cluster.Spec.NetworkPolicy.Head.IngressRules
    +
    +	assert.Contains(t, rulePorts(rules[0]), int32(9365), "dashboard access should use the configured dashboard port")
    +	assert.Contains(t, rulePorts(rules[0]), int32(DefaultClientPort), "client access should retain the client port")
    +	assert.Contains(t, rulePorts(rules[1]), int32(9365), "RayJob submission should use the configured dashboard port")
    +	assert.Contains(t, rulePorts(rules[4]), int32(9090), "monitoring should use the configured metrics port")

    We already have coverage for the resulting policy structure:

  • Head selector, labels, policy types, and rule structure: networkpolicy_controller_test.go:122-208

  • Worker selector and peer structure: networkpolicy_controller_test.go:210-240

  • Base/head peer rules and RayJob-specific peers: networkpolicy_controller_unit_test.go:336-406

  • Custom ingress/egress rules: networkpolicy_controller_unit_test.go:433-480

  • Default and custom dashboard-port handling: networkpolicy_controller_unit_test.go:483-505

  • Policy deletion/recreation and spec transitions: networkpolicy_controller_test.go:257-287 and 469-556

  • OpenShift monitoring defaulting and idempotence: openshift_test.go:16-59
  • 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.

    chipspeak chipspeak commented on code on Oct 23, 2026 08:19 UTC
    Code Review
    ray-operator/controllers/ray/utils/openshift.go:1
    @@ -105,19 +108,28 @@ func ensureOpenShiftNetworkPolicy(spec *rayv1.RayClusterSpec) {
     		}
     		return append(rules, rule)
     	}
    +	// TODO(ODH NetworkPolicy): The same-namespace 10001 allowance is retained
    +	// while the platform client-source contract is unresolved. Users may install
    +	// Jupyter workbenches in arbitrary namespaces, so this rule must not be
    +	// broadened to all namespaces. A future cross-namespace rule requires a
    +	// protected namespace label contract or explicit per-RayCluster source rules.
     	spec.NetworkPolicy.Head.IngressRules = appendIngress(spec.NetworkPolicy.Head.IngressRules, networkingv1.NetworkPolicyIngressRule{
     		From:  []networkingv1.NetworkPolicyPeer{{PodSelector: &metav1.LabelSelector{}}},
    -		Ports: []networkingv1.NetworkPolicyPort{port(8265), port(10001)},
    +		Ports: []networkingv1.NetworkPolicyPort{port(dashboardPort), port(DefaultClientPort)},
     	})
     	spec.NetworkPolicy.Head.IngressRules = appendIngress(spec.NetworkPolicy.Head.IngressRules, networkingv1.NetworkPolicyIngressRule{
     		From: []networkingv1.NetworkPolicyPeer{{PodSelector: &metav1.LabelSelector{
     			MatchLabels: map[string]string{
     				RayOriginatedFromCRDLabelKey: RayOriginatedFromCRDLabelValue(RayJobCRD),

    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.

    chipspeak chipspeak commented on code on Oct 23, 2026 08:37 UTC
    Code Review
    ray-operator/pkg/webhooks/v1/raycluster_validating_webhook.go:1
    @@ -49,6 +49,11 @@ func (w *RayClusterWebhook) ValidateDelete(_ context.Context, _ *rayv1.RayCluste
     func (w *RayClusterWebhook) validateRayCluster(rayCluster *rayv1.RayCluster) error {
     	var allErrs field.ErrorList
     
    +	// TODO(ODH NetworkPolicy): Define whether explicitly supplied managed

    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.

    chipspeak chipspeak commented on code on Oct 23, 2026 08:38 UTC
    Code Review
    ray-operator/controllers/ray/utils/openshift.go:1
    @@ -105,19 +108,28 @@ func ensureOpenShiftNetworkPolicy(spec *rayv1.RayClusterSpec) {
     		}
     		return append(rules, rule)
     	}
    +	// TODO(ODH NetworkPolicy): The same-namespace 10001 allowance is retained
    +	// while the platform client-source contract is unresolved. Users may install
    +	// Jupyter workbenches in arbitrary namespaces, so this rule must not be
    +	// broadened to all namespaces. A future cross-namespace rule requires a
    +	// protected namespace label contract or explicit per-RayCluster source rules.
     	spec.NetworkPolicy.Head.IngressRules = appendIngress(spec.NetworkPolicy.Head.IngressRules, networkingv1.NetworkPolicyIngressRule{
     		From:  []networkingv1.NetworkPolicyPeer{{PodSelector: &metav1.LabelSelector{}}},
    -		Ports: []networkingv1.NetworkPolicyPort{port(8265), port(10001)},
    +		Ports: []networkingv1.NetworkPolicyPort{port(dashboardPort), port(DefaultClientPort)},
     	})
     	spec.NetworkPolicy.Head.IngressRules = appendIngress(spec.NetworkPolicy.Head.IngressRules, networkingv1.NetworkPolicyIngressRule{
     		From: []networkingv1.NetworkPolicyPeer{{PodSelector: &metav1.LabelSelector{
     			MatchLabels: map[string]string{
     				RayOriginatedFromCRDLabelKey: RayOriginatedFromCRDLabelValue(RayJobCRD),
     			},
     		}}},
    -		Ports: []networkingv1.NetworkPolicyPort{port(8265)},
    +		Ports: []networkingv1.NetworkPolicyPort{port(dashboardPort)},
     	})
     	spec.NetworkPolicy.Head.IngressRules = appendIngress(spec.NetworkPolicy.Head.IngressRules, networkingv1.NetworkPolicyIngressRule{
    +		// TODO(ODH NetworkPolicy): The supported caller for the kube-rbac-proxy
    +		// port is not yet established. The Gateway HTTPRoute currently targets
    +		// the dashboard service port, so do not guess a gateway peer here until
    +		// the 8443 data path is confirmed; changing this rule may break auth.
     		Ports: []networkingv1.NetworkPolicyPort{port(8443)},

    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.

    chipspeak chipspeak commented on code on Oct 23, 2026 08:49 UTC
    Code Review
    ray-operator/controllers/ray/utils/openshift.go:1
    @@ -162,6 +176,19 @@ func ensureOpenShiftNetworkPolicy(spec *rayv1.RayClusterSpec) {
     	})
     }
     
    +// effectiveHeadPort returns a valid integer Ray start parameter or its default.
    +// RayCluster pod construction applies the same fallback behavior when it builds
    +// the Ray command, so NetworkPolicy ports stay aligned with the effective head
    +// configuration.
    +func effectiveHeadPort(spec *rayv1.RayClusterSpec, key string, defaultPort int32) int32 {

    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.

    chipspeak chipspeak commented on code on Oct 23, 2026 09:01 UTC
    Code Review
    ray-operator/controllers/ray/utils/openshift.go:1
    @@ -93,6 +94,8 @@ func ensureOpenShiftNetworkPolicy(spec *rayv1.RayClusterSpec) {
     	mode := rayv1.NetworkPolicyDenyAllIngress
     	spec.NetworkPolicy = &rayv1.NetworkPolicyConfig{Mode: &mode, Head: &rayv1.NetworkPolicyRules{}}
     	tcp := corev1.ProtocolTCP
    +	dashboardPort := effectiveHeadPort(spec, "dashboard-port", DefaultDashboardPort)

    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.

    chipspeak chipspeak commented on Oct 27, 2026 18:06 UTC
    Author

    run-kuberay-e2e

    chipspeak chipspeak commented on Oct 28, 2026 12:29 UTC
    Author

    /run-kuberay-e2e

    ugiordan ugiordan commented on code on Oct 28, 2026 15:55 UTC
    Code Review
    ray-operator/pkg/webhooks/v1/raycluster_validating_webhook.go:1
    @@ -66,6 +97,146 @@ func (w *RayClusterWebhook) validateRayCluster(rayCluster *rayv1.RayCluster) err
     		rayCluster.Name, allErrs)
     }
     
    +func (w *RayClusterWebhook) isOpenShift() (bool, error) {
    +	if w.RESTMapper == nil {
    +		return false, nil
    +	}
    +	_, err := w.RESTMapper.RESTMapping(routev1.GroupVersion.WithKind("Route").GroupKind(), routev1.GroupVersion.Version)
    +	if err == nil {
    +		return true, nil
    +	}
    +	if meta.IsNoMatchError(err) {
    +		return false, nil
    +	}
    +	return false, err
    +}
    +
    +// validateManagedOpenShiftNetworkPolicy enforces the OpenShift/RHOAI platform
    +// policy contract. Valid custom dashboard and metrics RayStartParams are
    +// supported, but managed clusters may not add or remove platform policy rules.
    +func validateManagedOpenShiftNetworkPolicy(rayCluster, oldRayCluster *rayv1.RayCluster) *field.Error {
    +	if !utils.IsLegacySecurityEnabled(rayCluster) {
    +		return nil
    +	}
    +
    +	networkPolicyPath := field.NewPath("spec").Child("networkPolicy")
    +	networkPolicy := rayCluster.Spec.NetworkPolicy
    +	if networkPolicy == nil {
    +		// Existing pre-webhook clusters can temporarily reach this state while
    +		// LegacySecurityController backfills the native field. Do not block that
    +		// migration; the controller and NetworkPolicy preservation guard own it.
    +		// TODO(ODH NetworkPolicy): Add an admission/migration integration test
    +		// proving that validation cannot strand a legacy 1.6 cluster in this state.
    +		return nil
    +	}
    +
    +	if networkPolicy.Mode == nil || *networkPolicy.Mode != rayv1.NetworkPolicyDenyAllIngress {
    +		var mode any
    +		if networkPolicy.Mode != nil {
    +			mode = *networkPolicy.Mode
    +		}
    +		return field.Invalid(networkPolicyPath.Child("mode"), mode,
    +			"managed OpenShift RayClusters must use DenyAllIngress; egress isolation is not part of the supported profile")
    +	}
    +
    +	if networkPolicy.Head == nil {
    +		return field.Required(networkPolicyPath.Child("head"), "managed OpenShift RayClusters require the platform head ingress rules")
    +	}
    +
    +	// Recompute the current platform defaults from the effective Ray ports and
    +	// require them to remain present. This allows supported custom ports while
    +	// rejecting updates that change Ray ports without updating the mandatory
    +	// platform access rules in the same object.
    +	defaults := rayCluster.DeepCopy()
    +	defaults.Spec.NetworkPolicy = nil
    +	utils.EnsureOpenShiftRayClusterNetworkPolicy(defaults)
    +	allowedHeadRules := defaults.Spec.NetworkPolicy.Head
    +	requireCurrentPlatformRules := oldRayCluster == nil

    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?

    ugiordan ugiordan commented on code on Oct 28, 2026 15:59 UTC
    Code Review
    ray-operator/controllers/ray/networkpolicy_controller.go:1
    @@ -251,8 +251,11 @@ func (r *NetworkPolicyController) buildHeadNetworkPolicy(instance *rayv1.RayClus
     	if mode == rayv1.NetworkPolicyDenyAll || mode == rayv1.NetworkPolicyDenyAllIngress {
     		policyTypes = append(policyTypes, networkingv1.PolicyTypeIngress)
     		ingressRules = r.buildHeadIngressRules(instance)
    +		if r.isOpenShift && utils.IsLegacySecurityEnabled(instance) {
    +			ingressRules = appendUniqueIngressRules(ingressRules, r.buildOpenShiftPlatformIngressRules(instance)...)
    +		}
     		if instance.Spec.NetworkPolicy.Head != nil {
    -			ingressRules = append(ingressRules, instance.Spec.NetworkPolicy.Head.IngressRules...)
    +			ingressRules = appendUniqueIngressRules(ingressRules, instance.Spec.NetworkPolicy.Head.IngressRules...)

    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?

    ugiordan ugiordan commented on code on Oct 28, 2026 16:00 UTC
    Code Review
    ray-operator/controllers/ray/utils/openshift.go:1
    @@ -147,18 +163,24 @@ func ensureOpenShiftNetworkPolicy(spec *rayv1.RayClusterSpec) {
     			From: []networkingv1.NetworkPolicyPeer{{NamespaceSelector: &metav1.LabelSelector{MatchExpressions: []metav1.LabelSelectorRequirement{{
     				Key: corev1.LabelMetadataName, Operator: metav1.LabelSelectorOpIn, Values: []string{monitoringNamespace},
     			}}}}},
    -			Ports: []networkingv1.NetworkPolicyPort{port(8080)},
    +			Ports: []networkingv1.NetworkPolicyPort{port(metricsPort)},
     		})
     	}
    -	gatewayNamespace := os.Getenv("GATEWAY_NAMESPACE")
    -	if gatewayNamespace == "" {
    -		gatewayNamespace = "openshift-ingress"
    +	// TODO(ODH NetworkPolicy): Confirm whether the supported monitoring
    +	// deployment scrapes worker Pods before adding worker-group metrics rules.
    +	gatewayNamespace := GetGatewayNamespace()
    +	gatewayName := GetGatewayName()
    +	gatewayPeer := networkingv1.NetworkPolicyPeer{
    +		NamespaceSelector: &metav1.LabelSelector{MatchExpressions: []metav1.LabelSelectorRequirement{{
    +			Key: corev1.LabelMetadataName, Operator: metav1.LabelSelectorOpIn, Values: []string{gatewayNamespace},
    +		}}},
    +		PodSelector: &metav1.LabelSelector{MatchLabels: map[string]string{
    +			"gateway.networking.k8s.io/gateway-name": gatewayName,

    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.

    ugiordan ugiordan requested changes on Oct 28, 2026 16:01 UTC
    Changes Requested Reviewer

    Requested changes.

    sefroberg sefroberg commented on code on Oct 28, 2026 16:38 UTC
    Code Review
    ray-operator/controllers/ray/networkpolicy_controller.go:1
    @@ -251,8 +251,11 @@ func (r *NetworkPolicyController) buildHeadNetworkPolicy(instance *rayv1.RayClus
     	if mode == rayv1.NetworkPolicyDenyAll || mode == rayv1.NetworkPolicyDenyAllIngress {
     		policyTypes = append(policyTypes, networkingv1.PolicyTypeIngress)
     		ingressRules = r.buildHeadIngressRules(instance)
    +		if r.isOpenShift && utils.IsLegacySecurityEnabled(instance) {
    +			ingressRules = appendUniqueIngressRules(ingressRules, r.buildOpenShiftPlatformIngressRules(instance)...)

    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?

    sefroberg sefroberg commented on code on Oct 28, 2026 16:38 UTC
    Code Review
    ray-operator/pkg/webhooks/v1/raycluster_validating_webhook.go:1
    @@ -66,6 +97,146 @@ func (w *RayClusterWebhook) validateRayCluster(rayCluster *rayv1.RayCluster) err
     		rayCluster.Name, allErrs)
     }
     
    +func (w *RayClusterWebhook) isOpenShift() (bool, error) {
    +	if w.RESTMapper == nil {
    +		return false, nil
    +	}
    +	_, err := w.RESTMapper.RESTMapping(routev1.GroupVersion.WithKind("Route").GroupKind(), routev1.GroupVersion.Version)
    +	if err == nil {
    +		return true, nil
    +	}
    +	if meta.IsNoMatchError(err) {
    +		return false, nil
    +	}
    +	return false, err
    +}
    +
    +// validateManagedOpenShiftNetworkPolicy enforces the OpenShift/RHOAI platform
    +// policy contract. Valid custom dashboard and metrics RayStartParams are
    +// supported, but managed clusters may not add or remove platform policy rules.
    +func validateManagedOpenShiftNetworkPolicy(rayCluster, oldRayCluster *rayv1.RayCluster) *field.Error {
    +	if !utils.IsLegacySecurityEnabled(rayCluster) {
    +		return nil
    +	}
    +
    +	networkPolicyPath := field.NewPath("spec").Child("networkPolicy")
    +	networkPolicy := rayCluster.Spec.NetworkPolicy
    +	if networkPolicy == nil {
    +		// Existing pre-webhook clusters can temporarily reach this state while
    +		// LegacySecurityController backfills the native field. Do not block that
    +		// migration; the controller and NetworkPolicy preservation guard own it.
    +		// TODO(ODH NetworkPolicy): Add an admission/migration integration test
    +		// proving that validation cannot strand a legacy 1.6 cluster in this state.
    +		return nil
    +	}
    +
    +	if networkPolicy.Mode == nil || *networkPolicy.Mode != rayv1.NetworkPolicyDenyAllIngress {
    +		var mode any
    +		if networkPolicy.Mode != nil {
    +			mode = *networkPolicy.Mode
    +		}
    +		return field.Invalid(networkPolicyPath.Child("mode"), mode,
    +			"managed OpenShift RayClusters must use DenyAllIngress; egress isolation is not part of the supported profile")
    +	}
    +
    +	if networkPolicy.Head == nil {
    +		return field.Required(networkPolicyPath.Child("head"), "managed OpenShift RayClusters require the platform head ingress rules")
    +	}
    +
    +	// Recompute the current platform defaults from the effective Ray ports and
    +	// require them to remain present. This allows supported custom ports while
    +	// rejecting updates that change Ray ports without updating the mandatory
    +	// platform access rules in the same object.
    +	defaults := rayCluster.DeepCopy()
    +	defaults.Spec.NetworkPolicy = nil
    +	utils.EnsureOpenShiftRayClusterNetworkPolicy(defaults)
    +	allowedHeadRules := defaults.Spec.NetworkPolicy.Head
    +	requireCurrentPlatformRules := oldRayCluster == nil

    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?

    sefroberg sefroberg commented on code on Oct 28, 2026 16:38 UTC
    Code Review
    ray-operator/controllers/ray/utils/openshift.go:1
    @@ -93,6 +97,8 @@ func ensureOpenShiftNetworkPolicy(spec *rayv1.RayClusterSpec) {
     	mode := rayv1.NetworkPolicyDenyAllIngress
     	spec.NetworkPolicy = &rayv1.NetworkPolicyConfig{Mode: &mode, Head: &rayv1.NetworkPolicyRules{}}
     	tcp := corev1.ProtocolTCP
    +	dashboardPort := EffectiveRayStartParamPort(spec.HeadGroupSpec.RayStartParams, "dashboard-port", DefaultDashboardPort)

    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?

    sefroberg sefroberg commented on code on Oct 28, 2026 16:38 UTC
    Code Review
    ray-operator/controllers/ray/utils/openshift.go:1
    @@ -105,19 +111,29 @@ func ensureOpenShiftNetworkPolicy(spec *rayv1.RayClusterSpec) {
     		}
     		return append(rules, rule)
     	}
    +	// TODO(ODH NetworkPolicy): ODH workbench Pods have stable controller-owned
    +	// labels (opendatahub.io/workbenches=true and
    +	// opendatahub.io/odh-managed=true), but this rule remains broad for now.
    +	// Removing the empty selector would tighten workbench access while breaking
    +	// supported clusterSelector RayJob submitters that do not receive the Ray
    +	// origin label. Cross-namespace workbench access is not supported.
     	spec.NetworkPolicy.Head.IngressRules = appendIngress(spec.NetworkPolicy.Head.IngressRules, networkingv1.NetworkPolicyIngressRule{
     		From:  []networkingv1.NetworkPolicyPeer{{PodSelector: &metav1.LabelSelector{}}},
    -		Ports: []networkingv1.NetworkPolicyPort{port(8265), port(10001)},
    +		Ports: []networkingv1.NetworkPolicyPort{port(dashboardPort), port(DefaultClientPort)},

    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.

    sefroberg sefroberg commented on code on Oct 28, 2026 16:38 UTC
    Code Review
    ray-operator/pkg/webhooks/v1/raycluster_validating_webhook.go:1
    @@ -47,8 +54,32 @@ func (w *RayClusterWebhook) ValidateDelete(_ context.Context, _ *rayv1.RayCluste
     }
     
     func (w *RayClusterWebhook) validateRayCluster(rayCluster *rayv1.RayCluster) error {
    +	return w.validateRayClusterUpdate(rayCluster, nil)
    +}
    +
    +func (w *RayClusterWebhook) validateRayClusterUpdate(rayCluster, oldRayCluster *rayv1.RayCluster) error {
     	var allErrs field.ErrorList
     
    +	// Detect the supported managed profile from the platform rather than using
    +	// the legacy annotation as a new opt-in contract. Existing in-place legacy
    +	// OpenShift clusters are still covered because the OpenShift API surface is
    +	// present even when their spec.networkPolicy has not been backfilled yet.
    +	isOpenShift, err := w.isOpenShift()
    +	if err != nil {
    +		// Do not fail open if platform discovery is temporarily unavailable.
    +		// The webhook has failurePolicy=fail, so returning the error prevents a
    +		// managed OpenShift request from bypassing the platform policy contract.
    +		return fmt.Errorf("detect OpenShift platform: %w", err)

    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.

    sefroberg sefroberg requested changes on Oct 28, 2026 16:38 UTC
    Changes Requested Reviewer

    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

  • Availability scope of fail-closed discovery: a transient discovery error fails all RayCluster admissions, including non-OpenShift clusters that never needed the platform decision. Defensible given failurePolicy=fail, but consider scoping the hard failure to requests that actually carry the managed profile (or did previously).

  • Housekeeping: the PR body is an unfilled template — no description or testing strategy for a 570-line security PR; one commit message says "more to come"; Jira link is only in the title. 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).

    chipspeak chipspeak commented on Oct 28, 2026 17:38 UTC
    Author

    Thanks @ugiordan @sefroberg re the gateway question:

    Validated on an active RHOAI OpenShift cluster:

  • data-science-gateway is Programmed=True.

  • Its dataplane pod carries gateway.networking.k8s.io/gateway-name=data-science-gateway.

  • The Gateway Service uses the same selector label and resolves to that pod.

  • The Gateway has three attached HTTPRoutes.
  • 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.

    chipspeak chipspeak commented on Oct 28, 2026 18:20 UTC
    Author

    /run-kuberay-e2e

    sefroberg sefroberg commented on code on Oct 29, 2026 14:04 UTC
    Code Review
    ray-operator/controllers/ray/networkpolicy_controller.go:1
    @@ -251,8 +251,11 @@ func (r *NetworkPolicyController) buildHeadNetworkPolicy(instance *rayv1.RayClus
     	if mode == rayv1.NetworkPolicyDenyAll || mode == rayv1.NetworkPolicyDenyAllIngress {
     		policyTypes = append(policyTypes, networkingv1.PolicyTypeIngress)
     		ingressRules = r.buildHeadIngressRules(instance)
    +		if r.isOpenShift && utils.IsLegacySecurityEnabled(instance) {
    +			ingressRules = appendUniqueIngressRules(ingressRules, r.buildOpenShiftPlatformIngressRules(instance)...)

    ✅ 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.

    sefroberg sefroberg commented on code on Oct 29, 2026 14:04 UTC
    Code Review
    ray-operator/pkg/webhooks/v1/raycluster_validating_webhook.go:1
    @@ -66,6 +97,146 @@ func (w *RayClusterWebhook) validateRayCluster(rayCluster *rayv1.RayCluster) err
     		rayCluster.Name, allErrs)
     }
     
    +func (w *RayClusterWebhook) isOpenShift() (bool, error) {
    +	if w.RESTMapper == nil {
    +		return false, nil
    +	}
    +	_, err := w.RESTMapper.RESTMapping(routev1.GroupVersion.WithKind("Route").GroupKind(), routev1.GroupVersion.Version)
    +	if err == nil {
    +		return true, nil
    +	}
    +	if meta.IsNoMatchError(err) {
    +		return false, nil
    +	}
    +	return false, err
    +}
    +
    +// validateManagedOpenShiftNetworkPolicy enforces the OpenShift/RHOAI platform
    +// policy contract. Valid custom dashboard and metrics RayStartParams are
    +// supported, but managed clusters may not add or remove platform policy rules.
    +func validateManagedOpenShiftNetworkPolicy(rayCluster, oldRayCluster *rayv1.RayCluster) *field.Error {
    +	if !utils.IsLegacySecurityEnabled(rayCluster) {
    +		return nil
    +	}
    +
    +	networkPolicyPath := field.NewPath("spec").Child("networkPolicy")
    +	networkPolicy := rayCluster.Spec.NetworkPolicy
    +	if networkPolicy == nil {
    +		// Existing pre-webhook clusters can temporarily reach this state while
    +		// LegacySecurityController backfills the native field. Do not block that
    +		// migration; the controller and NetworkPolicy preservation guard own it.
    +		// TODO(ODH NetworkPolicy): Add an admission/migration integration test
    +		// proving that validation cannot strand a legacy 1.6 cluster in this state.
    +		return nil
    +	}
    +
    +	if networkPolicy.Mode == nil || *networkPolicy.Mode != rayv1.NetworkPolicyDenyAllIngress {
    +		var mode any
    +		if networkPolicy.Mode != nil {
    +			mode = *networkPolicy.Mode
    +		}
    +		return field.Invalid(networkPolicyPath.Child("mode"), mode,
    +			"managed OpenShift RayClusters must use DenyAllIngress; egress isolation is not part of the supported profile")
    +	}
    +
    +	if networkPolicy.Head == nil {
    +		return field.Required(networkPolicyPath.Child("head"), "managed OpenShift RayClusters require the platform head ingress rules")
    +	}
    +
    +	// Recompute the current platform defaults from the effective Ray ports and
    +	// require them to remain present. This allows supported custom ports while
    +	// rejecting updates that change Ray ports without updating the mandatory
    +	// platform access rules in the same object.
    +	defaults := rayCluster.DeepCopy()
    +	defaults.Spec.NetworkPolicy = nil
    +	utils.EnsureOpenShiftRayClusterNetworkPolicy(defaults)
    +	allowedHeadRules := defaults.Spec.NetworkPolicy.Head
    +	requireCurrentPlatformRules := oldRayCluster == nil

    ✅ 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.

    sefroberg sefroberg commented on code on Oct 29, 2026 14:04 UTC
    Code Review
    ray-operator/controllers/ray/utils/openshift.go:1
    @@ -93,6 +97,8 @@ func ensureOpenShiftNetworkPolicy(spec *rayv1.RayClusterSpec) {
     	mode := rayv1.NetworkPolicyDenyAllIngress
     	spec.NetworkPolicy = &rayv1.NetworkPolicyConfig{Mode: &mode, Head: &rayv1.NetworkPolicyRules{}}
     	tcp := corev1.ProtocolTCP
    +	dashboardPort := EffectiveRayStartParamPort(spec.HeadGroupSpec.RayStartParams, "dashboard-port", DefaultDashboardPort)

    ✅ Addressed in 954abf7d — new validateManagedOpenShiftRayPorts (raycluster_validating_webhook.go:113-159) closes the three-way port-source gap from both directions:

  • With a declared head container (: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.

  • Without a head container (: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.

    sefroberg sefroberg commented on code on Oct 29, 2026 14:04 UTC
    Code Review
    ray-operator/controllers/ray/utils/openshift.go:1
    @@ -105,19 +111,29 @@ func ensureOpenShiftNetworkPolicy(spec *rayv1.RayClusterSpec) {
     		}
     		return append(rules, rule)
     	}
    +	// TODO(ODH NetworkPolicy): ODH workbench Pods have stable controller-owned
    +	// labels (opendatahub.io/workbenches=true and
    +	// opendatahub.io/odh-managed=true), but this rule remains broad for now.
    +	// Removing the empty selector would tighten workbench access while breaking
    +	// supported clusterSelector RayJob submitters that do not receive the Ray
    +	// origin label. Cross-namespace workbench access is not supported.
     	spec.NetworkPolicy.Head.IngressRules = appendIngress(spec.NetworkPolicy.Head.IngressRules, networkingv1.NetworkPolicyIngressRule{
     		From:  []networkingv1.NetworkPolicyPeer{{PodSelector: &metav1.LabelSelector{}}},
    -		Ports: []networkingv1.NetworkPolicyPort{port(8265), port(10001)},
    +		Ports: []networkingv1.NetworkPolicyPort{port(dashboardPort), port(DefaultClientPort)},

    ✅ 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.

    sefroberg sefroberg commented on code on Oct 29, 2026 14:05 UTC
    Code Review
    ray-operator/pkg/webhooks/v1/raycluster_validating_webhook.go:1
    @@ -47,8 +54,32 @@ func (w *RayClusterWebhook) ValidateDelete(_ context.Context, _ *rayv1.RayCluste
     }
     
     func (w *RayClusterWebhook) validateRayCluster(rayCluster *rayv1.RayCluster) error {
    +	return w.validateRayClusterUpdate(rayCluster, nil)
    +}
    +
    +func (w *RayClusterWebhook) validateRayClusterUpdate(rayCluster, oldRayCluster *rayv1.RayCluster) error {
     	var allErrs field.ErrorList
     
    +	// Detect the supported managed profile from the platform rather than using
    +	// the legacy annotation as a new opt-in contract. Existing in-place legacy
    +	// OpenShift clusters are still covered because the OpenShift API surface is
    +	// present even when their spec.networkPolicy has not been backfilled yet.
    +	isOpenShift, err := w.isOpenShift()
    +	if err != nil {
    +		// Do not fail open if platform discovery is temporarily unavailable.
    +		// The webhook has failurePolicy=fail, so returning the error prevents a
    +		// managed OpenShift request from bypassing the platform policy contract.
    +		return fmt.Errorf("detect OpenShift platform: %w", err)

    ✅ 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.

    sefroberg sefroberg commented on Oct 29, 2026 14:05 UTC
    Reviewer

    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)

  • The source-less 8443 rule and the empty same-namespace selector remain deliberately deferred (tracked TODO at raycluster_validating_webhook.go:243), pending validation of the gateway, kube-rbac-proxy, RayJob submitter, and workbench caller contracts — consistent with szaher's checklist.

  • Transition corner worth one sentence in the PR description: during a port transition the webhook whitelists old spec rules while the controller ignores CR-retained rules, so pre-profile custom rules stop applying when the profile activates (tightening direction).
  • From my side the substantive blockers are resolved. Leaving the formal gate to @ugiordan's and @szaher's re-reviews.

    ugiordan ugiordan approved these changes on Oct 29, 2026 14:12 UTC
    Approved Reviewer

    Approved these changes.

    pawelpaszki pawelpaszki commented on Oct 29, 2026 14:41 UTC
    Contributor

    /run-kuberay-e2e

    sefroberg sefroberg approved these changes on Oct 29, 2026 15:03 UTC
    Approved Reviewer

    /LGTM

    chipspeak chipspeak commented on Oct 29, 2026 16:33 UTC
    Author

    /run-kuberay-e2e

    rhods-ci-bot rhods-ci-bot commented on Oct 29, 2026 19:36 UTC
    Bot

    <!-- 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
    

    szaher szaher approved these changes on Oct 29, 2026 22:47 UTC
    Approved Reviewer

    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.

    Reviewers
    Assignees
    chipspeak chipspeak
    Labels
    risk: low confidence: 71.4% reviewed sensitive_module
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 79.3% (HIGH) · Higher = larger blast radius
    79.3%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 71.4% · Lower = rushed or shallow review
    71.4%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 22.7% · Safe to merge
    22.7%