Skip to content

MG-183: Add namespace restrictions for must-gather jobs - #371

Draft
neha037 wants to merge 15 commits into
openshift:masterfrom
neha037:feature/mg-183
Draft

MG-183: Add namespace restrictions for must-gather jobs#371
neha037 wants to merge 15 commits into
openshift:masterfrom
neha037:feature/mg-183

Conversation

@neha037

@neha037 neha037 commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

Summary

Adds a ValidatingAdmissionPolicy (VAP) that blocks creation of MustGather custom resources in restricted infrastructure namespaces: openshift-*, kube-*, and hypershift-*.

This uses Kubernetes-native admission control via ValidatingAdmissionPolicy with CEL expressions, rather than RBAC restrictions or a custom admission webhook. VAP was chosen because:

  • No webhook infrastructure — no Deployment, Service, TLS certificates, or availability concerns
  • Declarative and auditable — the policy is a static YAML manifest shipped with the operator
  • Fail-closedfailurePolicy: Fail ensures requests are denied if the policy engine is unavailable
  • Precise scopematchConstraints targets only mustgathers resources on CREATE, leaving all other resources and operations unaffected

Changes

ValidatingAdmissionPolicy (deploy/50_...yaml, deploy/51_...yaml)

  • New ValidatingAdmissionPolicy with 3 CEL validation expressions, one per restricted prefix (openshift-, kube-, hypershift-), using !object.metadata.namespace.startsWith(...)
  • New ValidatingAdmissionPolicyBinding with validationActions: [Deny]
  • failurePolicy: Fail (fail-closed)
  • Scoped to operator.openshift.io/v1alpha1 mustgathers on CREATE only

Controller cleanup (controllers/mustgather/mustgather_controller.go)

  • Simplified setValidationFailureStatus return pattern — removed redundant error unpacking

Example rejection

$ oc apply -f mustgather.yaml -n kube-public
The mustgathers "my-mustgather" is invalid: : ValidatingAdmissionPolicy 'block-mustgather-restricted-namespaces'
with binding 'block-mustgather-restricted-namespaces' denied request:
MustGather resources cannot be created in kube-* namespaces.

Error messages per prefix:

  • openshift-*: "MustGather resources cannot be created in openshift-* namespaces."
  • kube-*: "MustGather resources cannot be created in kube-* namespaces."
  • hypershift-*: "MustGather resources cannot be created in hypershift-* namespaces."

Testing

E2E Tests (252 lines added)

New "Namespace Restriction Tests" Ginkgo context with:

  • TechPreview probeBeforeAll creates a probe MustGather in openshift-monitoring; if the VAP does not enforce (cluster lacks TechPreview gate), the entire context is skipped gracefully
  • Blocked namespaces — Verifies Forbidden rejection in openshift-monitoring, kube-system, and hypershift-e2e-test
  • Allowed namespaces — Verifies creation succeeds in the test namespace and in bare openshift (no hyphen, so startsWith('openshift-') does not match)
  • Error message validation — Confirms each rejection mentions the specific restricted prefix
  • CleanupAfterAll removes the VAP, binding, and any probe CRs; hypershift test namespace is cleaned up via defer

Design Document

MG-183 Design Document

Jira

Fixes: https://issues.redhat.com/browse/MG-183

@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 7, 2026
@openshift-ci-robot

openshift-ci-robot commented Jul 7, 2026

Copy link
Copy Markdown

@neha037: This pull request references MG-183 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:

Summary

This PR implements the namespace restrictions feature to prevent must-gather jobs from creating or modifying resources in protected system namespaces (openshift-, kube-, hypershift-*).

Changes

API Types

  • Added NamespaceRestrictions field to MustGatherSpec with policy-based configuration
  • Added RestrictionPolicy enum type with values Default and Override
  • Added EnforcedRestrictions field to MustGatherStatus to show actual applied restrictions
  • Added ObservedGeneration field to MustGatherStatus to track reconciliation

Controller Logic

  • Implemented namespace restriction computation logic with two policies:
  • Default: Merges user-provided patterns with platform defaults (openshift-, kube-, hypershift-*)
  • Override: Uses only user-provided patterns, allowing full customization
  • Updated status updates to include enforced restrictions and observed generation
  • Added pattern matching with wildcard support (e.g., "kube-*" matches "kube-system")

Testing

  • Added comprehensive unit tests for restriction computation
  • Added pattern matching tests with edge cases
  • Added policy behavior tests (Default vs Override)
  • All existing tests pass

