sanic-org / sanic-ext

Extended Sanic functionality
https://sanic.dev/en/plugins/sanic-ext/getting-started.html
MIT License
50 stars 36 forks source link

[Bug] pydantic validation exception when validating unknown query strings #256

Closed Panaetius closed 3 months ago

Panaetius commented 3 months ago

Describe the bug when validating query strings with @validate(query=MyModel), the code can fail with a key error before reaching actual pydantic validation if query parameters not on the model are supplied.

Specifically, https://github.com/sanic-org/sanic-ext/blob/main/sanic_ext/extras/validation/clean.py#L6 fails because data contains a key that isn't in hints, as the model doesn't have that key that was sent in data.

This will lead to a KeyError instead of a pydantic ValidationError, making it hard to deal with. In our case, we pretty format ValidationError before returning errors to the client, but KeyError will just be a generic 500 error. And we don't want to catch all KeyErrors, as there could be KeyErrors unrelated to validation as well.

Expected behavior A pydantic ValidationError to be created (if the Model has extra = "forbid") or validation to pass (if the model has extra = "ignore")

Environment (please complete the following information):

Additional context We use schemathesis to test our API, which will create many negative test cases like passing random arguments, and it expects those to fail with a 4xx error, but the issue above causes 500 errors, failing schemathesis.

Pirulax commented 3 months ago

Duplicate of #247? Also, related to validate: #257

Panaetius commented 3 months ago

ah yes you're right. I had searched for open issues and couldn't find one for some reason

I'll close this one