python-json-pointer icon indicating copy to clipboard operation
python-json-pointer copied to clipboard

Fix invalid array index validation to reject indices with leading zeros

Open Copilot opened this issue 9 months ago • 4 comments

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:

  1. Uses an OR condition (0|[1-9][0-9]*$)
  2. Is missing a start anchor (^)
  3. 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 avatar May 27 '25 21:05 Copilot

@copilot please fix that whitespace issue that is reported by flake8

stefankoegl avatar May 28 '25 09:05 stefankoegl

@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 avatar May 28 '25 09:05 Copilot

@copilot rebase

stefankoegl avatar Jun 10 '25 21:06 stefankoegl

@copilot rebase

Rebase completed successfully. The branch has been updated to be based on the latest master branch (commit afee507).

Copilot avatar Jun 10 '25 21:06 Copilot