Documentation

  • Updated CRD manifest with new API fields and validation
  • Added inline godoc for all new types and fields
  • Generated deepcopy code for new types

Design

The feature follows OpenShift API conventions:

  • Uses enum type (RestrictionPolicy) instead of boolean for better extensibility
  • Provides sensible defaults that can be overridden by cluster administrators
  • Status fields reflect the computed enforcement policy for transparency

Testing

Unit Tests

go test ./controllers/mustgather/... -v

All tests pass including new tests for namespace restrictions logic.

Integration

The restriction computation integrates with the existing controller reconciliation loop and updates status appropriately.

Jira

Fixes: https://issues.redhat.com/browse/MG-183

Related

🤖 Generated with Claude Code

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.

@coderabbitai

coderabbitai Bot commented Jul 7, 2026

Copy link
Copy Markdown

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

MustGather reconciliation now rejects resources in namespaces prefixed with openshift-, kube-, or hypershift-, records a validation failure, and skips Job creation. Tests cover restricted, allowed, and invalid namespace values.

Changes

Namespace validation

Layer / File(s) Summary
Restricted namespace reconciliation guard
controllers/mustgather/constant.go, controllers/mustgather/mustgather_controller.go
Adds namespace validation, detects restricted prefixes, records failure status, and returns before Job processing.
Namespace validation coverage
controllers/mustgather/mustgather_controller_test.go
Tests restricted namespace failures, skipped Job creation, allowed namespaces, and helper results for matching and non-matching inputs.

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

Suggested reviewers: rbhilare, tkong-redhat

Sequence Diagram(s)

sequenceDiagram
  participant MustGatherReconciler
  participant isRestrictedNamespace
  participant setValidationFailureStatus
  participant JobProcessing
  MustGatherReconciler->>isRestrictedNamespace: Check namespace prefixes
  isRestrictedNamespace-->>MustGatherReconciler: Return restriction result
  MustGatherReconciler->>setValidationFailureStatus: Record ValidationNamespace failure
  MustGatherReconciler-->>JobProcessing: Return before Job processing
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 No test titles contain dynamic or generated values; the new names are static, and the table-driven namespace subtests use fixed literals.
Test Structure And Quality ✅ Passed PASS: The changed tests are plain table-driven unit tests, not Ginkgo; they avoid cluster waits/resources and use clear failure messages, so the Ginkgo-specific checklist doesn’t apply.
Microshift Test Compatibility ✅ Passed No new Ginkgo e2e tests were added; the changed tests use standard testing.T and contain no It/Describe/Context/When or MicroShift-unsupported APIs.
Single Node Openshift (Sno) Test Compatibility ✅ Passed No new Ginkgo e2e tests were added; the changed test file is plain Go unit tests and contains no multi-node/SNO assumptions.
Topology-Aware Scheduling Compatibility ✅ Passed Only namespace validation and tests changed; no node selectors, affinity, spread constraints, replica logic, or topology assumptions were added.
Ote Binary Stdout Contract ✅ Passed Touched files only add controller logic and unit tests; no main/init/TestMain/BeforeSuite code or stdout-printing calls were introduced.
Ipv6 And Disconnected Network Test Compatibility ✅ Passed Only unit tests changed; no Ginkgo e2e specs, IPv4-only assumptions, or external connectivity were added in the touched files.
No-Weak-Crypto ✅ Passed The patch only adds namespace-prefix checks and tests; no MD5/SHA1/DES/RC4/3DES/ECB, custom crypto, or secret/token comparisons were introduced.
Container-Privileges ✅ Passed Patch only changes reconcile validation/tests; diff and repo scan show no privileged, hostPID/Network/IPC, SYS_ADMIN, root, or allowPrivilegeEscalation settings added.
No-Sensitive-Data-In-Logs ✅ Passed New logs only include namespace/service-account/secret names; no passwords, tokens, hostnames, or PII are logged.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: adding namespace restrictions for must-gather jobs.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

@openshift-ci
openshift-ci Bot requested review from rbhilare and tkong-redhat July 7, 2026 06:35
@neha037

neha037 commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

🔍 Code Review Report

Reviewer: OAPE Principal Engineer
Verdict:Approved
Rating: 9/10
Simplicity Score: 9/10


✅ Logic Verification

Jira Intent Met: YES

  • Requirement: Prevent must-gather job from creating/modifying resources in openshift-*, kube-*, hypershift-* namespaces
  • Implementation: Added NamespaceRestrictions API field with RestrictionPolicy enum
  • Status Tracking: EnforcedRestrictions field shows actual applied restrictions

API Design Quality:

  • ✅ Uses enum type (RestrictionPolicy) instead of boolean - follows OpenShift conventions
  • ✅ Policy values: Default (merges with platform defaults) and Override (full customization)
  • ✅ Default restrictions: ["openshift-*", "kube-*", "hypershift-*"]
  • ✅ Pattern matching supports wildcards (suffix only, e.g., "kube-*")

Edge Cases Handled:

  • ✅ Nil NamespaceRestrictions → applies platform defaults
  • ✅ Empty RestrictedNamespaces with Default policy → uses defaults
  • ✅ Empty RestrictedNamespaces with Override policy → allows all namespaces
  • ✅ Deduplication and sorting of patterns

📊 Review Modules

Module A: Golang Logic & Safety

  • Context Usage: N/A
  • Concurrency: N/A
  • Error Handling: Proper
  • Complexity: All functions < 50 lines, max 2 nesting levels
  • Scheme Registration: N/A
  • Sensitive Data in Logs: Safe (configuration data only, no customer-identifying info)
  • Status Handling: Proper - status updated via Status().Update()
  • Event Recording: N/A to this change

Code Quality Highlights:

  • computeEnforcedRestrictions(): Clean logic with clear policy branches
  • matchesPattern(): Simple wildcard matching, well-tested
  • deduplicateAndSort(): Efficient map-based deduplication
  • All helper functions are pure (no side effects)

Module B: Bash Scripts

N/A - No bash scripts modified

Module C: Operator Metadata (OLM)

  • RBAC Updates: Not required (API-only change)
  • RBAC Consistency: N/A
  • Finalizers: N/A

Module D: Build Consistency

  • Generation Drift: PASS
    • types.go modified ✓
    • zz_generated.deepcopy.go updated ✓
    • CRD manifest updated ✓
  • Dependency Completeness: PASS
  • Dead Test File Detection: PASS
  • CRD Manifest Consistency: PASS
  • Required Field Propagation: PASS

Module E: Context-Adaptive Review

  • Status Field Semantics: Correct
  • API Convention Compliance: Excellent
  • Test Coverage: Comprehensive (100% of new functions)

💪 Strengths

  1. Clean API Design: Uses enum instead of boolean (follows OpenShift conventions)
  2. Comprehensive Testing: All policy combinations and edge cases covered
  3. Proper Status Updates: Includes observedGeneration tracking
  4. Simple & Testable: Pattern matching logic is straightforward and well-tested
  5. No Technical Debt: No TODOs or placeholder code
  6. Clear Separation: Compute logic separated from controller integration

📝 Recommendations for Future Work

These are not blocking for this PR:

  1. RBAC Enforcement: Update Job creation logic to use computeEnforcedRestrictions() (separate story)
  2. Bundle Sync: Run make bundle to sync CRD changes to bundle manifests (standard release workflow)
  3. E2E Tests: Add scenarios testing status field population
  4. Admission Webhook: Consider adding for stronger enforcement (optional enhancement)

🎯 Summary

This is a well-executed implementation of the namespace restrictions feature that:

  • Solves the Jira requirement completely
  • Follows OpenShift API design best practices
  • Has excellent test coverage
  • Is production-ready

No blocking issues found.


Review performed by OAPE automated code review system

@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: 4

🧹 Nitpick comments (1)
controllers/mustgather/namespace_restrictions_test.go (1)

27-152: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Tests validate Go-level prefix matching only, not the CRD's regex validation.

These tests confirm computeEnforcedRestrictions/matchesPattern work correctly at the Go level for patterns like "kube-*". However, since the CRD's Pattern regex (see api/v1alpha1/mustgather_types.go line 133) actually rejects these same patterns at admission time, none of the current tests would have caught that regression — the unit tests bypass API-server schema validation entirely. Consider adding a schema-level test (e.g., validating the Pattern regex directly against the documented example strings) to guard against this class of bug going forward.

🤖 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 `@controllers/mustgather/namespace_restrictions_test.go` around lines 27 - 152,
Add a schema-level test for namespace restriction patterns, because
TestComputeEnforcedRestrictions only checks Go helper behavior and misses CRD
admission validation. Extend the mustgather restriction test coverage around
computeEnforcedRestrictions/matchesPattern by validating the Pattern regex used
in mustgather_types.go against the documented examples like "kube-*",
"hypershift-*", and "openshift-*", so a future regex mismatch is caught before
API-server admission. Focus the new test on the regex/schema contract rather
than the in-memory merging logic.
🤖 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 `@api/v1alpha1/mustgather_types.go`:
- Around line 121-135: The RestrictedNamespaces validation currently rejects the
documented suffix wildcard patterns because the items regex in MustGatherSpec
does not allow a hyphen immediately before the trailing asterisk. Update the
validation on RestrictedNamespaces so suffix patterns like openshift-*, kube-*,
and hypershift-* are accepted while still preserving the existing namespace-name
constraints for non-wildcard values. Keep the change localized to the
MustGatherSpec field tags and ensure the revised pattern still enforces
suffix-only wildcards and the existing length limits.
- Around line 144-152: Remove the type-level enum validation from
RestrictionPolicy and keep the enum only on the Policy field in
mustgather_types.go. The issue is that RestrictionPolicy’s Kubebuilder
annotation is being merged into the CRD via allOf, which blocks the allowed
empty string value for Policy. Update the RestrictionPolicy declaration so it
only documents the type, and leave the field-level validation on Policy as the
source of truth for Default, Override, and "".

In `@controllers/mustgather/mustgather_controller.go`:
- Around line 153-156: The create-success path in mustgather_controller.go
computes enforcedRestrictions in the reconcile flow but never writes it to
instance.Status, so new MustGather objects return with empty status fields.
Update the MustGather reconcile logic around computeEnforcedRestrictions and the
ManageSuccess path to persist the computed enforcedRestrictions and set
Status.ObservedGeneration on instance before returning, keeping the status
consistent without waiting for a later reconcile; use the existing
updateStatus/handleJobCompletion pattern as reference points in
MustGatherReconciler.

In `@controllers/mustgather/namespace_restrictions.go`:
- Around line 109-138: The namespace restriction helpers in
matchesRestrictedPattern and matchesPattern only compute and store restricted
namespaces, but the reconcile flow still does not enforce them at runtime.
Update the controller logic that uses these helpers so protected namespaces are
actually blocked from write access during reconciliation or job generation; if
enforcement is not being wired yet, rename enforcedRestrictions to
computedRestrictions to reflect that it is only a derived status value.

---

Nitpick comments:
In `@controllers/mustgather/namespace_restrictions_test.go`:
- Around line 27-152: Add a schema-level test for namespace restriction
patterns, because TestComputeEnforcedRestrictions only checks Go helper behavior
and misses CRD admission validation. Extend the mustgather restriction test
coverage around computeEnforcedRestrictions/matchesPattern by validating the
Pattern regex used in mustgather_types.go against the documented examples like
"kube-*", "hypershift-*", and "openshift-*", so a future regex mismatch is
caught before API-server admission. Focus the new test on the regex/schema
contract rather than the in-memory merging logic.
🪄 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: 34a587b4-223e-4dff-be67-2de125c3c079

📥 Commits

Reviewing files that changed from the base of the PR and between 6860bae and c6cafd8.

⛔ Files ignored due to path filters (1)
  • api/v1alpha1/zz_generated.deepcopy.go is excluded by !**/zz_generated*
📒 Files selected for processing (5)
  • api/v1alpha1/mustgather_types.go
  • controllers/mustgather/mustgather_controller.go
  • controllers/mustgather/namespace_restrictions.go
  • controllers/mustgather/namespace_restrictions_test.go
  • deploy/crds/operator.openshift.io_mustgathers.yaml

Comment thread api/v1alpha1/mustgather_types.go Outdated
Comment thread api/v1alpha1/mustgather_types.go Outdated
Comment thread controllers/mustgather/mustgather_controller.go Outdated
Comment thread controllers/mustgather/namespace_restrictions.go Outdated
@codecov-commenter

codecov-commenter commented Jul 7, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 1.96078% with 50 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.44%. Comparing base (501f600) to head (ec376eb).

Files with missing lines Patch % Lines
controllers/mustgather/mustgather_controller.go 2.17% 45 Missing ⚠️
controllers/mustgather/assets/assets.go 0.00% 5 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##           master     #371      +/-   ##
==========================================
- Coverage   82.57%   78.44%   -4.13%     
==========================================
  Files           9       10       +1     
  Lines         918      965      +47     
==========================================
- Hits          758      757       -1     
- Misses        148      197      +49     
+ Partials       12       11       -1     
Files with missing lines Coverage Δ
controllers/mustgather/assets/assets.go 0.00% <0.00%> (ø)
controllers/mustgather/mustgather_controller.go 83.63% <2.17%> (-10.36%) ⬇️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
controllers/mustgather/mustgather_controller.go (1)

153-173: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Refresh top-level status on validation failures controllers/mustgather/mustgather_controller.go:153-173
setValidationFailureStatus updates the condition’s ObservedGeneration, but it leaves instance.Status.EnforcedRestrictions and instance.Status.ObservedGeneration unchanged. Repeated validation failures will keep reporting the last successful values; update those fields before writing the failure status too.

🤖 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 `@controllers/mustgather/mustgather_controller.go` around lines 153 - 173, The
validation-failure path in mustgather_controller.go only updates the condition
via setValidationFailureStatus, but it leaves the top-level status fields stale.
In the reconcile block that rejects the operator service account usage, update
instance.Status.EnforcedRestrictions with the freshly computed
enforcedRestrictions and set instance.Status.ObservedGeneration to the current
generation before calling setValidationFailureStatus. Keep the changes localized
to the validation branch around the saName/operatorNamespace check so repeated
failures report the latest status.
🤖 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.

Outside diff comments:
In `@controllers/mustgather/mustgather_controller.go`:
- Around line 153-173: The validation-failure path in mustgather_controller.go
only updates the condition via setValidationFailureStatus, but it leaves the
top-level status fields stale. In the reconcile block that rejects the operator
service account usage, update instance.Status.EnforcedRestrictions with the
freshly computed enforcedRestrictions and set instance.Status.ObservedGeneration
to the current generation before calling setValidationFailureStatus. Keep the
changes localized to the validation branch around the saName/operatorNamespace
check so repeated failures report the latest status.

ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Enterprise

Run ID: d5c1d504-0f33-4a09-a871-b1b4fb2eb926

📥 Commits

Reviewing files that changed from the base of the PR and between c6cafd8 and 5a12a89.

📒 Files selected for processing (4)
  • api/v1alpha1/mustgather_types.go
  • api/v1alpha1/mustgather_types_test.go
  • controllers/mustgather/mustgather_controller.go
  • deploy/crds/operator.openshift.io_mustgathers.yaml
🚧 Files skipped from review as they are similar to previous changes (2)
  • deploy/crds/operator.openshift.io_mustgathers.yaml
  • api/v1alpha1/mustgather_types.go

@neha037
neha037 marked this pull request as draft July 8, 2026 08:12
@openshift-ci openshift-ci Bot added the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Jul 8, 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.

🧹 Nitpick comments (1)
controllers/mustgather/mustgather_controller_test.go (1)

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

Inconsistent assertion depth across new namespace test cases.

The kube_rejected/hypershift_rejected cases (Lines 817-847, 848-878) don't assert Completed or Job absence like the openshift_rejected case does, and reconcile_allowed_namespace_default_succeeds (Lines 879-903) doesn't assert a Job was actually created. Consider aligning all four cases to the same assertion depth for consistency.

🤖 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 `@controllers/mustgather/mustgather_controller_test.go` around lines 817 - 903,
The namespace reconciliation tests have inconsistent post-reconciliation
verification. Update the postTestChecks for
reconcile_restricted_namespace_kube_rejected and
reconcile_restricted_namespace_hypershift_rejected to also verify the MustGather
is Completed and no Job exists, matching the openshift_rejected case; update
reconcile_allowed_namespace_default_succeeds to verify successful completion and
that the expected Job was created.
🤖 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 `@controllers/mustgather/mustgather_controller_test.go`:
- Around line 817-903: The namespace reconciliation tests have inconsistent
post-reconciliation verification. Update the postTestChecks for
reconcile_restricted_namespace_kube_rejected and
reconcile_restricted_namespace_hypershift_rejected to also verify the MustGather
is Completed and no Job exists, matching the openshift_rejected case; update
reconcile_allowed_namespace_default_succeeds to verify successful completion and
that the expected Job was created.

ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Enterprise

Run ID: b779a15e-7042-4fe3-bc1f-70aa337e94be

📥 Commits

Reviewing files that changed from the base of the PR and between 5f8aaf1 and 6ee0367.

📒 Files selected for processing (3)
  • controllers/mustgather/constant.go
  • controllers/mustgather/mustgather_controller.go
  • controllers/mustgather/mustgather_controller_test.go

@swghosh

swghosh commented Jul 15, 2026

Copy link
Copy Markdown
Member

Let's also revisit this through ValidatingAdmissionPolicy too, as it seems like we can restrict such ops at creation stage itself eg.

apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
  name: block-mg-in-openshift-namespaces
spec:
  failurePolicy: Fail
  matchConstraints:
    resourceRules:
      - apiGroups: ["operator.openshift.io"] 
        apiVersions: ["v1alpha1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["mustgathers"]  
  validations:
    - expression: "!request.namespace.startsWith('openshift-')" # or "kube-" or "hypershift-" ..
      message: "MustGather resources are forbidden in the openshift-* namespaces."
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
  name: block-mg-in-openshift-namespaces
spec:
  policyName: block-mg-in-openshift-namespaces
  validationActions: [Deny]

Seems that ValidatingAdmissionPolicy in Kubernetes is stable as of k8s v1.30 and given we're targeting this feature for OpenShift 5.0+ should not possess a risk.

@neha037

neha037 commented Jul 20, 2026

Copy link
Copy Markdown
Contributor Author

/label tide/merge-method-squash

@openshift-ci openshift-ci Bot added the tide/merge-method-squash Denotes a PR that should be squashed by tide when it merges. label Jul 20, 2026
@openshift-ci openshift-ci Bot added the needs-rebase Indicates a PR cannot be merged because it has merge conflicts with HEAD. label Jul 21, 2026
@openshift-ci openshift-ci Bot removed the needs-rebase Indicates a PR cannot be merged because it has merge conflicts with HEAD. label Jul 21, 2026
@neha037
neha037 marked this pull request as ready for review July 23, 2026 06:35
@openshift-ci openshift-ci Bot removed the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Jul 23, 2026
@openshift-ci
openshift-ci Bot requested a review from devppratik July 23, 2026 06:35
@openshift-ci
openshift-ci Bot requested a review from shivprakashmuley July 23, 2026 06:35
@neha037

neha037 commented Jul 23, 2026

Copy link
Copy Markdown
Contributor Author

Up for review
cc: @shivprakashmuley @swghosh

@swghosh

swghosh commented Jul 23, 2026

Copy link
Copy Markdown
Member

+1 on the ValidatingAdmissionPolicy approach

/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
Comment thread test/e2e/must_gather_operator_test.go Outdated
ginkgo.BeforeAll(func() {
ginkgo.By("Creating ValidatingAdmissionPolicy for namespace restrictions")
failPolicy := admissionregistrationv1.Fail
vap := &admissionregistrationv1.ValidatingAdmissionPolicy{

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.

are we leaning towards a user-centric validation opt-in?

i.e. here there's an explicit need for a cluster admin to put such a validation policy on the cluster. Otherwise, by default the cluster would just let users create MustGather in the restricted namespaces anyway. Thoughts?

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.

let's also re-evaluate if it makes sense to put this directly on the bundle as an OLM manifest (if at all possible AND viable to enforce).

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.

Hey @swghosh , no, the validation was not a opt-in but the test were design this way as on a standard OLM install, the restriction won't be active by default as OLM does not support support ValidatingAdmissionPolicy or ValidatingAdmissionPolicyBinding as bundle manifest objects.
Currently looking into asset embedding ( baking the VAP yaml files into the operator binary ) to resolve this issue. Using openshift/cluster-kube-descheduler-operator for reference.

@swghosh swghosh Jul 29, 2026

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.

+1, thanks SGTM!

@neha037
neha037 marked this pull request as draft July 28, 2026 05:33
@openshift-ci openshift-ci Bot added the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Jul 28, 2026
@neha037

neha037 commented Jul 29, 2026

Copy link
Copy Markdown
Contributor Author

/retest

@openshift-ci

openshift-ci Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

@neha037: The following test failed, say /retest to rerun all failed tests or /retest-required to rerun all mandatory failed tests:

Test name Commit Details Required Rerun command
ci/prow/validate-boilerplate ec376eb link false /test validate-boilerplate

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-ci openshift-ci Bot added the lgtm Indicates that a PR is ready to be merged. label Jul 29, 2026
@openshift-ci

openshift-ci Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: neha037, swghosh

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

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. do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. 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. tide/merge-method-squash Denotes a PR that should be squashed by tide when it merges.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants