Skip to content

[ROSAENG-61345] harden NetworkPolicy ingress to pod-label selectors fo… - #326

Open
charlesgong wants to merge 1 commit into
openshift:masterfrom
charlesgong:ROSAENG-61345
Open

[ROSAENG-61345] harden NetworkPolicy ingress to pod-label selectors fo…#326
charlesgong wants to merge 1 commit into
openshift:masterfrom
charlesgong:ROSAENG-61345

Conversation

@charlesgong

@charlesgong charlesgong commented Aug 10, 2026

Copy link
Copy Markdown

What type of PR is this?

bug / security hardening

What this PR does / why we need it?

Extends callerPodSelector in ocmagenthandler_networkpolicy.go to cover the RHOBS (observatorium-mst-production) and OBO (openshift-observability-operator) fleet-mode namespaces with combined namespace + pod-label selectors.

Previously, only openshift-monitoring (Alertmanager) and openshift-managed-upgrade-operator (MUO) had pod-level selectors. The RHOBS and OBO NetworkPolicies used namespace-only selectors, meaning any pod running in those namespaces could reach the ocm-agent HTTP API and trigger privileged OCM state-change calls — a confused-deputy gap.

With this change, all four permitted caller namespaces use a combined NamespaceSelector + PodSelector in their ingress peer, so only the specific caller pods (not any pod in the namespace) can reach the agent.

Also adds:

  • Constants for RHOBS and OBO pod label key/value pairs (values marked TODO for cluster verification before merge)
  • Missing unit test coverage for MUO, RHOBS, and OBO pod selector assertions

Which Jira/Github issue(s) this PR fixes?

ROSAENG-61345

Special notes for your reviewer:

The RHOBSPodLabelValue and OBOPodLabelValue constants in pkg/consts/ocmagenthandler/ocmagenthandler.go are marked TODO and must be verified against a live fleet-mode cluster before this PR is merged:
oc get pods -n observatorium-mst-production --show-labels
oc get pods -n openshift-observability-operator --show-labels

No changes to the agent HTTP stack or caller configuration — this is a NetworkPolicy-only change confined to ocm-agent-operator.

Pre-checks (if applicable):

  • Tested latest changes against a cluster
  • Ran make generate command locally to validate code changes
  • Included documentation changes with PR

Summary by CodeRabbit

  • Security Enhancements

    • Network policies now restrict ingress to verified caller workloads within known namespaces.
    • Unknown namespaces continue to use namespace-based access controls.
    • Fleet-mode agent connectivity is covered by the updated policy behavior.
    • Access controls now consistently identify supported monitoring and alerting workloads.
  • Tests

    • Added coverage for monitoring, managed upgrade, RHOBS, and OBO workload selectors.
    • Verified policy behavior for both standard and fleet-mode configurations.

@openshift-ci
openshift-ci Bot requested review from Tafhim and vaidehi411 August 10, 2026 02:13
@openshift-ci

openshift-ci Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: charlesgong

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

coderabbitai Bot commented Aug 10, 2026

Copy link
Copy Markdown

Important

Review available on request

  • 🔍 Trigger review

Reviews should be triggered manually for repositories with fewer than 10 stars. Select Trigger review above or comment @coderabbitai review to review the latest changes. For a full review, comment @coderabbitai full review.

⚙️ Run configuration

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

Review profile: CHILL

Plan: Pro Plus

Run ID: d93554e7-ec49-45c8-8496-80bc89e1db44

Walkthrough

The change adds exported pod-label constants and applies namespace-specific caller pod selectors to generated NetworkPolicies. Tests cover monitoring, managed-upgrade-operator, RHOBS, and OBO namespaces, including fleet-mode agents. The Tekton pipeline reference also changes.

Changes

NetworkPolicy caller selection

Layer / File(s) Summary
Selector contract and policy wiring
pkg/consts/ocmagenthandler/ocmagenthandler.go, pkg/ocmagenthandler/ocmagenthandler_networkpolicy.go
Adds pod-label constants and maps supported namespaces to caller pod selectors. NetworkPolicy ingress peers combine namespace and caller pod selectors.
Selector validation
pkg/ocmagenthandler/ocmagenthandler_networkpolicy_test.go
Tests caller pod selectors for monitoring, MUO, RHOBS, and OBO namespaces, including fleet-mode agents.

Tekton pipeline revision

Layer / File(s) Summary
Boilerplate repository reference
.tekton/ocm-agent-operator-agentic-sdlc-check-pull-request.yaml
Updates the Tekton Git resolver revision.

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

Suggested reviewers: tafhim, vaidehi411

🚥 Pre-merge checks | ✅ 14 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Test Structure And Quality ⚠️ Warning The MUO, RHOBS, and OBO Its use assertions without meaningful failure messages (lines 87-88, 100-101, and 113-114). Add diagnostic messages to the new selector assertions, such as identifying the expected namespace and pod label key/value.
✅ Passed checks (14 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: hardening NetworkPolicy ingress with pod-label selectors.
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 All seven added Ginkgo titles are fixed string literals; they contain no generated names, timestamps, UUIDs, node names, IPs, or interpolated values.
Microshift Test Compatibility ✅ Passed The added Ginkgo cases are package unit tests using mocks and in-memory NetworkPolicy objects; no e2e tests or MicroShift-incompatible API calls were added.
Single Node Openshift (Sno) Test Compatibility ✅ Passed Added Ginkgo cases are unit tests in pkg/ocmagenthandler using mocks and local NetworkPolicy objects; no new e2e tests or multi-node/HA assumptions were found.
Topology-Aware Scheduling Compatibility ✅ Passed The PR changes only NetworkPolicy selectors, label constants, tests, and Tekton metadata; it introduces no replicas, affinity, topology spread, node selectors, tolerations, or PDB constraints.
Ote Binary Stdout Contract ✅ Passed The pull request changes only NetworkPolicy constants, selectors, tests, and Tekton metadata; it adds no OTE process-level stdout writes.
Ipv6 And Disconnected Network Test Compatibility ✅ Passed The added Ginkgo cases are unit tests using mocked clients and static NetworkPolicy selectors; they contain no IPv4 assumptions or external connectivity.
No-Weak-Crypto ✅ Passed Commit c7b1034 adds only pod-label constants, NetworkPolicy selectors, and tests; scans found no MD5, SHA1, DES, RC4, Blowfish, ECB, custom crypto, or secret comparisons.
Container-Privileges ✅ Passed The PR adds NetworkPolicy selectors, constants, tests, and a Tekton reference only; scans found no privileged:true, host* flags, SYS_ADMIN, allowPrivilegeEscalation:true, or root settings.
No-Sensitive-Data-In-Logs ✅ Passed The PR adds selectors, constants, tests, and pipeline metadata only; the aggregate diff adds no logging calls or log arguments that could expose sensitive data.
✨ 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.

@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)
pkg/ocmagenthandler/ocmagenthandler_networkpolicy_test.go (2)

85-89: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Cover both selectors and the fallback branch.

The MUO, RHOBS, and OBO cases assert only PodSelector. Also assert that NamespaceSelector matches testNamespace in each case. Add a case that verifies callerPodSelector returns nil for an unsupported namespace and that the policy keeps namespace-only behavior.

As per coding guidelines, unit tests are required for all new functions and should prioritize meaningful coverage over metric-only coverage.

Also applies to: 98-102, 111-115

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

In `@pkg/ocmagenthandler/ocmagenthandler_networkpolicy_test.go` around lines 85 -
89, Expand the network policy tests for the MUO, RHOBS, and OBO cases to assert
each ingress rule’s NamespaceSelector matches testNamespace in addition to
PodSelector. Add coverage for callerPodSelector with an unsupported namespace,
verifying it returns nil and the resulting policy preserves namespace-only
ingress behavior.

Source: Coding guidelines


69-73: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add diagnostic messages to the new assertions.

The added Expect calls do not include failure messages. Add messages that identify the namespace and expected selector so a failure states which ingress contract broke.

As per coding guidelines, assertion messages must include meaningful failure messages.

Also applies to: 75-77, 85-89, 98-102, 111-115

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

In `@pkg/ocmagenthandler/ocmagenthandler_networkpolicy_test.go` around lines 69 -
73, Add meaningful failure messages to every new Expect assertion in the ingress
network policy tests, including the block “Should restrict ingress to
alertmanager pods in the monitoring namespace” and the referenced assertion
ranges. Messages must identify the monitoring namespace, ingress contract, and
expected pod selector or label values so failures clearly indicate what was
violated.

Source: Coding guidelines

🤖 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 `@pkg/ocmagenthandler/ocmagenthandler_networkpolicy_test.go`:
- Around line 85-89: Expand the network policy tests for the MUO, RHOBS, and OBO
cases to assert each ingress rule’s NamespaceSelector matches testNamespace in
addition to PodSelector. Add coverage for callerPodSelector with an unsupported
namespace, verifying it returns nil and the resulting policy preserves
namespace-only ingress behavior.
- Around line 69-73: Add meaningful failure messages to every new Expect
assertion in the ingress network policy tests, including the block “Should
restrict ingress to alertmanager pods in the monitoring namespace” and the
referenced assertion ranges. Messages must identify the monitoring namespace,
ingress contract, and expected pod selector or label values so failures clearly
indicate what was violated.

ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Pro Plus

Run ID: 976491ab-b2aa-4f86-9b07-5beac5b64db9

📥 Commits

Reviewing files that changed from the base of the PR and between 6f8340c and c7b1034.

📒 Files selected for processing (3)
  • pkg/consts/ocmagenthandler/ocmagenthandler.go
  • pkg/ocmagenthandler/ocmagenthandler_networkpolicy.go
  • pkg/ocmagenthandler/ocmagenthandler_networkpolicy_test.go

@codecov-commenter

codecov-commenter commented Aug 10, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 65.31%. Comparing base (6f8340c) to head (a5b78d0).

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##           master     #326      +/-   ##
==========================================
+ Coverage   65.03%   65.31%   +0.28%     
==========================================
  Files          23       23              
  Lines        1570     1583      +13     
==========================================
+ Hits         1021     1034      +13     
  Misses        471      471              
  Partials       78       78              
Files with missing lines Coverage Δ
pkg/consts/ocmagenthandler/ocmagenthandler.go 100.00% <ø> (ø)
...g/ocmagenthandler/ocmagenthandler_networkpolicy.go 77.39% <100.00%> (+2.88%) ⬆️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@openshift-ci openshift-ci Bot added needs-rebase Indicates a PR cannot be merged because it has merge conflicts with HEAD. and removed needs-rebase Indicates a PR cannot be merged because it has merge conflicts with HEAD. labels Aug 10, 2026
Comment thread pkg/consts/ocmagenthandler/ocmagenthandler.go
Comment thread pkg/consts/ocmagenthandler/ocmagenthandler.go
MatchLabels: map[string]string{"kubernetes.io/metadata.name": namespace},
},
}
if podSelector := callerPodSelector(namespace); podSelector != nil {

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.

There's no condition nil, are we going to allow it? What happens if the podSelector is nil? i feel only NamespaceSelector enforced and podSelector is more like permissive mode.

…r fleet namespaces

Extend callerPodSelector to cover NamespaceRHOBS and NamespaceOBO so that
fleet-mode NetworkPolicies use combined namespace+pod selectors instead of
namespace-only selectors. This eliminates the residual confused-deputy gap
where any pod in the permitted namespace could reach the ocm-agent HTTP API.

Adds constants for MUO/RHOBS/OBO pod labels and fills in test coverage for
MUO, RHOBS, and OBO pod selector assertions.

Review fixes:
- OBOPodLabelValue corrected from "main" to "hypershift-monitoring-stack",
  confirmed via: oc get po -n openshift-observability-operator -l
  alertmanager=hypershift-monitoring-stack. RHOBSPodLabelValue is left
  pending cluster verification (open review thread).
- callerPodSelector no longer has a silent nil fallback: an ingress peer
  with only NamespaceSelector matches every pod in that namespace, so a
  nil podSelector for an unhandled namespace would silently defeat the
  pod-level restriction this policy is meant to enforce. Unhandled
  namespaces now panic (programming error) instead of degrading to a
  namespace-wide policy; added a regression test for this.
- Refreshed the UBI9 minimal base image tag (9.8-1786927599) via
  `make boilerplate-update` to satisfy boilerplate's live generate-check.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@openshift-ci

openshift-ci Bot commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

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

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.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants