Skip to content

OCPBUGS-58181: Fix nil pointer dereference in ensureRolesAssignedToManagedIdentity#987

Open
jstuever wants to merge 1 commit intoopenshift:masterfrom
jstuever:OCPBUGS-58181
Open

OCPBUGS-58181: Fix nil pointer dereference in ensureRolesAssignedToManagedIdentity#987
jstuever wants to merge 1 commit intoopenshift:masterfrom
jstuever:OCPBUGS-58181

Conversation

@jstuever
Copy link
Copy Markdown
Contributor

@jstuever jstuever commented Mar 12, 2026

Add nil checks for Properties, RoleDefinitionID, and Scope fields before dereferencing role assignments. This prevents panics during retry scenarios when Azure API returns role assignments with nil properties.

Assisted-by: Claude Sonnet 4.6

Summary by CodeRabbit

  • Bug Fixes

    • Improved robustness when reconciling Azure managed identity role assignments by ignoring incomplete or malformed role-assignment entries, preventing crashes during detection and cleanup.
  • Tests

    • Added unit tests covering partially populated or missing role-assignment data to ensure reconciliation and cleanup complete without errors.

@openshift-ci-robot openshift-ci-robot added jira/severity-low Referenced Jira bug's severity is low for the branch this PR is targeting. jira/valid-reference Indicates that this PR references a valid Jira ticket of any type. jira/invalid-bug Indicates that a referenced Jira bug is invalid for the branch this PR is targeting. labels Mar 12, 2026
@openshift-ci-robot
Copy link
Copy Markdown
Contributor

@jstuever: This pull request references Jira Issue OCPBUGS-58181, which is invalid:

  • expected the bug to target the "4.22.0" version, but no target version was set

Comment /jira refresh to re-evaluate validity if changes to the Jira bug are made, or edit the title of this pull request to link to a different bug.

The bug has been updated to refer to the pull request using the external bug tracker.

Details

In response to this:

Add nil checks for Properties, RoleDefinitionID, and Scope fields before dereferencing role assignments. This prevents panics during retry scenarios when Azure API returns role assignments with nil properties.

Assisted-by: Claude Sonnet 4.5

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
Copy link
Copy Markdown

coderabbitai Bot commented Mar 12, 2026

Walkthrough

Adds defensive nil checks when iterating and cleaning up Azure role assignments for managed identities; incomplete armauthorization.RoleAssignment objects (nil Properties, RoleDefinitionID, Scope, or Name) are skipped to avoid dereference panics. Unit tests extended with cases for partially-populated role assignments.

Changes

Cohort / File(s) Summary
Nil-safety guards for role assignments
pkg/cmd/provisioning/azure/create_managed_identities.go
Added nil checks when iterating existingRoleAssignments to skip entries with Properties == nil, Properties.RoleDefinitionID == nil, Properties.Scope == nil, and checks Name where relevant during both existence detection and cleanup.
Extended tests for partial role assignments
pkg/cmd/provisioning/azure/create_managed_identities_test.go
Added five table-driven tests covering partially-populated armauthorization.RoleAssignment objects (cases with nil Properties, missing RoleDefinitionID, missing Scope, and nil Name) to ensure reconciliation and cleanup paths tolerate malformed/incomplete Azure responses without panicking.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes


Important

Pre-merge checks failed

Please resolve all errors before merging. Addressing warnings is optional.

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Ote Binary Stdout Contract ❓ Inconclusive The modified files referenced in the pull request are not present in the repository. Verify the repository contains the correct pull request changes and provide the actual file contents for assessment.
✅ Passed checks (10 passed)
Check name Status Explanation
Title check ✅ Passed The title directly and accurately describes the main change: adding nil pointer dereference protection in the ensureRolesAssignedToManagedIdentity function.
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 Test file uses standard Go testing with table-driven tests, not Ginkgo. All test names are static descriptive strings with no dynamic values.
Test Structure And Quality ✅ Passed Test uses standard Go table-driven pattern with clear test cases covering nil pointer conditions. Each case has single responsibility testing one specific nil-pointer scenario or combination.
Microshift Test Compatibility ✅ Passed The pull request adds standard Go unit tests using table-driven patterns, not Ginkgo e2e tests. These tests do not use Ginkgo framework elements (It, Describe, Context) and are component-level unit tests for Azure role assignment logic.
Single Node Openshift (Sno) Test Compatibility ✅ Passed The changes add unit test cases to TestEnsureRolesAssignedToManagedIdentity using Go's testing package with table-driven patterns, not Ginkgo e2e tests. No Ginkgo imports or test functions are present.
Topology-Aware Scheduling Compatibility ✅ Passed The PR modifies Azure managed identity role assignment reconciliation logic without introducing topology-aware scheduling constraints, manifests, or policies.
Ipv6 And Disconnected Network Test Compatibility ✅ Passed PR adds table-driven test cases to standard Go unit tests using testing package and testify, not Ginkgo e2e tests.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

@jstuever
Copy link
Copy Markdown
Contributor Author

/jira refresh

@openshift-ci-robot openshift-ci-robot added jira/valid-bug Indicates that a referenced Jira bug is valid for the branch this PR is targeting. and removed jira/invalid-bug Indicates that a referenced Jira bug is invalid for the branch this PR is targeting. labels Mar 12, 2026
@openshift-ci-robot
Copy link
Copy Markdown
Contributor

@jstuever: This pull request references Jira Issue OCPBUGS-58181, which is valid. The bug has been moved to the POST state.

3 validation(s) were run on this bug
  • bug is open, matching expected state (open)
  • bug target version (4.22.0) matches configured target version for branch (4.22.0)
  • bug is in the state New, which is one of the valid states (NEW, ASSIGNED, POST)
Details

In response to this:

/jira refresh

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.

@jstuever
Copy link
Copy Markdown
Contributor Author

/jira backport release-4.21,release-4.22

@openshift-ci-robot
Copy link
Copy Markdown
Contributor

@jstuever: Missing required branches for backport chain:

  • openshift-4.23 OR release-4.23,
Details

In response to this:

/jira backport release-4.21,release-4.22

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
Copy link
Copy Markdown
Contributor

@jstuever: This pull request references Jira Issue OCPBUGS-58181, which is valid.

3 validation(s) were run on this bug
  • bug is open, matching expected state (open)
  • bug target version (4.22.0) matches configured target version for branch (4.22.0)
  • bug is in the state POST, which is one of the valid states (NEW, ASSIGNED, POST)
Details

In response to this:

Add nil checks for Properties, RoleDefinitionID, and Scope fields before dereferencing role assignments. This prevents panics during retry scenarios when Azure API returns role assignments with nil properties.

Assisted-by: Claude Sonnet 4.5

Summary by CodeRabbit

  • Bug Fixes
  • Improved robustness when handling Azure managed identity role assignments by adding validation checks that gracefully skip incomplete or malformed role assignment data instead of causing system failures.

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 openshift-ci Bot requested review from 2uasimojo and suhanime March 12, 2026 16:46
@openshift-ci
Copy link
Copy Markdown
Contributor

