Skip to content

feat(validation): stricter request checks - #686

Merged
uniqueg merged 7 commits into
devfrom
feat/617-stricter-validation
Nov 4, 2026
Merged

uniqueg merged 7 commits into
devfrom
feat/617-stricter-validation

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #617.

Connexion 2 lets three kinds of invalid requests through. New in foca.api.validation, for the app's APIs and the permissions API:

  • Unpaired surrogates in JSON bodies (e.g., \ud800), also in keys and nested strings, are refused with 400 instead of failing with 500 on storage. Only where Connexion checks bodies at all: operations with a schema and only JSON media types.
  • The formats date-time, date and uri are checked, which jsonschema only does with optional packages. Importing the module registers them on jsonschema's Draft 4 checker for the process, which is the object Connexion uses. So they apply to responses with validate_responses too, which then fail with 500, e.g., for stored timestamps without a time zone.
  • Query parameters of operations without parameters are refused with strict_validation, via a resolver wrapper. Extra parameters are handled here, not left to build: add support for Connexion 3+ #188. API keys in the query are exempt.

A custom body validator in validator_map wins, and takes over the surrogate check. To be revisited with the move to Connexion 3 (#188).

Docs: docs/configuration/api.md, docs/migration-0.21.md, docs/reference.md.

How it was verified

  • Local checks on Python 3.13 with own MongoDB: ruff, mypy, docs, pytest, 100% coverage.
  • Reviewers: both, two rounds. Round 1 found the query API key refusal, the overwritten validator_map, the permissions API without body check, and docs overstating the coverage; all fixed. Round 2 ran a matrix of apiKey security on Swagger 2 and OpenAPI 3 against real Connexion apps, without findings.
  • Not run: the lowest pin of jsonschema locally; CI covers it.
  • CI: see below.

Declined review findings

  • Registration in an explicit function instead of on import: the module has to be imported wherever the checks are used, and the global effect is documented in its docstring and the docs.
  • operation._security_schemes is private to Connexion: Connexion has no public accessor, FOCA already reads operation._operation, and the test of API keys goes through a real app, so a rename would show.
  • Operations with mixed media types or */* aren't checked: Connexion skips them for all body checks; documented.

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Enforce stricter request validation across application and permissions APIs to reject malformed values and undeclared query parameters consistently.

New Features:

  • Add stricter API and permissions request validation for invalid JSON strings, declared date-time/date/URI formats, and unexpected query parameters.

Bug Fixes:

  • Reject unpaired Unicode surrogates in JSON bodies with a client error instead of allowing later storage failures.
  • Apply the stricter format validation to response validation as well, surfacing invalid responses as server errors.

Enhancements:

  • Preserve application-supplied body validators while integrating the new validation behavior.
  • Allow query parameters used for API-key authentication while rejecting other undeclared parameters under strict validation.

Documentation:

  • Document the stricter request and response checks and their migration impact.

Tests:

  • Add coverage for surrogate detection, format validation, strict query parameters, API-key exceptions, custom validators, response validation, and permissions API behavior.

uniqueg and others added 4 commits November 4, 2026 08:49
Connexion 2 lets three kinds of invalid requests through:

- Unpaired surrogates in JSON bodies can't be encoded for storage, and
  fail with a server error: refused with a client error.
- The formats date-time, date and uri aren't checked without optional
  packages of jsonschema: registered on the format checker in use.
- Query parameters of operations without any parameters aren't checked
  with strict_validation: refused via a resolver wrapper.

To be revisited with the move to Connexion 3 (#188).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
From review: API keys in the query aren't extra parameters, validators
of apps are kept, the permissions API checks bodies as well, and the
format checks of the service info are public, in one place. Adds tests
of responses, dates, resolvers and the permissions API.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The body was refused before the query was looked at.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.21.0 milestone Nov 4, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Introduces centralized stricter validation for application and permissions APIs by extending Connexion's body and resolver hooks, registering additional JSON Schema formats, and documenting and testing the resulting 400/500 failure behavior and compatibility exceptions.

Sequence diagram for stricter request validation

sequenceDiagram
    actor Client
    participant API
    participant BodyValidator
    participant StrictParametersResolver
    participant Connexion

    Client->>API: Send request
    API->>BodyValidator: validate_schema(data, url)
    alt Unpaired surrogate
        BodyValidator-->>Client: 400 BadRequestProblem
    else Valid body
        BodyValidator->>Connexion: Validate schema and formats
        Connexion->>StrictParametersResolver: Resolve operation
        alt strict_validation and unexpected query parameter
            StrictParametersResolver-->>Client: 400 ExtraParameterProblem
        else API key query parameter
            StrictParametersResolver->>Connexion: Invoke operation
            Connexion-->>Client: API response
        end
    end
Loading

File-Level Changes

Change Details Files
Added centralized stricter validation for request bodies, schema formats, and query parameters.
  • Reject unpaired Unicode surrogates recursively in JSON bodies, including nested values and object keys.
  • Register and apply date-time, date, and uri format checks through Connexion's Draft 4 validator, including response validation.
  • Wrap operation resolution to reject undeclared query parameters under strict_validation while exempting query API keys.
  • Preserve application-supplied body validators and compose custom resolvers.
foca/api/validation.py
foca/api/register_openapi.py
foca/utils/service_info.py
Applied the stricter validation behavior to the permissions API.
  • Wrap the access-control resolver with strict query-parameter checking.
  • Install the surrogate-aware body validator for permission specifications.
foca/security/access_control/register_access_control.py
Added comprehensive coverage for validation behavior and integration points.
  • Test surrogate detection across nested structures and keys, valid bodies, deep nesting, and non-string values.
  • Test date-time/date/URI validation in bodies and parameters, invalid responses, strict query handling, API-key exemptions, custom validators, and resolver composition.
  • Test permissions API enforcement and update service-info format helper tests.
tests/api/test_validation.py
tests/security/access_control/test_enforcement.py
tests/utils/test_service_info_utils.py
Documented the new validation rules and migration impact.
  • Describe stricter request and response checks, media-type/schema limitations, custom validator precedence, and API-key exemptions.
  • Expose validation classes and date-related helpers in the reference documentation.
docs/configuration/api.md
docs/migration-0.21.md
docs/reference.md

Possibly linked issues


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 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (aa06849) to head (527226c).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #686   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           62        63    +1     
  Lines         8130      8197   +67     
=========================================
+ Hits          8130      8197   +67     
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 4, 2026 08:29

@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 3 issues

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

## Individual Comments

### Comment 1
<location path="foca/api/validation.py" line_range="33" />
<code_context>
+
+# The format checker that Connexion uses
+for _name, _check in (
+    ("date-time", is_date_time),
+    ("date", is_date),
+    ("uri", is_uri),
</code_context>
<issue_to_address>
**Invalid leap seconds pass validation**

When a request or response contains a `date-time` value with seconds `60` at a time that is not a leap second, `is_date_time` accepts the value without verifying that the leap second occurs at the end of the day, so the registered format checker lets invalid `date-time` values pass request and response validation.

Update `is_date_time` to accept seconds `60` only for an actual leap second at the end of a day.

Also at `foca/utils/service_info.py:65`, `foca/api/validation.py:37`.
</issue_to_address>

### Comment 2
<location path="foca/api/validation.py" line_range="37" />
<code_context>
+    ("date", is_date),
+    ("uri", is_uri),
+):
+    Draft4Validator.FORMAT_CHECKER.checks(_name)(_check)
+
+
</code_context>
<issue_to_address>
**Unrelated validators accept malformed URIs**

When another component in the process validates formats using the shared Draft 4 checker, `Draft4Validator.FORMAT_CHECKER.checks` replaces the URI checker on the shared Draft 4 checker with FOCA’s intentionally lenient `is_uri`; other components that reuse that checker then accept URI values their previous checker rejected.

Scope the custom format checker to FOCA’s Connexion validators instead of changing the shared checker.
</issue_to_address>

### Comment 3
<location path="tests/api/test_validation.py" line_range="375-377" />
<code_context>
+
+        resolver = StrictParametersResolver(_resolve)
+        operation = MagicMock(strict_validation=True)
+        resolution = resolver.resolve(operation)
+        assert isinstance(resolution, Resolution)
+        assert len(calls) == 1
+
+
</code_context>
<issue_to_address>
**Custom resolver result goes unchecked**

When the wrapper invokes the custom resolver but fails to preserve its returned function, if `StrictParametersResolver.resolve` calls the configured resolver but discards its returned function, this test still passes: it checks only that the result is a `Resolution` and that the resolver was called once. The app can then dispatch the wrong function without this test catching it.

Assert that invoking the resulting resolution dispatches to the function returned by the custom resolver.
</issue_to_address>

Linked issues

#617 feat(validation): stricter request checks · 5 of 5 met

# Requirement Status Notes
1 Refuse unpaired surrogates in bodies, including nested strings ✅ Met BodyValidator checks strings recursively, including dictionary keys and nested values; tests cover both nested strings and keys.
2 Check JSON Schema formats such as date-time ✅ Met The Draft 4 format checker registers checks for date-time, date, and uri; tests cover body and parameter validation, and response validation.
3 Refuse extra query parameters on parameterless operations with strict_validation ✅ Met StrictParametersResolver rejects extras for parameterless operations and exempts query API keys; tests cover these cases.
4 Test each case, including nested strings, with 100% coverage ✅ Met Tests cover the listed validation cases, including nested surrogate strings; the PR description reports 100% coverage.
5 Document that format checks can make previously passing requests fail ✅ Met The API documentation describes the format checks, and the migration guide warns that previously accepted values can now fail.

Sourcery assessment

Approval pending. 3 findings to address first.

Blocking findings: foca/api/validation.py:33, foca/api/validation.py:37, tests/api/test_validation.py:377


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

Comment thread foca/api/validation.py Resolved
Comment thread foca/api/validation.py Resolved
Comment thread tests/api/test_validation.py Resolved
@uniqueg
uniqueg merged commit 359ae43 into dev Nov 4, 2026
58 checks passed
@uniqueg
uniqueg deleted the feat/617-stricter-validation branch November 4, 2026 09:48
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.

feat(validation): stricter request checks

1 participant