Fix invalid array index validation to reject indices with leading zeros
Issue
The current regex pattern used to validate array indices in the jsonpointer package incorrectly accepts indices with leading zeros (such as "01", "00", "0123"), which violates the JSON Pointer specification (RFC 6901).
Root Cause
The current regex pattern has a logical flaw:
_RE_ARRAY_INDEX = re.compile('0|[1-9][0-9]*$')
This pattern:
- Uses an OR condition (
0|[1-9][0-9]*$) - Is missing a start anchor (
^) - Causes any string starting with "0" to match the first part of the OR condition, regardless of what follows
Fix
Updated the regex pattern to properly validate array indices according to RFC 6901:
_RE_ARRAY_INDEX = re.compile('^(?:0|[1-9][0-9]*)$')
This fix:
- Anchors the pattern to the start of string with
^ - Uses a non-capturing group
(?:...)for efficiency - Properly validates that the entire string must match either a single "0" OR a number starting with 1-9 followed by zero or more digits
Added Tests
Added tests to verify that invalid array indices with leading zeros are properly rejected:
def test_invalid_index_leading_zeros(self):
# RFC 6901 specifies that array indices must not have leading zeros
doc = [0, 1, 2]
self.assertRaises(JsonPointerException, resolve_pointer, doc, '/01')
self.assertRaises(JsonPointerException, resolve_pointer, doc, '/00')
self.assertRaises(JsonPointerException, resolve_pointer, doc, '/001')
All tests pass, confirming that the fix works correctly and doesn't break existing functionality.
Fixes #63.
💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.
@copilot please fix that whitespace issue that is reported by flake8
@copilot please fix that whitespace issue that is reported by flake8
Fixed the whitespace issue in tests.py (line 222 had trailing whitespace). The flake8 checks now pass without any errors. Commit: c7b4416
@copilot rebase
@copilot rebase
Rebase completed successfully. The branch has been updated to be based on the latest master branch (commit afee507).