Security and hardening · Intermediate · 28 min
Defend a sign-in form against credential stuffing and password spraying
By Padding · Updated 26 Nov 2026
python:3.15-slim (Debian 13) · Python 3.15.2 · FastAPI 0.165.0 · Uvicorn 0.54.0 · argon2-cffi 25.1.0 · httpx 0.29.0 · pytest 9.2.0
You will have a small FastAPI sign-in service that gives the same answer for unknown users and wrong passwords, slows repeated failures per account and per address with a sliding window in SQLite, refuses breached passwords through the Pwned Passwords range API, and raises an alert when failures spike.
On this page
Credential stuffing does not guess. An attacker takes username and password pairs leaked from some other site and replays them against yours, betting that people reuse passwords. Each account gets one or two tries, so a rule like "lock after five failures" never fires. Password spraying is the mirror image: one or two very common passwords tried against thousands of accounts. Both look like a steady trickle of ordinary failed sign-ins, spread across many accounts and, with a botnet, many addresses.
No single control stops this. You build a stack of small ones, each covering a gap the others leave:
- Same answer, same time for an unknown user and a wrong password, so the attacker cannot sort their list into real and fake accounts.
- Progressive delays per account, which make guessing one account slow without letting anyone lock a real user out.
- A limit per address, which catches one machine spraying many accounts.
- A breached-password check at sign-up, so the passwords on the attacker's lists never get in.
- An alert on failure spikes, because a distributed attack slips under every per-account and per-address limit.
You build all five into a small FastAPI service in ~/stuffing-demo, prove each with pytest, then fire a scripted burst of failed sign-ins at it and watch the defences respond. Everything runs against your own app on 127.0.0.1. The breach check talks to a local stand-in that answers exactly like the Pwned Passwords range API, so nothing leaves your machine while you practise.
Step 1 · Create the project and install the libraries
Make the demo folder and a virtual environment, then install exact versions:
mkdir -p ~/stuffing-demo
cd ~/stuffing-demo
python3 -m venv .venv
.venv/bin/pip install --quiet fastapi==0.165.0 starlette==1.10.0 uvicorn==0.54.0 argon2-cffi==25.1.0 httpx==0.29.0 httpx2==2.16.2 pytest==9.2.0FastAPI serves the app and Uvicorn runs it. argon2-cffi hashes passwords. httpx makes the breach-check call and drives the burst script. httpx2 is there for FastAPI's test client: Starlette 1.10, pinned here because FastAPI 0.165 accepts any Starlette from 1.6 up, uses httpx2 when it is installed and prints a deprecation warning when it has to fall back to httpx.
Check it worked
.venv/bin/python -c "from importlib.metadata import version as v; print(v('fastapi'), v('uvicorn'), v('argon2-cffi'), v('httpx'), v('pytest'))"The command prints 0.165.0 0.54.0 25.1.0 0.29.0 9.2.0.
Step 2 · Give unknown users and wrong passwords the same answer
The first thing a stuffing tool learns from your sign-in form is which usernames exist. If the error says "no such user", the attacker drops those rows and spends the rest of their budget on real accounts. Changing the message is not enough. A sign-in that returns at once for an unknown user, but spends 40 milliseconds hashing for a real one, leaks the same fact through timing.
The fix is to always run the hash. When the username is unknown, verify the submitted password against a dummy hash made at start-up with the same settings. The work is the same, and the answer is always False.
Create passwords.py:
cat > passwords.py <<'PY'
import secrets
import unicodedata
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerificationError
# OWASP's minimum for Argon2id: 19 MiB, two passes, one lane.
hasher = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
# A hash of a random password nobody knows. Unknown usernames are checked
# against it, so they cost the same time as real ones.
DUMMY_HASH = hasher.hash(secrets.token_urlsafe(32))
def normalise(password: str) -> str:
# The same word can arrive as different code points depending on the
# keyboard. NFC makes them one byte string before hashing.
return unicodedata.normalize("NFC", password)
def hash_password(password: str) -> str:
return hasher.hash(normalise(password))
def check_password(stored_hash: str | None, password: str) -> bool:
target = DUMMY_HASH if stored_hash is None else stored_hash
try:
hasher.verify(target, normalise(password))
except (VerificationError, InvalidHashError):
return False
return stored_hash is not None
PYThe normalise call matters for anyone typing outside plain ASCII. A Yoruba name such as Ìbàdàn can be typed as one character per accented letter on one phone keyboard and as a letter plus a combining tone mark on another. Without normalisation, a user who signed up on one device cannot sign in on the other. NIST SP 800-63B-4 recommends NFC for exactly this reason.
Now write a test that proves the leak in a naive version and its absence in yours. It times each path seven times and compares the medians:
cat > test_passwords.py <<'PY'
import statistics
import time
import unicodedata
from passwords import check_password, hash_password
STORED = hash_password("lantern-orchard-copper-41")
def naive_check(stored_hash, password):
if stored_hash is None:
return False # returns at once: this is the leak
return check_password(stored_hash, password)
def median_seconds(fn, *args, runs=7):
times = []
for _ in range(runs):
start = time.perf_counter()
fn(*args)
times.append(time.perf_counter() - start)
return statistics.median(times)
def test_right_and_wrong_passwords():
assert check_password(STORED, "lantern-orchard-copper-41")
assert not check_password(STORED, "lantern-orchard-copper-42")
assert not check_password(None, "lantern-orchard-copper-41")
def test_naive_check_leaks_unknown_users():
unknown = median_seconds(naive_check, None, "a-guess")
known = median_seconds(naive_check, STORED, "a-guess")
assert unknown < known / 10
def test_unknown_users_cost_the_same():
unknown = median_seconds(check_password, None, "a-guess")
known = median_seconds(check_password, STORED, "a-guess")
assert 0.5 < unknown / known < 2
def test_composed_and_decomposed_accents_match():
password = "Ìbàdàn-ojo-oru-2026"
composed = unicodedata.normalize("NFC", password)
decomposed = unicodedata.normalize("NFD", password)
assert composed != decomposed
assert check_password(hash_password(composed), decomposed)
PY
.venv/bin/python -m pytest -q test_passwords.pyCheck it worked
pytest reports 4 passed. The naive version answers unknown users more than ten times faster than real ones, which anyone with a stopwatch and a list of usernames can measure. Yours stays within a factor of two either way, and on most machines the two medians are within a few per cent of each other.
Step 3 · Count failures in a sliding window
To slow attackers down you need to know how many times something failed recently. "Recently" here means a sliding window: count the failures in the last 15 minutes, measured from now, rather than resetting a counter on the hour. A fixed hourly counter lets an attacker spend a full allowance at 10:59 and another at 11:00.
Each failure is one row in SQLite, with a scope (account or ip), a key (the username or the address) and a timestamp. Counting the window is one indexed SELECT. SQLite keeps the counts across restarts of a single server. If you run several app servers, put the same table in your shared database, or use Redis sorted sets keyed the same way.
The clock is a parameter, so tests can move time forward without sleeping. Create limits.py:
cat > limits.py <<'PY'
import math
import sqlite3
import threading
import time
class FailureLog:
"""Failed sign-ins in SQLite, counted over a sliding window."""
def __init__(self, path, clock=time.time):
self.path = str(path)
self.clock = clock
self.lock = threading.Lock()
self._run(
"CREATE TABLE IF NOT EXISTS failures "
"(scope TEXT NOT NULL, key TEXT NOT NULL, at REAL NOT NULL)"
)
self._run("CREATE INDEX IF NOT EXISTS failures_by_key ON failures (scope, key, at)")
def _run(self, sql, args=()):
with self.lock:
db = sqlite3.connect(self.path, timeout=5)
try:
with db:
return db.execute(sql, args).fetchall()
finally:
db.close()
def record(self, scope, key):
now = self.clock()
self._run("INSERT INTO failures VALUES (?, ?, ?)", (scope, key, now))
self._run("DELETE FROM failures WHERE at < ?", (now - 86400,))
def recent(self, scope, key, window):
"""Count, oldest and newest failure for one key inside the window."""
since = self.clock() - window
count, oldest, newest = self._run(
"SELECT COUNT(*), MIN(at), MAX(at) FROM failures "
"WHERE scope = ? AND key = ? AND at > ?",
(scope, key, since),
)[0]
return count, oldest, newest
def totals(self, scope, window):
"""All failures in the window, and how many distinct keys they came from."""
since = self.clock() - window
return self._run(
"SELECT COUNT(*), COUNT(DISTINCT key) FROM failures WHERE scope = ? AND at > ?",
(scope, since),
)[0]
def clear(self, scope, key):
self._run("DELETE FROM failures WHERE scope = ? AND key = ?", (scope, key))
class Throttle:
"""Progressive delays per account and a hard limit per address."""
def __init__(self, log, window=900, free_attempts=3, max_delay=300, ip_limit=30):
self.log = log
self.window = window
self.free_attempts = free_attempts
self.max_delay = max_delay
self.ip_limit = ip_limit
def account_delay(self, failures):
if failures < self.free_attempts:
return 0
return min(2 ** (failures - self.free_attempts), self.max_delay)
def retry_after(self, username, ip):
"""0 if this attempt may go ahead, otherwise whole seconds to wait."""
now = self.log.clock()
count, oldest, _ = self.log.recent("ip", ip, self.window)
if count >= self.ip_limit:
return max(1, math.ceil(oldest + self.window - now))
count, _, newest = self.log.recent("account", username, self.window)
wait = self.account_delay(count)
if wait and newest + wait > now:
return max(1, math.ceil(newest + wait - now))
return 0
def failed(self, username, ip):
self.log.record("account", username)
self.log.record("ip", ip)
def succeeded(self, username):
self.log.clear("account", username)
PYThrottle is written here too, and you test it in the next step. For now, test only the window:
cat > test_limits.py <<'PY'
from limits import FailureLog, Throttle
class FakeClock:
def __init__(self):
self.now = 1_000_000.0
def __call__(self):
return self.now
def test_window_forgets_old_failures(tmp_path):
clock = FakeClock()
log = FailureLog(tmp_path / "t.db", clock)
for _ in range(3):
log.record("account", "amara")
clock.now += 60
assert log.recent("account", "amara", 900)[0] == 3
clock.now += 900 - 150
assert log.recent("account", "amara", 900)[0] == 2
clock.now += 300
assert log.recent("account", "amara", 900)[0] == 0
PY
.venv/bin/python -m pytest -q test_limits.pyCheck it worked
pytest reports 1 passed. The three failures happen a minute apart. Fifteen minutes after the first one, that first failure has slid out of the window and the count is 2. Five minutes later the other two have gone as well.
Step 4 · Slow attackers down without locking anyone out
The obvious defence, "lock the account after five failures", hands attackers a weapon. Anyone who knows or can guess your usernames can lock every one of them, including your support staff and your biggest customer, by typing wrong passwords. That is a denial of service you built yourself, and the people it hurts are the real users.
A progressive delay keeps most of the protection without that cost. The first three failures in the window are free, for typos. After that, the account must wait 1 second after its latest failure, then 2, then 4, doubling up to a cap of five minutes. An attempt made during the wait is answered with 429 Too Many Requests and a Retry-After header, without checking the password and without counting as another failure. A patient attacker who waits out every delay gets about a dozen guesses per account in the first 15 minutes. After that, old failures slide out of the window and the free attempts come back, so the rate settles at roughly 30 to 40 guesses an hour. That is slow enough to make stuffing one account pointless, but it is not a hard cap. The real user is never locked out: at worst they wait a few minutes, and a correct password clears the account's count.
Delays per account do nothing against a single machine spraying one password across thousands of accounts, because each account fails only once. That is what the per-address limit is for: 30 failures per address in 15 minutes, then 429 until the oldest one slides out of the window. Keep this number generous. Mobile networks in Nigeria, Kenya and many other places put large numbers of phones behind a few shared public addresses, so a tight per-address limit locks out whole neighbourhoods of honest users.
Add three tests to test_limits.py:
cat >> test_limits.py <<'PY'
def make_throttle(tmp_path, **options):
clock = FakeClock()
return Throttle(FailureLog(tmp_path / "t.db", clock), **options), clock
def test_delay_doubles_instead_of_locking(tmp_path):
throttle, clock = make_throttle(tmp_path)
waits = []
for _ in range(8):
wait = throttle.retry_after("amara", "198.51.100.7")
waits.append(wait)
clock.now += wait # a patient attacker waits out each delay
throttle.failed("amara", "198.51.100.7")
assert waits == [0, 0, 0, 1, 2, 4, 8, 16]
def test_real_user_gets_back_in(tmp_path):
throttle, clock = make_throttle(tmp_path)
for _ in range(12):
clock.now += throttle.retry_after("amara", "203.0.113.50")
throttle.failed("amara", "203.0.113.50")
wait = throttle.retry_after("amara", "192.0.2.44")
assert 0 < wait <= 300 # a wait, never a lockout
clock.now += wait
assert throttle.retry_after("amara", "192.0.2.44") == 0
throttle.succeeded("amara")
assert throttle.retry_after("amara", "192.0.2.44") == 0
def test_spraying_from_one_address_hits_the_address_limit(tmp_path):
throttle, clock = make_throttle(tmp_path, ip_limit=5)
for n in range(5):
assert throttle.retry_after(f"user{n}", "203.0.113.9") == 0
throttle.failed(f"user{n}", "203.0.113.9")
assert throttle.retry_after("user99", "203.0.113.9") == 900
assert throttle.retry_after("user99", "198.51.100.7") == 0
PY
.venv/bin/python -m pytest -q test_limits.pyThe second test is the honest trade-off. The attacker's failures delay the account for everyone, the real user included, but the delay is capped and it ends. Compare that with a lockout, which ends only when someone in support unlocks it. NIST SP 800-63B-4 also sets an outer bound: no more than 100 consecutive failed attempts on one account in total, not per window. The sliding window does not enforce that on its own. Because failures slide out after 15 minutes, a patient attacker passes 100 consecutive failures on one account in about three hours, and nothing here ever stops them. To meet the requirement, keep a separate consecutive-failure counter per account that only a successful sign-in resets, and when it reaches 100, stop accepting the password alone: require a second factor or send the user through a reset flow.
Check it worked
pytest reports 4 passed. The waits read [0, 0, 0, 1, 2, 4, 8, 16]. The sixth address-limited attempt is told to wait the full 900 seconds, while the same username from a different address goes straight through.
Step 5 · Refuse passwords that are already on attackers' lists
Stuffing only works when the leaked password is still in use. NIST SP 800-63B-4 requires checking every new password against a list of compromised ones. The best-known public list is Pwned Passwords, from Have I Been Pwned, built from passwords exposed in real breaches. You never send it the password, or even its full hash. Its range API uses k-anonymity:
- Hash the password with SHA-1 and write the hash in uppercase hex.
- Send only the first five characters, as
GET /range/ABCDE. - The API returns every leaked hash that starts with those five characters, usually around 800 of them, as
SUFFIX:COUNTlines. - Look for the remaining 35 characters in that list, on your own server.
The service sees a prefix shared by hundreds of unrelated passwords, so it cannot tell which one you were checking. SHA-1 is fine here: it is only a lookup key into the list, not how you store passwords. Sending the header Add-Padding: true makes every response 800 to 1,000 lines long, with fake lines whose count is 0, so even the response size gives nothing away.
Write the local stand-in first. It serves the same format for a few made-up "breached" passwords, adds padding when asked, and remembers every path it was sent so a test can check what left your app:
cat > pwned_standin.py <<'PY'
"""A local stand-in for the Pwned Passwords range API, for practice and tests."""
import hashlib
import secrets
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
# Made-up counts for practice. The real service holds far more.
DEMO_BREACHED = {
"summer-holiday-2025": 48213,
"welcome-to-the-team-1": 9077,
"correct-horse-battery-staple": 412,
}
def build_ranges(breached):
ranges = {}
for password, count in breached.items():
digest = hashlib.sha1(password.encode("utf-8")).hexdigest().upper()
ranges.setdefault(digest[:5], []).append(f"{digest[5:]}:{count}")
return ranges
def make_server(port=8100, breached=DEMO_BREACHED):
ranges = build_ranges(breached)
seen = []
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
seen.append(self.path)
prefix = self.path.removeprefix("/range/")
if len(prefix) != 5 or any(c not in "0123456789abcdefABCDEF" for c in prefix):
self.send_error(400)
return
lines = list(ranges.get(prefix.upper(), []))
if self.headers.get("Add-Padding") == "true":
lines += [f"{secrets.token_hex(18).upper()[:35]}:0" for _ in range(5)]
body = "\r\n".join(lines).encode()
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, format, *args):
pass
server = ThreadingHTTPServer(("127.0.0.1", port), Handler)
server.seen = seen
return server
if __name__ == "__main__":
print("Stand-in range API on http://127.0.0.1:8100/range/", flush=True)
make_server().serve_forever()
PYThe stand-in pads with five lines rather than hundreds, to keep it small. Now the client, breach.py. If the service is down or slow, it returns None and logs a warning, and the caller lets the sign-up go ahead. That is a choice: failing open keeps sign-ups working during an outage, at the cost of skipping the check for a few minutes. If you would rather refuse sign-ups while the check is down, change the caller, not this function.
cat > breach.py <<'PY'
import hashlib
import logging
import httpx
log = logging.getLogger("signin")
DEFAULT_RANGE_URL = "https://api.pwnedpasswords.com/range/"
def breach_count(password: str, range_url: str = DEFAULT_RANGE_URL, timeout: float = 3.0):
"""How many times the password appears in known breaches, or None if the check failed."""
digest = hashlib.sha1(password.encode("utf-8")).hexdigest().upper()
prefix, suffix = digest[:5], digest[5:]
try:
response = httpx.get(
range_url + prefix,
headers={"Add-Padding": "true", "User-Agent": "stuffing-demo"},
timeout=timeout,
)
response.raise_for_status()
except httpx.HTTPError as err:
log.warning("breach check unavailable: %s", type(err).__name__)
return None
for line in response.text.splitlines():
candidate, _, count = line.partition(":")
if candidate == suffix:
return int(count)
return 0
PYPadded lines carry a count of 0, so a random match against one of them still reads as "not breached".
Check it worked
Start the stand-in on a spare port and look up two passwords:
.venv/bin/python - <<'PY'
import threading
from breach import breach_count
from pwned_standin import make_server
server = make_server(port=8199)
threading.Thread(target=server.serve_forever, daemon=True).start()
url = "http://127.0.0.1:8199/range/"
print("summer-holiday-2025:", breach_count("summer-holiday-2025", url))
print("lantern-orchard-copper-41:", breach_count("lantern-orchard-copper-41", url))
print("paths sent:", server.seen)
server.shutdown()
PYThe output shows 48213 for the first password and 0 for the second. The paths line lists two requests, each /range/ followed by exactly five hex characters: that is all the service ever sees.
Step 6 · Wire the defences into a FastAPI app
Now put the pieces together. app.py has a factory, create_app, so tests can pass in their own database file, stand-in address, limits and alert threshold. When Uvicorn calls it with no arguments it reads environment variables instead.
The alert is the defence against the attack the limits cannot see. A botnet that sends one leaked pair per account from a different address each time never trips a per-account delay or a per-address limit. What it cannot hide is volume: the total number of failures across the whole site jumps. The app counts all failures in the last 60 seconds, and when they pass a threshold it logs one ALERT line naming how many accounts and addresses were involved, then stays quiet for five minutes so one attack does not produce a flood of alerts. Set the threshold well above your normal busy-hour failure rate, which you can read from the same table.
cat > app.py <<'PY'
import logging
import os
import sqlite3
import time
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from breach import DEFAULT_RANGE_URL, breach_count
from limits import FailureLog, Throttle
from passwords import check_password, hash_password, normalise
log = logging.getLogger("signin")
WRONG = {"detail": "Incorrect username or password."}
SLOW_DOWN = {"detail": "Too many sign-in attempts. Wait a moment and try again."}
class Credentials(BaseModel):
username: str = Field(min_length=1, max_length=120)
password: str = Field(min_length=1, max_length=256)
class Users:
def __init__(self, path):
self.path = str(path)
self._run("CREATE TABLE IF NOT EXISTS users (username TEXT PRIMARY KEY, hash TEXT NOT NULL)")
def _run(self, sql, args=()):
db = sqlite3.connect(self.path, timeout=5)
try:
with db:
return db.execute(sql, args).fetchall()
finally:
db.close()
def get_hash(self, username):
rows = self._run("SELECT hash FROM users WHERE username = ?", (username,))
return rows[0][0] if rows else None
def add(self, username, password_hash):
try:
self._run("INSERT INTO users VALUES (?, ?)", (username, password_hash))
except sqlite3.IntegrityError:
return False
return True
def create_app(db_path=None, range_url=None, clock=time.time, alert_threshold=None, ip_limit=30):
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
db_path = db_path or os.environ.get("AUTH_DB", "auth.db")
range_url = range_url or os.environ.get("PWNED_RANGE_URL", DEFAULT_RANGE_URL)
alert_threshold = alert_threshold or int(os.environ.get("ALERT_FAILURES_PER_MINUTE", "50"))
users = Users(db_path)
failures = FailureLog(db_path, clock)
throttle = Throttle(failures, ip_limit=ip_limit)
last_alert = {"at": float("-inf")}
def watch_for_spike():
count, accounts = failures.totals("account", 60)
if count < alert_threshold or clock() - last_alert["at"] < 300:
return
last_alert["at"] = clock()
_, addresses = failures.totals("ip", 60)
log.warning(
"ALERT sign-in failure spike: %d failures in 60s across %d accounts from %d addresses",
count, accounts, addresses,
)
app = FastAPI()
@app.post("/signup", status_code=201)
def signup(creds: Credentials):
username = creds.username.strip().lower()
if len(normalise(creds.password)) < 15:
return JSONResponse({"detail": "Use at least 15 characters."}, status_code=422)
seen = breach_count(normalise(creds.password), range_url)
if seen:
return JSONResponse(
{"detail": f"This password has appeared in {seen:,} data breaches. Choose another."},
status_code=422,
)
if not users.add(username, hash_password(creds.password)):
return JSONResponse({"detail": "That username is taken."}, status_code=409)
return {"created": username}
@app.post("/signin")
def signin(creds: Credentials, request: Request):
username = creds.username.strip().lower()
ip = request.client.host if request.client else "unknown"
wait = throttle.retry_after(username, ip)
if wait:
return JSONResponse(SLOW_DOWN, status_code=429, headers={"Retry-After": str(wait)})
if check_password(users.get_hash(username), creds.password):
throttle.succeeded(username)
return {"signed_in": username}
throttle.failed(username, ip)
watch_for_spike()
return JSONResponse(WRONG, status_code=401)
return app
PYA few details are doing real work here. Usernames are trimmed and lowercased before every lookup, so Amara and amara ` share one delay count. The delay is keyed on the submitted username whether or not the account exists, so the `429 itself does not reveal which accounts are real. The 15-character minimum follows NIST SP 800-63B-4 for password-only sign-in; it allows 8 when a second factor is always required. max_length stops anyone sending a megabyte "password" to make you hash it. A real app would set a session cookie on success; that part is left out here.
The sign-up "username is taken" message does reveal which accounts exist. Most products accept that for usability. If yours cannot, send a confirmation email in both cases and say the same thing on screen.
Write the app tests. Each test gets its own database and its own stand-in on a free port, and TestClient(app, client=(address, port)) sets the address the app sees:
cat > test_app.py <<'PY'
import hashlib
import logging
import threading
import pytest
from fastapi.testclient import TestClient
from app import create_app
from pwned_standin import make_server
AMARA = {"username": "amara", "password": "lantern-orchard-copper-41"}
@pytest.fixture
def standin():
server = make_server(port=0)
threading.Thread(target=server.serve_forever, daemon=True).start()
yield server
server.shutdown()
server.server_close()
@pytest.fixture
def make_app(tmp_path, standin):
def build(**options):
options.setdefault("range_url", f"http://127.0.0.1:{standin.server_address[1]}/range/")
return create_app(db_path=str(tmp_path / "auth.db"), **options)
return build
def client(app, ip="192.0.2.10"):
return TestClient(app, client=(ip, 50000))
def sign_in(c, username, password):
return c.post("/signin", json={"username": username, "password": password})
def test_sign_up_then_sign_in(make_app):
c = client(make_app())
assert c.post("/signup", json=AMARA).status_code == 201
assert sign_in(c, " Amara", AMARA["password"]).status_code == 200
def test_unknown_user_and_wrong_password_look_the_same(make_app):
c = client(make_app())
c.post("/signup", json=AMARA)
wrong = sign_in(c, "amara", "not-her-password-at-all")
unknown = sign_in(c, "nobody-by-this-name", "not-her-password-at-all")
assert wrong.status_code == unknown.status_code == 401
assert wrong.json() == unknown.json()
def test_delays_look_the_same_for_real_and_unknown_accounts(make_app):
c = client(make_app())
c.post("/signup", json=AMARA)
real = [sign_in(c, "amara", f"guess-number-{n}").status_code for n in range(4)]
ghost = [sign_in(c, "ghost", f"guess-number-{n}").status_code for n in range(4)]
assert real == ghost == [401, 401, 401, 429]
def test_sign_up_refuses_short_and_breached_passwords(make_app, standin):
c = client(make_app())
short = c.post("/signup", json={"username": "kofi", "password": "short-pass"})
assert short.status_code == 422
breached = c.post("/signup", json={"username": "kofi", "password": "summer-holiday-2025"})
assert breached.status_code == 422
assert "48,213" in breached.json()["detail"]
full = hashlib.sha1(b"summer-holiday-2025").hexdigest().upper()
assert len(standin.seen) == 1
prefix = standin.seen[0].removeprefix("/range/")
assert len(prefix) == 5 and full.startswith(prefix)
def test_breach_check_outage_lets_sign_up_through(make_app, caplog):
c = client(make_app(range_url="http://127.0.0.1:9/range/"))
with caplog.at_level(logging.WARNING, logger="signin"):
assert c.post("/signup", json=AMARA).status_code == 201
assert "breach check unavailable" in caplog.text
def test_one_address_spraying_many_accounts_gets_429(make_app):
app = make_app(ip_limit=5)
sprayer = client(app, ip="203.0.113.10")
codes = [sign_in(sprayer, f"user{n}", "Summer2026-welcome").status_code for n in range(7)]
assert codes == [401] * 5 + [429] * 2
blocked = sign_in(sprayer, "user99", "Summer2026-welcome")
assert 0 < int(blocked.headers["retry-after"]) <= 900
assert sign_in(client(app, ip="192.0.2.44"), "user99", "Summer2026-welcome").status_code == 401
def test_spread_out_stuffing_raises_one_alert(make_app, caplog):
app = make_app(alert_threshold=5)
with caplog.at_level(logging.WARNING, logger="signin"):
for n in range(8):
bot = client(app, ip=f"198.51.100.{n + 1}")
assert sign_in(bot, f"leaked{n}@example.com", "old-password").status_code == 401
alerts = [r.getMessage() for r in caplog.records if "ALERT" in r.getMessage()]
assert len(alerts) == 1
assert "5 failures in 60s across 5 accounts from 5 addresses" in alerts[0]
PY
.venv/bin/python -m pytest -q test_app.pyThe last test is the one to read twice. Eight leaked pairs from eight addresses: every attempt is a plain 401, no limit fires, and the only sign anything is wrong is the alert.
Check it worked
pytest reports 7 passed, with no warnings. If you see a StarletteDeprecationWarning about httpx, httpx2 is missing from the environment; repeat the install from the first step.
Step 7 · Fire a burst of failed sign-ins at the running app
Tests call the app in-process. Now run it for real and attack it from a script, the way a stuffing tool would. In your second terminal, from ~/stuffing-demo, start the stand-in and leave it running:
cd ~/stuffing-demo
.venv/bin/python pwned_standin.pyIn your third terminal, start the app with Uvicorn, pointed at the stand-in:
cd ~/stuffing-demo
AUTH_DB=auth.db PWNED_RANGE_URL=http://127.0.0.1:8100/range/ .venv/bin/uvicorn app:create_app --factory --port 8000--factory tells Uvicorn that create_app is a function returning the app. In production, leave out PWNED_RANGE_URL so the app calls the real Pwned Passwords service.
The burst script plays three parts. First, one machine sprays a common password across 40 accounts. Second, a botnet tries 60 leaked pairs, each from its own address. Last, the real user signs in. To pretend to be many machines, it sets X-Forwarded-For. Uvicorn believes that header only from connections it trusts, and by default it trusts just 127.0.0.1 and ::1, which is where a reverse proxy on the same server connects from. That default is why this works on your laptop. On your server, make sure the proxy overwrites the header rather than passing on whatever the client sent, and that the app port is not reachable from outside, or anyone can choose their own address and walk past the per-address limit.
cat > burst.py <<'PY'
import collections
import httpx
COMMON = "Summer2026-welcome"
def attempt(client, username, password, ip):
return client.post(
"/signin",
json={"username": username, "password": password},
headers={"X-Forwarded-For": ip},
)
with httpx.Client(base_url="http://127.0.0.1:8000", timeout=10.0) as client:
created = client.post("/signup", json={"username": "amara", "password": "lantern-orchard-copper-41"})
print("sign-up amara:", created.status_code)
spray = collections.Counter()
retry = None
for n in range(40):
r = attempt(client, f"user{n:03}", COMMON, "203.0.113.10")
spray[r.status_code] += 1
retry = r.headers.get("retry-after", retry)
print("spraying from one address:", dict(sorted(spray.items())), "Retry-After:", retry)
stuffing = collections.Counter()
for n in range(60):
r = attempt(client, f"leaked{n:03}@example.com", f"old-password-{n}", f"198.51.100.{n + 1}")
stuffing[r.status_code] += 1
print("stuffing from 60 addresses:", dict(sorted(stuffing.items())))
r = attempt(client, "amara", "lantern-orchard-copper-41", "192.0.2.44")
print("amara with her real password:", r.status_code)
PY
.venv/bin/python burst.py | tee burst.txttee keeps a copy of the output in burst.txt while printing it. The addresses come from the ranges reserved for documentation, so they belong to nobody.
Check it worked
The script prints four lines:
sign-up amara: 201.spraying from one address: {401: 30, 429: 10}and aRetry-Aftera little under 900 seconds. The address limit stopped the spray after 30 accounts.stuffing from 60 addresses: {401: 60}. Not one of those attempts hit a limit.amara with her real password: 200. Two attacks ran against the service and the real user still got straight in.
In the Uvicorn terminal there is exactly one line containing ALERT sign-in failure spike: 50 failures in 60s across 50 accounts, followed by how many addresses were involved. It fired on the 50th failure, partway through the botnet run, and stayed quiet afterwards. In production, send that line to wherever your on-call team looks: a log alert rule, a chat webhook or a paging tool.
If you run the script a second time within 15 minutes, the spray line shows {429: 40}, because the address is still over its limit. Delete auth.db and restart Uvicorn to start from zero.
The layer that actually ends credential stuffing
Everything above makes stuffing slower, noisier and less rewarding. None of it helps the user whose reused password the attacker already has: their one attempt succeeds on the first try. Only a second factor, or no password at all, closes that gap:
- Passkeys replace the password with a key pair bound to your domain. There is nothing to leak or reuse, and a phishing site on another domain cannot use it. See add passkey sign-in with WebAuthn.
- TOTP codes from an authenticator app mean a stolen password alone is not enough. See add TOTP two-factor sign-in. Where you can, do not make SMS codes the only option: a SIM swap hands the attacker the code as well.
Offer passkeys first, keep the password path protected by everything you built here, and ask for a second factor when a sign-in looks unusual: a new device, a new country, or during an alert.
Step 8 · Stop the servers and clean up
Press Ctrl+C in the second and third terminals to stop the stand-in and Uvicorn. Then remove the demo folder, which holds the virtual environment, the code and the SQLite database:
cd ~
rm -rf ~/stuffing-demoCheck it worked
ls ~/stuffing-demo reports that there is no such file or directory.
Next steps
- Take the password out of the attack entirely: add passkey sign-in with WebAuthn.
- Make a leaked password worthless on its own: add TOTP two-factor sign-in to a web app.
- Tune the hash this tutorial reuses, and migrate old hashes: hash and verify passwords with Argon2id.
- Block abusive addresses before they reach the app: block brute-force logins with Fail2ban.
Related tutorials
- Write custom Fail2ban jails and filters for your own appsYou will have Fail2ban 1.1 banning repeated failed sign-ins to your own app and to an nginx basic-auth area, with filters you tested against sample logs, your own addresses allow-listed, and longer bans for repeat offenders.
- Validate file uploads before you store or serve themYou will take a FastAPI image upload route that trusts everything the browser sends, prove its flaws with pytest, and rebuild it with size limits, type checks from the file's own bytes, Pillow re-encoding, random storage names and safe download headers.
- Use SSH certificates instead of copying keys to every serverYou will run a small SSH certificate authority with ssh-keygen, log in to an Ubuntu 26.04 server with an eight-hour user certificate, give the server a host certificate so clients stop asking about fingerprints, and revoke a certificate the server then refuses.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials