Skip to content

pattern: preserve literal $ in classes and anchor $ after even backslashes - #247

Open
PStarH wants to merge 1 commit into
horejsek:masterfrom
PStarH:fix/pattern-dollar-escaping
Open

PStarH wants to merge 1 commit into
horejsek:masterfrom
PStarH:fix/pattern-dollar-escaping

Conversation

@PStarH

@PStarH PStarH commented Nov 27, 2026

Copy link
Copy Markdown

Problem

DOLLAR_FINDER rewrites an unescaped $ to Python's \Z so that JSON Schema pattern gets ECMA-262 end-of-input behavior instead of Python's $ (which also matches before a final newline). The rewrite is:

DOLLAR_FINDER = re.compile(r"(?<!\\)\$")  # Finds any un-escaped $ (including inside []-sets)

It has two issues:

  1. Even backslashes are skipped. In \\$, the $ is an anchor after a literal backslash, but the negative lookbehind sees a backslash and leaves it unchanged. Python then accepts "\\\n", although ECMA-262 requires the input to end after the backslash.
  2. Literal $ inside a character class is rewritten. [$] becomes [\Z], which Python rejects with re.PatternError: bad escape \Z.

Both pattern and patternProperties are affected; propertyNames reaches the same code through pattern.

Reproduction

import fastjsonschema
from fastjsonschema import JsonSchemaValueException

def outcome(validate, value):
    try:
        validate(value)
        return "accepted"
    except JsonSchemaValueException:
        return "rejected"

validate = fastjsonschema.compile({"type": "string", "pattern": r"\\$"})
print(outcome(validate, "\\"))    # accepted
print(outcome(validate, "\\\n"))  # accepted on HEAD; should be rejected

fastjsonschema.compile({"type": "string", "pattern": "[$]"})
# re.PatternError: bad escape \Z at position 1

The parity failure also reproduces through patternProperties:

fastjsonschema.compile({
    "type": "object",
    "patternProperties": {r"\\$": {"type": "integer"}},
    "additionalProperties": False,
})({"\\\n": 1})  # accepted on HEAD; should be rejected

Expected behavior

JSON Schema Validation 2020-12 §6.3.3 requires pattern to be a valid ECMA-262 regular expression and notes that patterns are not implicitly anchored. ECMA-262 $ asserts end of input unless the m flag is set; JSON Schema does not set m.

Bun 1.3.14 confirms the oracle:

$ bun -e 'const r = /\\$/; console.log(r.toString(), r.test("\\"), r.test("\\\n"));'
/\\$/ true false

[$] is a character class containing a literal dollar sign and must compile and match strings containing $.

Fix

Replace the regex substitution with a small scanner that tracks escape state and character-class state:

def _fix_pattern(pattern: str) -> str:
    result = []
    escaped = False
    in_class = False
    class_first = False
    for char in pattern:
        if escaped:
            result.append(char)
            escaped = False
        elif char == '\\':
            result.append(char)
            escaped = True
        elif in_class:
            result.append(char)
            if class_first:
                if char == '^':
                    continue
                class_first = False
                if char == ']':
                    continue
            elif char == ']':
                in_class = False
        elif char == '[':
            result.append(char)
            in_class = True
            class_first = True
        elif char == '$':
            result.append(r'\Z')
        else:
            result.append(char)
    return ''.join(result)

Both call sites use it:

-            end_of_string_fixed_pattern = DOLLAR_FINDER.sub(r'\\Z', pattern)
+            end_of_string_fixed_pattern = _fix_pattern(pattern)

The scanner preserves \$ and $ inside [...], still rewrites unescaped $ outside classes, and handles an even number of backslashes because escape state is consumed pairwise. DOLLAR_FINDER and its misleading comment are removed.

Tests

Added tests/test_pattern_dollar_character_class.py, covering:

  • [$], [^$], [a$], [\$], and []] in pattern;
  • $ after two and four backslashes, including rejection of a trailing newline;
  • the same cases through patternProperties with additionalProperties: False;
  • propertyNames with pattern: "[$]".

Results on 89805b9:

  • Before the fix: the new file reports 8 failed, 3 passed.
  • After the fix: 183 passed across the affected modules (test_pattern_dollar_character_class.py, test_string.py, test_pattern_properties.py, test_object.py).
  • qa_harness.py: {"ok": true, "drafts": 5, "checks": 208, "failures": []}. The same harness exits 1 with 39 failures on the original source.

Prior art

The parity bug is the primary fix here; the class crash is fixed at the same time because both come from the same helper.

Changelog

Added under === UNRELEASED:

* Fixed `$` anchors preceded by an even number of backslashes in `pattern` and `patternProperties` matching before a trailing newline, and `$` inside a character class crashing compilation

Replace DOLLAR_FINDER with a scanner that tracks backslash parity and character-class state. This stops rewriting a literal $ inside [...], and correctly anchors $ after an even number of backslashes in pattern and patternProperties.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant