Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Trust boundaries and input validation

At an input boundary, bound the size before parsing and validate the resulting value against application rules.

Version: Python 3.14; repository image, production runtime not attested

Syntax

data = json.loads(raw)
if type(data) is not int:
    raise ValueError('integer required')

At an input boundary, bound the size before parsing and validate the resulting value against application rules.

A JSON parser checks syntax, but does not know that a quantity must be an integer from 1 to 50. On bytes input len counts bytes. The exact int check rejects bool despite its int ancestry.

Input 12 passes. Syntactically valid true and 51 are rejected with quantity.

import json
def parse(raw):
    if len(raw)>32: raise ValueError('size')
    value=json.loads(raw)
    if type(value) is not int or not 1<=value<=50: raise ValueError('quantity')
    return value
assert parse(b'1')==1 and parse(b'50')==50
for raw in (b'false',b'1.0',b'0',b' '*33,b'{'):
    try: parse(raw)
    except ValueError: pass
    else: raise AssertionError

Examples

import json

def quantity(raw):
    if len(raw) > 32:
        raise ValueError("size")
    value = json.loads(raw)
    if type(value) is not int or not 1 <= value <= 50:
        raise ValueError("quantity")
    return value

for raw in (b"12", b"true", b"51"):
    try:
        print(quantity(raw))
    except ValueError as exc:
        print(str(exc))

Result

12
quantity
quantity

Input 12 passes. Syntactically valid true and 51 are rejected with quantity.

Sources