Skip to content

NO-JIRA: Add e2e test to detect named ports in NetworkPolicies#31375

Merged
openshift-merge-bot[bot] merged 2 commits into
openshift:mainfrom
machine424:nettpol
Jul 24, 2026
Merged

NO-JIRA: Add e2e test to detect named ports in NetworkPolicies#31375
openshift-merge-bot[bot] merged 2 commits into
openshift:mainfrom
machine424:nettpol

Conversation

@machine424

@machine424 machine424 commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

Some network plugins (e.g. OVN-Kubernetes) do not support named ports in NetworkPolicies and may silently convert them into allow-all rules. Add a test that lists all cluster NetworkPolicies and fails if any use named ports instead of numeric ones, with a skip list for now.

Summary by CodeRabbit

  • Tests
    • Added a new validation test suite for networking.k8s.io/v1 NetworkPolicy resources to ensure rule ports are specified numerically.
    • The test scans ingress and egress rules across namespaces, flags any named-port usage in platform namespaces, excludes a small set of known exceptions, and fails if any non-exempt violations are found.

@openshift-merge-bot

Copy link
Copy Markdown
Contributor

Pipeline controller notification
This repo is configured to use the pipeline controller. Second-stage tests will be triggered either automatically or after lgtm label is added, depending on the repository configuration. The pipeline controller will automatically detect which contexts are required and will utilize /test Prow commands to trigger the second stage.

For optional jobs, comment /test ? to see a list of all defined jobs. To trigger manually all jobs from second stage use /pipeline required command.

This repository is configured in: automatic mode

@machine424

Copy link
Copy Markdown
Contributor Author

/pipeline required

@openshift-merge-bot

Copy link
Copy Markdown
Contributor

Scheduling required tests:
/test e2e-aws-csi
/test e2e-aws-ovn-fips
/test e2e-aws-ovn-microshift
/test e2e-aws-ovn-microshift-serial
/test e2e-aws-ovn-serial-1of2
/test e2e-aws-ovn-serial-2of2
/test e2e-gcp-csi
/test e2e-gcp-ovn
/test e2e-gcp-ovn-upgrade
/test e2e-metal-ipi-ovn-ipv6
/test e2e-vsphere-ovn
/test e2e-vsphere-ovn-upi

@coderabbitai

coderabbitai Bot commented Jul 9, 2026

Copy link
Copy Markdown

Walkthrough

Adds a Ginkgo test that lists all cluster NetworkPolicies, skips known exceptions, scans ingress and egress ports for named ports, and fails when violations are found.

Changes

NetworkPolicy Port Validation Test

Layer / File(s) Summary
Collect policies and configure exceptions
test/extended/networking/networkpolicy_validation.go
Defines the test suite, exception list, cluster-wide NetworkPolicy listing, and initial assertions.
Validate policy ports
test/extended/networking/networkpolicy_validation.go
Scans platform-namespace ingress and egress ports, excludes configured policies, records named-port violations, and asserts that none remain.

Estimated code review effort: 2 (Simple) | ~10 minutes

Suggested reviewers: jluhrsen, martinkennelly

Sequence Diagram(s)

sequenceDiagram
  participant Ginkgo
  participant OpenShiftCLI
  participant KubernetesAPI
  participant PolicyValidator
  Ginkgo->>OpenShiftCLI: create cluster-wide client
  OpenShiftCLI->>KubernetesAPI: list NetworkPolicies across namespaces
  KubernetesAPI-->>OpenShiftCLI: return NetworkPolicies
  PolicyValidator->>PolicyValidator: filter platform namespaces and exceptions
  PolicyValidator->>PolicyValidator: inspect ingress and egress port types
  PolicyValidator->>Ginkgo: report violations
  Ginkgo->>Ginkgo: assert violations are empty
Loading
🚥 Pre-merge checks | ✅ 15
✅ Passed checks (15 passed)
Check name Status Explanation
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 new Ginkgo titles are static strings with no generated values or changing runtime data.
Test Structure And Quality ✅ Passed One It block checks one behavior, creates no resources, uses no waits, and all assertions include clear failure messages.
Microshift Test Compatibility ✅ Passed The new test only reads Kubernetes NetworkPolicy objects and uses no MicroShift-blocked OpenShift APIs, namespaces, or HA assumptions.
Single Node Openshift (Sno) Test Compatibility ✅ Passed The new test only lists NetworkPolicies and checks port types; it has no multi-node/HA assumptions and no SNO skip is needed.
Topology-Aware Scheduling Compatibility ✅ Passed PR only adds a NetworkPolicy validation test; no manifests, controllers, or topology-sensitive scheduling constraints were introduced.
Ote Binary Stdout Contract ✅ Passed The new suite only registers a Describe/It and uses e2e.Logf, which writes to GinkgoWriter, not stdout; no main/init/TestMain/BeforeSuite writes were added.
Ipv6 And Disconnected Network Test Compatibility ✅ Passed The new Ginkgo test only lists NetworkPolicies and checks port types; it has no hardcoded IPs, URL construction, or external network access.
No-Weak-Crypto ✅ Passed The added NetworkPolicy test contains no crypto primitives or secret/token comparisons; only networking/listing logic is present.
Container-Privileges ✅ Passed PR only adds a Go e2e test; the single changed file contains no container/K8s manifest or privileged settings.
No-Sensitive-Data-In-Logs ✅ Passed The new test only logs platform NetworkPolicy namespace/name plus named port strings on violations; it does not log passwords, tokens, PII, or other secret data.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adding an e2e test to detect named ports in NetworkPolicies.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
test/extended/networking/networkpolicy_validation.go (2)

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

Typo: "Sone CNI" → "Some CNI".

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

In `@test/extended/networking/networkpolicy_validation.go` at line 39, Fix the
typo in the comment inside the NetworkPolicy validation test by changing the
wording in the nearby comment under the networking validation logic from “Sone
CNI” to “Some CNI”; this is only a text correction and should be applied where
the comment mentions named ports in NetworkPolicies.

43-46: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Use a bounded context instead of context.Background().

The List call has no deadline, so it can hang indefinitely if the API server is slow or unresponsive.

⏱️ Suggested fix
-		ctx := context.Background()
+		ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
+		defer cancel()

(remember to add "time" to imports)

As per path instructions, Go code should use context.Context for cancellation and timeouts.

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

In `@test/extended/networking/networkpolicy_validation.go` around lines 43 - 46,
The NetworkPolicies list call is using an unbounded context, so it can hang
indefinitely if the API server is slow. Update the NetworkPolicy validation test
to use a bounded context with timeout instead of `context.Background()` near the
`List` call in the validation flow, and add the needed `time` import when
creating that timeout-based context.

Source: Path instructions

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

Nitpick comments:
In `@test/extended/networking/networkpolicy_validation.go`:
- Line 39: Fix the typo in the comment inside the NetworkPolicy validation test
by changing the wording in the nearby comment under the networking validation
logic from “Sone CNI” to “Some CNI”; this is only a text correction and should
be applied where the comment mentions named ports in NetworkPolicies.
- Around line 43-46: The NetworkPolicies list call is using an unbounded
context, so it can hang indefinitely if the API server is slow. Update the
NetworkPolicy validation test to use a bounded context with timeout instead of
`context.Background()` near the `List` call in the validation flow, and add the
needed `time` import when creating that timeout-based context.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Central YAML (inherited)

Review profile: CHILL

Plan: Enterprise

Run ID: 28d1c930-b729-45ed-80e8-b0124854a545

📥 Commits

Reviewing files that changed from the base of the PR and between a40276a and f3bcd07.

📒 Files selected for processing (1)
  • test/extended/networking/networkpolicy_validation.go

@openshift-ci openshift-ci Bot added the ready-for-human-review Indicates a PR has been reviewed by automated tools and is ready for human review label Jul 9, 2026
@openshift-ci
openshift-ci Bot requested review from jluhrsen and martinkennelly July 9, 2026 16:29
@openshift-trt

openshift-trt Bot commented Jul 9, 2026

Copy link
Copy Markdown

Risk analysis has seen new tests most likely introduced by this PR.
Please ensure that new tests meet guidelines for naming and stability.

New tests seen in this PR at sha: f3bcd07

  • "[sig-network] NetworkPolicy should use numeric ports in all platform NetworkPolicies [apigroup:networking.k8s.io] [Suite:openshift/conformance/parallel]" [Total: 5, Pass: 5, Fail: 0, Flake: 0]

Comment thread test/extended/networking/networkpolicy_validation.go Outdated
@openshift-merge-bot

Copy link
Copy Markdown
Contributor

Scheduling required tests:
/test e2e-aws-csi
/test e2e-aws-ovn-fips
/test e2e-aws-ovn-microshift
/test e2e-aws-ovn-microshift-serial
/test e2e-aws-ovn-serial-1of2
/test e2e-aws-ovn-serial-2of2
/test e2e-gcp-csi
/test e2e-gcp-ovn
/test e2e-gcp-ovn-upgrade
/test e2e-metal-ipi-ovn-ipv6
/test e2e-vsphere-ovn
/test e2e-vsphere-ovn-upi

Some network plugins (e.g. OVN-Kubernetes) do not support named ports in
NetworkPolicies and may silently convert them into allow-all rules. Add
a test that lists all cluster NetworkPolicies and fails if
any use named ports instead of numeric ones, with a skip list for now.
Comment on lines +45 to +46
nps, err := oc.AdminKubeClient().NetworkingV1().NetworkPolicies("").List(ctx, metav1.ListOptions{})
o.Expect(err).NotTo(o.HaveOccurred(), "failed to list NetworkPolicies across all namespaces")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Test name says "in all platform NetworkPolicies" but we collect all NPs across all namespaces. This will be intermittently misbehaving because while other tests are creating&deleting namespaces, we will be also sweeping through those.

Maybe it's better to only filter for openshift-* / kube-* namespaces?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

that's safer, you're right.
Pushed a filter with a justification.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I am not sure if that's actually better so please confirm. But my gut feeling is that you could list the namespaces, get the ones you are interested in and only afterwards call NetworkPolicies.List on those namespaces only.

Maybe that's better for apiserver, maybe not. Fell free to judge yourself and ignore this comment completely.

If anything, that would be something along the lines of

+		namespaces, err := oc.AdminKubeClient().CoreV1().Namespaces().List(ctx, metav1.ListOptions{})
+		var networkPolicies []networkingv1.NetworkPolicy
+		for _, namespace := range namespaces.Items {
+			name := namespace.Name
+			if !strings.HasPrefix(name, "openshift-") &&
+				!strings.HasPrefix(name, "kube-") &&
+				name != "default" {
+				continue
+			}
+			nps, err := oc.AdminKubeClient().
+				NetworkingV1().
+				NetworkPolicies(name).
+				List(ctx, metav1.ListOptions{})
+			)
+
+			networkPolicies = append(networkPolicies, nps.Items...)
+		}

@machine424 machine424 Jul 23, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I believe most of the NetworkPolicies will live in platform namespaces, and the overall NetworkPolicies footprint shouldn't pose a problem for either the API server or the client. Plus, it's a single query instead of N+1

@mkowalski

Copy link
Copy Markdown
Contributor

/approve

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

Copy link
Copy Markdown
Contributor

Scheduling required tests:
/test e2e-aws-csi
/test e2e-aws-ovn-fips
/test e2e-aws-ovn-microshift
/test e2e-aws-ovn-microshift-serial
/test e2e-aws-ovn-serial-1of2
/test e2e-aws-ovn-serial-2of2
/test e2e-gcp-csi
/test e2e-gcp-ovn
/test e2e-gcp-ovn-upgrade
/test e2e-metal-ipi-ovn-ipv6
/test e2e-vsphere-ovn
/test e2e-vsphere-ovn-upi

@machine424

Copy link
Copy Markdown
Contributor Author

/retitle NO-JIRA: Add e2e test to detect named ports in NetworkPolicies

@openshift-ci openshift-ci Bot changed the title Add e2e test to detect named ports in NetworkPolicies NO-JIRA: Add e2e test to detect named ports in NetworkPolicies Jul 23, 2026
@openshift-ci-robot openshift-ci-robot added the jira/valid-reference Indicates that this PR references a valid Jira ticket of any type. label Jul 23, 2026
@openshift-ci-robot

Copy link
Copy Markdown

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

Details

In response to this:

Some network plugins (e.g. OVN-Kubernetes) do not support named ports in NetworkPolicies and may silently convert them into allow-all rules. Add a test that lists all cluster NetworkPolicies and fails if any use named ports instead of numeric ones, with a skip list for now.

Summary by CodeRabbit

  • Tests
  • Added a new validation test suite for networking.k8s.io/v1 NetworkPolicy resources to ensure rule ports are specified numerically.
  • The test scans ingress and egress rules across namespaces, flags any named-port usage in platform namespaces, excludes a small set of known exceptions, and fails if any non-exempt violations are found.

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the openshift-eng/jira-lifecycle-plugin repository.

@machine424

Copy link
Copy Markdown
Contributor Author

/retest

@machine424

Copy link
Copy Markdown
Contributor Author

/verified by #31375 (comment)

@openshift-ci-robot openshift-ci-robot added the verified Signifies that the PR passed pre-merge verification criteria label Jul 23, 2026
@openshift-ci-robot

Copy link
Copy Markdown

@machine424: This PR has been marked as verified by https://github.com/openshift/origin/pull/31375#issuecomment-5060029432.

Details

In response to this:

/verified by #31375 (comment)

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the openshift-eng/jira-lifecycle-plugin repository.

@mkowalski

Copy link
Copy Markdown
Contributor

/lgtm

@openshift-ci openshift-ci Bot added the lgtm Indicates that a PR is ready to be merged. label Jul 23, 2026
@openshift-ci

openshift-ci Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: machine424, mkowalski

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 commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

@machine424: all tests passed!

Full PR test history. Your PR dashboard.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository. I understand the commands that are listed here.

@openshift-trt

openshift-trt Bot commented Jul 24, 2026

Copy link
Copy Markdown

Risk analysis has seen new tests most likely introduced by this PR.
Please ensure that new tests meet guidelines for naming and stability.

New Test Risks for sha: 14a8058

Job Name New Test Risk
pull-ci-openshift-origin-main-e2e-aws-ovn-fips High - "[sig-network] NetworkPolicy should use numeric ports in all platform NetworkPolicies [apigroup:networking.k8s.io] [Suite:openshift/conformance/parallel]" is a new test that was not present in all runs against the current commit.

New tests seen in this PR at sha: 14a8058

  • "[sig-network] NetworkPolicy should use numeric ports in all platform NetworkPolicies [apigroup:networking.k8s.io] [Suite:openshift/conformance/parallel]" [Total: 6, Pass: 6, Fail: 0, Flake: 0]

@openshift-merge-bot
openshift-merge-bot Bot merged commit 398edca into openshift:main Jul 24, 2026
22 checks passed
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. jira/valid-reference Indicates that this PR references a valid Jira ticket of any type. lgtm Indicates that a PR is ready to be merged. ready-for-human-review Indicates a PR has been reviewed by automated tools and is ready for human review verified Signifies that the PR passed pre-merge verification criteria

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants