RFC 8785 and stable JSON bytes for a warehouse receipt
A two-field inventory record illustrates the 2020 JSON canonicalization standard. The test compares raw bytes, canonical digests and rejected inputs.
Archive retrospective · Topic year 2020
In this article
One delivery record, two byte digests
A warehouse counting client sends a small JSON document with a product code and the number counted. One tool writes fields in data-entry order. Another writes them alphabetically. Whitespace also varies with the producer. The parsed records hold equal values, but their raw SHA-256 digests differ because the algorithm receives different bytes. A service comparing that digest with a delivery receipt may reject a valid file solely because serialization changed. Published in 2020, RFC 8785 specifies the JSON Canonicalization Scheme for producing a defined representation of JSON values. This worksheet applies the idea to a small warehouse schema. Both producers should see the same bytes for identical codes and counts. The producer and receiver agree which representation the receipt covers, so they can reproduce it on their own systems.
Define the accepted values first
The record has two fields. sku is a nonempty string of ASCII letters and digits. units is a whole number from zero to one hundred thousand. The program rejects extra fields and repeated member names. Python's ordinary JSON parser can collapse repeated names into a dictionary retaining the last value. The object_pairs_hook lets this example catch repeats while the members are still separate pairs. That avoids inconsistent choices when multiple receivers see different values for the same name. A literal 3.0 also fails the example's integer rule. General JSON numbers cover more forms, and another contract could accept them. This count has no need for floating-point conversion. Python treats bool as a subclass of int, so the validation uses the exact type of the count. That keeps a JSON true value from becoming a unit count.
Compare the bytes in a local run
The first text begins with units and has spaces around separators. The second starts with sku and uses compact punctuation. The test first checks that their raw digests differ. It then verifies equal bytes after validation and serialization. On Windows with Python 3.12.10, the result was {"sku":"N17","units":3}. Its SHA-256 digest was c3105d649829b918c9d4770f767eb2ae461443f973ea51d74fffcfc306383e52. Changing the count to four produced different canonical bytes. A repeated units field was rejected as a duplicate member, and a 3.0 literal was rejected as unsupported. These cases test three behaviors together. Formatting differences disappear, changes to the actual payload survive, and ambiguous input fails early. The local runtime is current. The specification published in 2020 is the historical reference. The same vectors can be run separately on older warehouse clients.
import hashlib
import json
def unique_object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError(f'duplicate member: {key}')
result[key] = value
return result
def canonical_manifest(text):
record = json.loads(text, object_pairs_hook=unique_object)
if (type(record) is not dict or set(record) != {'units', 'sku'}
or type(record['units']) is not int
or not 0 <= record['units'] <= 100_000
or type(record['sku']) is not str
or not record['sku'].isascii() or not record['sku'].isalnum()):
raise ValueError('unsupported manifest')
return json.dumps(record, separators=(',', ':'), sort_keys=True).encode('utf-8')
first = '{ "units" : 3, "sku" : "N17" }'
second = '{"sku":"N17","units":3}'
payload = canonical_manifest(first)
assert payload == canonical_manifest(second) == b'{"sku":"N17","units":3}'
assert hashlib.sha256(first.encode()).digest() != hashlib.sha256(second.encode()).digest()
assert payload != canonical_manifest('{"sku":"N17","units":4}')
for invalid in ('{"sku":"N17","units":3,"units":4}', '{"sku":"N17","units":3.0}'):
try:
canonical_manifest(invalid)
except ValueError as error:
print('rejected:', error)
else:
raise AssertionError('invalid input accepted')
print(payload.decode())
print('SHA-256:', hashlib.sha256(payload).hexdigest())
Beyond the worksheet's limited schema
Sorting the two ASCII member names and omitting whitespace works for these specific fields. Full JCS sorts names by UTF-16 code units. Names outside ASCII, especially characters outside the basic multilingual plane, can expose differences from Python's everyday string ordering. JCS also uses ECMAScript number serialization. It preserves array order and sorts members of objects inside arrays. It defines how to handle escaping and invalid Unicode. Extending the worksheet to arbitrary JSON would require exercising all those behaviors. Interoperating with an outside implementation calls for a common collection of standard test vectors. Where the schema is deliberately limited, include the restriction and rejection conditions in the contract. Adding new types can change the byte guarantees even if existing sample documents still pass.
Make the receipt reproducible
A receipt can store the document format version, digest algorithm and canonical digest in separate fields. When a client upgrades, the server can still recognize old-format submissions and apply the corresponding version. Give each producer a sample record with expected bytes and a digest. If the business also retains the uploaded file, store its raw digest separately. The raw digest tracks the actual transfer bytes. The canonical digest tracks the agreed representation of the document. A transfer that changes character encoding or adds an encoding marker may alter the former. Specify which encodings are accepted before parsing. This example emits UTF-8 bytes directly. Limit oversized and malformed input at the application boundary, where doing so can prevent extra work before serialization even begins.
Authentication and duplicate delivery
A matching digest helps compare representations. Sender identity needs an authenticated transfer or an appropriate signature. A previously accepted document produces the same digest on replay, so the application checks the delivery identifier, operation and any sequencing rules separately. Consider a corrected inventory count whose quantity happens to be unchanged. The intent of the correction belongs in the delivery metadata. Write separate application tests for the first approved delivery, a repeated request returning the original receipt, and an authorized correction using a different identifier. The worksheet establishes that its document bytes are stable. The service that updates warehouse records must test access decisions, sender authentication and repeat handling at their own boundaries. The expected byte string gives those tests a small common fixture.
Acceptance vectors for two producers
Ask two clients to produce the same stock count with different field orders in their first integration run. Both compute the receipt digest locally and compare it with the shared fixture. Then send counts of three and four and check that the application records a change. Where raw documents cannot be shared in a fault report, keep the schema version, error class and digest algorithm. Expand the fixture set with minimum and maximum counts, an empty SKU, and a duplicated field. One matching sample gives limited evidence about compatibility over the supported input range.
Reader discussion
How would you measure this development's real-world impact?
No comments yet. Be the first to contribute.
Write a comment