Property-Based Testing
A fuzzer asks one question of every input: does the program crash? Many security bugs never crash. A codec that silently corrupts long inputs, a parser that accepts a message the serialiser can never produce, an authorisation check that gives a different answer for the same user written in upper case: all of these return politely. Property-based testing (PBT) asks a richer question. You state a property that must hold for every input, a tool generates hundreds of inputs, and when one breaks the property it shrinks it to a minimal counterexample. It is fuzzing with a smarter oracle, run inside your unit-test suite.
Properties worth testing
| Property | Example | Catches |
|---|---|---|
| round trip | decode(encode(x)) == x |
lost or corrupted data, truncated counters |
| never raises / never crashes | parse(any_bytes) returns or rejects, never throws an unexpected exception |
robustness bugs, denial of service |
| differential | fast_impl(x) == reference_impl(x) |
optimisation bugs, the JIT bugs of a later lesson |
| invariant | the result is sorted; a balance is never negative; output length is bounded | logic bugs |
| idempotence | normalise(normalise(p)) == normalise(p) |
path and URL canonicalisation bugs that enable traversal |
| metamorphic | allowed(user) equals allowed(user.upper()) when names are case-insensitive |
inconsistent security decisions |
The best security properties come from the threat model: "a path that the check accepts must still point inside the upload folder after normalisation", "two parsers in the request chain must agree on where a request ends" (the root of request smuggling, see Request Smuggling and Cache Poisoning).
A tiny property-based tester
Libraries such as Hypothesis (Python), QuickCheck (Haskell), proptest (Rust) and jqwik (Java) do the generating and shrinking for you. To see the mechanism, the example writes a small one: a generator, a check loop, and a greedy shrinker that tries halves, dropping one byte, and replacing byte values with zero, keeping any smaller input that still fails. The target is a run-length encoder with two seeded bugs: it stores each run length in one byte, so a run of 256 or more wraps around, and the decoder assumes its input always has an even length. A fixed seed keeps the output stable. It runs in your browser:
import random
def rle_encode(data):
"""Run-length encoding: pairs of (count, byte). Seeded bug: count stored in one byte."""
out, i = bytearray(), 0
while i < len(data):
j = i
while j < len(data) and data[j] == data[i]:
j += 1
out += bytes([(j - i) & 0xFF, data[i]]) # BUG: runs longer than 255 wrap around
i = j
return bytes(out)
def rle_decode(enc):
out = bytearray()
for k in range(0, len(enc), 2):
out += bytes([enc[k + 1]]) * enc[k] # BUG: odd-length input -> IndexError
return bytes(out)
# --- a tiny property-based tester: generate, check, shrink ---------------------------
def gen_bytes(rng):
"""Random byte strings that like long runs (a generator tuned for this kind of code)."""
out = bytearray()
while len(out) < rng.choice([4, 40, 400]):
out += bytes([rng.choice(b"ab\x00")]) * rng.randint(1, 300)
return bytes(out)
def shrink(x, fails):
"""Greedy shrinking: try smaller versions, keep any that still fail."""
changed = True
while changed:
changed = False
candidates = [x[:len(x) // 2], x[len(x) // 2:], x[1:], x[:-1]]
candidates += [x.replace(bytes([c]), b"\x00") for c in set(x) if c != 0]
for c in candidates:
if len(c) < len(x) or (len(c) == len(x) and c < x):
if fails(c):
x, changed = c, True
break
return x
def check(name, prop, gen, runs=200, seed=1):
rng = random.Random(seed)
def fails(x):
try:
return not prop(x)
except Exception:
return True
for i in range(1, runs + 1):
x = gen(rng)
if fails(x):
small = shrink(x, fails)
print(f"{name}: FAILED on example {i} ({len(x)} bytes), shrunk to {len(small)} bytes: {small[:6]!r}...")
return small
print(f"{name}: passed {runs} examples")
roundtrip = lambda x: rle_decode(rle_encode(x)) == x
never_crashes = lambda x: rle_decode(x) is not None
short_rng_bytes = lambda rng: bytes(rng.randrange(256) for _ in range(rng.randint(0, 9)))
check("roundtrip, short random inputs", roundtrip, short_rng_bytes)
small = check("roundtrip, run-heavy inputs ", roundtrip, gen_bytes)
print(" counterexample is", len(small), "x", small[:1], "-> encoded", rle_encode(small))
bad = check("decode never raises ", never_crashes, short_rng_bytes)
try:
rle_decode(bad)
except Exception as e:
print(f" decoding {bad!r} raises {type(e).__name__}: {e}")roundtrip, short random inputs: passed 200 examples
roundtrip, run-heavy inputs : FAILED on example 5 (271 bytes), shrunk to 256 bytes: b'\x00\x00\x00\x00\x00\x00'...
counterexample is 256 x b'\x00' -> encoded b'\x00\x00'
decode never raises : FAILED on example 2 (1 bytes), shrunk to 1 bytes: b'\x00'...
decoding b'\x00' raises IndexError: index out of range
Three lessons hide in those lines:
- Generators decide what you find. Two hundred short random strings pass the round-trip property: runs of 256 equal bytes never occur by chance. A generator that likes long runs fails on its fifth example. Good PBT generators are tuned to the code, the same idea as a grammar or a dictionary in fuzzing.
- Shrinking explains the bug. The failing input had 271 bytes; the shrunk one is exactly 256 zero bytes, which encodes to
00 00: a run of "zero" zeros. The boundary (256) is the bug report. - "Never raises" is a security property. A one-byte input makes the decoder index past the end. In Python that is an exception; in a C port of the same decoder it is an out-of-bounds read. A service that does not catch it crashes on one byte, a denial of service.
The same tests with Hypothesis
In a real project you write the properties as ordinary tests and let the library generate, shrink and remember failures (Hypothesis keeps a database of counterexamples and replays them first on the next run). Not run here:
from hypothesis import given, strategies as st
@given(st.binary(max_size=2000))
def test_roundtrip(data):
assert rle_decode(rle_encode(data)) == data
@given(st.binary(max_size=64))
def test_decode_rejects_or_returns(data):
try:
rle_decode(data)
except ValueError:
pass # documented rejection is fine; anything else fails the testHypothesis's generators lean towards boundaries and small, repeated values, but a run of 256 equal bytes is still unlikely from st.binary() alone. As in the hand-written tester, you help it with a strategy that builds runs, for example st.lists(st.tuples(st.binary(min_size=1, max_size=1), st.integers(1, 600))).map(lambda rs: b"".join(b * n for b, n in rs)); its shrinker should then report a minimal run of 256 bytes. For C code, the same properties go into a libFuzzer harness: decode, re-encode, assert equality, with ASan as a second oracle.
How these bugs are fixed
- Round trip: split runs longer than 255 into several pairs (
while run > 255: emit(255, b); run -= 255), or store lengths in a wider field. The property test is the proof that every length now survives. - Never raises: validate before use:
if len(enc) % 2: raise ValueError("truncated RLE stream"), and make thatValueErrorthe documented failure. Callers catch it and reject the input.
Both counterexamples become fixed unit tests next to the properties, so the exact failing cases are replayed forever even if the generator changes.
Pitfalls
- Properties that restate the implementation.
assert encode(x) == my_encode_logic(x)tests nothing. Use round trips, references and invariants. - Filtering too much. A generator that discards 99% of inputs (
assume(valid(x))) is slow and narrow; generate valid inputs directly. - Ignoring exceptions as "fine". Only documented, deliberate rejections are fine;
IndexErrorandKeyErrorare bugs. - No time budget. PBT in unit tests runs hundreds of examples; keep fuzzing for the long campaigns.
Practice
1. Fix rle_encode and re-run. Which lines change?
With runs split at 255, the run-heavy round trip passes 200 examples. The decoder bug remains until you add the length check; then the third check passes too (with ValueError accepted as rejection, or with a property that expects it).
2. Write a property for a path normaliser used before an access check.
For every generated path p (with .., ., //, encoded %2e%2e, backslashes): if allowed(p) is true, then resolve(UPLOAD_DIR, normalise(p)) starts with UPLOAD_DIR, and normalise(normalise(p)) == normalise(p). The second catches double-decoding bugs.
3. Why is differential testing a property, and what is its oracle?
The property is "both implementations agree on every input"; the oracle is the other implementation. It finds logic bugs that crash nothing, as long as at least one implementation is right.
Test yourself
What does property-based testing add to plain fuzzing?
- Speed
- A richer oracle: a property that must hold for every input, plus shrinking of failures
- Coverage instrumentation
- Network access
Why did 200 short random inputs pass the round-trip property?
- The encoder is correct
- A run of 256 equal bytes never occurs by chance in short random strings
- The shrinker hid the failure
- The seed was unlucky
What did shrinking reveal about the round-trip bug?
- Nothing
- The boundary: exactly 256 equal bytes encode to a count of 0
- That the decoder is wrong
- That inputs must be ASCII
Which property catches inconsistent security decisions such as case handling?
- Round trip
- A metamorphic property: equivalent inputs must get the same decision
- Never raises
- Idempotence of encoding