openshift-ci Bot commented Mar 12, 2026

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: jstuever

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 Mar 12, 2026
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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@pkg/cmd/provisioning/azure/create_managed_identities.go`:
- Around line 313-316: The cleanup loop may still nil-deref
existingRoleAssignment.Name; move the guard that checks
existingRoleAssignment.Properties, RoleDefinitionID, and Scope to execute before
any dereference of existingRoleAssignment.Name and extend it to also check
existingRoleAssignment.Name != nil; specifically, in the loop that iterates
existingRoleAssignment (the cleanup loop logic where the code compares
*existingRoleAssignment.Name and later logs it), add Name to the nil checks and
run that guard before the name comparison and before logging to avoid panics.

ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Pro

Run ID: 5879ed38-c555-4581-8eb1-97770b5a6bfb

📥 Commits

Reviewing files that changed from the base of the PR and between ed39a12 and baaee2b.

📒 Files selected for processing (1)
  • pkg/cmd/provisioning/azure/create_managed_identities.go

Comment thread pkg/cmd/provisioning/azure/create_managed_identities.go Outdated
@codecov
Copy link
Copy Markdown

codecov Bot commented Mar 12, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 46.91%. Comparing base (c502923) to head (b5f8b6a).
⚠️ Report is 2 commits behind head on master.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##           master     #987      +/-   ##
==========================================
+ Coverage   46.88%   46.91%   +0.02%     
==========================================
  Files          98       98              
  Lines       12558    12564       +6     
==========================================
+ Hits         5888     5894       +6     
  Misses       6015     6015              
  Partials      655      655              
Files with missing lines Coverage Δ
...md/provisioning/azure/create_managed_identities.go 55.94% <100.00%> (+0.52%) ⬆️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@jstuever
Copy link
Copy Markdown
Contributor Author

/test e2e-azure-manual-oidc

@huangmingxia
Copy link
Copy Markdown
Contributor

@jstuever e2e-azure-manual-oidc job is blocked by https://issues.redhat.com/browse/OCPBUGS-77845

@jstuever jstuever marked this pull request as draft March 18, 2026 19:55
@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 Mar 18, 2026
@jstuever jstuever marked this pull request as ready for review April 21, 2026 22:07
@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 Apr 21, 2026
@jstuever
Copy link
Copy Markdown
Contributor Author

/jira refresh

@openshift-ci-robot
Copy link
Copy Markdown
Contributor

@jstuever: This pull request references Jira Issue OCPBUGS-58181, which is valid.

3 validation(s) were run on this bug
  • bug is open, matching expected state (open)
  • bug target version (5.0.0) matches configured target version for branch (5.0.0)
  • bug is in the state POST, which is one of the valid states (NEW, ASSIGNED, POST)

Requesting review from QA contact:
/cc @miyadav

Details

In response to this:

/jira refresh

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 openshift-ci Bot requested a review from miyadav April 21, 2026 22:08
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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@pkg/cmd/provisioning/azure/create_managed_identities_test.go`:
- Around line 933-1063: Add a sibling table test mirroring the existing
nil-Properties/nil-RoleDefinitionID/nil-Name cases that verifies the cleanup
loop skips assignments with a nil Scope: create a case named like "Extra role
assignment with nil Scope in cleanup loop is skipped without panic" and in its
mockAzureClientWrapper call to mockRoleAssignmentsListForScopePager include a
second armauthorization.RoleAssignment whose Properties exists but has
Properties.Scope == nil (and PrincipalID/RoleDefinitionID set as needed), then
keep the mockRoleDefinitionsListPager entry identical to the others; this will
exercise the cleanup guard in create_managed_identities.go (the nil Scope branch
around lines 306-327) and ensure no panic.
🪄 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: Pro Plus

Run ID: 8fb213fa-83ac-406c-a026-5e1303cd867a

📥 Commits

Reviewing files that changed from the base of the PR and between baaee2b and 5245d9f.

📒 Files selected for processing (2)
  • pkg/cmd/provisioning/azure/create_managed_identities.go
  • pkg/cmd/provisioning/azure/create_managed_identities_test.go
✅ Files skipped from review due to trivial changes (1)
  • pkg/cmd/provisioning/azure/create_managed_identities.go

Comment thread pkg/cmd/provisioning/azure/create_managed_identities_test.go
Add defensive nil checks when iterating over existing role assignments
to prevent panics when Azure's eventual consistency results in incomplete
data structures with nil Properties, RoleDefinitionID, Scope, or Name fields.

Co-Authored-By: Claude Sonnet 4.6
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.

♻️ Duplicate comments (1)
pkg/cmd/provisioning/azure/create_managed_identities.go (1)

271-274: ⚠️ Potential issue | 🔴 Critical

Remaining nil-deref paths in role-assignment matching/cleanup

The new guards are incomplete: Line 313 still dereferences *shouldExistRoleAssignment.Name without a nil check, and both loops assume assignment pointers are non-nil. This can still panic on malformed Azure responses.

