Skip to content

[Resource] Prevent IndexError in az policy assignment list --scope parsing - #33787

Open
Aditya Pujara (a0x1ab) with Copilot wants to merge 2 commits into
devfrom
copilot/fix-az-policy-assignment-index-error
Open

[Resource] Prevent IndexError in az policy assignment list --scope parsing#33787
Aditya Pujara (a0x1ab) with Copilot wants to merge 2 commits into
devfrom
copilot/fix-az-policy-assignment-index-error

Conversation

Copilot AI commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Related command
az policy assignment list --scope <scope>

Description
az policy assignment list --scope <resource-group> could crash with IndexError when --scope was not in an expected ARM ID shape. This change hardens scope parsing so invalid shapes produce a normal argument validation error instead of an unhandled exception.

  • Scope parser hardening

    • Guard index access in Common.ResolveScopeForList with length checks before reading scope segments.
    • Keep existing behavior for valid management group and subscription scopes.
    • Only set resource_group when the segment is explicitly resourceGroups (case-insensitive).
  • Behavioral test coverage

    • Added focused unit tests for:
      • malformed/short scope -> InvalidArgumentValueError
      • valid subscription/resource-group scope parsing
      • valid management-group scope parsing
scope_parts = ctx.args.scope._data.split('/')
if len(scope_parts) > 4 and scope_parts[1] == 'providers':
    ...
elif len(scope_parts) > 2 and scope_parts[1] == 'subscriptions':
    ...

Testing Guide

# Repro path this PR addresses
az policy assignment list --scope <malformed-scope>

# Expected with this change:
# command returns InvalidArgumentValueError instead of IndexError traceback

History Notes
[Resource] az policy assignment list: Prevent IndexError for malformed --scope by validating scope segment access


This checklist is used to make sure that common guidelines for a pull request are followed.

@azure-client-tools-bot-prd

Copy link
Copy Markdown

Hi Copilot,
Since the current milestone time is less than 7 days, this pr will be reviewed in the next milestone.

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
There may be pipelines that require an authorized user to comment /azp run to run.

@microsoft-github-policy-service microsoft-github-policy-service Bot added Auto-Assign Auto assign by bot ARM az resource/group/lock/tag/deployment/policy/managementapp/account management-group act-identity-squad labels Jul 24, 2026
Copilot AI linked an issue Jul 24, 2026 that may be closed by this pull request
Copilot AI changed the title [WIP] Fix index error when running az policy assignment list [Resource] Prevent IndexError in az policy assignment list --scope parsing Jul 24, 2026
@azure-client-tools-agent

Copy link
Copy Markdown

Live test results — azdev test --live --series (changed test files only)

PASS

Selectors: test_resource_validators (module)
PR head ref: copilot/fix-az-policy-assignment-index-error
PR head sha: 28c569e9ffc7c7b08315fa23d08283adf22dbabb
PR base ref: dev
New test files in PR: false

Changed test files run
src/azure-cli/azure/cli/command_modules/resource/tests/latest/test_resource_validators.py

Workflow run: https://github.com/Azure/issue-sentinel/actions/runs/30100594031

Last 80 lines of azdev output

=============
| Run Tests |
=============


=====================
| Discovering Tests |
=====================

/home/runner/work/issue-sentinel/issue-sentinel/azure-cli/src/azure-cli/azure/cli/command_modules/identity/tests/latest/test_identity.py:18: SyntaxWarning: invalid escape sequence '\{'
  'resource_restriction_compute': '\{"providers":\["Microsoft.Compute"\]\}',
/home/runner/work/issue-sentinel/issue-sentinel/azure-cli/src/azure-cli/azure/cli/command_modules/identity/tests/latest/test_identity.py:19: SyntaxWarning: invalid escape sequence '\{'
  'resource_restriction_empty': '\{"providers":\[\]\}'
/home/runner/work/issue-sentinel/issue-sentinel/azure-cli/src/azure-cli/azure/cli/command_modules/vm/tests/latest/test_vm_commands.py:13533: SyntaxWarning: invalid escape sequence '\]'
  self.cmd('vmss application set -g {rg} -n {vmss} --app-version-ids {vid1} {vid2} --enable-automatic-upgrade True\]', checks=[

test index updated: /home/runner/.azdev/env_config/home/runner/work/issue-sentinel/issue-sentinel/.venv/test_index/latest.json

Test on modules: test_resource_validators

WARNING: RUNNING TESTS LIVE
The tests are set to run against current profile "latest"
============================= test session starts ==============================
platform linux -- Python 3.12.13, pytest-9.1.1, pluggy-1.6.0 -- /home/runner/work/issue-sentinel/issue-sentinel/.venv/bin/python
cachedir: .pytest_cache
rootdir: /home/runner/work/issue-sentinel/issue-sentinel/azure-cli/src/azure-cli
plugins: xdist-3.8.0, forked-1.6.0
collecting ... collected 6 items

azure-cli/src/azure-cli/azure/cli/command_modules/resource/tests/latest/test_resource_validators.py::TestResourceValidators::test_generate_deployment_name_from_file PASSED [ 16%]
azure-cli/src/azure-cli/azure/cli/command_modules/resource/tests/latest/test_resource_validators.py::TestResourceValidators::test_validate_lock_params PASSED [ 33%]
azure-cli/src/azure-cli/azure/cli/command_modules/resource/tests/latest/test_resource_validators.py::TestResourceValidators::test_validate_lock_params_invalid PASSED [ 50%]
azure-cli/src/azure-cli/azure/cli/command_modules/resource/tests/latest/test_resource_validators.py::TestPolicyCommon::test_resolve_scope_for_list_raises_for_short_scope PASSED [ 66%]
azure-cli/src/azure-cli/azure/cli/command_modules/resource/tests/latest/test_resource_validators.py::TestPolicyCommon::test_resolve_scope_for_list_sets_management_group_for_mg_scope PASSED [ 83%]
azure-cli/src/azure-cli/azure/cli/command_modules/resource/tests/latest/test_resource_validators.py::TestPolicyCommon::test_resolve_scope_for_list_sets_resource_group_for_subscription_scope PASSED [100%]

- generated xml file: /home/runner/work/issue-sentinel/issue-sentinel/test-output/results.xml -
============================== 6 passed in 0.26s ===============================

Posted by agent-assist live-test workflow.

@azure-client-tools-agent azure-client-tools-agent 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.

CI Review — Changes Requested

The Azure DevOps validation pipeline for this PR has 2 failing checks (Build #20260724.16):

The live-test workflow (live-test.yml) for the changed test file(s) passed successfully, so the regression is isolated to the ADO build/lint/homebrew-formula checks above, not the live functional test.

Copilot please investigate the failing Azure.azure-cli build and Test Homebrew Formula checks linked above (open the ADO build to see the exact failing step/log), fix the root cause, and push an update to this PR.


Posted by agent-assist (autonomous bug-fix pipeline).

@a0x1ab

Copy link
Copy Markdown
Member

Copilot the automated CI and live-test review on this PR found failures. Please look into the requested changes here: #33787 (review) and push a fix.


Posted by agent-assist (autonomous bug-fix pipeline).

@azure-client-tools-agent
azure-client-tools-agent Bot marked this pull request as ready for review August 4, 2026 02:22
@azure-client-tools-agent
azure-client-tools-agent Bot requested a review from a team as a code owner August 4, 2026 02:22
Copilot AI review requested due to automatic review settings August 4, 2026 02:22
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
There may be pipelines that require an authorized user to comment /azp run to run.

Copilot AI 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.

Pull request overview

Note

Copilot could not run the full agentic suite for this review because it was automatically requested on a bot-authored pull request. Request a review from Copilot under Reviewers to retry with the full agentic suite. Improved support for bot-authored pull requests is coming soon.

Adds validation coverage around policy scope parsing and hardens ResolveScopeForList against short/partial scope strings.

Changes:

  • Added unit tests for Common.ResolveScopeForList to cover management group and subscription+resource group scopes.
  • Updated scope parsing guards in ResolveScopeForList to avoid index errors on short/partial scopes.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 4 comments.

File Description
src/azure-cli/azure/cli/command_modules/resource/tests/latest/test_resource_validators.py Adds unit tests for scope resolution behavior and error handling.
src/azure-cli/azure/cli/command_modules/resource/policy.py Tightens length checks and adds resourceGroups segment validation before indexing.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +161 to +165
def test_resolve_scope_for_list_raises_for_short_scope(self):
cmd = self._create_policy_command('resource-group-name')

with self.assertRaises(InvalidArgumentValueError):
Common.ResolveScopeForList(cmd)
Comment on lines +164 to 166
if len(scope_parts) > 4 and scope_parts[1] == 'providers':
ctx.args.management_group = scope_parts[4]
ctx.args.resource_group = None
Comment on lines +167 to 173
elif len(scope_parts) > 2 and scope_parts[1] == 'subscriptions':
# store subscription from scope for later use
self.subscription_from_scope = scope_parts[2]
if len(scope_parts) > 3:
if len(scope_parts) > 4 and scope_parts[3].lower() == 'resourcegroups':
ctx.args.resource_group = scope_parts[4]
else:
ctx.args.resource_group = None
Comment on lines +149 to +155
@staticmethod
def _create_policy_command(scope):
cmd = mock.MagicMock()
cmd.ctx = mock.MagicMock()
cmd.ctx.args = mock.MagicMock()
cmd.ctx.args.scope = mock.MagicMock()
cmd.ctx.args.scope._data = scope
@a0x1ab Aditya Pujara (a0x1ab) added agent-assist On-demand trigger for the agent-assist autonomous bug-fix pipeline azure-client-tools-agent Pull request commented on or reviewed by Azure Client Tools Agent and removed agent-assist On-demand trigger for the agent-assist autonomous bug-fix pipeline labels Aug 6, 2026
@microsoft-github-policy-service

Copy link
Copy Markdown
Contributor

🔔 Routing this PR to @Azure/act-identity-squad.

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

Labels

act-identity-squad ARM az resource/group/lock/tag/deployment/policy/managementapp/account management-group Auto-Assign Auto assign by bot azure-client-tools-agent Pull request commented on or reviewed by Azure Client Tools Agent

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Running az policy assignment list gives an IndexError

3 participants