Section 15.33

jsonschema and referencing

Full name: jsonschema and referencing: two Python libraries; jsonschema checks data against a JSON (JavaScript Object Notation) Schema, and referencing resolves the references between schema documents.

Definition

jsonschema is a Python §12.23 library that checks whether a JSON §12.26 (JavaScript Object Notation) document, called the instance, satisfies a JSON Schema §12.27: a JSON document that lists constraints, such as types, required fields and ranges. referencing is the library that jsonschema has used since version 4.18 to find the schema that a $ref keyword points to. It maps each URI (Uniform Resource Identifier), a name for a resource, to the schema stored under that name. Acceptance therefore depends on every schema reached through references, not only the first.

The idea

An order service validates each incoming order against order.json, a schema saying that the items list is described by another schema, limits.json, which allows at most 10 items. One morning an order with 15 items is accepted. Nobody changed order.json, the order format or the program. Someone changed limits.json to allow 20 items, or the server that limits.json was fetched from began to serve a different file.

The rule that decides acceptance is not one file but a graph of files. The root schema refers to others by URI, those may refer to more, and the validator follows the references while it validates. Whoever controls any file in that graph, or the lookup that turns a URI into a file, controls what is accepted. Fixing the rule therefore means fixing the whole graph and the lookup, and naming the dialect: the edition of the JSON Schema specification whose keyword meanings apply.

How it works

Four keywords take part:

Resolution happens in this order:

  1. The validator meets $ref while it checks an instance.

  2. It resolves the reference against the current base URI by the rules of RFC 3986, the URI standard [395]: limits.json inside a schema whose $id is https://example.com/order.json becomes https://example.com/limits.json.

  3. It asks the referencing Registry, a fixed collection of schemas stored under their URIs, for that URI. A registry never changes: with_resource returns a new registry with one more schema.

  4. If the registry holds no schema under that URI and was built with a retrieve function, it calls that function, which may read a file, a database or the network. Without a retrieve function, resolution fails with an error.

  5. The fragment selects part of the schema found, and validation continues with that part.

One default needs care. A jsonschema validator created without a registry argument uses a built-in fallback that downloads remote references over the network; as of jsonschema 4.25 it does so with a DeprecationWarning saying that automatic retrieval can be a security vulnerability and will become an error. The jsonschema documentation notes that the JSON Schema specifications discourage automatic retrieval over the network. A program that validates untrusted input should always pass a registry of its own.

To fix the accepted set:

  1. Keep every schema of the graph in local files, and record the SHA-256 §5.2 (Secure Hash Algorithm with a 256-bit output) digest of each file’s bytes in a manifest §13.4.

  2. At start-up, read each file, check its digest against the manifest, and add it to a Registry under its URI.

  3. Create the validator with that registry and no retrieve function, so that a reference outside the recorded set fails instead of being fetched.

  4. Name the dialect with $schema in every schema, or choose the validator class explicitly, such as Draft202012Validator.

  5. Record the versions of jsonschema and referencing, because their behavior is part of the rule.

The recorded graph is the schema’s dependency closure §13.6: everything it depends on, directly or through other schemas.

Worked example

The root schema order.json:

{"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.com/order.json",
"type": "object",
"properties": {"items":
{"$ref": "limits.json#/$defs/itemList"}}}

and the first version of limits.json:

{"$id": "https://example.com/limits.json",
"$defs": {"itemList":
{"type": "array", "maxItems": 10}}}

The instance is an object whose items list holds the 15 numbers 0 to 14. The validator meets $ref, resolves limits.json against https://example.com/order.json to https://example.com/limits.json, and the fragment /$defs/itemList selects {"type": "array", "maxItems": 10}. The list is a JSON array, but 15>1015 > 10, so validation fails with the message that the list is too long.

Now replace limits.json with a version that differs only in "maxItems": 20. Since 15≤2015 \le 20, the same instance passes. The bytes of order.json and of the instance are identical in both runs, so a digest of either is unchanged; only the referenced file differs. With jsonschema 4.25.1 and referencing 0.37.0, a Draft202012Validator given a registry that holds the first version reports the list as too long, one given the second version reports no error, and one given an empty registry raises an error naming the unresolvable reference limits.json#/$defs/itemList.

The dialect changes acceptance as well. Draft 7 of the specification [507] says that keywords next to $ref are ignored, and draft 2020-12 applies them [504]. A schema whose $ref points to {"type": "array"} and which also says "maxItems": 3 accepts a 5-element array when it is read as draft 7 and rejects the same array when it is read as draft 2020-12. jsonschema 4.25.1 gives exactly these two results.

Stated precisely

The set of instances a validator accepts is determined jointly by five things: the root schema; every schema reachable from it through references; the dialect applied to each schema; the validator implementation and its version, including whether it checks format; and the resolution policy, meaning the registry contents and any retrieve function. Holding the root schema fixed fixes none of the other four.

The accepted set is fixed when four conditions hold.

  1. Every schema reachable from the root is held locally and matches a recorded digest.

  2. The resolution policy performs no retrieval, so a reference outside the recorded set fails.

  3. The dialect is named explicitly, in every schema or by the validator class.

  4. The versions and options of the libraries, including the JSON parser that turns the instance’s bytes into data, are recorded and do not change.

Under these conditions, the same instance bytes give the same verdict on every run. The guarantee covers conformance to the schemas, nothing more.

Limits and common mistakes

A schema states shape, not permission. An instance that conforms can still name a file that must not be touched, request an operation the sender may not perform, or carry a number that the schema allows but that is too expensive to act on. Authorization §1.7 and resource limits are separate checks.

jsonschema does not check format by default. With "format": "date", the string not-a-date passes unless the validator is given a format checker, for example with this argument:

format_checker=Draft202012Validator.FORMAT_CHECKER

Schemas from untrusted sources are input too. A schema can reference a huge remote file, or carry a regular expression §12.44 in its pattern keyword that takes exponential time on some strings, which turns validation into an algorithmic complexity attack §15.35. Accept schemas only from a trusted, recorded set.

Missing or unresolvable references must fail closed §1.13. Resolution failure raises an error; a program that treats that error as a pass silently drops the constraint the reference carried.

JSON parsing comes first and has its own ambiguities. A document with a duplicate JSON key is read differently by different parsers, and the validator sees only what the parser kept.

A cache is a second source of truth. A cached copy of a URI and a freshly fetched copy can be two different rules under one name, so two validators can disagree about the same instance.

Questions answered

Can a remote or changed referenced schema alter accepted input?

Yes. A JSON Schema (a JSON document that lists the constraints valid data must meet) that uses $ref hands part of its rule to the referenced schema, so a change to the referenced schema, or to the place its URI (Uniform Resource Identifier) is fetched from, changes which inputs pass while the root schema and the input stay byte-for-byte the same. For example, a root schema that refers to limits.json with "maxItems": 10 rejects a list of 15 items; change limits.json to allow 20 and the same list passes.

The defense is to fix the whole reference graph. List every schema it contains, keep local copies checked against recorded SHA-256 (Secure Hash Algorithm with a 256-bit output) digests, load them into a referencing Registry, and give the validator that registry with no retrieve function, so that an unknown reference fails instead of being fetched. Always pass the registry explicitly: a jsonschema validator created without one falls back to downloading remote references, with only a deprecation warning. Also name the dialect with $schema and record the library versions, because a different dialect or library version can change acceptance too. Conformance to the schema still says nothing about permission, which needs its own check.

Related entries: JSON (§12.26), JSON Schema (§12.27), Source closure (§13.6), Duplicate JSON key (§15.20), Manifest (§13.4), Fail closed (§1.13). Further reading: [53, 54, 395, 504, 507].