Finding and Fixing Access Control, API and Session Flaws
Prove BOLA, broken function-level authorization, mass assignment, unrestricted resource consumption, CSRF and weak session handling in a small local FastAPI app, then fix each on the server and lock it with a pytest test that fails on the flawed version.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Build the flawed API and prove two flaws
- Step 2: Write regression tests that fail on the flawed API
- Step 3: Fix sessions and add a CSRF guard
- Step 4: Fix object, function and page-size checks
- Step 5: Fix mass assignment, oversized bodies and the GET state change
- 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
- Detect broken access control, session weaknesses and API-specific flaws in web pages and APIs (IDOR/BOLA, broken function-level authorization, mass assignment, unrestricted resource consumption, CSRF, weak session handling) and implement server-side fixes.
01. Goal and setup
Scanners are good at finding missing headers and outdated libraries. They are poor at finding authorization flaws, because only someone who knows the business rules can say that Bob must not see Alice's invoice. This lab uses the pattern from the proxy lab: a small flawed API, a harmless proof, a fix, and a test that fails on the flawed version and passes on the fixed one.
The API has seven flaws. Four come from the OWASP API Security Top 10 (2023):
- API1, Broken Object Level Authorization (BOLA): a signed-in user reads an object that belongs to someone else by changing its ID.
- API5, Broken Function Level Authorization (BFLA): a member calls a function meant only for admins.
- API3, Broken Object Property Level Authorization: here, mass assignment, where the server copies every field the client sends, including
role. - API4, Unrestricted Resource Consumption: no limit on page size or request body size.
The other three are browser and session flaws: cross-site request forgery (CSRF), where another site makes the victim's browser send a request with their cookie; session fixation, where the server keeps a session ID chosen before login; and a logout that leaves the session valid on the server.
The app keeps its data in Python dictionaries, so you need no database. Passwords are plain strings to keep the lab short; real apps store Argon2id hashes, as in the password hashing lesson.
# Reuse the environment from the proxy lab
mkdir websec-lab2 && cd websec-lab2
. ../websec-lab/.venv/bin/activate02. Step 1: Build the flawed API and prove two flaws
common.py holds the seeded data and the session lookup that both versions share. Alice and Bob are members of tenant t1, Carol is the t1 admin, and Dave belongs to tenant t2. Each password is the user name plus -pw.
"""Seeded lab data and the session lookup shared by both apps.
Lab only: real apps store password hashes (see the Argon2id lesson).
"""
import copy
from fastapi import HTTPException, Request
from pydantic import BaseModel
SEED_USERS = {
"alice": {"tenant": "t1", "role": "member", "email": "[email protected]"},
"bob": {"tenant": "t1", "role": "member", "email": "[email protected]"},
"carol": {"tenant": "t1", "role": "admin", "email": "[email protected]"},
"dave": {"tenant": "t2", "role": "member", "email": "[email protected]"},
}
SEED_INVOICES = {
"inv_100": {"tenant": "t1", "owner": "alice", "total": 120},
"inv_101": {"tenant": "t1", "owner": "bob", "total": 80},
"inv_200": {"tenant": "t2", "owner": "dave", "total": 300},
}
USERS, INVOICES, SESSIONS = {}, {}, {} # SESSIONS: session id -> session
def reset() -> None:
for live, seed in ((USERS, SEED_USERS), (INVOICES, SEED_INVOICES)):
live.clear()
live.update(copy.deepcopy(seed))
SESSIONS.clear()class Login(BaseModel):
username: str
password: str
def password_ok(body: Login) -> bool:
return body.username in USERS and body.password == f"{body.username}-pw"
def session(request: Request) -> dict:
found = SESSIONS.get(request.cookies.get("sid", ""))
if found is None:
raise HTTPException(401, "not signed in")
return found
reset()Read flawed_app.py and try to name each flaw before you read its comment. Every route checks that the caller is signed in. That is authentication, not authorization: none of them asks whether this caller may do this to this object.
"""Intentionally flawed API. Run it only on 127.0.0.1."""
import secrets
from fastapi import Depends, FastAPI, HTTPException, Request, Response
from common import INVOICES, SESSIONS, USERS, Login, password_ok, session
app = FastAPI()
@app.post("/login")
def login(body: Login, request: Request, response: Response):
if not password_ok(body):
raise HTTPException(401, "invalid credentials")
sid = request.cookies.get("sid") or secrets.token_urlsafe(32) # FLAW 1
SESSIONS[sid] = {"sid": sid, "user": body.username, "csrf": ""}
response.set_cookie("sid", sid, httponly=True, samesite="lax")
return {"csrf_token": ""}
@app.post("/logout")
def logout(response: Response):
response.delete_cookie("sid") # FLAW 2: the server still accepts the id
return {"signed_out": True}
@app.get("/me")
def read_me(s: dict = Depends(session)):
return USERS[s["user"]]@app.get("/invoices")
def list_invoices(limit: int = 20, s: dict = Depends(session)): # FLAW 3
own = [i for i, inv in INVOICES.items() if inv["owner"] == s["user"]]
return own[:limit]
@app.get("/invoices/{invoice_id}")
def get_invoice(invoice_id: str, s: dict = Depends(session)):
if invoice_id not in INVOICES: # FLAW 4: never asks whose invoice it is
raise HTTPException(404, "invoice not found")
return INVOICES[invoice_id]
@app.post("/admin/users/{name}/ban")
def ban_user(name: str, s: dict = Depends(session)): # FLAW 5: any user
USERS[name]["banned"] = True
return {"banned": name}
@app.patch("/me")
async def update_me(request: Request, s: dict = Depends(session)):
USERS[s["user"]].update(await request.json()) # FLAW 6: copies every key
return USERS[s["user"]]
@app.get("/me/email") # FLAW 7: a state change on GET, with no CSRF check
def change_email(new: str, s: dict = Depends(session)):
USERS[s["user"]]["email"] = new
return {"email": new}Start it on loopback and prove two flaws as Bob. With two accounts, this is how a tester finds BOLA in a proxy: sign in as each user, then swap the IDs in requests.
# Terminal 1
uvicorn flawed_app:app --host 127.0.0.1 --port 8000
# Terminal 2: sign in as Bob, read Alice's invoice, then promote yourself
J='Content-Type: application/json'
curl -s -c bob.jar -H "$J" -d '{"username": "bob", "password": "bob-pw"}' \
http://127.0.0.1:8000/login; echo
curl -s -b bob.jar http://127.0.0.1:8000/invoices/inv_100; echo
curl -s -b bob.jar -X PATCH -H "$J" -d '{"role": "admin"}' \
http://127.0.0.1:8000/me; echo{"csrf_token":""}
{"tenant":"t1","owner":"alice","total":120}
{"tenant":"t1","role":"admin","email":"[email protected]"}Bob read invoice inv_100, which belongs to Alice, and one PATCH made him an admin. Stop the server with Ctrl+C; the remaining steps use pytest's TestClient, which calls the app in-process.
03. Step 2: Write regression tests that fail on the flawed API
Each test states one rule as an attack that must fail, plus, where useful, a legitimate request that must still work. A fix that blocks everything should not pass. sign_in returns a client with Bob's cookie and the headers a same-origin page would send. The client uses an https:// base URL, so it sends Secure cookies.
import importlib
import os
import pytest
from fastapi.testclient import TestClient
import common
lab = importlib.import_module(os.environ.get("APP", "fixed_app"))
SITE = "https://app.lab.test"
@pytest.fixture(autouse=True)
def fresh_data():
common.reset()
def sign_in(name: str) -> tuple[TestClient, dict]:
client = TestClient(lab.app, base_url=SITE)
login = {"username": name, "password": f"{name}-pw"}
token = client.post("/login", json=login).json()["csrf_token"]
return client, {"X-CSRF-Token": token, "Origin": SITE}
def test_member_cannot_read_peer_invoice():
bob, _ = sign_in("bob")
assert bob.get("/invoices/inv_101").status_code == 200 # his own
assert bob.get("/invoices/inv_100").status_code == 404 # alice's
def test_admin_stays_inside_own_tenant():
carol, _ = sign_in("carol")
assert carol.get("/invoices/inv_100").status_code == 200
assert carol.get("/invoices/inv_200").status_code == 404 # tenant t2
def test_member_cannot_call_admin_function():
bob, headers = sign_in("bob")
assert bob.post("/admin/users/alice/ban", headers=headers).status_code == 403
assert "banned" not in common.USERS["alice"]def test_profile_update_cannot_set_role():
bob, headers = sign_in("bob")
body = {"display_name": "Bob", "role": "admin"}
assert bob.patch("/me", json=body, headers=headers).status_code == 422
assert common.USERS["bob"]["role"] == "member"
def test_page_size_is_capped():
bob, _ = sign_in("bob")
assert bob.get("/invoices", params={"limit": 100}).status_code == 200
assert bob.get("/invoices", params={"limit": 100_000}).status_code == 422
def test_oversized_body_is_refused():
bob, headers = sign_in("bob")
big = {"display_name": "B" * 100_000}
assert bob.patch("/me", json=big, headers=headers).status_code == 413
chunks = (b"B" * 4096 for _ in range(10)) # sent with no Content-Length
assert bob.patch("/me", content=chunks, headers=headers).status_code == 413
def test_email_change_is_not_a_get():
bob, _ = sign_in("bob")
bob.get("/me/email", params={"new": "[email protected]"})
assert common.USERS["bob"]["email"] == "[email protected]"
def test_email_change_needs_token_and_origin():
bob, headers = sign_in("bob")
new = {"email": "[email protected]"}
assert bob.post("/me/email", json=new).status_code == 403 # no token
cross = {**headers, "Origin": "https://evil.test"}
assert bob.post("/me/email", json=new, headers=cross).status_code == 403
assert bob.post("/me/email", json=new, headers=headers).status_code == 200def test_login_issues_a_fresh_session_id():
client = TestClient(lab.app, base_url=SITE)
client.cookies.set("sid", "planted-by-attacker")
common.SESSIONS["planted-by-attacker"] = {"sid": "planted-by-attacker"}
resp = client.post("/login", json={"username": "bob", "password": "bob-pw"})
assert resp.cookies["sid"] != "planted-by-attacker"
assert "planted-by-attacker" not in common.SESSIONS
cookie = resp.headers["set-cookie"].lower()
assert "httponly" in cookie and "samesite=lax" in cookie and "secure" in cookie
def test_logout_revokes_the_session_on_the_server():
bob, headers = sign_in("bob")
old_sid = bob.cookies["sid"]
bob.post("/logout", headers=headers)
copied = TestClient(lab.app, base_url=SITE, cookies={"sid": old_sid})
assert copied.get("/me").status_code == 401APP=flawed_app python -m pytest -v --no-header -p no:cacheprovider \
--tb=no -rN test_flaws.py============================= test session starts ==============================
collecting ... collected 10 items
test_flaws.py::test_member_cannot_read_peer_invoice FAILED [ 10%]
test_flaws.py::test_admin_stays_inside_own_tenant FAILED [ 20%]
test_flaws.py::test_member_cannot_call_admin_function FAILED [ 30%]
test_flaws.py::test_profile_update_cannot_set_role FAILED [ 40%]
test_flaws.py::test_page_size_is_capped FAILED [ 50%]
test_flaws.py::test_oversized_body_is_refused FAILED [ 60%]
test_flaws.py::test_email_change_is_not_a_get FAILED [ 70%]
test_flaws.py::test_email_change_needs_token_and_origin FAILED [ 80%]
test_flaws.py::test_login_issues_a_fresh_session_id FAILED [ 90%]
test_flaws.py::test_logout_revokes_the_session_on_the_server FAILED [100%]
============================== 10 failed in 3.66s ==============================04. Step 3: Fix sessions and add a CSRF guard
Start fixed_app.py. At login, the fixed app deletes any session ID the browser already had and issues a new random one. Session fixation works because the flawed login keeps an ID the attacker could have planted, for example through a cookie set on a shared subdomain. A new ID at every privilege change makes the planted one useless. Logout deletes the session on the server before it clears the cookie. Otherwise, anyone who copied the ID could keep using it.
Login also creates a CSRF token, a random value stored with the session and returned in the login response. checked guards every state-changing route. It refuses a request whose Origin header names another site, and it requires the token in an X-CSRF-Token header. The browser attaches cookies by itself, but a page on another origin cannot read the token (unless the site has an XSS flaw), and a plain HTML form cannot add custom headers.
"""The same API with server-side fixes. Run it only on 127.0.0.1."""
import secrets
from fastapi import Depends, FastAPI, HTTPException, Query, Request, Response
from fastapi.responses import PlainTextResponse
from pydantic import BaseModel, ConfigDict, Field
from common import INVOICES, SESSIONS, USERS, Login, password_ok, session
app = FastAPI()
ORIGIN = "https://app.lab.test" # the only origin allowed to change state
@app.post("/login")
def login(body: Login, request: Request, response: Response):
if not password_ok(body):
raise HTTPException(401, "invalid credentials")
SESSIONS.pop(request.cookies.get("sid", ""), None) # FIX: drop the old id
sid, csrf = secrets.token_urlsafe(32), secrets.token_urlsafe(32)
SESSIONS[sid] = {"sid": sid, "user": body.username, "csrf": csrf}
response.set_cookie("sid", sid, httponly=True, secure=True, samesite="lax")
return {"csrf_token": csrf}
def checked(request: Request, s: dict = Depends(session)) -> dict:
"""Guard for every state change: same Origin and the session's token."""
if request.headers.get("origin", ORIGIN) != ORIGIN:
raise HTTPException(403, "cross-origin request refused")
sent = request.headers.get("x-csrf-token", "").encode()
if not secrets.compare_digest(sent, s["csrf"].encode()):
raise HTTPException(403, "missing or wrong CSRF token")
return s
@app.post("/logout")
def logout(response: Response, s: dict = Depends(checked)):
SESSIONS.pop(s["sid"], None) # FIX: revoke on the server, then the cookie
response.delete_cookie("sid", httponly=True, secure=True, samesite="lax")
return {"signed_out": True}
@app.get("/me")
def read_me(s: dict = Depends(session)):
return USERS[s["user"]]python -m pytest -v --no-header -p no:cacheprovider -k "login or logout" \
test_flaws.py============================= test session starts ==============================
collecting ... collected 10 items / 8 deselected / 2 selected
test_flaws.py::test_login_issues_a_fresh_session_id PASSED [ 50%]
test_flaws.py::test_logout_revokes_the_session_on_the_server PASSED [100%]
======================= 2 passed, 8 deselected in 1.09s ========================05. Step 4: Fix object, function and page-size checks
Append part 2. can_see is the single object rule: nobody crosses tenants, admins see their whole tenant, and members see only their own invoices. The list and the detail route both use it, so the two cannot drift apart. A missing invoice and someone else's invoice get the same 404, so Bob cannot probe which IDs exist. Random IDs would only make guessing harder: IDs leak through links, emails and logs, so the ownership check on the server is the fix.
require_admin checks the role for the ban function itself. Hiding the admin button in the UI protects nothing: anyone who finds the URL in a JavaScript bundle or an API document can call it. Query(20, ge=1, le=100) bounds the page size. Without it, one request for limit=100000 makes the server load and serialise as many rows as exist.
def can_see(invoice: dict, name: str) -> bool:
user = USERS[name]
if invoice["tenant"] != user["tenant"]:
return False # nobody crosses tenants
return user["role"] == "admin" or invoice["owner"] == name
@app.get("/invoices")
def list_invoices(
limit: int = Query(20, ge=1, le=100), # FIX: bounded page size
s: dict = Depends(session),
):
return [i for i, inv in INVOICES.items() if can_see(inv, s["user"])][:limit]
@app.get("/invoices/{invoice_id}")
def get_invoice(invoice_id: str, s: dict = Depends(session)):
invoice = INVOICES.get(invoice_id)
if invoice is None or not can_see(invoice, s["user"]): # FIX: object check
raise HTTPException(404, "invoice not found") # same answer either way
return invoice
def require_admin(s: dict = Depends(checked)) -> dict:
if USERS[s["user"]]["role"] != "admin":
raise HTTPException(403, "admins only") # FIX: function-level check
return s
@app.post("/admin/users/{name}/ban")
def ban_user(name: str, s: dict = Depends(require_admin)):
if USERS.get(name, {}).get("tenant") != USERS[s["user"]]["tenant"]:
raise HTTPException(404, "user not found")
USERS[name]["banned"] = True
return {"banned": name}python -m pytest -v --no-header -p no:cacheprovider \
-k "invoice or admin or page" test_flaws.py============================= test session starts ==============================
collecting ... collected 10 items / 6 deselected / 4 selected
test_flaws.py::test_member_cannot_read_peer_invoice PASSED [ 25%]
test_flaws.py::test_admin_stays_inside_own_tenant PASSED [ 50%]
test_flaws.py::test_member_cannot_call_admin_function PASSED [ 75%]
test_flaws.py::test_page_size_is_capped PASSED [100%]
======================= 4 passed, 6 deselected in 0.99s ========================06. Step 5: Fix mass assignment, oversized bodies and the GET state change
The real fix for mass assignment is the explicit input model. ProfileUpdate declares the one field a user may change, and the handler stores only body.model_dump(), so role can never come from the request. extra="forbid" adds a loud failure: Pydantic's default is to ignore unknown keys silently, and the 422 tells a client, or a tester, that the field is not accepted.
The email change moves from GET to POST behind checked. That matters even though the cookie is SameSite=Lax. Lax keeps the cookie off cross-site POSTs and off subrequests such as images, fetch() calls and iframes. It still sends the cookie on a top-level navigation with a safe method, such as a click on a link from another site. So a link to /me/email?new=... on any page would have changed Bob's email. Never change state on GET, and treat SameSite as an extra layer on top of the token and Origin checks.
class ProfileUpdate(BaseModel):
model_config = ConfigDict(extra="forbid") # unknown keys -> 422
display_name: str = Field(min_length=1, max_length=50)
class EmailChange(BaseModel):
model_config = ConfigDict(extra="forbid")
email: str = Field(max_length=254, pattern=r"^[^@\s]+@[^@\s]+$")
@app.patch("/me")
def update_me(body: ProfileUpdate, s: dict = Depends(checked)):
USERS[s["user"]].update(body.model_dump()) # FIX: only declared fields
return USERS[s["user"]]
@app.post("/me/email") # FIX: POST plus the CSRF guard; no GET route at all
def change_email(body: EmailChange, s: dict = Depends(checked)):
USERS[s["user"]]["email"] = body.email
return {"email": body.email}Field limits such as max_length=50 are checked only after the whole body has been read and parsed. BodySizeLimit stops a 50 MB body before that. It rejects a declared Content-Length that is too large at once, and it counts the bytes of chunked uploads, which carry no length, as they arrive. Many deployments also set a body limit in the reverse proxy in front of the app. Rate limits and timeouts are the other API4 controls; they are not built in this lab.
class BodySizeLimit:
"""ASGI middleware: refuse request bodies larger than max_bytes."""
def __init__(self, app, max_bytes: int):
self.app, self.max_bytes = app, max_bytes
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
return await self.app(scope, receive, send)
declared = dict(scope["headers"]).get(b"content-length")
if declared is not None and int(declared) > self.max_bytes:
too_big = PlainTextResponse("request body too large", 413)
return await too_big(scope, receive, send) # refuse before reading
received = 0
async def counting_receive():
nonlocal received # chunked bodies have no Content-Length: count
message = await receive()
received += len(message.get("body", b""))
if received > self.max_bytes:
raise HTTPException(413, "request body too large")
return message
await self.app(scope, counting_receive, send)
app.add_middleware(BodySizeLimit, max_bytes=16_384) # FIX: cap request bodiespython -m pytest -v --no-header -p no:cacheprovider test_flaws.py============================= test session starts ==============================
collecting ... collected 10 items
test_flaws.py::test_member_cannot_read_peer_invoice PASSED [ 10%]
test_flaws.py::test_admin_stays_inside_own_tenant PASSED [ 20%]
test_flaws.py::test_member_cannot_call_admin_function PASSED [ 30%]
test_flaws.py::test_profile_update_cannot_set_role PASSED [ 40%]
test_flaws.py::test_page_size_is_capped PASSED [ 50%]
test_flaws.py::test_oversized_body_is_refused PASSED [ 60%]
test_flaws.py::test_email_change_is_not_a_get PASSED [ 70%]
test_flaws.py::test_email_change_needs_token_and_origin PASSED [ 80%]
test_flaws.py::test_login_issues_a_fresh_session_id PASSED [ 90%]
test_flaws.py::test_logout_revokes_the_session_on_the_server PASSED [100%]
============================== 10 passed in 1.25s ==============================07. Check your understanding
08. Apply it
Pick one API you work on. For each route that takes an ID, write the BOLA test first: a second user in the same tenant and one in another tenant must both get 404. Find every handler that passes a raw request body to a model, ORM or dict.update, and replace it with an explicit input model. Check every list endpoint for an upper bound, and every GET route for side effects.
In the next lesson you will write findings like these up for a developer, with severity, reproduction steps and an interim WAF rule.
09. Review prompt
Without looking back, explain the difference between BOLA and BFLA, and why the fixed app answers 404 rather than 403 for someone else's invoice. Describe how mass assignment works and which line of the fix prevents it. Explain why a SameSite=Lax cookie does not protect a state-changing GET route, and what the checked guard adds. Finally, describe session fixation and the two server-side session fixes.
References
- OWASP API Security Top 10: API1:2023 Broken Object Level Authorization
- OWASP API Security Top 10: API3:2023 Broken Object Property Level Authorization
- OWASP API Security Top 10: API4:2023 Unrestricted Resource Consumption
- OWASP API Security Top 10: API5:2023 Broken Function Level Authorization
- OWASP Cross-Site Request Forgery Prevention Cheat Sheet
- OWASP Session Management Cheat Sheet: Renew Session ID on Privilege Escalation
- MDN: Set-Cookie, SameSite attribute
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.