NordicSemiconductor / zcbor

Low footprint C/C++ CBOR library and Python tool providing code generation from CDDL descriptions.
Apache License 2.0
118 stars 37 forks source link

.validate_str() not validating float size. #318

Closed rmsaad closed 9 months ago

rmsaad commented 1 year ago

Hello, I have come across a limitation to using .validate_str(). It does not respect float size when validating. here is an example:

cddl file:

test = {
    "var" => float32,
}

sample code:

import cbor2
import zcbor
import os

CDDL_PATH = "."
MX_QTY = 3

def read_cddl(cddl_filename):
    script_dir = os.path.dirname(__file__)
    abs_file_path = os.path.join(script_dir, CDDL_PATH) 
    with open(f'{abs_file_path}/{cddl_filename}', 'r') as file:
        cddl = zcbor.DataTranslator.from_cddl(file.read(), MX_QTY)
        return cddl

def validate_test(data):
    try:
        encoded_data = cbor2.dumps(data)
        read_cddl("test.cddl").my_types['test'].validate_str(encoded_data)
        print("Matched cddl")
    except zcbor.CddlValidationError:
        print("Did not match cddl schema")

if __name__=="__main__":

    test = {
        "var": 32.0,
    }

    validate_test(test) # expecting cddlValidation error because double instead of float (32 bit)

    enc_data = cbor2.dumps(test)
    print(enc_data.hex(' ').upper()) # 0xfb indicating double precision

validate_str() is telling me that the encoded data matches the cddl file but that is not really the case, the data is 64 bit but the cddl specifies a 32 bit float.

oyvindronningstad commented 1 year ago

Yes, this is unfortunately a limitation in the cbor2 library that zcbor depends on. It does not allow the user to know what size the float was.