diff --git a/CHANGELOG.md b/CHANGELOG.md index af8993c..298584d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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** @@ -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** diff --git a/jsonpath/__about__.py b/jsonpath/__about__.py index 7a5a1a3..943015f 100644 --- a/jsonpath/__about__.py +++ b/jsonpath/__about__.py @@ -1,4 +1,4 @@ # SPDX-FileCopyrightText: 2023-present James Prior # # SPDX-License-Identifier: MIT -__version__ = "2.3.0" +__version__ = "2.3.1" diff --git a/jsonpath/__init__.py b/jsonpath/__init__.py index 86156bc..9fa6f5a 100644 --- a/jsonpath/__init__.py +++ b/jsonpath/__init__.py @@ -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 @@ -63,6 +64,7 @@ "JSONPathIndexError", "JSONPathMatch", "JSONPathNameError", + "JSONPathOverflowError", "JSONPathSyntaxError", "JSONPathTypeError", "JSONPointer", diff --git a/jsonpath/exceptions.py b/jsonpath/exceptions.py index 0585022..14f1203 100644 --- a/jsonpath/exceptions.py +++ b/jsonpath/exceptions.py @@ -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.""" diff --git a/jsonpath/filter.py b/jsonpath/filter.py index 494e2bc..114f254 100644 --- a/jsonpath/filter.py +++ b/jsonpath/filter.py @@ -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.""" @@ -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): diff --git a/jsonpath/lex.py b/jsonpath/lex.py index 2ab0838..65dfdcf 100644 --- a/jsonpath/lex.py +++ b/jsonpath/lex.py @@ -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` diff --git a/jsonpath/parse.py b/jsonpath/parse.py index 6ea4f6b..f3ee694 100644 --- a/jsonpath/parse.py +++ b/jsonpath/parse.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +import math import re from typing import TYPE_CHECKING from typing import Callable @@ -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 @@ -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 @@ -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.""" @@ -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 @@ -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: @@ -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 @@ -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) @@ -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, + ) diff --git a/jsonpath/path.py b/jsonpath/path.py index cf305e3..e62179d 100644 --- a/jsonpath/path.py +++ b/jsonpath/path.py @@ -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 diff --git a/tests/test_issues.py b/tests/test_issues.py index cfc2ad0..3070c1d 100644 --- a/tests/test_issues.py +++ b/tests/test_issues.py @@ -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 @@ -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(@)]") diff --git a/tests/test_parse.py b/tests/test_parse.py index 8415b74..d3206c7 100644 --- a/tests/test_parse.py +++ b/tests/test_parse.py @@ -140,12 +140,12 @@ class Case: Case( description="filter with logical not", path="$.some[?(@.thing > 1 and not $.other)]", - want="$['some'][?@['thing'] > 1 && !$['other']]", + want="$['some'][?(@['thing'] > 1 && !$['other'])]", ), Case( description="filter with grouped expression", path="$.some[?(@.thing > 1 and ($.foo or $.bar))]", - want="$['some'][?@['thing'] > 1 && ($['foo'] || $['bar'])]", + want="$['some'][?(@['thing'] > 1 && ($['foo'] || $['bar']))]", ), Case( description="keys selector",