python-jsonschema / jsonschema

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

float number, range validation failure #1274

Closed trolldbois closed 3 weeks ago

trolldbois commented 3 weeks ago

It seems that jsonschema fails to properly validate number type in a range.

cve-short-test-fail.json cve-short-test-success.json number_float_schema.json

When using jsonschema to validate float number in a range, the validation fails. Attached

the failure tested on python 3.12.4 , jsonschema 4.22 (screenshots attached ) jsonschema-number-float-validation-fail jsonschema-number-float-validation-fail-schema

Schema was tested successfully, no validation error in

Julian commented 3 weeks ago

Hi there. You haven't provided your code so it's not a sure thing, but I'd bet you've used float division (as it's the default when loading JSON) and expecting non-float behavior. For floats, 5.6 indeed is not divisible by 0.1.

If you don't want that, don't use floats, e.g.:

⊙  ~[jsonschema:python] -c '
quote> from pathlib import Path                                                     
import decimal
import json

import jsonschema.validators

def load(path):
    return json.loads(path.read_text(), parse_float=decimal.Decimal)

fail = load(Path("cve-short-test-fail.json"))
success = load(Path("cve-short-test-success.json"))
schema = load(Path("number_float_schema.json"))

Validator = jsonschema.validators.validator_for(schema)
validator = Validator(schema)
print(validator.is_valid(fail))
print(validator.is_valid(success))
'
True
True

(I thought I'd added this to the FAQ, but it's certainly covered in quite a few previous issues. I'll add it at some point.)

trolldbois commented 3 weeks ago

Thank you for the fast answer @Julian
I used the jsonschema module main command line for the validation.

python -m jsonschema -i cve-short-test-fail.json number_float_schema.json

I also tried the same with check-jsonschema , same result.

I can see how this could be solved. thanks

Julian commented 3 weeks ago

I'm not as familiar with check-jsonschema as one might expect, but I'd either look for an option there to configure how it deserializes JSON or else in the event it doesn't yet have one, open an issue.

trolldbois commented 3 weeks ago

Thanks, I tried your proposal on the original codebase (cvelib), and it fixes the issue.

Many thanks !