Skip to content

MCO-1944: Add NetworkPolicy Test case#6283

Open
ptalgulk01 wants to merge 1 commit into
openshift:mainfrom
ptalgulk01:add-networpolicy-testcase
Open

MCO-1944: Add NetworkPolicy Test case#6283
ptalgulk01 wants to merge 1 commit into
openshift:mainfrom
ptalgulk01:add-networpolicy-testcase

Conversation

@ptalgulk01

@ptalgulk01 ptalgulk01 commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Test Coverage:

  • Verifies existence of 5 managed network policies (allow-all-egress,
    allow-machine-config-controller, allow-machine-config-operator,
    allow-machine-os-builder, default-deny)
  • Validates allow-all-egress policy allows all egress traffic
  • Validates default-deny policy blocks both ingress and egress
  • Verifies MCO/MCC/MOB pods have ingress rules on port 9001 only
  • Tests that test pod has no ingress allow policy
  • Validates MCC pod cannot reach test pod (ingress blocked)
  • Tests port restrictions (9001 allowed, 8443/443 blocked)
  • Verifies MCO pod can reach Kubernetes API (egress works)
  • Validates ValidatingAdmissionPolicy blocks deletion of managed policies
  • Validates ValidatingAdmissionPolicy blocks modification of managed policies

Implementation Details:

  • Uses Resource wrapper for NetworkPolicy operations
  • Uses RemoteShPod/RemoteShContainer for pod exec operations
  • Uses existing utility functions (getMachineConfigControllerPod,
    getMachineConfigOperatorPod)
  • Validates VAP denials using regexp pattern matching on stderr
  • Added MachineConfigControllerPodSelector and
    MachineConfigOperatorPodSelector constants to const.go

Summary by CodeRabbit

  • Tests
    • Added a new end-to-end security suite for MCO network policy behavior, including readiness checks and network reachability validation.
    • Verifies external egress restrictions/allowance (internet access when applicable), Kubernetes API /healthz reachability, and expected blocked/unreachable connectivity between MCO components and the test pod.
    • Confirms port-level access controls to the MCC endpoints (e.g., metrics access expectations) and blocks other related ports.
  • Chores
    • Enhanced shared test utilities to support safer resource deletion with clearer failure handling.

@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: LGTM mode

@coderabbitai

coderabbitai Bot commented Jul 8, 2026

Copy link
Copy Markdown

Walkthrough

This PR adds a disruptive serial Ginkgo suite that provisions a nettest pod and verifies external egress, Kubernetes API access, MCC reachability restrictions, port-specific MCC access, and MCO API access. It also adds resource deletion helpers for extended-privileged tests.

Changes

MCO network policy connectivity coverage

Layer / File(s) Summary
Suite setup and test pod provisioning
test/extended-priv/mco_network_policies.go, test/extended-priv/resource.go
Defines the suite and prechecks, creates and waits for the nettest pod, and adds Delete and DeleteOrFail resource helpers.
Connectivity and component reachability checks
test/extended-priv/mco_network_policies.go
Checks conditional internet egress, Kubernetes API /healthz access, MCC isolation from nettest, MCC port behavior, and MCO API access.

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

Sequence Diagram(s)

sequenceDiagram
  participant TestSuite
  participant NetTestPod
  participant MCCPod
  participant MCOPod
  participant KubernetesAPI
  TestSuite->>NetTestPod: create and wait for readiness
  NetTestPod->>KubernetesAPI: fetch /healthz
  KubernetesAPI-->>NetTestPod: ok
  TestSuite->>MCCPod: test access to nettest:8080
  MCCPod-->>TestSuite: connection failure
  NetTestPod->>MCCPod: request :9001/metrics
  MCCPod-->>NetTestPod: Unauthorized
  NetTestPod->>MCCPod: connect to :8797
  MCCPod-->>NetTestPod: connection failure
  MCOPod->>KubernetesAPI: fetch /healthz
  KubernetesAPI-->>MCOPod: ok
Loading

Suggested reviewers: dkhater-redhat

🚥 Pre-merge checks | ✅ 12 | ❌ 3

❌ Failed checks (3 warnings)

Check name Status Explanation Resolution
Test Structure And Quality ⚠️ Warning The new suite puts egress, API reachability, ingress blocking, and multiple port checks into one long It, and it does setup/cleanup inline instead of structured BeforeEach/AfterEach. Split the behaviors into focused It blocks; move pod setup/teardown into BeforeEach/AfterEach (or consistent DeferCleanup), and keep each assertion step-specific with clearer messages.
Microshift Test Compatibility ⚠️ Warning The new suite has no MicroShift skip/tag and calls PreChecks, which lists MachineConfigPools (machineconfiguration.openshift.io), an unsupported OpenShift API on MicroShift. Add an [apigroup:machineconfiguration.openshift.io] tag or a [Skipped:MicroShift] label, or guard the suite with exutil.IsMicroShiftCluster() before PreChecks.
Ipv6 And Disconnected Network Test Compatibility ⚠️ Warning Test fetches https://google.com and builds pod URLs with fmt.Sprintf("http://%s:..."), so it needs public internet and is not IPv6-safe. Add [Skipped:Disconnected] or use an in-cluster endpoint for egress checks, and build pod URLs with net.JoinHostPort or IP-family detection.
✅ Passed checks (12 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and accurately summarizes the main change: adding an MCO NetworkPolicy test case.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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 fixed strings; the only identifier is a static PolarionID, with no dynamic pod/IP/namespace/date data.
Single Node Openshift (Sno) Test Compatibility ✅ Passed PASS: The new Ginkgo test only creates a pod and checks API/network-policy connectivity; it doesn't count nodes, require cross-node scheduling, or drain/scale nodes.
Topology-Aware Scheduling Compatibility ✅ Passed PASS: The PR only adds an e2e test and ResourceList delete helpers; no deployment manifests, replicas, node selectors, affinity, or topology-aware scheduling changes.
Ote Binary Stdout Contract ✅ Passed Changed files only add Ginkgo It/JustBeforeEach code and Resource methods; no init/BeforeSuite/TestMain or stdout writes in process-level code.
No-Weak-Crypto ✅ Passed The touched files add network-policy tests and delete helpers only; no crypto imports, weak algorithms, custom crypto, or secret/token comparisons appear.
Container-Privileges ✅ Passed PASS: The commit changes only test code and delete helpers; no privileged, hostPID/Network/IPC, SYS_ADMIN, root, or allowPrivilegeEscalation settings appear.
No-Sensitive-Data-In-Logs ✅ Passed No added logs print secrets/PII/tokens; new messages are generic status lines and delete errors only.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@openshift-ci

openshift-ci Bot commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: ptalgulk01

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

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

Copy link
Copy Markdown
Contributor Author

/retest

@ptalgulk01 ptalgulk01 force-pushed the add-networpolicy-testcase branch from fc41c29 to 7c16b3e Compare July 9, 2026 09:13
@ptalgulk01 ptalgulk01 changed the title Add NetworkPolicy Test case MCO-1944: Add NetworkPolicy Test case Jul 9, 2026
@openshift-ci-robot

openshift-ci-robot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

@ptalgulk01: This pull request references MCO-1944 which is a valid jira issue.

Warning: The referenced jira issue has an invalid target version for the target branch this PR targets: expected the story to target the "5.0.0" version, but no target version was set.

Details

In response to this:

Test Coverage:

  • Verifies existence of 5 managed network policies (allow-all-egress,
    allow-machine-config-controller, allow-machine-config-operator,
    allow-machine-os-builder, default-deny)
  • Validates allow-all-egress policy allows all egress traffic
  • Validates default-deny policy blocks both ingress and egress
  • Verifies MCO/MCC/MOB pods have ingress rules on port 9001 only
  • Tests that test pod has no ingress allow policy
  • Validates MCC pod cannot reach test pod (ingress blocked)
  • Tests port restrictions (9001 allowed, 8443/443 blocked)
  • Verifies MCO pod can reach Kubernetes API (egress works)
  • Validates ValidatingAdmissionPolicy blocks deletion of managed policies
  • Validates ValidatingAdmissionPolicy blocks modification of managed policies

Implementation Details:

  • Uses Resource wrapper for NetworkPolicy operations
  • Uses RemoteShPod/RemoteShContainer for pod exec operations
  • Uses existing utility functions (getMachineConfigControllerPod,
    getMachineConfigOperatorPod)
  • Validates VAP denials using regexp pattern matching on stderr
  • Added MachineConfigControllerPodSelector and
    MachineConfigOperatorPodSelector constants to const.go

Summary by CodeRabbit

  • Tests
  • Added new end-to-end coverage for machine config network policies.
  • Verified expected policy behavior for traffic allowance, default-deny rules, and access restrictions between test pods and machine config components.
  • Added checks that protected network policies cannot be deleted or modified.

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.

@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 9, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
test/extended-priv/mco_network_policies.go (1)

61-64: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

External dependency on google.com will be flaky in disconnected/restricted CI.

Reaching https://google.com (and asserting the Moved redirect body) makes this step dependent on outbound internet and Google's response text. On disconnected or egress-restricted clusters this fails for reasons unrelated to the allow-all-egress policy. Consider validating egress against an in-cluster or otherwise guaranteed endpoint, or gate this on a connectivity precheck.

🤖 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-priv/mco_network_policies.go` around lines 61 - 64, The egress
verification in the test pod currently depends on google.com and a specific
redirect response, which is flaky in restricted or disconnected CI. Update the
check in the test body around exutil.RemoteShPod to use a guaranteed in-cluster
or prevalidated endpoint instead of external internet, or add a connectivity
precheck before running it. Keep the assertion tied to the allow-all-egress
validation by referencing the same test step and RemoteShPod-based curl call.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/extended-priv/mco_network_policies.go`:
- Around line 101-112: The ingress-block check in the MCC-to-test-pod path is
currently a false positive because the test pod only runs sleep and nothing
listens on port 8080. Update the logic around getMachineConfigControllerPod,
NewNamespacedResource, and the curl call in the TEST 3 block so the target pod
runs a simple HTTP server (or another reachable listener) before asserting the
connection is denied, and keep a positive control that confirms the listener
works when not blocked. This ensures the RemoteShContainer failure actually
validates the NetworkPolicy ingress restriction rather than an unopened port.
- Around line 124-132: The port checks in the extended-priv MCO network policy
test are hitting ports that the MCC pod does not actually listen on, so the
failures don’t prove NetworkPolicy is working. Update the probes in the test
that uses exutil.RemoteShPod and mccPodIP to target a real exposed listener,
such as the kube-rbac-proxy metrics port or the Service endpoint, so the
assertions verify network blocking rather than closed ports.

---

Nitpick comments:
In `@test/extended-priv/mco_network_policies.go`:
- Around line 61-64: The egress verification in the test pod currently depends
on google.com and a specific redirect response, which is flaky in restricted or
disconnected CI. Update the check in the test body around exutil.RemoteShPod to
use a guaranteed in-cluster or prevalidated endpoint instead of external
internet, or add a connectivity precheck before running it. Keep the assertion
tied to the allow-all-egress validation by referencing the same test step and
RemoteShPod-based curl call.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Enterprise

Run ID: 1d9be135-55b7-4eb3-b963-051f4cb10fac

📥 Commits

Reviewing files that changed from the base of the PR and between b53e441 and 7c16b3e.

📒 Files selected for processing (1)
  • test/extended-priv/mco_network_policies.go

Comment on lines +101 to +112
exutil.By("TEST 3: Verify MCC pod cannot reach test pod (test pod ingress is blocked)")
mccPodName, err := getMachineConfigControllerPod(oc.AsAdmin())
o.Expect(err).NotTo(o.HaveOccurred(), "Failed to get MCC pod")
o.Expect(mccPodName).NotTo(o.BeEmpty(), "MCC pod not found")

testPod := NewNamespacedResource(oc.AsAdmin(), "pod", MachineConfigNamespace, testPodName)
testPodIP := testPod.GetOrFail("{.status.podIP}")

// Try to reach test pod from MCC (should fail due to ingress block)
_, err = exutil.RemoteShContainer(oc.AsAdmin(), MachineConfigNamespace, mccPodName, "machine-config-controller", "curl", "-sk", "--connect-timeout", "5", fmt.Sprintf("http://%s:8080", testPodIP))
o.Expect(err).To(o.HaveOccurred(), "MCC pod should not be able to reach test pod")
logger.Infof("OK!\n")

@coderabbitai coderabbitai Bot Jul 9, 2026

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Ingress-block assertion is a false positive. test/extended-priv/mco_network_policies.go:101-112 only starts sleep 36000, so nothing is listening on :8080; this curl can fail even if the NetworkPolicy is ineffective. Run a simple server in the pod, or add an allowed control, so the failure actually proves ingress is blocked.

🤖 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-priv/mco_network_policies.go` around lines 101 - 112, The
ingress-block check in the MCC-to-test-pod path is currently a false positive
because the test pod only runs sleep and nothing listens on port 8080. Update
the logic around getMachineConfigControllerPod, NewNamespacedResource, and the
curl call in the TEST 3 block so the target pod runs a simple HTTP server (or
another reachable listener) before asserting the connection is denied, and keep
a positive control that confirms the listener works when not blocked. This
ensures the RemoteShContainer failure actually validates the NetworkPolicy
ingress restriction rather than an unopened port.

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.

It seems to be imporant, nothing is listening in the test pod.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@sergiordlr Agreed — since the test pod is only running sleep 36000, there's no listener on port 8080, so the "MCC cannot reach test pod" assertion would pass even if the NetworkPolicy weren't blocking anything. That makes it a false positive rather than a real verification of the ingress block.

A simple fix would be to start a lightweight HTTP server as the pod's command instead of sleep, e.g.:

"--command", "--", "python3", "-c",
"import http.server,socketserver; s=socketserver.TCPServer(('0.0.0.0',8080), http.server.SimpleHTTPRequestHandler); s.serve_forever()",

or with nc:

"--command", "--", "sh", "-c", "while true; do nc -lk -p 8080 -e /bin/true; done",

(the exact command depends on what's available in registry.access.redhat.com/ubi9/ubi-minimal:latestubi-minimal doesn't ship nc or python3 by default, so you may need microdnf install first, or switch to an image that already includes a simple server, such as registry.access.redhat.com/ubi9/ubi-minimal with busybox, or a test-utility image already used elsewhere in this test suite).

Once the pod has an actual listener on 8080:

  • The MCC → test-pod curl failure genuinely proves ingress is blocked.
  • You could also add a positive control (e.g., verify a pod with an allow-ingress label can reach the same port) to further validate the policy is being enforced rather than the port simply being closed.

Comment thread test/extended-priv/mco_network_policies.go Outdated

@HarshwardhanPatil07 HarshwardhanPatil07 left a comment

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 recommend checking presubmit tests ones, I see duplicate scenarios. this are already there policy existence, deletion blocked, update blocked, coexistence


// Test-scoped variables
testPodName := "nettest"
testPodImage := "registry.access.redhat.com/ubi9/ubi-minimal:latest"

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.

We should use images stored in quay.io/openshifttest since they will be cloned in disconnected clusters.

https://quay.io/organization/openshifttest

Can all checks be executed in a disconnected cluster?

If not, can we discriminate which check can be executed in a disconnected cluster and ignore the ones that can't? (it could be done by using IsDisconnectedCluster function)

We should tag the test as connected only if there are checks that cannot run in a disconnected env and we don't want to discriminate.

Comment on lines +33 to +34
_ = oc.AsAdmin().WithoutNamespace().Run("delete").Args("pod", "-n", MachineConfigNamespace, testPodName, "--ignore-not-found=true").Execute()
}()

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.

In openshift-test-private in the workflow.go file we created a Pod resource and a Job resource.

The idea was to abstract everything involving pods and jobs and encapsulate everything in there.

It looks like that those resources haven't already been migrated because they will be migrated with the ocb test cases.

Nevertheless, we should try to continue with this idea, and encapsulate everything regarding pods inside the Pod resource. Even if we make the same call to exutils.RemoteShPod, for example. At least everything will be encapsulated and will be easier to use and maintain.

"--command", "--", "sleep", "36000",
).Execute()
o.Expect(err).NotTo(o.HaveOccurred(), "Failed to create test pod")
exutil.AssertPodToBeReady(oc, testPodName, MachineConfigNamespace)

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.

Once we use a Pod resource we can start using our gomega matches like "HaveCondition("Ready", "status", "true") to check the resources.

Comment on lines +92 to +98
mcoComponents := []string{"allow-machine-config-controller", "allow-machine-config-operator", "allow-machine-os-builder"}
for _, component := range mcoComponents {
np := NewNamespacedResource(oc.AsAdmin(), "networkpolicy", MachineConfigNamespace, component)
ingressSpec := np.GetOrFail("{.spec.ingress}")
o.Expect(ingressSpec).To(o.ContainSubstring("9001"), "%s does not allow port 9001", component)
o.Expect(ingressSpec).To(o.ContainSubstring("TCP"), "%s does not specify TCP protocol", component)
}

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.

If we verify that 9001 is present in the MCO ones, it means that we need to check that it is not present in the rest, right?

Comment on lines +101 to +112
exutil.By("TEST 3: Verify MCC pod cannot reach test pod (test pod ingress is blocked)")
mccPodName, err := getMachineConfigControllerPod(oc.AsAdmin())
o.Expect(err).NotTo(o.HaveOccurred(), "Failed to get MCC pod")
o.Expect(mccPodName).NotTo(o.BeEmpty(), "MCC pod not found")

testPod := NewNamespacedResource(oc.AsAdmin(), "pod", MachineConfigNamespace, testPodName)
testPodIP := testPod.GetOrFail("{.status.podIP}")

// Try to reach test pod from MCC (should fail due to ingress block)
_, err = exutil.RemoteShContainer(oc.AsAdmin(), MachineConfigNamespace, mccPodName, "machine-config-controller", "curl", "-sk", "--connect-timeout", "5", fmt.Sprintf("http://%s:8080", testPodIP))
o.Expect(err).To(o.HaveOccurred(), "MCC pod should not be able to reach test pod")
logger.Infof("OK!\n")

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.

It seems to be imporant, nothing is listening in the test pod.

Comment on lines +125 to +132
_, err = exutil.RemoteShPod(oc.AsAdmin(), MachineConfigNamespace, testPodName, "curl", "-sk", "--connect-timeout", "5", fmt.Sprintf("https://%s:8443/metrics", mccPodIP))
o.Expect(err).To(o.HaveOccurred(), "Port 8443 should be blocked")
logger.Infof("OK!\n")

// Test port 443 (should fail - connection blocked)
_, err = exutil.RemoteShPod(oc.AsAdmin(), MachineConfigNamespace, testPodName, "curl", "-sk", "--connect-timeout", "5", fmt.Sprintf("https://%s:443", mccPodIP))
o.Expect(err).To(o.HaveOccurred(), "Port 443 should be blocked")
logger.Infof("OK!\n")

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.

Is the MCC pod actually listening in the those ports?

sh-5.1$ ss -tulnp
Netid          State           Recv-Q          Send-Q                     Local Address:Port                     Peer Address:Port          Process                                          
tcp            LISTEN          0               4096                           127.0.0.1:8797                          0.0.0.0:*              users:(("machine-config-",pid=1,fd=7))          
tcp            LISTEN          0               4096                                   *:9001                                *:*                                                         


exutil.By("TEST 5: Verify VAP blocks deletion of all 5 managed policies")
for _, netpol := range expectedNetPols {
err = oc.AsAdmin().WithoutNamespace().Run("delete").Args("networkpolicy", "-n", MachineConfigNamespace, netpol).Execute()

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.

Let's avoid using "oc....Run..." commands. Lets use a NamespacedResourceList

It seems that ResourceList structs don't have a Delete method, let's add it so that it can be reused in the future.

{"allow-all-egress", `{"spec":{"egress":[{"ports":[{"port":443,"protocol":"TCP"}]}]}}`},
}
for _, tc := range patchTests {
err = oc.AsAdmin().WithoutNamespace().Run("patch").Args("networkpolicy", tc.name, "-n", MachineConfigNamespace, "--type=merge", "-p", tc.patch).Execute()

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.

Let's avoid using "oc....Run" commands, let's use a NamespacedResource and use the patch method.

@ptalgulk01

Copy link
Copy Markdown
Contributor Author

Summary of changes made to address review comments:

  1. Line 146: Replaced oc.Run("delete") with NamespacedResource.Delete() method
  2. Line 160: Replaced oc.Run("patch") with NamespacedResource.Patch() method
  3. Added to resource.go: Delete() and DeleteOrFail() methods for ResourceList struct (for future reuse)
  4. Lines 124-132: Replaced invalid port tests (8443/443 - not listening) with port 8797 test (MCC is listening on this port, but network policy blocks it - validates the network policy actually works)

Re: Line 110 (test pod ingress test):
The test pod runs sleep 36000 with no listening services - this is intentional. The test validates that the network policy blocks ingress at the network layer, not that a service rejects the connection. The default-deny policy should block the connection attempt from MCC before it reaches the pod.

@ptalgulk01 ptalgulk01 force-pushed the add-networpolicy-testcase branch from 7c16b3e to 10352e7 Compare July 14, 2026 11:32

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

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

Inline comments:
In `@test/extended-priv/mco_network_policies.go`:
- Around line 74-77: Replace broad HaveOccurred assertions in both
network-policy checks at test/extended-priv/mco_network_policies.go lines 74-77
and 91-94 with validation that the connection fails specifically due to a
timeout, or expose a real listener on the test pod for the port-8080 check and
retain equivalent timeout validation. Ensure both tests cannot pass because the
target port is merely closed or refuses connections.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Enterprise

Run ID: d133fa09-4ae2-4bcc-8f18-4dc52239258c

📥 Commits

Reviewing files that changed from the base of the PR and between 7c16b3e and 10352e7.

📒 Files selected for processing (2)
  • test/extended-priv/mco_network_policies.go
  • test/extended-priv/resource.go

Comment on lines +74 to +77
// Try to reach test pod from MCC (should fail due to default-deny ingress block)
_, err = exutil.RemoteShContainer(oc.AsAdmin(), MachineConfigNamespace, mccPodName, "machine-config-controller", "wget", "-q", "-O-", "--timeout=5", fmt.Sprintf("http://%s:8080", testPodIP))
o.Expect(err).To(o.HaveOccurred(), "MCC pod should not be able to reach test pod due to default-deny")
logger.Infof("OK!\n")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

NetworkPolicy assertions are false positives due to broad error matching on closed ports. Both of these tests intend to verify that a NetworkPolicy drops traffic, but because they use o.Expect(err).To(o.HaveOccurred()), they will pass on any connection failure, including "Connection refused" when a port is closed. The target ports are not actually accessible (the test pod has no listener on 8080, and the MCC pod only binds 8797 to 127.0.0.1), so these tests will pass even if the NetworkPolicy is completely missing.

  • test/extended-priv/mco_network_policies.go#L74-L77: run a listener on the test pod (e.g., a simple python/nc server instead of sleep 36000), or explicitly assert that err contains a connection timeout message rather than "Connection refused".
  • test/extended-priv/mco_network_policies.go#L91-L94: assert that the error is specifically a timeout. Since 8797 is bound to 127.0.0.1, you should either pick a port exposed on the Pod IP or rely on the timeout string so the test doesn't pass for the wrong reason.
📍 Affects 1 file
  • test/extended-priv/mco_network_policies.go#L74-L77 (this comment)
  • test/extended-priv/mco_network_policies.go#L91-L94
🤖 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-priv/mco_network_policies.go` around lines 74 - 77, Replace
broad HaveOccurred assertions in both network-policy checks at
test/extended-priv/mco_network_policies.go lines 74-77 and 91-94 with validation
that the connection fails specifically due to a timeout, or expose a real
listener on the test pod for the port-8080 check and retain equivalent timeout
validation. Ensure both tests cannot pass because the target port is merely
closed or refuses connections.

@openshift-ci

openshift-ci Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

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

logger "github.com/openshift/machine-config-operator/test/extended-priv/util/logext"
)

var _ = g.Describe("[sig-mco][Suite:openshift/machine-config-operator/security][Serial][Disruptive] MCO Network Policies", func() {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Where's our openshift/machine-config-operator/security suite?

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.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants