Testing a Practice App Through an Intercepting Proxy
Run a small, intentionally flawed FastAPI app on 127.0.0.1, confirm SQL injection, path traversal, XSS and SSRF through mitmproxy with harmless canary checks, then fix each flaw and lock the fix with a pytest regression test.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Build and start the flawed app
- Step 2: Prove each flaw through the proxy
- Step 3: Lock each flaw with a failing test
- Step 4: Apply the fixes
- Step 5: Re-run the tests and replay the captured requests
- Check your understanding
- Apply it
- Review prompt
Lessons of Web Application Security
- Browser Trust and Client-Side Hardening Concept · 25 min
- Injection, Traversal, XSS and SSRF: Root Causes and Fixes Worked example · 30 min
- Testing a Practice App Through an Intercepting Proxy Lab · 30 min
- Finding and Fixing Access Control, API and Session Flaws Lab · 30 min
- Findings, Fixes and Interim WAF Mitigations Worked example · 25 min
- Web Application Security Check Knowledge check · 10 questions
What you will learn
- Explain how the browser security model (same-origin policy, cookies, CORS) and server-side request handling create the conditions for common web vulnerabilities.
- Confirm injection, path traversal, cross-site scripting and server-side request forgery flaws in an intentionally vulnerable application and apply the matching defence: parameterised queries, canonicalised and allow-listed file paths, contextual output encoding with CSP, and allow-listed outbound requests.
01. Goal and setup
In the previous lesson you saw why injection, path traversal, cross-site scripting (XSS) and server-side request forgery (SSRF) happen. In this lab you meet them in running code. You will build a practice app with one tiny flawed route for each class, and work through four moves for every flaw: spot it, prove it harmlessly, fix it, and lock the fix with a test.
The proofs use only the lab's own seeded data. A second database row appears that should not, a canary file the lab created is read, a marker string comes back unescaped, and a second local "internal" server answers. Nothing is executed and nothing leaves your machine.
Testers watch this traffic with an intercepting proxy: a program that sits between the client and the server, records every request and response, and lets you edit or resend them. ZAP (formerly OWASP ZAP), Burp Suite and Caido are graphical proxies. This lab uses mitmproxy 12.3.1, whose mitmdump command works in a terminal, so every step has text output you can compare.
The run below used Python 3.12.13 on Linux. Each app gets its own virtual environment, because mitmproxy pins many of its dependencies. httpx2 is the HTTP client that current FastAPI TestClient releases use; the app itself uses httpx for outgoing calls.
mkdir websec-lab && cd websec-lab
python3.12 -m venv .venv && . .venv/bin/activate
pip install fastapi==0.163.1 uvicorn==0.54.0 httpx==0.28.1 httpx2==2.16.2 \
pytest==9.2.0
# mitmproxy pins many dependencies, so give it its own environment
python3.12 -m venv ../proxyvenv && ../proxyvenv/bin/pip install mitmproxy==12.3.1
../proxyvenv/bin/mitmdump --version | head -1Mitmproxy: 12.3.102. Step 1: Build and start the flawed app
Create three files in websec-lab/. seed.py makes an in-memory SQLite table with two users and two text files: files/welcome.txt, which the app may serve, and secret.txt one folder up, a canary that no route should ever return. internal.py plays an internal-only service on port 9001.
"""Seed data for the lab: an in-memory SQLite table and two text files."""
import sqlite3
from pathlib import Path
LAB = Path(__file__).parent / "lab_data"
FILES = LAB / "files" # the only folder that /files may serve
def seed() -> sqlite3.Connection:
FILES.mkdir(parents=True, exist_ok=True)
(FILES / "welcome.txt").write_text("Welcome to the practice app.\n")
# Canary: a file outside FILES that no route should ever return
(LAB / "secret.txt").write_text("CANARY-SECRET-1234\n")
db = sqlite3.connect(":memory:", check_same_thread=False)
db.execute("CREATE TABLE users (name TEXT, email TEXT)")
db.executemany(
"INSERT INTO users VALUES (?, ?)",
[("alice", "[email protected]"), ("bob", "[email protected]")],
)
return db"""Stand-in for an internal-only service, listening on 127.0.0.1:9001."""
from http.server import BaseHTTPRequestHandler, HTTPServer
class Internal(BaseHTTPRequestHandler):
def do_GET(self):
body = b"INTERNAL-CANARY: only the server's own network sees this\n"
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, *args):
pass # keep the terminal quiet
HTTPServer(("127.0.0.1", 9001), Internal).serve_forever()Now the app. Read each route and spot the flaw before you look at the comment:
/userspastesnameinto the SQL text, so a quote in the input ends the string literal./filesjoinsnameonto the folder, so../steps climb out of it./greetpastesnameandsiteinto HTML without encoding them./previewfetches whatever URL it is given, and follows redirects.
"""Intentionally flawed practice app. Run it only on 127.0.0.1."""
import httpx
from fastapi import FastAPI
from fastapi.responses import HTMLResponse, PlainTextResponse
from seed import FILES, seed
app = FastAPI()
db = seed()
client = httpx.Client(follow_redirects=True, timeout=3)
@app.get("/users")
def find_users(name: str):
sql = f"SELECT name, email FROM users WHERE name = '{name}'" # FLAW 1
return [{"name": n, "email": e} for n, e in db.execute(sql)]
@app.get("/files", response_class=PlainTextResponse)
def read_file(name: str):
return (FILES / name).read_text() # FLAW 2: name may contain ../
@app.get("/greet", response_class=HTMLResponse)
def greet(name: str, site: str = "https://example.com"):
# FLAW 3: user input pasted into HTML without encoding
return f'<p>Hello {name}</p><a href="{site}">your site</a>'
@app.get("/preview", response_class=PlainTextResponse)
def preview(url: str):
return client.get(url).text # FLAW 4: fetches any URL it is given# Terminal 1: the internal canary service
python internal.py
# Terminal 2: the flawed app, bound to loopback only
uvicorn flawed_app:app --host 127.0.0.1 --port 8000INFO: Started server process [191798]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)03. Step 2: Prove each flaw through the proxy
Start mitmdump and send one benign proof per flaw. curl -x sends the request through the proxy, -G with --data-urlencode puts the value in the query string with the right encoding, and -w flows.mitm saves each request and response so you can resend them later.
# Terminal 3: the proxy, saving every request and response to flows.mitm
../proxyvenv/bin/mitmdump --listen-host 127.0.0.1 --listen-port 8080 \
--set termlog_verbosity=warn -w flows.mitm
# Terminal 4: one harmless proof per flaw, each sent through the proxy (-x)
X="curl -s -x http://127.0.0.1:8080 -G"
$X http://127.0.0.1:8000/users --data-urlencode "name=alice' OR '1'='1"; echo
$X http://127.0.0.1:8000/files --data-urlencode "name=../secret.txt"
$X http://127.0.0.1:8000/greet --data-urlencode "name=<script>alert(1)</script>"; echo
$X http://127.0.0.1:8000/preview --data-urlencode "url=http://127.0.0.1:9001/"[{"name":"alice","email":"[email protected]"},{"name":"bob","email":"[email protected]"}]
CANARY-SECRET-1234
<p>Hello <script>alert(1)</script></p><a href="https://example.com">your site</a>
INTERNAL-CANARY: only the server's own network sees this127.0.0.1:56030: GET http://127.0.0.1:8000/users?name=alice%27+OR+%271%27%3D…
<< 200 OK 81b
127.0.0.1:46614: GET http://127.0.0.1:8000/files?name=..%2Fsecret.txt
<< 200 OK 19b
127.0.0.1:46628: GET http://127.0.0.1:8000/greet?name=%3Cscript%3Ealert%281%…
<< 200 OK 81b
127.0.0.1:46644: GET http://127.0.0.1:8000/preview?url=http%3A%2F%2F127.0.0.…
<< 200 OK 57bEach line of terminal 4 is one confirmed flaw:
- SQL injection: the query became
WHERE name = 'alice' OR '1'='1', which is true for every row, so Bob's row came back too. - Path traversal:
files/../secret.txtresolved to the canary outside the served folder. - XSS: the marker came back as live markup. curl only prints it, but a browser would run it as part of the page from
127.0.0.1:8000. To the same-origin policy, an injected script is the app's own code, so it could read the page and call the app's API with the user's cookies. - SSRF: the app fetched
127.0.0.1:9001on the caller's behalf. From inside a real network, the same request could reach an admin service or a cloud metadata address.
The proxy log is the tester's record: the exact encoded request and the status and size of each reply. To test a browser instead of curl, two details matter. Chrome sends requests for localhost and 127.0.0.1 directly, skipping the proxy, unless you start it with --proxy-bypass-list="<-loopback>". For HTTPS sites the proxy must decrypt the traffic, so the browser has to trust mitmproxy's certificate authority (CA) from ~/.mitmproxy/. Trust it only in a throwaway browser profile: anyone who holds that CA's private key can impersonate any site to whatever trusts it.
04. Step 3: Lock each flaw with a failing test
Turn each proof into a regression test before you fix anything. A test that fails on the flawed app shows that it really detects the flaw; the same test passing later shows the fix works. The APP environment variable picks which module the tests import.
The SSRF tests must not depend on real DNS or real servers, so the offline fixture swaps in an httpx.MockTransport: 127.0.0.1 answers with the canary, and every other host redirects to it. It also replaces the app's DNS lookup with a fixed public answer, which one test changes to a private address.
import importlib
import os
import httpx
import pytest
from fastapi.testclient import TestClient
lab = importlib.import_module(os.environ.get("APP", "fixed_app"))
client = TestClient(lab.app)
def test_sql_injection_returns_no_extra_rows():
rows = client.get("/users", params={"name": "alice' OR '1'='1"}).json()
assert "bob" not in str(rows)
assert client.get("/users", params={"name": "alice"}).json()[0]["name"] == "alice"
def test_traversal_cannot_read_the_canary():
resp = client.get("/files", params={"name": "../secret.txt"})
assert resp.status_code == 404 and "CANARY" not in resp.text
assert client.get("/files", params={"name": "welcome.txt"}).status_code == 200
def test_script_marker_is_escaped():
resp = client.get("/greet", params={"name": "<script>alert(1)</script>"})
assert "<script>" not in resp.text
assert "<script>" in resp.text
def test_javascript_url_is_not_rendered():
resp = client.get("/greet", params={"name": "a", "site": "javascript:alert(1)"})
assert "javascript:" not in resp.text.lower()def fake_network(request: httpx.Request) -> httpx.Response:
"""127.0.0.1 plays the internal canary; every other host redirects to it."""
if request.url.host == "127.0.0.1":
return httpx.Response(200, text="INTERNAL-CANARY")
return httpx.Response(302, headers={"Location": "http://127.0.0.1:9001/"})
@pytest.fixture
def offline(monkeypatch):
"""No real network: a fake transport and a fake public DNS answer."""
fake = httpx.Client(
transport=httpx.MockTransport(fake_network),
follow_redirects=lab.client.follow_redirects,
)
monkeypatch.setattr(lab, "client", fake)
monkeypatch.setattr(lab, "resolve", lambda host: ["93.184.215.14"], raising=False)
@pytest.mark.parametrize(
"url", ["http://127.0.0.1:9001/", "https://evil.test/"], ids=["loopback", "other"]
)
def test_preview_refuses_unlisted_destinations(offline, url):
resp = client.get("/preview", params={"url": url})
assert resp.status_code == 400 and "CANARY" not in resp.text
def test_preview_refuses_allowed_name_with_private_ip(offline, monkeypatch):
monkeypatch.setattr(lab, "resolve", lambda host: ["10.0.0.7"], raising=False)
resp = client.get("/preview", params={"url": "https://status.partner.example/"})
assert resp.status_code == 400
def test_preview_refuses_redirects(offline):
resp = client.get("/preview", params={"url": "https://status.partner.example/"})
assert resp.status_code == 502 and "CANARY" not in resp.textAPP=flawed_app python -m pytest -v --no-header -p no:cacheprovider \
--tb=no -rN test_flaws.py============================= test session starts ==============================
collecting ... collected 8 items
test_flaws.py::test_sql_injection_returns_no_extra_rows FAILED [ 12%]
test_flaws.py::test_traversal_cannot_read_the_canary FAILED [ 25%]
test_flaws.py::test_script_marker_is_escaped FAILED [ 37%]
test_flaws.py::test_javascript_url_is_not_rendered FAILED [ 50%]
test_flaws.py::test_preview_refuses_unlisted_destinations[loopback] FAILED [ 62%]
test_flaws.py::test_preview_refuses_unlisted_destinations[other] FAILED [ 75%]
test_flaws.py::test_preview_refuses_allowed_name_with_private_ip FAILED [ 87%]
test_flaws.py::test_preview_refuses_redirects FAILED [100%]
============================== 8 failed in 2.08s ===============================05. Step 4: Apply the fixes
Create fixed_app.py with the same routes. Two fixes are a one-line change. FIX 1 passes name as a bound parameter (?), so SQLite receives it as a value and never parses it as SQL. FIX 2 resolves the joined path to its canonical absolute form, following .. and symbolic links, and serves it only if it is still inside the base folder.
"""The same four routes, each with its fix."""
import html
import ipaddress
import socket
from urllib.parse import urlsplit
import httpx
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse, PlainTextResponse
from seed import FILES, seed
app = FastAPI()
db = seed()
client = httpx.Client(follow_redirects=False, timeout=3)
BASE = FILES.resolve()
ALLOWED = {("https", "status.partner.example", 443)} # exact destinations
CSP = "default-src 'none'" # this page needs no scripts, styles or images
@app.get("/users")
def find_users(name: str):
sql = "SELECT name, email FROM users WHERE name = ?" # FIX 1: bound value
return [{"name": n, "email": e} for n, e in db.execute(sql, (name,))]
@app.get("/files", response_class=PlainTextResponse)
def read_file(name: str):
target = (BASE / name).resolve() # FIX 2: canonical path ...
if not target.is_relative_to(BASE) or not target.is_file():
raise HTTPException(404, "file not found") # ... must stay inside
return target.read_text()FIX 3 encodes for the context. html.escape turns <, >, & and quotes into entities, so text stays text. That is not enough for an href. Escaping changes no character in javascript:alert(1), and a browser runs that URL when the link is clicked. Prove it in the terminal:
python -c "import html; print(html.escape('javascript:alert(1)'))"javascript:alert(1)So safe_href allow-lists the URL scheme first: only http and https pass, and anything else becomes #. urlsplit lowercases the scheme and drops the tab and newline characters that browsers also ignore, so JavaScript: and java\tscript: are caught too. The Content-Security-Policy header is a second layer: default-src 'none' tells the browser this page may load and run nothing, which also blocks inline script.
FIX 4 turns the open fetcher into one for a known partner. The exact scheme, host and port must be on the allow-list. Every address the host name resolves to must be public, which catches a partner record that points inside your network. And the client does not follow redirects: a 3xx answer is refused, because the next hop has not been checked.
This sketch has a limit you should know. httpx looks the name up again when it connects, so an attacker who controls the DNS answer could still switch it between the check and the fetch (DNS rebinding). The guard in the previous lesson closes that gap by connecting to the vetted IP. It also checks more than is_global.
def safe_href(url: str) -> str:
"""Escaping cannot make javascript: harmless, so allow-list the scheme."""
return url if urlsplit(url).scheme in ("http", "https") else "#"
@app.get("/greet", response_class=HTMLResponse)
def greet(name: str, site: str = "https://example.com"):
page = f"<p>Hello {html.escape(name)}</p>" # FIX 3: encode for HTML
page += f'<a href="{html.escape(safe_href(site))}">your site</a>'
return HTMLResponse(page, headers={"Content-Security-Policy": CSP})
def resolve(host: str) -> list[str]:
return [info[4][0] for info in socket.getaddrinfo(host, 443)]
@app.get("/preview", response_class=PlainTextResponse)
def preview(url: str):
parts = urlsplit(url) # FIX 4: allow-list, resolved IP, no redirects
if (parts.scheme, parts.hostname, parts.port or 443) not in ALLOWED:
raise HTTPException(400, "destination not allowed")
if not all(ipaddress.ip_address(ip).is_global for ip in resolve(parts.hostname)):
raise HTTPException(400, "destination resolves to a non-public address")
resp = client.get(url)
if resp.is_redirect:
raise HTTPException(502, "redirect refused")
return resp.text06. Step 5: Re-run the tests and replay the captured requests
python -m pytest -v --no-header -p no:cacheprovider test_flaws.py============================= test session starts ==============================
collecting ... collected 8 items
test_flaws.py::test_sql_injection_returns_no_extra_rows PASSED [ 12%]
test_flaws.py::test_traversal_cannot_read_the_canary PASSED [ 25%]
test_flaws.py::test_script_marker_is_escaped PASSED [ 37%]
test_flaws.py::test_javascript_url_is_not_rendered PASSED [ 50%]
test_flaws.py::test_preview_refuses_unlisted_destinations[loopback] PASSED [ 62%]
test_flaws.py::test_preview_refuses_unlisted_destinations[other] PASSED [ 75%]
test_flaws.py::test_preview_refuses_allowed_name_with_private_ip PASSED [ 87%]
test_flaws.py::test_preview_refuses_redirects PASSED [100%]
============================== 8 passed in 0.69s ===============================The tests protect the code. The proxy lets you check the running service from the outside, the way a tester or a bug bounty report would. Swap the server to the fixed app and resend the four requests you saved in step 2:
# Terminal 3: stop the capture (Ctrl+C). Terminal 2: Ctrl+C, then start the fix
uvicorn fixed_app:app --host 127.0.0.1 --port 8000
# Terminal 3: resend the four saved requests exactly as captured (-C),
# with no proxy listening (-n), printing full requests and responses
../proxyvenv/bin/mitmdump -n -C flows.mitm --flow-detail 3 \
--set termlog_verbosity=warn[replay]: GET http://127.0.0.1:8000/greet?name=%3Cscript%3Ealert%281%29%3C%2Fscript%3E
Host: 127.0.0.1:8000
User-Agent: curl/7.81.0
Accept: */*
Proxy-Connection: Keep-Alive
name: <script>alert(1)</script>
<< 200 OK 93b
date: Mon, 16 Nov 2026 19:07:00 GMT
server: uvicorn
content-security-policy: default-src 'none'
content-length: 93
content-type: text/html; charset=utf-8
<p>Hello <script>alert(1)</script></p>
<a href="https://example.com">your site</a>
[replay]: GET http://127.0.0.1:8000/preview?url=http%3A%2F%2F127.0.0.1%3A9001%2F
Host: 127.0.0.1:8000
User-Agent: curl/7.81.0
Accept: */*
Proxy-Connection: Keep-Alive
url: http://127.0.0.1:9001/
<< 400 Bad Request 36b
date: Mon, 16 Nov 2026 19:07:00 GMT
server: uvicorn
content-length: 36
content-type: application/json
{
"detail": "destination not allowed"
}The first two flows, not shown, now return [] and 404 Not Found. The injection string is compared as one whole name, and the traversal never leaves the folder. The marker comes back as harmless text with the CSP header attached, and the internal URL is refused before any connection is made. Keep flows.mitm: replaying it after later changes is a quick end-to-end check that the fixes are still deployed.
07. Check your understanding
08. Apply it
Point the same workflow at a larger practice target you run locally, such as OWASP Juice Shop in a container bound to 127.0.0.1. Confirm one injection and one XSS through the proxy, save the flows, and write a regression test for each before you look up the fix. Then add a fifth route to this lab, for example an avatar upload that saves under a user-supplied file name, and take it through the same four moves.
In the next lesson you will use the same flawed-then-fixed pattern for access control, API and session flaws.
09. Review prompt
Without looking back, name the harmless proof the lab used for each of the four flaws and the fix that made its test pass. Explain why html.escape stops the <script> marker but not a javascript: link, and what the CSP header adds. List the three checks in FIX 4 and the gap that remains when the HTTP client resolves the name again. Finally, describe two things the proxy gives a tester that unit tests do not.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.