Skip to content

fix: populate PodUID in admission alerts#380

Merged
matthyx merged 3 commits into
mainfrom
fix/admission-alert-pod-uid-cluster-uid
May 29, 2026
Merged

fix: populate PodUID in admission alerts#380
matthyx merged 3 commits into
mainfrom
fix/admission-alert-pod-uid-cluster-uid

Conversation

@matthyx
Copy link
Copy Markdown
Contributor

@matthyx matthyx commented May 29, 2026

This PR fixes a bug where admission alerts (like R2000 Exec-to-pod and R2001 Port-forward) were sent without the podUID field in their RuntimeAlertK8sDetails payload.

Changes:

  1. Populate PodUID: Populated the PodUID inside RuntimeAlertK8sDetails using the fetched pod.UID in both R2000ExecToPod and R2001PortForward rule processors.
  2. Unit Tests: Updated unit tests to include a mock pod UID and verify the resolved podUID assertions.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 29, 2026

📝 Walkthrough

Walkthrough

Two admission rules (R2000 exec-to-pod, R2001 port-forward) now populate PodUID in runtime alert details from resolved pod identity. Test suites verify this field, the mock pod infrastructure provides deterministic UIDs, and GetClusterUID gains optional environment variable sourcing to bypass RBAC-restricted lookups.

Changes

Pod and Cluster Identity Enrichment

Layer / File(s) Summary
Mock pod UID for test support
objectcache/objectcache_mock.go
Kubernetes cache mock now initializes pod ObjectMeta with deterministic UID field to support test assertions.
R2000 and R2001 rules populate PodUID
admission/rules/v1/r2000_exec_to_pod.go, admission/rules/v1/r2000_exec_to_pod_test.go, admission/rules/v1/r2001_portforward.go, admission/rules/v1/r2001_portforward_test.go
R2000 and R2001 now set PodUID from resolved pod identity in RuntimeAlertK8sDetails; tests validate PodUID matches expected values in normal execution and when container name is empty.
GetClusterUID environment variable support
utils/utils.go
GetClusterUID imports os and checks CLUSTER_UID environment variable; if present and non-empty, returns immediately with logged value instead of issuing kube-system namespace request.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

  • kubescape/operator#357: Adds controller-resolved pod/workload UID plumbing to the same R2000/R2001 ProcessEvent flow.
  • kubescape/operator#359: Also enriches RuntimeAlertK8sDetails in R2000 and R2001 rules with additional cluster and image identity fields.

Suggested labels

release

Poem

🐰 Pod UIDs now travel forth,
Through alerts and rules of worth,
With cluster vars from env's call,
Identity enriches all!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title directly summarizes the main change: populating PodUID in admission alerts, which matches the primary objective of the changeset.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/admission-alert-pod-uid-cluster-uid

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 and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
utils/utils.go (2)

179-180: ⚡ Quick win

Update function documentation to mention environment variable.

The function comment should document that GetClusterUID first checks the CLUSTER_UID environment variable before falling back to the kube-system namespace lookup.

📝 Proposed documentation update
-// GetClusterUID retrieves the UID of the kube-system namespace to use as a stable cluster identifier.
-// If the namespace cannot be accessed (e.g., due to RBAC restrictions), it returns an empty string and logs a warning.
+// GetClusterUID retrieves a stable cluster identifier. It first checks the CLUSTER_UID environment variable.
+// If not set, it falls back to retrieving the UID of the kube-system namespace.
+// If the namespace cannot be accessed (e.g., due to RBAC restrictions), it returns an empty string and logs a warning.
 func GetClusterUID(k8sClient kubernetes.Interface) string {
🤖 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 `@utils/utils.go` around lines 179 - 180, Update the GetClusterUID function
comment to state that it first checks the CLUSTER_UID environment variable and
returns its value if set, then falls back to retrieving the UID from the
kube-system namespace; mention that if the namespace cannot be accessed (e.g.,
RBAC) the function returns an empty string and logs a warning.

182-185: ⚡ Quick win

Consider validating the CLUSTER_UID format.

The environment variable value is accepted without validation. Kubernetes UIDs follow UUID format (e.g., 123e4567-e89b-12d3-a456-426614174000). Invalid values could cause downstream issues if systems expect properly formatted UIDs.

✅ Proposed validation check
 func GetClusterUID(k8sClient kubernetes.Interface) string {
 	if envUID := os.Getenv("CLUSTER_UID"); envUID != "" {
+		// Validate UUID format (basic check for length and hyphens)
+		if len(envUID) != 36 || envUID[8] != '-' || envUID[13] != '-' || envUID[18] != '-' || envUID[23] != '-' {
+			logger.L().Warning("CLUSTER_UID environment variable has invalid UUID format, ignoring", helpers.String("value", envUID))
+		} else {
 			logger.L().Info("retrieved ClusterUID from environment variable CLUSTER_UID", helpers.String("clusterUID", envUID))
 			return envUID
+		}
 	}
🤖 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 `@utils/utils.go` around lines 182 - 185, Validate the CLUSTER_UID environment
value before returning it: when reading os.Getenv("CLUSTER_UID") (envUID) check
it matches a UUID format (e.g., via github.com/google/uuid.Parse or a UUID
regex); if valid, keep the logger.L().Info call and return it, otherwise log a
warning/error (using logger) indicating invalid CLUSTER_UID and fall through to
the existing fallback logic instead of returning the invalid value.
🤖 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 `@utils/utils.go`:
- Around line 179-180: Update the GetClusterUID function comment to state that
it first checks the CLUSTER_UID environment variable and returns its value if
set, then falls back to retrieving the UID from the kube-system namespace;
mention that if the namespace cannot be accessed (e.g., RBAC) the function
returns an empty string and logs a warning.
- Around line 182-185: Validate the CLUSTER_UID environment value before
returning it: when reading os.Getenv("CLUSTER_UID") (envUID) check it matches a
UUID format (e.g., via github.com/google/uuid.Parse or a UUID regex); if valid,
keep the logger.L().Info call and return it, otherwise log a warning/error
(using logger) indicating invalid CLUSTER_UID and fall through to the existing
fallback logic instead of returning the invalid value.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 45080c06-5e51-423a-bc9d-e40278092385

📥 Commits

Reviewing files that changed from the base of the PR and between a5313f3 and d2e17d8.

📒 Files selected for processing (6)
  • admission/rules/v1/r2000_exec_to_pod.go
  • admission/rules/v1/r2000_exec_to_pod_test.go
  • admission/rules/v1/r2001_portforward.go
  • admission/rules/v1/r2001_portforward_test.go
  • objectcache/objectcache_mock.go
  • utils/utils.go

@matthyx matthyx changed the title fix: populate PodUID in admission alerts and add CLUSTER_UID env fallback fix: populate PodUID in admission alerts May 29, 2026
@matthyx matthyx added the release Create release label May 29, 2026
@matthyx matthyx merged commit 44b6510 into main May 29, 2026
8 of 9 checks passed
@github-actions
Copy link
Copy Markdown

Summary:

  • License scan: success
  • Credentials scan: failure
  • Vulnerabilities scan: success
  • Unit test: success
  • Go linting: failure

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release Create release

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant