Skip to content

fix: match pattern $ only at the end of values - #810

Merged
uniqueg merged 5 commits into
devfrom
fix/797-pattern-end-anchor
Nov 21, 2026
Merged

uniqueg merged 5 commits into
devfrom
fix/797-pattern-end-anchor

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

Summary

Connexion and jsonschema check pattern with Python's re.search(), where $ also matches before a newline at the end, so ^[0-9a-f]{24}$ accepted "<24 hex digits>\n" (e.g., ?pageToken=...%0A), and controllers that parse such values further could answer 500. ECMA 262, to which JSON Schema and OpenAPI refer, matches $ only at the end.

FOCA's request validation (foca/api/validation.py) now checks pattern as in ECMA 262 at the end of values:

  • _end_anchored() replaces anchors $ by \Z, keeping escaped dollar signs, those in sets (read as Python reads sets, including a leading ]) and those in (?#...) comments (ended by the first unescaped )); cached with lru_cache.
  • Bodies: BodyValidator uses Connexion's Draft4RequestValidator extended with FOCA's pattern check, unless a validator class is passed.
  • Parameters (query, path, header, cookie, form data): after Connexion accepts a parameter, FOCA checks it again if a pattern of its schema has a $ (same message as Connexion's reason); FOCA's own listing of invalid parameters (after the first invalid one, or after an invalid body) uses the same check (shared _schema_errors()).
  • Field errors: pattern-mismatch, as before for other pattern errors.
  • Unchanged: response validation, patternProperties keys, and apps with their own body or parameter validator in validator_map.

Docs: "Stricter request checks" in docs/configuration/api.md, and a new section "Patterns match at the end only" in docs/migration-0.23.md (listed in its intro), as requests with a trailing newline that passed before are now refused with 400.

Closes #797

Verification

  • Test-driven: the new TestPatterns tests in tests/api/test_validation.py (query, path and body parameters with a trailing %0A, body + parameters, after the first invalid parameter, translation table, default and custom body validator, custom parameter validator) failed before the fix and pass now.
  • pytest tests/api/test_validation.py: 113 passed; coverage of foca/api/validation.py 100%.
  • Full unit suite (coverage run -m pytest): 5242 passed, 2 skipped. The 246 MongoDB-dependent tests failed in the first run because the local mongod couldn't start in the sandbox; I reran them against a private MongoDB 7.0 on port 12345: 1150 passed, 2 skipped (8 files: tests/factories/test_celery_worker_fork.py, tests/plugins/test_plugin_store.py, tests/security/access_control/..., tests/test_cli.py, tests/testing/test_pytest_plugin.py). The overall coverage gate therefore didn't run in a single local pass; CI runs it.
  • ruff check, ruff format --check, mypy: clean. mkdocs build --strict: passes.
  • Not run locally: integration tests, Helm chart and image jobs (CI).
  • Sourcery's finding on $ref parameter schemas: Connexion resolves references before validation; covered by the new test_referenced_schema (passes without code changes), thread answered and resolved.
  • CI: run 44869054737 on the head commit passed, as did run 44866683544 (unit tests with coverage, lowest dependencies, integration, charts, scans, CI passed), after merging dev (conflict in the intro list of docs/migration-0.23.md, both bullets kept).

Declined review findings

  • (?m) patterns: $ becomes \Z under Python's inline MULTILINE flag as well. Declined: ECMA 262 has no inline flags, so these patterns aren't valid JSON Schema patterns anyway. The behaviour is documented.
  • Comments in verbose patterns ((?x), #) aren't recognized, so anchors after a [ in such a comment keep Python's meaning (fails open). Declined: Python-only syntax; documented in the docstring.
  • _has_end_anchor() scans each parameter schema per request and has no cycle guard. Declined: schemas are small; recursive parameter schemas already fail in Connexion before this check (RecursionError).
  • _pattern_reason() repeats the null and file checks of _parameter_errors(). Declined: the schema check is shared (_schema_errors()); the remaining checks are three lines, and the two functions return different things.
  • BodyValidator.__init__ repeats the signature of Connexion 2's RequestBodyValidator. Kept on purpose, with a note: it mirrors Connexion 2 until the move to Connexion 3 (build: add support for Connexion 3+ #188).

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 3 commits November 21, 2026 03:36
Connexion and jsonschema check `pattern` with Python's `re.search()`,
where `$` also matches before a trailing newline, so `^[0-9a-f]{24}$`
accepted "<24 hex digits>\n". ECMA 262, to which JSON Schema and
OpenAPI refer, matches `$` only at the end.

FOCA's body and parameter validators now check `pattern` with `$`
anchors replaced by `\Z` (escapes and sets kept). Parameters that
Connexion accepted are checked again only if a pattern has a `$`.
Docs: stricter request checks and the 0.23.0 migration guide.

Closes #797

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Keep `$` in pattern comments, share the schema check of parameters,
type the body validator's arguments, test the default body validator,
and document inline flags and custom parameter validators.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
As in Python, an escaped `)` does not end a `(?#...)` comment. Also
test custom parameter validators and rewrap the docs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg self-assigned this Nov 21, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Implementation

Translate unescaped $ anchors in request patterns to \Z and apply the ECMA 262 matching behavior to body and parameter validation, preserving custom validators and existing error handling.

  • foca/api/validation.py L73-180, L224-260, L410-457 (+4 small edits)

Documentation

Explain the stricter request pattern semantics and identify the migration impact for clients sending values with trailing newlines.

  • docs/configuration/api.md L221-232
  • docs/migration-0.23.md L20-22, L229-245

Tests

Cover anchor translation and matching, nested and referenced schemas, request validation errors, and custom validator behavior.

  • tests/api/test_validation.py L142-151, L456-606, L748-758 (+6 small edits)

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (4f5412d) to head (2754a94).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #810   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           76        76           
  Lines        10568     10634   +66     
=========================================
+ Hits         10568     10634   +66     
Flag Coverage Δ
test_unit 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@uniqueg
uniqueg marked this pull request as ready for review November 21, 2026 04:45
@sourcery-ai

sourcery-ai Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit 2754a94

#797 fix: schema patterns accept a trailing newline · 2 of 2 met

# Requirement Status Notes
1 Make request body and parameter pattern checks match $ only at the end of values. ✅ Met The default body and parameter validators replace unescaped $ anchors outside sets and comments with \Z; the checks also cover nested schemas.
2 Test trailing newlines on query parameters, path parameters, and body fields. ✅ Met The new tests exercise all three cases and assert the requests are rejected.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="foca/api/validation.py" line_range="452" />
<code_context>
+    if value is None or (is_nullable(param) and is_null(value)):
+        return None
+    schema = param.get("schema", param)
+    if schema.get("type") == "file" or not _has_end_anchor(schema):
+        return None
+    # Converted by Connexion already, without error
</code_context>
<issue_to_address>
**Referenced parameter patterns are skipped**

When an operation parameter references a schema whose pattern ends in `$`, `_has_end_anchor` does not follow `$ref` targets, so `_pattern_reason` skips its strict check when the parameter schema is a reference. Connexion's Python regex check then accepts a trailing newline, and the request reaches the controller with a value the referenced pattern was meant to reject.

Resolve parameter schema references before scanning and validating them, or use the same resolved schema Connexion validated.
</issue_to_address>

Sourcery assessment

Approval pending. 1 finding to address first.

Blocking findings: foca/api/validation.py:452


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread foca/api/validation.py Resolved
@uniqueg
uniqueg merged commit 2b1e6fb into dev Nov 21, 2026
129 of 133 checks passed
@uniqueg
uniqueg deleted the fix/797-pattern-end-anchor branch November 21, 2026 05:36
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.

fix: schema patterns accept a trailing newline

1 participant