Suggested hardening patch
 for _, roleAssignment := range existingRoleAssignments {
-	if roleAssignment.Properties == nil || roleAssignment.Properties.RoleDefinitionID == nil || roleAssignment.Properties.Scope == nil {
+	if roleAssignment == nil || roleAssignment.Name == nil ||
+		roleAssignment.Properties == nil || roleAssignment.Properties.RoleDefinitionID == nil || roleAssignment.Properties.Scope == nil {
 		log.Printf("skipping incomplete role assignment (nil Properties, RoleDefinitionID, or Scope)")
 		continue
 	}
@@
 for _, existingRoleAssignment := range existingRoleAssignments {
-	if existingRoleAssignment.Name == nil || existingRoleAssignment.Properties == nil || existingRoleAssignment.Properties.RoleDefinitionID == nil || existingRoleAssignment.Properties.Scope == nil {
+	if existingRoleAssignment == nil || existingRoleAssignment.Name == nil ||
+		existingRoleAssignment.Properties == nil || existingRoleAssignment.Properties.RoleDefinitionID == nil || existingRoleAssignment.Properties.Scope == nil {
 		log.Printf("skipping incomplete existing role assignment during cleanup (nil Name, Properties, RoleDefinitionID, or Scope)")
 		continue
 	}
 	found := false
 	for _, shouldExistRoleAssignment := range shouldExistRoleAssignments {
-		if shouldExistRoleAssignment != nil && *shouldExistRoleAssignment.Name == *existingRoleAssignment.Name {
+		if shouldExistRoleAssignment != nil && shouldExistRoleAssignment.Name != nil &&
+			*shouldExistRoleAssignment.Name == *existingRoleAssignment.Name {
 			found = true
+			break
 		}
 	}

Also applies to: 307-313

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/cmd/provisioning/azure/create_managed_identities.go` around lines 271 -
274, The code still dereferences pointers without full nil checks causing
potential panics; update the loops that iterate role assignments to first ensure
each roleAssignment and each shouldExistRoleAssignment is non-nil before
accessing fields, and add a nil check on shouldExistRoleAssignment.Name (and its
pointer) before dereferencing *shouldExistRoleAssignment.Name in the
matching/cleanup logic (the loop that compares assignments and the block that
uses shouldExistRoleAssignment.Name); change conditions to skip entries where
roleAssignment == nil, shouldExistRoleAssignment == nil,
shouldExistRoleAssignment.Name == nil, or
roleAssignment.Properties/RoleDefinitionID/Scope are nil so no pointer is
dereferenced without validation.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@pkg/cmd/provisioning/azure/create_managed_identities.go`:
- Around line 271-274: The code still dereferences pointers without full nil
checks causing potential panics; update the loops that iterate role assignments
to first ensure each roleAssignment and each shouldExistRoleAssignment is
non-nil before accessing fields, and add a nil check on
shouldExistRoleAssignment.Name (and its pointer) before dereferencing
*shouldExistRoleAssignment.Name in the matching/cleanup logic (the loop that
compares assignments and the block that uses shouldExistRoleAssignment.Name);
change conditions to skip entries where roleAssignment == nil,
shouldExistRoleAssignment == nil, shouldExistRoleAssignment.Name == nil, or
roleAssignment.Properties/RoleDefinitionID/Scope are nil so no pointer is
dereferenced without validation.

ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Pro Plus

Run ID: 0383d1dc-1906-4b8d-92a6-8a05a98feba2

📥 Commits

Reviewing files that changed from the base of the PR and between 5245d9f and b5f8b6a.

📒 Files selected for processing (2)
  • pkg/cmd/provisioning/azure/create_managed_identities.go
  • pkg/cmd/provisioning/azure/create_managed_identities_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/cmd/provisioning/azure/create_managed_identities_test.go

@jstuever
Copy link
Copy Markdown
Contributor Author

/retest

1 similar comment
@jstuever
Copy link
Copy Markdown
Contributor Author

/retest

@jstuever
Copy link
Copy Markdown
Contributor Author

/test e2e-azure-manual-oidc

@jstuever
Copy link
Copy Markdown
Contributor Author

/override ci/prow/security
Unrleated, covered by other bugs.

@openshift-ci
Copy link
Copy Markdown
Contributor

openshift-ci Bot commented Apr 22, 2026

@jstuever: Overrode contexts on behalf of jstuever: ci/prow/security

Details

In response to this:

/override ci/prow/security
Unrleated, covered by other bugs.

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.

@openshift-ci
Copy link
Copy Markdown
Contributor

openshift-ci Bot commented Apr 23, 2026

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

@jstuever
Copy link
Copy Markdown
Contributor Author

/assign @dlom

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/severity-low Referenced Jira bug's severity is low for the branch this PR is targeting. jira/valid-bug Indicates that a referenced Jira bug is valid for the branch this PR is targeting. 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.

4 participants