Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 19 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,22 @@
# Python JSONPath Change Log

# 2.3.0
## Version 2.3.1 (unreleased)

**Fixes**

- Fixed detection of function expressions with a `ValueType` result that are not part of a comparison expression. Previously we allowed `ValueType` functions without a comparison if they were part of a prefix expression. Now we raise a `JSONPathTypeError`, as required by RFC 9535.

- Fixed a typo in the regular expression used for scanning shorthand names. Previously we were rejecting some names containing characters in the Unicode BMP.

- Fixed parsing of some int and float literal corner cases involving leading zeros.

- Added `JSONPathOverflowError`, which is now raised when extremely large integer literals can't be parsed. Previously a standard `OverflowError` was raised in such cases.

- Fixed handling of JSONPath expressions with many segments (hundreds). Previously we would get a `RecursionError` at evaluation time from deeply nested generator functions. Now we materialize internal node lists every 100 segments to avoid the recursion error.

- Fixed handling of `logical-not-op`. We now raise a `JSONPathSyntaxError` when `!` is not followed by a parenthesized expression, filter query or function expression.

## 2.3.0

**Fixes**

Expand All @@ -15,14 +31,14 @@
- Removed the `iregexp-check` dependency. We now include faster and more correct implementations of `check_iregexp` and `map_iregexp` in this project.
- Added the `check_iregexp` argument to `jsonpath.function_extensions.Match` and `jsonpath.function_extensions.Search` for controlling I-Regexp validation. By default, `check_iregexp` is `True` if the `regex` package is installed.

# Version 2.2.2
## Version 2.2.2

**Fixes**

- JSON Patch `move` and `copy` operations now use `add` semantics for their target locations. Previously it was not possible to move or copy to the end of an array with the special `-` index, and we would silently append to arrays given an index greater than the array's length. We now raise a `JSONPatchError` if the target index is greater than the number of elements in the array.
- Fixed JSONPatch `move` operations with immutable Mapping or Sequence source objects. Previously we silently ignored the internal `remove` op if the source was immutable, making the operation a copy. Now we raise a `JSONPatchError`.

# Version 2.2.1
## Version 2.2.1

**Fixes**

Expand Down
2 changes: 1 addition & 1 deletion jsonpath/__about__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# SPDX-FileCopyrightText: 2023-present James Prior <jamesgr.prior@gmail.com>
#
# SPDX-License-Identifier: MIT
__version__ = "2.3.0"
__version__ = "2.3.1"
2 changes: 2 additions & 0 deletions jsonpath/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from .exceptions import JSONPathError
from .exceptions import JSONPathIndexError
from .exceptions import JSONPathNameError
from .exceptions import JSONPathOverflowError
from .exceptions import JSONPathSyntaxError
from .exceptions import JSONPathTypeError
from .exceptions import JSONPointerError
Expand Down Expand Up @@ -63,6 +64,7 @@
"JSONPathIndexError",
"JSONPathMatch",
"JSONPathNameError",
"JSONPathOverflowError",
"JSONPathSyntaxError",
"JSONPathTypeError",
"JSONPointer",
Expand Down
4 changes: 4 additions & 0 deletions jsonpath/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,10 @@ def __init__(self, *args: object, token: Optional[Token]) -> None:
self.token = token


class JSONPathOverflowError(JSONPathError):
"""The exceptions raised when a float literal can't be converted to an integer."""


class JSONPointerError(Exception):
"""Base class for all JSON Pointer errors."""

Expand Down
30 changes: 30 additions & 0 deletions jsonpath/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,35 @@ def set_children(self, children: List[BaseExpression]) -> None: # noqa: ARG002
self.items = children


class GroupExpression(BaseExpression):
"""A parenthesized expression."""

__slots__ = ("expr",)

def __init__(self, expr: BaseExpression) -> None:
self.expr = expr
super().__init__()

def __str__(self) -> str:
return str(self.expr)

def __eq__(self, other: object) -> bool:
return isinstance(other, GroupExpression) and self.expr == other.expr

def evaluate(self, context: FilterContext) -> object:
return self.expr.evaluate(context)

async def evaluate_async(self, context: FilterContext) -> object:
return await self.expr.evaluate_async(context)

def children(self) -> List[BaseExpression]:
return [self.expr]

def set_children(self, children: List[BaseExpression]) -> None:
assert len(children) == 1
self.expr = children[0]


class PrefixExpression(BaseExpression):
"""An expression composed of a prefix operator and another expression."""

Expand Down Expand Up @@ -376,6 +405,7 @@ def set_children(self, children: List[BaseExpression]) -> None:
PRECEDENCE_LOGICAL_OR = 3
PRECEDENCE_LOGICAL_AND = 4
PRECEDENCE_PREFIX = 7
PRECEDENCE_HIGHEST = 9


class FilterExpression(BaseExpression):
Expand Down
4 changes: 2 additions & 2 deletions jsonpath/lex.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,12 @@ class attributes. Then setting `lexer_class` on a `JSONPathEnvironment`.

strict_key_pattern = (
r"[\u0080-\uD7FF\uE000-\U0010FFFFa-zA-Z_]"
r"[\u0080-\u10FFFF\uE000-\U0010FFFFa-zA-Z0-9_]*"
r"[\u0080-\uD7FF\uE000-\U0010FFFFa-zA-Z0-9_]*"
)

key_pattern = (
r"[\u0080-\uD7FF\uE000-\U0010FFFFa-zA-Z_]"
r"[\u0080-\u10FFFF\uE000-\U0010FFFFa-zA-Z0-9_-]*"
r"[\u0080-\uD7FF\uE000-\U0010FFFFa-zA-Z0-9_-]*"
)

# ! or `not`
Expand Down
90 changes: 76 additions & 14 deletions jsonpath/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

import json
import math
import re
from typing import TYPE_CHECKING
from typing import Callable
Expand All @@ -16,6 +17,8 @@
from jsonpath.function_extensions.filter_function import ExpressionType
from jsonpath.function_extensions.filter_function import FilterFunction

from .exceptions import JSONPathNameError
from .exceptions import JSONPathOverflowError
from .exceptions import JSONPathRecursionError
from .exceptions import JSONPathSyntaxError
from .exceptions import JSONPathTypeError
Expand All @@ -31,6 +34,7 @@
from .filter import FilterQuery
from .filter import FloatLiteral
from .filter import FunctionExtension
from .filter import GroupExpression
from .filter import InfixExpression
from .filter import IntegerLiteral
from .filter import ListLiteral
Expand Down Expand Up @@ -148,6 +152,12 @@
"\x1f",
]

_RE_FLOAT = re.compile(
r"-?([1-9][0-9]*|0)\.[0-9]+(?:[eE][+-]?[0-9]+)?|-?([1-9][0-9]*|0)[eE]-[0-9]+"
)

_RE_INT = re.compile(r"-?([1-9][0-9]*|0)([eE]\+?[0-9]+)?")


class Parser:
"""A JSONPath parser bound to a JSONPathEnvironment."""
Expand Down Expand Up @@ -625,30 +635,45 @@ def parse_integer_literal(self, stream: TokenStream) -> BaseExpression:
token = stream.next()
value = token.value

if self.env.strict and value.startswith("0") and len(value) > 1:
if self.env.strict and not _RE_INT.fullmatch(value):
raise JSONPathSyntaxError("invalid integer literal", token=token)

# Convert to float first to handle scientific notation.
return IntegerLiteral(value=int(float(value)))
f = float(value)
if f == math.inf:
raise JSONPathOverflowError(
"cannot convert float infinity to integer", token
)

return IntegerLiteral(value=int(f))

def parse_float_literal(self, stream: TokenStream) -> BaseExpression:
token = stream.next()
value = token.value

if value.startswith("0") and len(value.split(".")[0]) > 1:
if self.env.strict and not _RE_FLOAT.fullmatch(value):
raise JSONPathSyntaxError("invalid float literal", token=token)

return FloatLiteral(value=float(value))

def parse_prefix_expression(self, stream: TokenStream) -> BaseExpression:
token = stream.next()
assert token.kind == TOKEN_NOT
return PrefixExpression(
operator="!",
right=self.parse_filter_expression(
stream, precedence=self.PRECEDENCE_PREFIX
),
)
stream.eat(TOKEN_NOT)
token = stream.current()
expr = self.parse_filter_expression(stream, precedence=self.PRECEDENCE_PREFIX)

if self.env.well_typed:
self._raise_for_not_compared(expr, token)

if self.env.strict and not isinstance(
expr, (FilterQuery, GroupExpression, FunctionExtension)
):
raise JSONPathSyntaxError(
"logical not must be followed by a query, "
"function or group expression",
token=token,
)

return PrefixExpression(operator="!", right=expr)

def parse_infix_expression(
self, stream: TokenStream, left: BaseExpression
Expand Down Expand Up @@ -680,6 +705,7 @@ def parse_infix_expression(

def parse_grouped_expression(self, stream: TokenStream) -> BaseExpression:
_token = stream.eat(TOKEN_LPAREN)
expr_token = stream.current()
expr = self.parse_filter_expression(stream)

while stream.current().kind != TOKEN_RPAREN:
Expand All @@ -689,8 +715,11 @@ def parse_grouped_expression(self, stream: TokenStream) -> BaseExpression:

expr = self.parse_infix_expression(stream, expr)

if self.env.well_typed:
self._raise_for_not_compared(expr, token=expr_token)

stream.eat(TOKEN_RPAREN)
return expr
return GroupExpression(expr)

def parse_absolute_query(self, stream: TokenStream) -> BaseExpression:
root = stream.next() # Could be TOKEN_ROOT or TOKEN_PSEUDO_ROOT
Expand Down Expand Up @@ -873,8 +902,12 @@ def _decode_string_literal(self, token: Token) -> str:
def _raise_for_non_comparable_function(
self, expr: BaseExpression, token: Token
) -> None:
if isinstance(expr, FilterQuery) and not expr.path.singular_query():
raise JSONPathTypeError("non-singular query is not comparable", token=token)
if isinstance(expr, FilterQuery):
if not expr.path.singular_query():
raise JSONPathTypeError(
"non-singular query is not comparable", token=token
)
return

if isinstance(expr, FunctionExtension):
func = self.env.function_extensions.get(expr.name)
Expand All @@ -885,9 +918,38 @@ def _raise_for_non_comparable_function(
raise JSONPathTypeError(
f"result of {expr.name}() is not comparable", token
)
return

if isinstance(expr, GroupExpression):
raise JSONPathTypeError("expression is not comparable", token)

def _raise_for_leading_zero(self, token: Token) -> None:
if (
len(token.value) > 1 and token.value.startswith("0")
) or token.value.startswith("-0"):
raise JSONPathSyntaxError("leading zero in index selector", token=token)

def _raise_for_not_compared(self, expr: BaseExpression, token: Token) -> None:
if isinstance(expr, FilterExpressionLiteral):
raise JSONPathSyntaxError(
"filter expression literals must be compared",
token=token,
)

if isinstance(expr, FunctionExtension):
func = self.env.function_extensions.get(expr.name)

if not func:
raise JSONPathNameError(
f"unknown function {expr.name!r}",
token=token,
)

if (
isinstance(func, FilterFunction)
and func.return_type == ExpressionType.VALUE
):
raise JSONPathTypeError(
f"result of {expr.name!r} must be compared",
token=token,
)
10 changes: 9 additions & 1 deletion jsonpath/path.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,16 @@ def finditer(
)
]

i = 0
for segment in self.segments:
matches = segment.resolve(matches)
# Guard against potential `RecursionError` from deeply nested generator
# functions.
i += 1 # noqa: SIM113

if i % 100:
matches = segment.resolve(matches)
else:
matches = list(segment.resolve(matches))

return matches

Expand Down
64 changes: 64 additions & 0 deletions tests/test_issues.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

from jsonpath import JSONPatch
from jsonpath import JSONPatchError
from jsonpath import JSONPathEnvironment
from jsonpath import JSONPathOverflowError
from jsonpath import JSONPathSyntaxError
from jsonpath import JSONPathTypeError
from jsonpath import JSONPointerIndexError
from jsonpath import findall
from jsonpath import pointer
Expand Down Expand Up @@ -131,3 +135,63 @@ def test_issue_124() -> None:

assert findall(query, data) == want
assert findall(query_raw, data) == want


def test_jsonpath_rfc9535_issue_37() -> None:
findall("$" + ".a" * 1000, {})
findall("$" + "..a" * 1000, {})


def test_jsonpath_rfc9535_issue_38() -> None:
with pytest.raises(JSONPathOverflowError):
WELL_TYPED_ENV.compile("$[?@ == 1e400]")


WELL_TYPED_ENV = JSONPathEnvironment(well_typed=True, strict=True)


def test_jsonpath_rfc9535_issue_39() -> None:
WELL_TYPED_ENV.compile("$[?@ == 0e1]")
WELL_TYPED_ENV.compile("$[?@ == 0E1]")
WELL_TYPED_ENV.compile("$[?@ == 0e-0027]")

with pytest.raises(JSONPathSyntaxError):
WELL_TYPED_ENV.compile("$[?@ == -01]")

with pytest.raises(JSONPathSyntaxError):
WELL_TYPED_ENV.compile("$[?@ == -00.5]")

with pytest.raises(JSONPathSyntaxError):
WELL_TYPED_ENV.compile("$[?@ == -01e1]")


def test_jsonpath_rfc9535_issue_41() -> None:
with pytest.raises(JSONPathTypeError):
WELL_TYPED_ENV.compile("$[?(@.a)==1]")

with pytest.raises(JSONPathSyntaxError):
WELL_TYPED_ENV.compile("$[?(1)==1]")

with pytest.raises(JSONPathTypeError):
WELL_TYPED_ENV.compile("$[?(@.a==1)==true]")

with pytest.raises(JSONPathSyntaxError):
WELL_TYPED_ENV.compile("$[?!!@]")

with pytest.raises(JSONPathSyntaxError):
WELL_TYPED_ENV.compile("$[?!true]")

with pytest.raises(JSONPathSyntaxError):
WELL_TYPED_ENV.compile("$[?!(true)]")

WELL_TYPED_ENV.compile("$[?!((true==true))]")


def test_jsonpath_rfc9535_issue_40() -> None:
WELL_TYPED_ENV.compile("$.a中")


def test_jsonpath_rfc9535_issue_42() -> None:
# `length` must be compared
with pytest.raises(JSONPathTypeError):
WELL_TYPED_ENV.compile("$[?!length(@)]")
Loading
Loading