python-jsonschema / jsonschema

An implementation of the JSON Schema specification for Python
https://python-jsonschema.readthedocs.io
MIT License
4.58k stars 578 forks source link

Wrong behaviour for enum keyword #1208

Closed otto-ifak closed 7 months ago

otto-ifak commented 8 months ago

The following schema accepts the instance although it should be rejected:

from jsonschema import validate
schema = {
    "enum": [
        [False]
    ],
    "$schema": "https://json-schema.org/draft/2020-12/schema"
}
instance = [0]
validate(instance, schema)  # erroneously accepts the instance

I guess, this is caused by the following line: https://github.com/python-jsonschema/jsonschema/blob/256dadd3539861ae696c03805923eb4097b871f9/jsonschema/_keywords.py#L271

([0] in [[False]] is true, so [0] not in [[False]] is false)


📚 Documentation preview 📚: https://python-jsonschema--1208.org.readthedocs.build/en/1208/

otto-ifak commented 8 months ago

There is currently no test for this PR, maybe you could give me a hint where to put it? Also, I am not sure if this change has a performance impact.

Julian commented 8 months ago

Thanks for the PR! I haven't looked carefully at it yet, but as for:

There is currently no test for this PR, maybe you could give me a hint where to put it?

The first step here would be a PR to the official JSON Schema test suite, specifically in the enum.json test file for each draft.

Once that's merged, we can bring the update in here, and then should be able to consider the PR.

Can you have a look there and let me know if you run into any trouble?

otto-ifak commented 7 months ago

Thanks for your reply. I have created the PR:

https://github.com/json-schema-org/JSON-Schema-Test-Suite/pull/712

gregsdennis commented 7 months ago

I'm not sure how implicit casting works in python, but is it possible that [0] and [False] are the same thing in python?

(I get that they're not the same in JSON.)

otto-ifak commented 7 months ago

@gregsdennis yes, that is right: In Python 0 == False holds, so that [0] == [False] holds and so does [0] in [[False]] hold, which is the cause for this issue.

Julian commented 7 months ago

Thanks again @otto-ifak!

otto-ifak commented 7 months ago

@Julian you're welcome - thank you for this great library :smile: