Skip to main content

Security and hardening · Intermediate · 26 min

Build a secure password reset flow with single-use tokens

By Padding · Updated 18 Nov 2026
Python 3.15.2 · FastAPI 0.165.0 · argon2-cffi 25.1.0 · Mailpit 1.34.0 · pytest 9.2.0

You will have a small FastAPI app whose password reset gives the same reply for every address, emails a 30-minute single-use link built from a configured base URL, stores only a hash of each token, signs out every device after a reset, and passes an end-to-end pytest suite that reads the links from Mailpit.

On this page

A password reset link is a password. Whoever holds it can take over the account, so the flow that issues it deserves the same care as sign-in. Most reset bugs are small: a form that says "no account with that email" and lets anyone test which addresses are registered, a token stored in plain text next to the users table, a link that still works a week later or a second time, an email whose link points at whatever Host header the attacker sent, or a reset that leaves the attacker's existing session signed in.

In this tutorial you build the whole flow in one FastAPI app and close each of those gaps on purpose:

  • The request form gives the same reply, in the same time, whether or not the address has an account.
  • Each token is 32 random bytes from secrets.token_urlsafe, and the database keeps only its SHA-256 hash.
  • A token expires after 30 minutes, works once, and dies when a newer token is issued or the password changes.
  • The link is built from a base URL you configure, never from the request.
  • A successful reset signs out every device and sends a "your password was changed" email.

Mailpit catches every email on your machine, so nothing reaches a real inbox, and a pytest suite proves each rule end to end by reading the links out of Mailpit's API. Everything lives in a throwaway folder, ~/reset-demo, with a SQLite file standing in for your database.

Step 1 · Install Mailpit and leave it running

Mailpit is a single binary that accepts email over SMTP on one port and shows it in a web page and a JSON API on another. Download release 1.34.0 for your system and install it:

Bash
MAILPIT_VERSION=1.34.0
OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
case "$(uname -m)" in x86_64) ARCH=amd64 ;; aarch64|arm64) ARCH=arm64 ;; *) ARCH=unsupported ;; esac
cd "$(mktemp -d)"
curl -fsSLO "https://github.com/axllent/mailpit/releases/download/v${MAILPIT_VERSION}/mailpit-${OS}-${ARCH}.tar.gz"
tar -xzf "mailpit-${OS}-${ARCH}.tar.gz" mailpit
sudo install -m 755 mailpit /usr/local/bin/mailpit
cd ~
mailpit version --no-release-check

The same commands work on Linux and macOS. A binary installed this way gets no updates from apt or Homebrew: to upgrade, set MAILPIT_VERSION to the newer release and run the block again.

Start Mailpit in a second terminal, bound to your own machine only, and leave it running:

Bash
mailpit --smtp 127.0.0.1:1025 --listen 127.0.0.1:8025

Check it worked

mailpit version --no-release-check prints something like mailpit v1.34.0 compiled with go1.x on linux/amd64. The second terminal logs lines saying the SMTP server is on 127.0.0.1:1025 and the web UI on 127.0.0.1:8025. Open http://127.0.0.1:8025 in a browser and you see an empty inbox. Back in the first terminal, this prints a JSON object with a "Version" field:

Bash
curl -s http://127.0.0.1:8025/api/v1/info; echo

Step 2 · Create the project and its settings

Make the folder and a virtual environment, and install exact versions. FastAPI needs python-multipart to read HTML form posts, argon2-cffi hashes the passwords, and httpx and pytest drive the end-to-end tests:

Bash
mkdir -p ~/reset-demo
cd ~/reset-demo
python3 -m venv .venv
.venv/bin/pip install --quiet fastapi==0.165.0 uvicorn==0.54.0 python-multipart==0.0.34 argon2-cffi==25.1.0 httpx==0.29.0 pytest==9.2.0

The app reads its settings from environment variables. Put them in a file and load it into your shell:

Bash
cat > reset.env <<'ENV'
APP_BASE_URL=http://127.0.0.1:8000
DB_PATH=app.db
SMTP_HOST=127.0.0.1
SMTP_PORT=1025
MAIL_FROM=no-reply@example.com
ENV
set -a; . ./reset.env; set +a

APP_BASE_URL is the most important line here. Every link the app emails starts with it, so on a live site it is your public https:// address, set by you and never worked out from the incoming request. This file holds no secrets because Mailpit needs no password. When you point the app at a real mail provider, pass its SMTP credentials the same way your other app secrets reach it, as environment variables from a secrets store, and keep them out of files you commit.

Check it worked

Bash
.venv/bin/python -c "import fastapi, argon2; print(fastapi.__version__, argon2.__version__)"
echo "$APP_BASE_URL"

The first line is 0.165.0 25.1.0 and the second is http://127.0.0.1:8000.

Step 3 · Store users and sessions

Before any reset logic, the app needs users with hashed passwords and sessions it can revoke. Write the first part of app.py:

Bash
cat > app.py <<'PY'
import hashlib
import os
import secrets
import smtplib
import sqlite3
import time
from contextlib import closing
from email.message import EmailMessage
from html import escape
from urllib.parse import urlsplit

from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerifyMismatchError
from fastapi import BackgroundTasks, FastAPI, Form, Header, HTTPException
from fastapi.responses import HTMLResponse

BASE_URL = os.environ["APP_BASE_URL"].rstrip("/")
if urlsplit(BASE_URL).scheme != "https" and urlsplit(BASE_URL).hostname not in ("127.0.0.1", "localhost"):
    raise RuntimeError("APP_BASE_URL must start with https:// outside local development")

DB_PATH = os.environ.get("DB_PATH", "app.db")
SMTP_HOST = os.environ.get("SMTP_HOST", "127.0.0.1")
SMTP_PORT = int(os.environ.get("SMTP_PORT", "1025"))
MAIL_FROM = os.environ.get("MAIL_FROM", "no-reply@example.com")

TOKEN_TTL_SECONDS = 30 * 60
MIN_PASSWORD_LENGTH = 15

hasher = PasswordHasher()
DUMMY_HASH = hasher.hash(secrets.token_urlsafe(16))

SCHEMA = """
CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY,
    email TEXT NOT NULL UNIQUE COLLATE NOCASE,
    password_hash TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS sessions (
    token_hash TEXT PRIMARY KEY,
    user_id INTEGER NOT NULL REFERENCES users(id)
);
CREATE TABLE IF NOT EXISTS reset_tokens (
    token_hash TEXT PRIMARY KEY,
    user_id INTEGER NOT NULL REFERENCES users(id),
    expires_at INTEGER NOT NULL
);
"""


def db():
    conn = sqlite3.connect(DB_PATH, isolation_level=None, timeout=10)
    conn.execute("PRAGMA foreign_keys = ON")
    return closing(conn)


with db() as conn:
    conn.executescript(SCHEMA)


def sha256(value: str) -> str:
    return hashlib.sha256(value.encode()).hexdigest()


def check_password_rules(password: str) -> None:
    if len(password) < MIN_PASSWORD_LENGTH:
        raise HTTPException(400, f"Use at least {MIN_PASSWORD_LENGTH} characters.")


def create_user(email: str, password: str) -> None:
    check_password_rules(password)
    with db() as conn:
        conn.execute(
            "INSERT INTO users (email, password_hash) VALUES (?, ?)",
            (email.strip(), hasher.hash(password)),
        )


def replace_password(conn, user_id: int, new_hash: str) -> None:
    """The one place a password changes. Call it inside a transaction."""
    conn.execute("UPDATE users SET password_hash = ? WHERE id = ?", (new_hash, user_id))
    conn.execute("DELETE FROM reset_tokens WHERE user_id = ?", (user_id,))
    conn.execute("DELETE FROM sessions WHERE user_id = ?", (user_id,))


def current_user(authorization: str | None) -> tuple[int, str]:
    token = (authorization or "").removeprefix("Bearer ")
    with db() as conn:
        row = conn.execute(
            "SELECT users.id, users.email FROM sessions"
            " JOIN users ON users.id = sessions.user_id WHERE sessions.token_hash = ?",
            (sha256(token),),
        ).fetchone()
    if row is None:
        raise HTTPException(401, "Sign in first.")
    return row


app = FastAPI()


@app.post("/login")
def login(email: str = Form(), password: str = Form()):
    with db() as conn:
        row = conn.execute(
            "SELECT id, password_hash FROM users WHERE email = ?", (email.strip(),)
        ).fetchone()
    try:
        # Unknown addresses still pay for one hash, so timing does not reveal them.
        hasher.verify(row[1] if row else DUMMY_HASH, password)
        if row is None:
            raise VerifyMismatchError
    except (VerifyMismatchError, InvalidHashError):
        raise HTTPException(401, "Wrong email or password.")
    session = secrets.token_urlsafe(32)
    with db() as conn:
        conn.execute(
            "INSERT INTO sessions (token_hash, user_id) VALUES (?, ?)", (sha256(session), row[0])
        )
    return {"session": session}


@app.get("/me")
def me(authorization: str | None = Header(default=None)):
    _, email = current_user(authorization)
    return {"email": email}
PY

Three choices here carry the rest of the tutorial:

  • Sessions are stored the same way reset tokens will be: the client holds a random token, the database holds only its SHA-256 hash. A leaked database then contains nothing anyone can sign in with. A single fast hash is enough for a 32-byte random value, because there is nothing to guess; slow hashes such as Argon2id are for passwords people choose. Hash and verify passwords with Argon2id covers tuning those.
  • replace_password is the only code that writes a new password hash, and it always deletes the user's reset tokens and sessions in the same transaction. Any future "change password" or admin reset path must go through it.
  • The 15-character minimum follows NIST SP 800-63B-4 for passwords used without a second factor. Long passphrases are easier to type on a phone keyboard than short strings full of symbols.

This app hands the session token back as JSON and reads it from an Authorization: Bearer header, which keeps the examples short. A browser app would put it in a Secure, HttpOnly cookie instead; Secure sessions and cookies in an Express app shows how.

Add a small script that creates a user and asks for the password without echoing it, so it never lands in your shell history:

Bash
cat > add_user.py <<'PY'
import getpass
import sys

from app import create_user

email = sys.argv[1]
if sys.stdin.isatty():
    password = getpass.getpass(f"Password for {email}: ")
else:
    password = sys.stdin.readline().rstrip("\n")
create_user(email, password)
print("created", email)
PY

Create a demo user. Type a password of at least 15 characters when asked:

Bash
.venv/bin/python add_user.py amara@example.com

Start the app in a third terminal and leave it running. --no-access-log matters later: an access log records every URL, and reset links carry their token in the URL.

Bash
cd ~/reset-demo
set -a; . ./reset.env; set +a
.venv/bin/uvicorn app:app --host 127.0.0.1 --port 8000 --no-access-log

Check it worked

Back in the first terminal, look at what the database holds, then ask the app who you are without a session:

Bash
cd ~/reset-demo
.venv/bin/python -c "import sqlite3; print(sqlite3.connect('app.db').execute('SELECT email, substr(password_hash, 1, 10) FROM users').fetchall())"
curl -s http://127.0.0.1:8000/me; echo

The first command prints [('amara@example.com', '$argon2id$')]: the password is stored only as an Argon2id hash. The second prints {"detail":"Sign in first."}.

Step 4 · Send a reset link that gives nothing away

Now the request side. Append it to app.py:

Bash
cat >> app.py <<'PY'


GENERIC_REPLY = {"message": "If an account exists for that address, we have sent a reset link to it."}


def send_email(to: str, subject: str, body: str) -> None:
    message = EmailMessage()
    message["From"] = MAIL_FROM
    message["To"] = to
    message["Subject"] = subject
    message.set_content(body)
    with smtplib.SMTP(SMTP_HOST, SMTP_PORT, timeout=10) as smtp:
        smtp.send_message(message)


def issue_reset_token(email: str) -> None:
    with db() as conn:
        row = conn.execute("SELECT id, email FROM users WHERE email = ?", (email,)).fetchone()
        if row is None:
            return
        user_id, address = row
        token = secrets.token_urlsafe(32)
        conn.execute("BEGIN IMMEDIATE")
        conn.execute("DELETE FROM reset_tokens WHERE user_id = ?", (user_id,))
        conn.execute(
            "INSERT INTO reset_tokens (token_hash, user_id, expires_at) VALUES (?, ?, ?)",
            (sha256(token), user_id, int(time.time()) + TOKEN_TTL_SECONDS),
        )
        conn.execute("COMMIT")
    link = f"{BASE_URL}/reset-password?token={token}"
    send_email(
        address,
        "Reset your password",
        "Someone asked to reset the password for this account.\n\n"
        f"Choose a new password here:\n{link}\n\n"
        "The link works once and expires in 30 minutes. If you did not ask for this, "
        "ignore this email: your password has not changed.\n",
    )


@app.post("/password-reset/request", status_code=202)
def request_reset(background: BackgroundTasks, email: str = Form()):
    background.add_task(issue_reset_token, email.strip())
    return GENERIC_REPLY
PY

Read request_reset closely, because it is two lines on purpose:

  • It never looks up the address itself. All the work, including the database lookup and the SMTP call, runs as a background task after the reply has gone. A known address and an unknown one get the same 202 and the same sentence, in the same time. If the reply waited for the email to send, the slower answers would mark the real accounts.
  • secrets.token_urlsafe(32) reads 32 bytes from the operating system's secure random source and encodes them as 43 URL-safe characters. Only sha256(token) reaches the database, so a stolen backup or a read-only SQL injection gives an attacker hashes they cannot turn back into working links.
  • Deleting the user's earlier tokens before inserting the new one means only the most recent email works. Someone who asks twice and clicks the older email gets "invalid link", which is the safe failure.
  • The email goes to the address stored on the account, not the text typed into the form. With COLLATE NOCASE the two can differ in case, and sending to the stored value closes a class of bugs where an address that merely looks equal receives the link.
  • The link starts with BASE_URL from your settings. Building it from request.base_url or the Host header would let anyone who sends Host: attacker.example make your server email a real user a link to the attacker's site, carrying a valid token.

The same reply applies to every other door into the account. If your sign-up form says "that address is already registered", it leaks what this form hides, so answer sign-ups the same way and send the explanation by email.

Stop the app with Ctrl+C in its terminal and start it again with the same uvicorn command, so it loads the new code.

Check it worked

Ask for a link for the demo user and for an address with no account:

Bash
cd ~/reset-demo
curl -s -d email=amara@example.com http://127.0.0.1:8000/password-reset/request; echo
curl -s -d email=nobody@example.com http://127.0.0.1:8000/password-reset/request; echo

Both lines are identical: {"message":"If an account exists for that address, we have sent a reset link to it."}. Mailpit's inbox in the browser now shows one email, "Reset your password", to amara@example.com, and nothing for nobody@example.com.

Add a helper that pulls the newest reset link for an address out of Mailpit's API, waiting a few seconds for the email to arrive:

Bash
cat > latest_link.py <<'PY'
import re
import sys
import time

import httpx

MAILPIT = "http://127.0.0.1:8025/api/v1"
address = sys.argv[1]

for _ in range(20):
    for summary in httpx.get(f"{MAILPIT}/messages").json()["messages"]:  # newest first
        if summary["Subject"] == "Reset your password" and any(
            to["Address"] == address for to in summary["To"]
        ):
            text = httpx.get(f"{MAILPIT}/message/{summary['ID']}").json()["Text"]
            print(re.search(r"\S+/reset-password\?token=[A-Za-z0-9_-]+", text).group(0))
            sys.exit(0)
    time.sleep(0.25)
sys.exit(f"no reset email for {address}")
PY
.venv/bin/python latest_link.py amara@example.com
.venv/bin/python -c "import sqlite3; print(sqlite3.connect('app.db').execute('SELECT token_hash FROM reset_tokens').fetchall())"

The helper prints a link like http://127.0.0.1:8000/reset-password?token= followed by 43 letters, digits, - and _. The database query prints one row: a 64-character hex string that does not contain the token. Ask for another link and run the query again: there is still one row, with a different hash, because a new token replaces the old one.

Step 5 · Spend the token once and sign out every device

Append the second half of the flow: the page the link opens, the endpoint that accepts the new password, and a normal "change password" endpoint for signed-in users:

Bash
cat >> app.py <<'PY'


BAD_LINK = "This reset link is invalid or has expired. Ask for a new one."


@app.get("/reset-password", response_class=HTMLResponse)
def reset_form(token: str = ""):
    page = f"""<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Choose a new password</title>
<form method="post" action="/password-reset/confirm">
  <input type="hidden" name="token" value="{escape(token)}">
  <label>New password
    <input type="password" name="new_password" minlength="{MIN_PASSWORD_LENGTH}"
           autocomplete="new-password" required>
  </label>
  <button>Save password</button>
</form>
</html>
"""
    return HTMLResponse(page, headers={"Referrer-Policy": "no-referrer", "Cache-Control": "no-store"})


def notify_password_changed(address: str) -> None:
    send_email(
        address,
        "Your password was changed",
        "The password for this account was just changed, and every device was signed out.\n\n"
        "If this was not you, reset your password now and contact support.\n",
    )


@app.post("/password-reset/confirm")
def confirm_reset(background: BackgroundTasks, token: str = Form(), new_password: str = Form()):
    check_password_rules(new_password)  # before spending the token, so a typo keeps the link
    new_hash = hasher.hash(new_password)
    with db() as conn:
        conn.execute("BEGIN IMMEDIATE")
        rows = conn.execute(
            "DELETE FROM reset_tokens WHERE token_hash = ? RETURNING user_id, expires_at",
            (sha256(token),),
        ).fetchall()
        if not rows or rows[0][1] <= time.time():
            conn.execute("COMMIT")
            raise HTTPException(400, BAD_LINK)
        user_id = rows[0][0]
        replace_password(conn, user_id, new_hash)
        (address,) = conn.execute("SELECT email FROM users WHERE id = ?", (user_id,)).fetchone()
        conn.execute("COMMIT")
    background.add_task(notify_password_changed, address)
    return {"message": "Password changed. Sign in with your new password."}


@app.post("/account/password")
def change_password(
    background: BackgroundTasks,
    authorization: str | None = Header(default=None),
    current_password: str = Form(),
    new_password: str = Form(),
):
    user_id, address = current_user(authorization)
    with db() as conn:
        (stored,) = conn.execute("SELECT password_hash FROM users WHERE id = ?", (user_id,)).fetchone()
    try:
        hasher.verify(stored, current_password)
    except VerifyMismatchError:
        raise HTTPException(401, "Your current password is wrong.")
    check_password_rules(new_password)
    new_hash = hasher.hash(new_password)
    with db() as conn:
        conn.execute("BEGIN IMMEDIATE")
        replace_password(conn, user_id, new_hash)
        conn.execute("COMMIT")
    background.add_task(notify_password_changed, address)
    return {"message": "Password changed. Sign in again on your other devices."}
PY

What each piece defends against:

  • Opening the link only shows a form; the token is spent when the form is posted. Some mail security scanners open every link in an incoming email, and a GET that used up the token would break resets for those users.
  • DELETE ... RETURNING finds and removes the token in one statement, inside a BEGIN IMMEDIATE transaction. Two requests racing with the same token cannot both succeed: the second finds nothing. An expired token is deleted too, then refused with the same message as a wrong one.
  • replace_password then removes every other reset token and every session for the user. If an attacker was signed in, or had requested their own link, both stop working. Sign-in is not automatic after a reset; the user signs in with the new password, which also means a mistyped password is noticed straight away.
  • /account/password goes through replace_password too, so changing a password while signed in cancels any reset link still sitting in an inbox.
  • The notification email gives the real owner a chance to react if someone else did this. It matters most for people who share a phone or an email account with family, which is common in many households.
  • Referrer-Policy: no-referrer stops the browser sending the page's URL, token included, to any other site the page loads from or links to. Cache-Control: no-store keeps the page out of shared caches. The token also appears in your web server's or reverse proxy's access log for this URL, which is why the app runs without one here; on a live site, strip query strings from logs for /reset-password instead.

Thirty minutes is long enough for an email that arrives slowly, or for someone who has to top up mobile data before they can open it, and short enough that an old email left in an inbox is useless. If your users regularly miss that window, show "ask for a new link" prominently on the error page rather than making tokens live longer.

Restart the app in its terminal (Ctrl+C, then the same uvicorn command).

Check it worked

Empty the Mailpit inbox, ask for a fresh link and print it:

Bash
cd ~/reset-demo
curl -s -X DELETE http://127.0.0.1:8025/api/v1/messages; echo
curl -s -d email=amara@example.com http://127.0.0.1:8000/password-reset/request; echo
.venv/bin/python latest_link.py amara@example.com

Open the printed link in your browser. You see the "New password" form. Type a new password of at least 15 characters and save: the browser shows {"message":"Password changed. Sign in with your new password."}.

List the subjects in the inbox:

Bash
curl -s http://127.0.0.1:8025/api/v1/messages | .venv/bin/python -c "import json, sys; [print(m['Subject']) for m in json.load(sys.stdin)['messages']]"

You see Your password was changed above Reset your password. Open the same reset link again and save another password: this time the reply is {"detail":"This reset link is invalid or has expired. Ask for a new one."}.

Step 6 · Prove the whole flow with pytest

Clicking through once shows the happy path. The rules that matter are the failures, so write them down as tests. Each test creates its own user, drives the running app over HTTP, and reads the emails back from Mailpit:

Bash
cat > test_reset_flow.py <<'PY'
import re
import sqlite3
import time
import uuid

import httpx
import pytest

from app import BASE_URL, DB_PATH, create_user, sha256

APP = "http://127.0.0.1:8000"
MAILPIT = "http://127.0.0.1:8025/api/v1"
OLD_PASSWORD = "plum-tree-river-seven"
NEW_PASSWORD = "copper-kettle-morning-light"


@pytest.fixture(autouse=True)
def empty_inbox():
    httpx.delete(f"{MAILPIT}/messages").raise_for_status()


@pytest.fixture
def email():
    address = f"user-{uuid.uuid4().hex[:8]}@example.com"
    create_user(address, OLD_PASSWORD)
    return address


def emails_to(address, subject, at_least=1, wait=10.0):
    deadline = time.monotonic() + wait
    while True:
        listing = httpx.get(f"{MAILPIT}/messages").json()["messages"]
        found = [
            m for m in listing
            if m["Subject"] == subject and any(to["Address"] == address for to in m["To"])
        ]
        if len(found) >= at_least or time.monotonic() > deadline:
            return [httpx.get(f"{MAILPIT}/message/{m['ID']}").json() for m in found]
        time.sleep(0.2)


def request_link(address, **kwargs):
    before = {m["ID"] for m in emails_to(address, "Reset your password", at_least=0, wait=0)}
    reply = httpx.post(f"{APP}/password-reset/request", data={"email": address}, **kwargs)
    assert reply.status_code == 202
    messages = emails_to(address, "Reset your password", at_least=len(before) + 1)
    new = [m for m in messages if m["ID"] not in before]
    assert len(new) == 1
    return new[0]


def link_in(message):
    return re.search(r"\S+/reset-password\?token=[A-Za-z0-9_-]+", message["Text"]).group(0)


def token_of(link):
    return link.split("token=", 1)[1]


def confirm(token, password=NEW_PASSWORD):
    return httpx.post(f"{APP}/password-reset/confirm", data={"token": token, "new_password": password})


def login(address, password):
    return httpx.post(f"{APP}/login", data={"email": address, "password": password})


def test_reply_is_the_same_for_unknown_addresses(email):
    unknown = f"nobody-{email}"
    a = httpx.post(f"{APP}/password-reset/request", data={"email": unknown})
    b = httpx.post(f"{APP}/password-reset/request", data={"email": email})
    assert a.status_code == b.status_code == 202
    assert a.json() == b.json()
    assert emails_to(email, "Reset your password")
    assert emails_to(unknown, "Reset your password", at_least=0, wait=0) == []


def test_link_uses_the_configured_base_url(email):
    message = request_link(email, headers={"Host": "attacker.example", "X-Forwarded-Host": "attacker.example"})
    assert link_in(message).startswith(f"{BASE_URL}/reset-password?token=")
    assert "attacker.example" not in message["Text"]


def test_token_is_random_and_stored_only_as_a_hash(email):
    token = token_of(link_in(request_link(email)))
    assert len(token) == 43  # 32 random bytes in URL-safe Base64
    with sqlite3.connect(DB_PATH) as conn:
        stored = [row[0] for row in conn.execute("SELECT token_hash FROM reset_tokens")]
    assert sha256(token) in stored
    assert token not in stored


def test_reset_signs_out_everywhere_and_notifies(email):
    auth = {"Authorization": f"Bearer {login(email, OLD_PASSWORD).json()['session']}"}
    assert httpx.get(f"{APP}/me", headers=auth).status_code == 200

    link = link_in(request_link(email))
    page = httpx.get(link)
    assert page.status_code == 200
    assert page.headers["referrer-policy"] == "no-referrer"
    assert 'name="new_password"' in page.text

    assert confirm(token_of(link)).status_code == 200
    assert httpx.get(f"{APP}/me", headers=auth).status_code == 401
    assert login(email, OLD_PASSWORD).status_code == 401
    assert login(email, NEW_PASSWORD).status_code == 200
    assert emails_to(email, "Your password was changed")


def test_token_works_only_once(email):
    token = token_of(link_in(request_link(email)))
    assert confirm(token).status_code == 200
    assert confirm(token, "a-different-long-passphrase").status_code == 400
    assert login(email, NEW_PASSWORD).status_code == 200


def test_newer_link_replaces_older(email):
    first = token_of(link_in(request_link(email)))
    second = token_of(link_in(request_link(email)))
    assert confirm(first).status_code == 400
    assert confirm(second).status_code == 200


def test_password_change_cancels_open_links(email):
    token = token_of(link_in(request_link(email)))
    session = login(email, OLD_PASSWORD).json()["session"]
    changed = httpx.post(
        f"{APP}/account/password",
        headers={"Authorization": f"Bearer {session}"},
        data={"current_password": OLD_PASSWORD, "new_password": NEW_PASSWORD},
    )
    assert changed.status_code == 200
    assert confirm(token, "someone-elses-long-passphrase").status_code == 400
    assert login(email, NEW_PASSWORD).status_code == 200


def test_expired_link_is_rejected(email):
    token = token_of(link_in(request_link(email)))
    with sqlite3.connect(DB_PATH) as conn:  # 31 minutes later, without waiting
        conn.execute(
            "UPDATE reset_tokens SET expires_at = expires_at - 1860 WHERE token_hash = ?",
            (sha256(token),),
        )
    assert confirm(token).status_code == 400
    assert login(email, OLD_PASSWORD).status_code == 200


def test_short_password_keeps_the_link(email):
    token = token_of(link_in(request_link(email)))
    assert confirm(token, "too-short").status_code == 400
    assert confirm(token).status_code == 200
PY
.venv/bin/python -m pytest -q test_reset_flow.py

The expiry test moves the stored expiry 31 minutes into the past instead of waiting, which proves the server compares against the stored time rather than trusting anything the client sends. The Host test sends both Host and X-Forwarded-Host headers pointing at another site, the two headers a framework most often uses to work out its own address.

Check it worked

pytest prints a row of nine dots and a summary line like 9 passed in 4.21s. To see a test catch a real bug, comment out the line conn.execute("DELETE FROM reset_tokens WHERE user_id = ?", (user_id,)) in issue_reset_token, restart the app, and run pytest again: test_newer_link_replaces_older fails. Put the line back and restart before you carry on.

Step 7 · Clean up

Stop the app and Mailpit with Ctrl+C in their terminals.

Then remove the demo folder. If you are moving on to the Mailpit tutorial, keep the binary; otherwise remove it too:

Bash
cd ~
rm -rf ~/reset-demo
sudo rm /usr/local/bin/mailpit

Check it worked

ls ~/reset-demo and ls /usr/local/bin/mailpit both report No such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.