SENIORCHAPTER 21

Security testing: fuzzing, scanners and abuse cases

Test the rules security depends on, feed the API what no customer would, and know what a scanner can and cannot tell you

55 MINSOFTWARE TESTING AND QUALITYUPDATED 2026-11-24
PREDICT

You write a Hypothesis test that posts 300 generated bodies (huge integers, negative numbers, Infinity, odd unicode, deep nesting) to the checkout API's /cart/price and asserts the status is never 500. The service has passing unit, integration and API tests and a Pydantic model that validates every field. What do you expect?

Functional tests ask whether the service does what it should. Security testing asks what it does when someone tries to make it do something else. The difference is the caller. A functional test is written for a customer who follows the page. A security test is written for a caller who changes the request: a different id, a different header, a number the page would never send.

This chapter covers three tools for that and what each one cannot do: abuse cases (the rules, written as tests), fuzzing (the inputs, generated), and scanners (a tool that probes a running service from outside). It is not a penetration test and it does not teach attacks. The Careers track has the security engineer’s side of the same work: Secure code review and AppSec, Threat modelling, and Pentests, bug bounties and vendor risk. The AppSec course will own fuzzing and scanner pipelines in depth, and both topics are planned there; this chapter teaches the testing side in full and stops where AppSec begins.

Abuse cases: write down what must not happen

An abuse case is a requirement written from the attacker’s side: “a caller with no account must not read any draft product”. It becomes a test the same way a requirement does. What makes it different is where it comes from. Functional cases come from the page and the story. Abuse cases come from asking, for every input and every identifier, who else could send this, and what could they put there?

For the checkout service that question has a short list of answers. Here is the list, with what the lab can test today.

Abuse case The attacker’s move Testable in the lab?
A seller reads another seller’s draft GET /search?q=tote&seller=adire-house for a draft that belongs to shea-co Yes: three tests below
A caller reads an order that is not theirs GET /orders/ord_... with someone else’s id Partly: the lab has no login and an order stores no buyer, so the rule can only be written as an expected failure
Counting orders by guessing ids GET /orders/ord_000000000001, then ...02 Yes: ids are ord_ plus 12 random hex characters
Quote characters reach SQL q=' OR '1'='1 in /search, or an order id with a quote in it Yes: every query is parameterised, and a test pins it
Hostile numbers reach the database or the price Quantity 10**30, product id 2**63, Infinity Yes: the fuzz test
A hostile header reaches the provider An Idempotency-Key with a non-ASCII character Yes: the live scan finds it
The service fetches a URL the caller chose A product image URL pointing at an internal address Not here: no field takes a URL
A forged or downgraded token An unsigned token, or one that names its own algorithm Not here: the lab has no tokens

The last two rows matter as much as the first six. A test you cannot write is information: it tells you which defences the system does not have yet. The day a seller can paste an image URL, SSRF becomes a row you can test, and the lesson SSRF shows what that test must try. The day the lab gains login tokens, JWT pitfalls is the list of attacks to write cases for.

The order that is not yours

The rule most marketplaces care about most is the one in the second row: a seller or buyer must never read another party’s order. It has a name, broken object level authorisation, and it heads the OWASP API Security Top 10 for 2023. Its cousin in the lessons is IDOR: you are logged in, and the server never asks whether this record is yours.

▶ SIMULATION
ACME (alice)
received: —
foreign data: none
SHARED: CACHE · JOBS · INDEX
cache empty
search index: 4 docs, both tenants · filter: none
GLOBEX (mallory)
received: —
foreign data: none
last—
✓ no tenant ever receives another tenant's data✓ every cache entry is keyed by the tenant whose data it holds
SCHEDULE
01[API]API: every handler scopes its own queries; cache key is "summary:<month>"
02[ACME]alice opens the dashboard
03[GLOBEX]mallory opens the dashboard
04[API]report
Start of break: cache key without tenant scenario. 4 steps.
// Each handler scopes its own query. The shared pieces do not.
const key = `summary:${month}`;                       // same key for every tenant
const hit = await cache.get(key);

await queue.add('export-overdue', { requestedBy: user.id });   // no tenant
// worker:
const rows = await db.invoice.findMany({ where: { status: 'overdue' } });

const hits = await index.search({ text: q });               // whole index

Run the sim and watch where the check lives. Every handler checks the tenant, and a cache in front of them does not. The cache returns tenant A’s page to tenant B because the key is the URL, not the URL plus the tenant. That is the shape of most isolation bugs: the rule is right in the place you looked and missing in the place you did not. An abuse test has to go through the whole stack, with two real identities, and ask for the other one’s data. The lesson page Tenant isolation has the exercises.

The lab cannot do that for orders yet. There is no login, POST /orders takes no buyer, and GET /orders/{id} returns whatever the id names. The honest way to record that is a test that states the rule and is marked as an expected failure:

@pytest.mark.xfail(strict=True, reason="no login, and an order stores no buyer: the rule cannot be enforced yet")
def test_a_buyer_cannot_read_another_buyers_order(client):
    ...

strict=True matters. When someone adds buyers and the rule starts to hold, the test passes, pytest reports it as a failure (an unexpected pass), and someone has to remove the marker on purpose. A rule you wrote down cannot quietly become true or quietly stay false.

What the lab can pin is the next best thing. An order id is ord_ plus 12 hex characters, which is 48 random bits, so ids cannot be walked in order, and a neighbouring id is a plain 404. OWASP lists unguessable identifiers as a defence in depth, not as the defence: a leaked id still opens the order. That is why the test says cannot be counted through and not is protected.

SQL, by test and not by faith

The lesson SQL injection explains the mechanism. For a tester the question is narrower: how would you know if someone replaced a parameterised query with string-building? A test with hostile text, run on the lab’s /search and /orders/{id}, would show it: the response stays a plain 200 or 404, nothing comes back that the text did not match, and the table is unchanged afterwards. It will not find every injection (it exercises two places), but it fails the day somebody formats a quote into a query, and it costs eight parameters.

Fuzzing: let the machine ask the strange questions

A fuzzer generates inputs a person would not write and watches what happens. The idea is old and plain. In 1990 Miller, Fredriksen and So fed random character streams to Unix utilities and found that a surprising share of them crashed or hung. The tool was a few lines of code. What made it work was not cleverness. It was the volume, and a clear oracle: a crash is wrong, whatever the input.

Your oracle sets the power of the test. For an HTTP API the cheap ones are:

  • Never a 5xx. A 500 means an exception nobody handled. It is a bug, and it is also the first sign of a path that was never designed: it may leak a stack trace, hold a connection, or sit one step from something worse.
  • Never a response that breaks the published schema. Clients are written against it.
  • Never another tenant’s data. This one needs two identities, so it belongs with the abuse cases.

Hypothesis as a fuzzer

You already have a generator in the lab. Hypothesis, the property-based testing library from the lesson Property-based testing, builds inputs from strategies, runs your test on each, and when one fails it shrinks the input to the smallest body that still fails. That last step is what separates it from raw random input: you get a case you can read, and a fix you can argue about.

Three decisions make a Hypothesis fuzz test work.

  1. Mix plausible and hostile. Noise alone is rejected at the front door and never reaches the pricing code. The lab’s strategy draws product ids and quantities mostly from valid values, with edge values mixed in: 0, -1, 2**31, 2**63 - 1, 2**63, 2**64, floats including Infinity and NaN.
  2. Fix the seed in CI. derandomize=True makes Hypothesis run the same examples every time. The run is reproducible and the build does not go red for a reason that disappears on the retry. It also means the search is the same search each time, so run a nightly variant without derandomize (and with the --hypothesis-seed option, to be able to replay it) to cover more ground.
  3. Know the health check. Hypothesis refuses to run a test that uses a function-scoped pytest fixture, because the fixture is built once for all the generated examples, not once per example. That is safe here (/cart/price changes nothing in the database), so the lab suppresses the check with a comment. A fuzz test of POST /orders would need to build its own database inside the test.

Why a 500 is a finding

Run the lab’s fuzz test on the clean code and it fails. It finds two real defects within seconds, and neither is in the pricing rules. A product id of 2**63 is accepted by the model, then passed to SQLite, whose integers stop at 2**63 - 1, so the driver raises OverflowError and the caller gets a 500. And a body containing Infinity (Python’s JSON parser accepts it, the JSON standard does not) is rejected with a 422 by Pydantic, whose error message echoes the input back, and the echoed Infinity cannot be serialised, so the error path itself returns a 500.

Both fixes are small and both are about the boundary of the service, not its logic. Bound every number a caller sends: the model should say what a sane id, quantity and distance look like. And never echo hostile input into an error body. In the lab you write both. The step is also the reason fuzzing works well beside the boundary-value techniques you used in tst1: those pick the edges you thought of, and the fuzzer picks the ones you did not.

Scanners and schema-driven tools

A scanner probes a running service from outside, without reading its code. Two families matter, and a third works from your code.

Kind Reads Finds Cannot find
DAST (dynamic): ZAP, Schemathesis the running service missing headers, server errors, schema violations, some injection and exposure a rule it was never told (who owns this order?)
SAST (static): code scanners your source risky patterns, hard-coded secrets, unsafe calls what depends on data and configuration at run time
Dependency scanners your lockfile known vulnerable library versions flaws in your own code

The planned AppSec chapter on SAST, DAST and dependency scanning in CI covers the third and second rows as a pipeline. Here is the part a tester needs: what each tool knows.

Schemathesis: the API’s own description as a test generator

FastAPI publishes an OpenAPI document at /openapi.json. Schemathesis reads it, builds Hypothesis strategies from every operation, and sends requests: valid ones, then deliberately invalid ones, with the checks you choose applied to each response. Its report gives a curl command for every failure. The lab pins version 4.4.4, which installs on Python 3.9.6 with every pin the lab already holds unchanged (checked 2026-11-24).

It will find things your in-process test cannot, for a reason worth stating in full. The in-process fuzz test above uses a stub payment client and FastAPI’s TestClient. Schemathesis goes through a real socket to the real payment client, and so a hostile Idempotency-Key header, with a character outside ASCII, passes the stub and fails the real HTTP library when the client tries to forward it as a header. The test double lied, in the way the lesson The mock that lied describes. A security fuzz test should reach as much of the real stack as it can afford.

Two practical points about its output.

  • It reports the checks you ask for. By default it also applies conformance checks, and on this API it complains that the service returns a 404 or a 200 the OpenAPI document never mentions. That is real, and it belongs on a list for the API’s owner. It is not a security gate. A gate that fails for documentation gaps trains people to ignore it, so the lab’s gate uses --checks not_a_server_error and a separate job reports the rest.
  • It writes to your database. The fuzzing creates products and orders. Point the API at a throwaway CHECKOUT_DB and never at a database you care about.

ZAP: passive baseline and why not to scan production

OWASP ZAP is the widely used open source DAST proxy and scanner. Its baseline scan runs the spider against a target for one minute by default, waits for passive scanning to finish, and reports. It sends no attacks. The ZAP documentation says plainly that it is safe for CI and for production sites, because all it does is read the pages and responses it sees. The command from the project’s docs is:

docker run -t ghcr.io/zaproxy/zaproxy:stable zap-baseline.py -t https://www.example.com

The lab does not use Docker, and this chapter does not require ZAP. If you have it, point it at a copy of the API and read what a passive scan reports: usually missing security headers and a cookie or cache flag. Then notice what it cannot report. It has no idea that adire-house should not read shea-co’s drafts. Access control depends on a rule only your service knows, and no generic scanner is told it.

An active scan does attack: it sends payloads to every parameter it finds. Run it against a test instance you own, with a throwaway database, and never against production or against a service you do not own. The permission is the point; the technique is the same one an attacker uses.

What a green security suite proves

Be precise about the claim. If the abuse tests, the fuzz test and the scan are green, you know this: for the inputs they tried, the service refused what they said it must refuse and never returned a server error. You do not know that no seller can read another seller’s data through a path you did not test. You do not know the service is free of injection outside the two places you probed. Fuzzing finds bugs; it does not prove there are none, and a short run of a deterministic fuzz test can pass on code that still has the defect. The lab’s break step shows that with a number.

The three tools also cover different things, which is why you want all of them and none of them alone.

Tool Strong at Blind to
Abuse cases Rules only you know: ownership, drafts, order ids Anything nobody thought to write
Fuzzing Hostile values, edge numbers, error paths Rules (it does not know who owns what)
Scanners Cheap breadth, headers, schema drift, what the stub hides Business logic, and everything behind a login it was not given

A security engineer reads this as coverage of a threat model. A tester’s contribution is to make it executable, to run it on every change, and to say what a green result does not show.

LAB Abuse cases, a fuzzer and a schema scan against the checkout API ~50 MIN
YOU NEEDPython 3.9+ with the lab set up (README, 'Set up')labs/testing, with .venv createdPorts 8094 and 8095 free (lsof -i :8094 -i :8095)

You will write abuse-case tests, fuzz /cart/price with Hypothesis and fix the two defects it finds, then run Schemathesis against the running API and fix what it finds. You edit checkout/api.py, and the last step puts the lab back. Work from labs/testing. Nothing here applies a seeded bug and nothing reads seeded/.

cd labs/testing
.venv/bin/pytest -q
23 passed, 1 skipped, 1 deselected: the clean starter suite. The skip is the browser test (no Chromium) and the deselect is the quarantined flaky test.

1. Add the tests folder and a client that reports a 500 as a response.

By default the test client raises a server error as a Python exception in the test. For security tests you want the status code, so ask for it as a response.

mkdir tests/security && touch tests/security/__init__.py

Create tests/security/conftest.py:

import pytest
from fastapi.testclient import TestClient

from checkout.api import create_app
from checkout.search_index import SearchIndex

@pytest.fixture
def client(db, payments, clock):
    """The API in-process. A server error comes back as a 500 response, not as an exception in the test."""
    return TestClient(create_app(db, payments, clock, SearchIndex()), raise_server_exceptions=False)
No output. db, payments and clock are the lab’s own fixtures from tests/conftest.py: a seeded temp database, a stub payment client and a fixed clock.

2. Write the abuse cases.

Create tests/security/test_abuse_cases.py:

import re
from urllib.parse import quote

import pytest

QUOTES = ["'", "' OR '1'='1", "'; DROP TABLE products; --", "%", "_", "\\", "\x00", "../../etc/passwd"]
ORDER_IDS = ["'", "' OR '1'='1", "'; DROP TABLE orders; --", "%", "_", "ord_000000000000", "ORD_000000000000", "ord_%"]

def names(resp):
    return [p["name"] for p in resp.json()]

def test_search_never_shows_a_draft_to_a_caller_with_no_seller(client):
    assert names(client.get("/search", params={"q": "tote"})) == []

def test_search_never_shows_one_sellers_draft_to_another_seller(client):
    assert names(client.get("/search", params={"q": "tote", "seller": "adire-house"})) == []

def test_a_seller_sees_their_own_draft(client):
    assert names(client.get("/search", params={"q": "tote", "seller": "shea-co"})) == ["Prototype tote bag"]

@pytest.mark.parametrize("payload", QUOTES)
def test_search_treats_hostile_text_as_text(client, db, payload):
    before = db.list_products()
    resp = client.get("/search", params={"q": payload, "seller": payload})
    assert resp.status_code == 200
    assert resp.json() == []
    assert db.list_products() == before

@pytest.mark.parametrize("order_id", ORDER_IDS)
def test_unknown_order_ids_all_look_the_same(client, order_id):
    resp = client.get("/orders/" + quote(order_id, safe=""))
    assert resp.status_code == 404
    assert resp.json()["error"] == "not_found"

def test_order_ids_cannot_be_counted_through(client):
    ids = []
    for n in range(5):
        body = {"lines": [{"product_id": 2, "qty": 1}]}
        ids.append(client.post("/orders", json=body, headers={"Idempotency-Key": "k%d" % n}).json()["id"])
    assert all(re.fullmatch(r"ord_[0-9a-f]{12}", i) for i in ids)
    assert len(set(ids)) == 5
    # a neighbour of a real id is not a real id
    assert client.get("/orders/" + ids[0][:-1] + ("0" if ids[0][-1] != "0" else "1")).status_code == 404

@pytest.mark.xfail(strict=True, reason="the lab has no login and an order stores no buyer: the rule cannot be enforced yet")
def test_a_buyer_cannot_read_another_buyers_order(client):
    body = {"lines": [{"product_id": 2, "qty": 1}]}
    order = client.post("/orders", json=body, headers={"Idempotency-Key": "a-1", "Authorization": "Bearer buyer-a"}).json()
    resp = client.get("/orders/" + order["id"], headers={"Authorization": "Bearer buyer-b"})
    assert resp.status_code in (403, 404)
.venv/bin/pytest tests/security/test_abuse_cases.py -q
20 passed, 1 xfailed, plus a line XFAIL tests/security/test_abuse_cases.py::test_a_buyer_cannot_read_another_buyers_order - the lab has no login .... The twenty pass because the clean code behaves as the table says. The XFAIL is the rule the lab cannot yet enforce, recorded as a test. Look at test_search_treats_hostile_text_as_text: it is parametrised over eight strings, which is how you cover quote characters without writing eight tests.

3. Fuzz /cart/price and read what it finds.

Create tests/security/test_fuzz_cart_price.py:

import json

from hypothesis import HealthCheck, given, settings, strategies as st

BIG = 2**70
EDGES = st.sampled_from([0, -1, 1, 2**31, 2**63 - 1, 2**63, 2**64])
numbers = st.one_of(
    EDGES,
    st.integers(min_value=-BIG, max_value=BIG),
    st.floats(allow_nan=True, allow_infinity=True),
)
junk = st.recursive(
    st.one_of(st.none(), st.booleans(), numbers, st.text()),
    lambda inner: st.one_of(st.lists(inner, max_size=3), st.dictionaries(st.text(max_size=8), inner, max_size=3)),
    max_leaves=10,
)
# Mostly plausible values with hostile ones mixed in: pure noise is rejected at the door and never reaches the pricing code.
line = st.fixed_dictionaries(
    {"product_id": st.one_of(st.integers(1, 4), numbers), "qty": st.one_of(st.integers(1, 5), numbers)},
    optional={"extra": junk},
)
bodies = st.one_of(
    st.fixed_dictionaries(
        {"lines": st.lists(line, max_size=4)},
        optional={"distance_km": numbers, "promo_code": st.one_of(st.none(), st.text())},
    ),
    junk,
)

# /cart/price changes nothing in the database, so sharing the function-scoped fixture is safe here.
@settings(max_examples=300, deadline=None, derandomize=True, suppress_health_check=[HealthCheck.function_scoped_fixture])
@given(body=bodies)
def test_cart_price_never_returns_a_server_error(client, body):
    resp = client.post("/cart/price", content=json.dumps(body), headers={"Content-Type": "application/json"})
    assert resp.status_code < 500, "%s for %s" % (resp.status_code, json.dumps(body)[:200])
.venv/bin/pytest tests/security/test_fuzz_cart_price.py -q
The test fails in about four seconds with AssertionError: 500 for {"lines": [{"product_id": 9223372036854775808, "qty": 1}]} and a Falsifying example block. Hypothesis started from a messy body and shrank it to one line with one number, which is exactly 2**63. The pydantic model accepted it; SQLite’s integer column cannot hold it. Run the command again: the same deterministic search finds it again in about 3 s. derandomize=True implies no example database, so nothing is saved in .hypothesis/ and nothing is replayed; saved examples need derandomize off.

4. Fix the first defect with bounds, find the second, fix it.

In checkout/api.py, give the cart models limits. Replace the ItemIn and CartIn classes with:

class ItemIn(BaseModel):
    product_id: int = Field(ge=1, le=2**31 - 1)
    qty: int = Field(ge=1, le=1_000)

class CartIn(BaseModel):
    lines: List[ItemIn] = Field(min_length=1)
    distance_km: int = Field(default=0, ge=0, le=20_000)
    promo_code: Optional[str] = Field(default=None, max_length=32)
.venv/bin/pytest tests/security/test_fuzz_cart_price.py -q
It fails again, and the example is a different defect: a body containing Infinity (the one Hypothesis printed here was a four-line cart with "qty": Infinity in the last line). The request is rejected, correctly, but the 422 response echoes the bad value and Infinity cannot be serialised to JSON, so the rejection itself returns a 500.

Add a handler that reports which field failed without echoing the input. In checkout/api.py add two imports under the existing from fastapi import FastAPI, Header:

from fastapi.exceptions import RequestValidationError
from fastapi.requests import Request

and, directly after the line app = FastAPI(title="Ojaline checkout") inside create_app, add:

    @app.exception_handler(RequestValidationError)
    def bad_request(_: Request, exc: RequestValidationError) -> JSONResponse:
        # Say which field failed and why, never echo the input back (it may not be JSON-safe).
        problems = [{"loc": list(e["loc"]), "msg": e["msg"], "type": e["type"]} for e in exc.errors()]
        return JSONResponse(status_code=422, content={"detail": problems})

The response keeps FastAPI’s own shape (detail with loc, msg, type), so no client and no schema check changes.

.venv/bin/pytest tests/security -q
.venv/bin/pytest -q
21 passed, 1 xfailed for the security folder: twenty abuse tests and the fuzz test. The whole suite ends with 44 passed, 1 skipped, 1 deselected, 1 xfailed, which is the 23 starter tests plus your 21 (your count is higher by any tests you added in earlier chapters). The existing API tests still pass, so the handler changed nothing for valid requests.

5. Install Schemathesis and scan the running API.

The lab’s requirements.txt already pins schemathesis==4.4.4, checked on Python 3.9.6 on 2026-11-24 with none of the other pins moving. If your .venv predates the pin, install it:

.venv/bin/pip install -r requirements.txt
.venv/bin/schemathesis --version
schemathesis, version 4.4.4. On the system Python that macOS ships, importing it prints a NotOpenSSLWarning about LibreSSL. It is harmless here, and the lab never makes an HTTPS request.

Start the provider and the API in two terminals. The API gets a throwaway database, because the scan creates products and orders.

# terminal 1
.venv/bin/uvicorn fake_provider.app:app --port 8095
# terminal 2
CHECKOUT_DB=$(mktemp -d)/fuzz.sqlite .venv/bin/uvicorn checkout.api:app --port 8094

In a third terminal, run the scan. The seed makes it repeatable, and --phases fuzzing leaves out the slower stateful phase:

.venv/bin/schemathesis run http://localhost:8094/openapi.json \
  --phases fuzzing --max-examples 100 --seed 1 --checks not_a_server_error
The fuzzing phase fails with 5 passed, 2 failed. The two failures are POST /products and POST /orders, each [500] Internal Server Error, each followed by a curl command that reproduces it, and the summary reads Server error: 2 and Seed: 1. The /cart/price operation is clean because of step 4. The reproduction for /orders shows idempotency-key: [Filtered]: Schemathesis hides header values in its output, so you cannot copy the key from the report.

Find the hidden value yourself. POST /products fails on a huge stock (the same SQLite limit as step 3). For /orders, send a key with a non-ASCII character:

curl -s -o /dev/null -w "%{http_code}\n" -X POST localhost:8094/orders \
  -H 'Content-Type: application/json' -H $'Idempotency-Key: caf\xc3\xa9-1' \
  -d '{"lines":[{"product_id":1,"qty":1}]}'
500. The key is passed to the payment client as an HTTP header, and the HTTP library cannot encode a non-ASCII value there, so it raises UnicodeEncodeError (visible in the API terminal). The in-process fuzz test never found it: its stub payment client takes any string. The stock was reserved and then released by the order code’s finally, so no stock leaked, but the caller still gets a 500.

6. Fix both, restart the API and scan again.

In checkout/api.py, replace ProductIn with bounds:

class ProductIn(BaseModel):
    seller_id: str = Field(max_length=64)
    name: str = Field(max_length=200)
    price_kobo: int = Field(gt=0, le=10**12)
    stock: int = Field(default=0, ge=0, le=1_000_000)
    status: str = Field(default="published", pattern="^(published|draft)$")

and constrain the header in create_order:

    def create_order(
        body: CartIn, idempotency_key: str = Header(..., min_length=1, max_length=64, pattern=r"^[A-Za-z0-9._:-]+$")
    ) -> Any:

Stop the API (Ctrl-C in terminal 2) and start it again, because uvicorn does not reload. Then rerun the scan and the curl from step 5.

The scan ends with 7 passed, 601 generated, 601 passed and No issues found. The curl now prints 422, with a body naming idempotency-key and the pattern it must match.

7. Read the findings the gate leaves out.

Run the scan once more with Schemathesis’s default checks:

.venv/bin/schemathesis run http://localhost:8094/openapi.json --phases fuzzing --max-examples 100 --seed 1
Undocumented HTTP status code failures, for example POST /cart/price Received: 404 Documented: 200, 422, and the same for GET /orders/{order_id} and for a replayed POST /orders (Received: 200 Documented: 201, 422). The service answers correctly; its OpenAPI document does not say so. That is a ticket for the API’s owner. It is not a reason to fail a security gate.

Stop both servers with Ctrl-C and confirm the ports are free with lsof -i :8094 -i :8095.

Break it, to see what a short fuzz run misses. In checkout/api.py remove the bound from product_id (change the line back to product_id: int). In tests/security/test_fuzz_cart_price.py change max_examples=300 to max_examples=20. Then run .venv/bin/pytest tests/security/test_fuzz_cart_price.py -q.

It passes. The defect is back and the test is green, because twenty examples of the same deterministic search never reach 2**63. Change max_examples back to 300 and run it again: it fails with "product_id": 9223372036854775808. A passing fuzz test is a statement about the examples it tried, not about the code. Put the bound back. Then decide how you would choose the budget for a CI run, and what you would run nightly.

8. Put the lab back. Later chapters count tests from the starter state. After the break above:

git checkout checkout/api.py
rm -rf tests/security .hypothesis
.venv/bin/pytest -q
23 passed, 1 skipped, 1 deselected, the starter state. The 2**63 product id and the Infinity price are open again, as the lab’s README says they are on the clean code.
DECIDE

Ojaline's marketplace team has fixed an authorisation gap that a seller reported through the bug bounty. Karabo wants a scanner in CI so the next one is caught before release. Masego has three options on the table and a team of eight that will not tolerate a pipeline that fails for no reason.

READING
  1. DOC
    OWASP Web Security Testing Guide

    The reference list of what to test in a web application, organised by area: identity, authorisation, input validation, error handling and more. Use it to build abuse cases; skim the sections for the areas your service has and skip the rest. Read on 2026-11-24; the page lists version 4.2 as the stable release.

  2. DOC
    OWASP Application Security Verification Standard (ASVS)

    A numbered list of security requirements a tester can verify one by one, so 'the service is secure' becomes a checklist with levels. Read the introduction and the access control and validation chapters; skip the rest on a first pass. Read on 2026-11-24; the site shows version 5.0.0.

  3. DOC
    OWASP API Security Top 10 2023: API1 Broken Object Level Authorization

    The page for the most common API flaw, with an attack scenario and prevention advice that includes writing automated tests of the authorisation logic. Read the whole page; it is short. The old owasp.org address redirects here.

  4. PAPER
    Miller, Fredriksen and So: An Empirical Study of the Reliability of UNIX Utilities Barton Miller, Lars Fredriksen, Bryan So, 1990

    The paper that named fuzzing: random input, a crash as the oracle, and a startling failure rate. Read it to see how little machinery the idea needs. The publisher site blocks automated fetches, so the title, authors and year were checked against Crossref on 2026-11-24. Read: Communications of the ACM, December 1990; read the method and results, skip the per-utility tables.

  5. DOC
    Schemathesis documentation

    The tool the lab uses: how it builds tests from an OpenAPI document, the list of checks, and how to run it from the CLI or pytest. Read the quick start and the page on checks; skip GraphQL and gRPC. Read on 2026-11-24.

  6. DOC
    ZAP: Baseline Scan

    What the passive baseline scan does and does not do, and the Docker command to run it. Read it to learn why it is safe for CI and why a clean report is weak evidence; skip the options for config files until you run it. Read on 2026-11-24.

  7. DOC
    Hypothesis documentation

    The library behind both the lab's fuzz test and Schemathesis: strategies, shrinking, the example database, and the settings used here (derandomize, health checks). Read the quickstart and the reference entries for settings and health checks; skip the extras. Read on 2026-11-24.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Testing data pipelines and migrations →