Skip to content

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

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

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

Conversation

Copilot AI commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

🤖 PR Validation — ❌ Action needed

Breaking Changes Tests
❌ 1 ️✔️ 130/130
❌AzureCLI-BreakingChangeTest
❌aro
rule cmd_name rule_message suggest_message
1012 - SubgroupRemove aro identity sub group aro identity removed please confirm sub group aro identity removed

Please submit your Breaking Change Pre-announcement ASAP if you haven't already. Please note:

  • Breaking changes can only be merged during the designated breaking change window
  • A pre-announcement must be released at least one month in advance

For more details on how to introduce breaking changes, refer to the documentation: azure-cli/doc/how_to_introduce_breaking_changes.md

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
Contributor

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
Contributor

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 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
@a0x1ab Aditya Pujara (a0x1ab) added the Azure Client Tools Agent Requested Request Azure Client Tools Agent testing and review label Aug 19, 2026
@azure-client-tools-agent azure-client-tools-agent Bot removed the Azure Client Tools Agent Requested Request Azure Client Tools Agent testing and review label Aug 19, 2026
@coopercox-ms

Copy link
Copy Markdown
Member

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).

@coopercox-ms Cooper Cox (coopercox-ms) changed the title [Resource] Prevent IndexError in az policy assignment list --scope parsing [Resource] az policy assignment list: Prevent IndexError when parsing --scope Aug 21, 2026
@coopercox-ms

Copy link
Copy Markdown
Member

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).

@a0x1ab Aditya Pujara (a0x1ab) added Azure Client Tools Agent Requested Request Azure Client Tools Agent testing and review and removed azure-client-tools-agent Pull request reviewed by Azure Client Tools Agent labels Aug 21, 2026
@coopercox-ms

Copy link
Copy Markdown
Member

Copilot Please update this PR branch with the latest  dev  without changing the functional fix. The branch is behind and needs to pick up the Homebrew CI fix from #33792. Resolve any conflicts and push the updated branch.

Co-authored-by: coopercox-ms <264909354+coopercox-ms@users.noreply.github.com>

Copilot AI commented Aug 21, 2026

Copy link
Copy Markdown
Contributor Author

Copilot Please update this PR branch with the latest  dev  without changing the functional fix. The branch is behind and needs to pick up the Homebrew CI fix from #33792. Resolve any conflicts and ...

Merged the latest dev (including #33792) without conflicts and pushed 2568ba9. The policy scope fix is unchanged.

@azure-client-tools-agent

Copy link
Copy Markdown
Contributor

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: 2568ba947272667274c5b8a802cc17fe664d91f4
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/32449109498

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/vm/tests/latest/test_vm_commands.py:13705: SyntaxWarning: invalid escape sequence '\]'
  self.cmd('vmss application set -g {rg} -n {vmss} --app-version-ids {vid1} {vid2} --enable-automatic-upgrade True\]', checks=[
/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":\[\]\}'

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.14, 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: forked-1.7.5, xdist-3.8.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.28s ===============================

Posted by agent-assist live-test workflow.

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

Automated Review Summary — PASS ✅

  • Live test (Tester): azdev test run on the changed test file(s) completed successfully.
  • CI: All 106 checks passed (0 failed, 0 pending).
  • Regression coverage: Production changes in resource/policy.py are covered by the updated test_resource_validators.py; no coverage gap detected.

No further automated action needed. Ready for human merge review.

@azure-client-tools-agent azure-client-tools-agent Bot added azure-client-tools-agent Pull request reviewed by Azure Client Tools Agent and removed Azure Client Tools Agent Requested Request Azure Client Tools Agent testing and review labels Aug 21, 2026
@microsoft-github-policy-service

Copy link
Copy Markdown
Contributor

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

@azure-client-tools-agent

Copy link
Copy Markdown
Contributor

Started a Copilot task using claude-sonnet-4.6 for human feedback at #33787 (comment): https://github.com/Azure/azure-cli/tasks/eadbca72-d9e3-4de3-b7bc-76ca25272176

…assignment-index-error

Co-authored-by: a0x1ab <59631311+a0x1ab@users.noreply.github.com>

Copilot AI commented Aug 21, 2026

Copy link
Copy Markdown
Contributor Author

Copilot Please update this PR branch with the latest  dev  without changing the functional fix. The branch is behind and needs to pick up the Homebrew CI fix from #33792. Resolve any conflicts and ...

Done. Merged the latest dev branch (through 1fa042c282) into the PR branch. The Homebrew CI fix from #33792 (627b99304f) is included. No conflicts occurred and the functional fix is unchanged.

@azure-client-tools-agent

Copy link
Copy Markdown
Contributor

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: dcdcdf8c4c45b2f5810ab739c7872602a223dbdd
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/32471381605

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/vm/tests/latest/test_vm_commands.py:13705: SyntaxWarning: invalid escape sequence '\]'
  self.cmd('vmss application set -g {rg} -n {vmss} --app-version-ids {vid1} {vid2} --enable-automatic-upgrade True\]', checks=[
/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":\[\]\}'

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.14, 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: forked-1.7.5, xdist-3.8.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.32s ===============================

Posted by agent-assist live-test workflow.

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

CI Failure Summary

The following check failed on the current head commit and needs to be fixed:

Please investigate whether this failure is caused by the change in this PR (src/azure-cli/azure/cli/command_modules/resource/policy.py) or is a pre-existing/unrelated packaging issue, and fix it if related. Other checks (17) are still pending and have been stuck for over 3 hours (likely stuck/abandoned runners); they were left as-is since none of them failed.

@azure-client-tools-agent

Copy link
Copy Markdown
Contributor

Started a Copilot task using claude-sonnet-4.6 for the automated review at #33787 (review): https://github.com/Azure/azure-cli/tasks/9c01d0ec-c98b-4458-b2c5-45328cd49ff0

Copilot AI commented Aug 21, 2026

Copy link
Copy Markdown
Contributor Author

CI Failure Summary

The following check failed on the current head commit and needs to be fixed:...

Investigated the Build Rpm Package Azure Linux 4.0 (Beta) ARM64 failure. This is not caused by this PR's changes.

Evidence:

  • At commit 2568ba9 (the previous PR head before the dev merge), all 106 CI checks passed — including packaging checks.
  • The failure appeared only at dcdcdf8, which is the merge commit that pulled in the latest dev branch.
  • The dev merge changed only acs, mysql, postgresql, and sql modules — no packaging scripts or resource module files were touched.
  • policy.py has no syntax errors (python3 -m py_compile passes).
  • Azure Linux 4.0 (Beta) ARM64 is itself a beta platform, and the failure looks like a transient/pre-existing infrastructure issue rather than anything introduced by this PR.

No code changes are needed to address this failure.

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

4 participants