Back to Blog

Modern API Security Testing: BOLA, BFLA, Mass Assignment, and GraphQL Abuse

Muhammad Saad
Head of RED team • RED TEAM
View Articles
API SecurityBOLABFLAGraphQLMass AssignmentOWASPPentesting

Modern API Security Testing: BOLA, BFLA, Mass Assignment, and GraphQL Abuse

In one sentence: the most damaging API bugs are not malformed requests but well-formed requests the server should have refused, and finding them is an exercise in asking "should this user be able to do that?" systematically.

Table of Contents


Introduction

For much of the 2000s, web security was a conversation about pages. A server rendered HTML, a browser displayed it, and nearly everything a user could do was something a developer had deliberately placed on screen as a link or a button. That arrangement hid a quiet assumption: that the interface was the boundary. If the "Delete user" button never appeared for ordinary accounts, ordinary accounts could not delete users.

Mobile apps, single-page applications, and microservices broke that assumption. Today the browser or app is a thin client over an API (application programming interface), and the API is the product. Every function the backend can perform is an HTTP endpoint that anyone with an intercepting proxy can call directly, in any order, with any parameters. The user interface no longer constrains anything. Only the server does.

Security tooling was slow to follow. Classic DAST (dynamic application security testing) scanners were built to find flaws that look the same wherever they appear: reflected input, injection patterns, missing headers. Those checks still matter, but the bugs that dominate API incidents are different. They are authorization flaws, where the request is well-formed, the caller is genuinely logged in, and the server simply never asks whether this caller may do this thing to this record. A scanner can see that an endpoint returned data. It cannot know the data belonged to someone else.

The industry's own risk catalogue reflects the shift. The OWASP API Security Top 10 ranked Broken Object Level Authorization (BOLA) first in 2019 and kept it first in the 2023 revision, which also merged excessive data exposure and mass assignment into a single property-level category. Public incident reports tell a similar story. Optus, the Australian telecom, was widely reported in 2022 to have exposed customer records through an internet-facing API that required no authentication and used predictable identifiers. In January 2023, T-Mobile disclosed that an attacker had pulled data on tens of millions of customers through a single API. When archivists scraped the social network Parler in early 2021, the instructive part was the mechanics: sequential post identifiers, no meaningful rate limiting, and content users had "deleted" that the API still served.

None of these required a novel exploit. They required someone to ask a question the application never asked. This article covers how to ask it systematically: the concepts behind the main API vulnerability classes, a testing methodology that scales, the ethics of testing systems that hold real people's data, the design-level fixes, and a small local lab you can build and break yourself.


How APIs and API Authorization Work

A short primer for readers who have not tested APIs before.

REST APIs expose many endpoints, usually one per resource and HTTP method: GET /api/notes/3, PATCH /api/users/me, DELETE /api/users/7. GraphQL APIs collapse that surface into usually a single endpoint, /graphql, where the request body is a query written in a flexible language that lets the client choose which fields to fetch, nest related objects, and request several things at once. The attack surface of REST is wide; the attack surface of GraphQL is deep.

Authentication answers "who are you?" It is usually a session cookie, a bearer token, or an API key. Authorization answers "what may you do?" Most of the bugs in this article live in the gap between the two: the server verifies that a token is valid and then behaves as though a valid token means every action is allowed.

Authorization has three levels, and each has its own failure mode:

  1. Object level: may this user touch this specific record? (Alice may read her notes, not Bob's.)
  2. Function level: may this user call this action? (Ordinary users may not list every account.)
  3. Property level: may this user read or write this field? (A user may change their email address, not their role.)

A trust boundary is the line where input from an untrusted party crosses into code that trusts it. The client is always on the untrusted side. A hidden button, a greyed-out form field, or a mobile app that never sends a particular parameter are user-experience choices, not access controls, because an attacker never has to use your client.

Takeaway: if a restriction exists only in the client, it does not exist.

The most useful artifact for an API tester is a role and permission matrix: a table of every role (anonymous, user, admin, and so on), every endpoint, and what each role should be allowed to do. It turns testing from improvisation into comparison. Every deviation between what the matrix says and what the server does is a finding or a question.


Where API Security Breaks Today

BOLA: Broken Object Level Authorization

BOLA occurs when an authenticated user can reach objects that belong to someone else. A request carries an identifier, such as a number, a UUID, or a slug. The server uses it to fetch a record and returns the record without checking that the caller is entitled to it. The test is almost embarrassingly simple: log in as Alice, request GET /api/notes/3 where note 3 is Bob's, and see what comes back.

Two clarifications matter. First, BOLA is the API-era name for what the older OWASP Top 10 called IDOR (Insecure Direct Object Reference). The mechanics are the same, but APIs make the pattern easier to find and to automate. Second, switching from sequential integers to UUIDs does not fix BOLA. Unguessable identifiers make enumeration harder, but identifiers leak constantly through logs, shared links, other endpoints, and GraphQL responses. The flaw is the missing ownership check, and only a check removes it.

BFLA: Broken Function Level Authorization

Where BOLA is about the wrong object, BFLA is about the wrong function: an ordinary user can invoke something intended for a more privileged role. Typical causes are admin routes that are merely unlinked rather than protected, endpoints whose protection depends on the HTTP method (the GET is checked, the PUT is not), and "internal" routes whose only defense was network placement. Network segmentation is a useful layer, but a leaked token or a server-side request forgery bug turns every "internal" endpoint into an exposed one. Function-level checks have to be enforced by the application, on every route, regardless of where the caller appears to come from.

Mass Assignment and BOPLA

Many frameworks can bind an incoming JSON body directly onto an internal model object. That is convenient, and dangerous when it is unrestricted. If a profile-update endpoint accepts {"email": "..."} and the code copies every key it receives onto the user record, a client that adds "role": "admin" has just promoted itself. This is mass assignment, sometimes called overposting.

The 2023 OWASP list files it under Broken Object Property Level Authorization (BOPLA) together with its mirror image, excessive data exposure: serializing an entire internal object, including fields such as internal notes or hashed passwords, and trusting the client to ignore what it should not see. Both failures share a cause. The server has no explicit, per-property rule about what a given caller may read or write.

GraphQL-Specific Abuse

GraphQL does not introduce new classes of authorization bug, but its flexibility changes how the existing ones are exploited.

  • Introspection. GraphQL servers can describe their own schema through meta-fields such as __schema and __type. In development that is a feature. In production it hands an attacker a complete map of types, fields, and arguments. Disabling introspection is worthwhile hygiene but not a security control: many servers answer mistyped field names with "did you mean ..." suggestions, and tools such as Clairvoyance use that behavior to reconstruct schemas even when introspection is off.
  • Aliasing and batching. Aliases let a client request the same field many times under different names in one operation, and some servers also accept arrays of operations in one request. A rate limiter that counts HTTP requests sees one request while the resolver runs dozens of times. PortSwigger's Web Security Academy includes labs showing how aliases can bypass brute-force protections for exactly this reason.
  • Deep or cyclic queries. If the schema contains a cycle (a user has notes, a note has an owner, an owner has notes), a client can nest the cycle repeatedly. The query text stays small while the server's work multiplies at every level. Depth and cost limits exist to bound this.
  • Field-level authorization gaps. REST usually has one handler per route to protect. GraphQL has a resolver per field, and a check in the top-level resolver does not protect the fields reachable from it. A caller who cannot fetch Bob's note directly may be able to reach it by walking from an object they are allowed to see.

Comparing the Three Classes

BOLA BFLA Mass assignment / BOPLA
Question the server skipped Does this record belong to the caller? May this role call this function? May the caller set (or see) this field?
Typical probe Swap an object ID between two accounts Call admin routes with a normal token Add unexpected fields such as role to a JSON body
Root cause Lookup by client-supplied ID, no ownership check No role check on the route Request body bound wholesale to the model
Fix Ownership check against the authenticated identity Deny by default, explicit role check Allowlist of writable and readable fields
Scanner visibility Low: the response looks like a normal success Low to medium: admin routes can be flagged but rarely verified Low: needs knowledge of the model's sensitive fields

Related Issues

Three neighbors deserve a mention. Missing rate limiting does not create an authorization bug but turns a one-record flaw into a bulk one. Unrestricted resource consumption (large payloads, unbounded queries) is a denial-of-service risk that GraphQL's nesting makes easy to trigger. And improper inventory management means old API versions, such as /v1/, often remain reachable long after /v2/ received fixes. Retired code is still attack surface.


A Realistic Testing Methodology

A competent API tester's day looks less like cleverness and more like disciplined comparison.

  1. Reconstruct the API surface. Start from an OpenAPI or Swagger specification and a Postman collection if the client provides them. Otherwise, proxy the web and mobile clients through Burp Suite or ZAP, read the JavaScript bundles for endpoint paths, and note undocumented routes.
  2. Build the role matrix with at least two accounts per role. Two ordinary users are essential: one to own data, one to try to reach it.
  3. Replay everything across identities. Replay every captured request as another user, as a lower role, and with no credentials at all. Extensions such as Autorize for Burp Suite automate this and flag responses that look suspiciously similar across identities.
  4. Probe properties, methods, and versions. Add unexpected fields to create and update bodies. Swap GET for PUT, PATCH, and DELETE. Try older versions of the same path.
  5. Test GraphQL field by field. Map the schema, then test resolvers individually, including every route by which an object can be reached.
  6. Report minimally. A finding is the smallest request that reproduces the problem, the response that proves it, and a one-sentence statement of impact.

The first eighty percent of this work is repetitive: enumerate, replay, diff. That is where tooling pays off, including AI assistants that can summarize a large specification or draft test cases from endpoint descriptions. The last twenty percent is judgment. A tool can say two responses differ. Only a person who understands the application can say whether the difference is a legitimate rule or a leak. A 200 OK is not proof of anything, and neither is a 403; what matters is whether the outcome matches what the business rules require.


Ethics, Scope, and Responsible Testing

API testing is unusually risky because proof of a flaw often is access to real data. A BOLA test against a production system does not simulate a privacy violation. It performs one. A careless DELETE can destroy a record that cannot be restored.

Three practices keep testing on the right side of that line:

  • Written authorization and explicit scope. Before any request is sent, the engagement should define which hosts and endpoints are in scope, which accounts you may use, and which actions (read, create, update, delete) are permitted. Anything not listed is out of scope.
  • Test accounts, not customers. Create your own users and prove access between your own accounts wherever possible. That demonstrates the flaw without touching anyone else's data.
  • Stop at proof. In bug bounty programs, the accepted norm is to retrieve the minimum needed to show the vulnerability, typically a single record, and then stop and report. Bulk enumeration of personal data is treated as harm, not as a stronger proof of concept.

The key tension: the most convincing demonstration of an authorization flaw is also the one that exposes the most data. Responsible testers resolve it by proving the flaw with the smallest possible footprint and letting the system owner judge the scale of the exposure.

Legal frameworks differ by country, and "I was only testing" is not a defense in any of them. Written permission is the only reliable one.


What This Means for Developers and Defenders

Every class above has the same underlying fix: make the server state, explicitly and in one place, who may do what to which data. In practice:

  • Centralize authorization and deny by default. Enforce access in a shared policy layer or middleware, using a dedicated engine such as Open Policy Agent if the rules are complex, rather than scattering if statements through handlers. A route with no rule should be refused.
  • Tie ownership to the authenticated identity. Compare a record's owner to the identity established by the server, never to anything the client supplies. When refusing, consider returning 404 instead of 403 for objects the caller should not know exist.
  • Use allowlists for what goes in and out. Define data transfer objects (DTOs) or explicit field lists for request bodies and responses. Never bind a request body wholesale onto a model, and never serialize a whole internal object.
  • Bound GraphQL. Set limits on query depth, query cost, and aliases per operation; authorize inside each resolver that returns sensitive data; and disable introspection in production as hygiene, not as a defense.
  • Test authorization continuously. Add integration tests with at least two users per role to your CI pipeline, asserting that user A cannot read, change, or call user B's resources. These tests catch regressions when new endpoints appear.
  • Keep an API inventory. Know every version and route that is deployed, and retire the ones nobody owns.

Authorization is an architectural property, not a feature. It cannot be added at the end of a project by checking a few endpoints. It has to be the default behavior of the system, with exceptions that someone had to argue for.


Hands-On Lab: Breaking and Fixing a Small Local API

Everything in this lab runs on your own machine and binds only to 127.0.0.1. The application is a deliberately flawed toy written for this article. Do not point the techniques here at systems you do not own or have written permission to test.

What the lab will show

We will build a small notes service with three users (Alice, Bob, and an admin), attack it through its REST and GraphQL interfaces to demonstrate BOLA, BFLA, mass assignment, and the GraphQL issues above, confirm the findings with a repeatable script, and then run the same tests against a fixed version of the same program. Commands and outputs below were captured from real runs with Python 3.12, Flask 3.1, Ariadne 1.1, and graphql-core 3.3.

Environment setup

You need Python 3 (the server and test script), a virtual environment (so the lab's packages stay separate from your system Python), Flask (a minimal web framework for the REST routes), Ariadne (a GraphQL library that works with Flask), Requests (for the test script), curl (to send raw HTTP requests), and jq (to pull the token out of JSON responses).

mkdir api-lab && cd api-lab
python3 -m venv venv
source venv/bin/activate
pip install flask ariadne requests

The application

Save the following as app.py. One file serves both versions of the program: run normally it is vulnerable, and with SECURE=1 it applies the fixes. Comments mark each vulnerable decision and its fix.

"""Toy notes API for a local API-security lab. Binds to 127.0.0.1 only.

Run vulnerable:  python app.py
Run fixed:       SECURE=1 python app.py
"""
import os
import secrets

from ariadne import ObjectType, QueryType, graphql_sync, make_executable_schema
from flask import Flask, jsonify, request
from graphql import NoSchemaIntrospectionCustomRule, parse
from graphql.language import FieldNode

SECURE = os.environ.get("SECURE") == "1"
MAX_DEPTH, MAX_ALIASES = 5, 5

app = Flask(__name__)

USERS = {
    1: {"id": 1, "username": "alice", "password": "alice-pw", "email": "alice@example.test", "role": "user"},
    2: {"id": 2, "username": "bob", "password": "bob-pw", "email": "bob@example.test", "role": "user"},
    3: {"id": 3, "username": "admin", "password": "admin-pw", "email": "admin@example.test", "role": "admin"},
}
NOTES = {
    1: {"id": 1, "owner_id": 1, "title": "Alice groceries", "content": "milk, eggs"},
    2: {"id": 2, "owner_id": 1, "title": "Alice diary", "content": "alice private thoughts"},
    3: {"id": 3, "owner_id": 2, "title": "Bob bank PIN", "content": "bob secret: 4821"},
    4: {"id": 4, "owner_id": 2, "title": "Bob todo", "content": "bob private todo"},
    5: {"id": 5, "owner_id": 3, "title": "Admin runbook", "content": "admin only: rotate keys"},
}
TOKENS = {}  # opaque bearer token -> user id


def current_user():
    header = request.headers.get("Authorization", "")
    if not header.startswith("Bearer "):
        return None
    uid = TOKENS.get(header[7:])
    return USERS.get(uid)


def can_read(user, note):
    return (not SECURE) or note["owner_id"] == user["id"] or user["role"] == "admin"


# ---------------------------------------------------------------- REST
@app.post("/api/login")
def login():
    data = request.get_json(force=True)
    for user in USERS.values():
        if user["username"] == data.get("username") and user["password"] == data.get("password"):
            token = secrets.token_hex(16)
            TOKENS[token] = user["id"]
            return jsonify({"token": token, "role": user["role"]})
    return jsonify({"error": "invalid credentials"}), 401


@app.get("/api/notes/<int:note_id>")
def get_note(note_id):
    user = current_user()
    if not user:
        return jsonify({"error": "unauthenticated"}), 401
    note = NOTES.get(note_id)
    if not note:
        return jsonify({"error": "not found"}), 404
    # VULNERABLE (BOLA): authenticated, but ownership is never checked.
    # FIX: compare the note's owner to the authenticated identity.
    if not can_read(user, note):
        return jsonify({"error": "not found"}), 404
    return jsonify(note)


@app.get("/api/admin/users")
def admin_list_users():
    user = current_user()
    if not user:
        return jsonify({"error": "unauthenticated"}), 401
    # VULNERABLE (BFLA): no role check on an admin-only function.
    # FIX: deny by default unless the caller is an admin.
    if SECURE and user["role"] != "admin":
        return jsonify({"error": "forbidden"}), 403
    return jsonify([{k: v for k, v in u.items() if k != "password"} for u in USERS.values()])


@app.patch("/api/users/me")
def update_me():
    user = current_user()
    if not user:
        return jsonify({"error": "unauthenticated"}), 401
    data = request.get_json(force=True)
    # VULNERABLE (mass assignment): every JSON key is bound to the user record.
    # FIX: only fields on an explicit allowlist can be set by the client.
    allowed = {"email"} if SECURE else set(data)
    for key in data:
        if key in allowed and key != "id":
            user[key] = data[key]
    return jsonify({k: v for k, v in user.items() if k != "password"})


# ------------------------------------------------------------- GraphQL
type_defs = """
type Query { me: User  note(id: ID!): Note }
type User { id: ID!  username: String!  email: String  notes: [Note!]! }
type Note { id: ID!  title: String!  content: String!  owner: User! }
"""
query, note_type, user_type = QueryType(), ObjectType("Note"), ObjectType("User")


@query.field("me")
def resolve_me(_, info):
    return info.context["user"]


@query.field("note")
def resolve_note(_, info, id):
    note = NOTES.get(int(id))
    # FIX: per-resolver authorization, not just "is the caller logged in?"
    if note and can_read(info.context["user"], note):
        return note
    return None


@note_type.field("owner")
def resolve_owner(note, _):
    return USERS[note["owner_id"]]


@user_type.field("notes")
def resolve_notes(user, info):
    return [n for n in NOTES.values() if n["owner_id"] == user["id"] and can_read(info.context["user"], n)]


@user_type.field("email")
def resolve_email(user, info):
    viewer = info.context["user"]
    if SECURE and viewer["id"] != user["id"] and viewer["role"] != "admin":
        return None
    return user["email"]


schema = make_executable_schema(type_defs, query, note_type, user_type)


def depth_and_aliases(selection_set, depth=1):
    """Return (max depth, alias count). Inline selections only; see article note on fragments."""
    max_depth, aliases = depth, 0
    for sel in selection_set.selections:
        if isinstance(sel, FieldNode):
            aliases += 1 if sel.alias else 0
            if sel.selection_set:
                d, a = depth_and_aliases(sel.selection_set, depth + 1)
                max_depth, aliases = max(max_depth, d), aliases + a
    return max_depth, aliases


@app.post("/graphql")
def graphql_endpoint():
    user = current_user()
    if not user:
        return jsonify({"error": "unauthenticated"}), 401
    data = request.get_json(force=True)
    rules = None
    if SECURE:
        for op in parse(data["query"]).definitions:
            if getattr(op, "selection_set", None):
                depth, aliases = depth_and_aliases(op.selection_set)
                if depth > MAX_DEPTH or aliases > MAX_ALIASES:
                    return jsonify({"errors": [{"message": "query too deep or too many aliases"}]}), 400
        rules = [NoSchemaIntrospectionCustomRule]  # hygiene, not a real control
    ok, result = graphql_sync(
        schema, data, context_value={"user": user}, validation_rules=rules
    )
    return jsonify(result), 200 if ok else 400


if __name__ == "__main__":
    print(f"Running in {'SECURE' if SECURE else 'VULNERABLE'} mode on http://127.0.0.1:5000")
    app.run(host="127.0.0.1", port=5000)

Before attacking it, read the code the way a tester would. Four decisions are wrong, and each one is a missing question:

  • get_note fetches a note by ID but never asks whether it belongs to the caller. That is BOLA.
  • admin_list_users is meant for administrators but never checks the caller's role. That is BFLA.
  • update_me copies every key in the JSON body onto the user record, including role. That is mass assignment.
  • The GraphQL layer exposes introspection, accepts any number of aliases, allows unlimited nesting through the User → Notes → Owner → User cycle, and its note resolver has no ownership check.

Passwords here are plaintext and tokens are random strings held in memory. That is acceptable for a lab and unacceptable anywhere else.

Logging in

Start the vulnerable server in one terminal with python app.py. In a second terminal, define a small helper and obtain tokens for Alice and Bob. A token is just proof that the server recognized a login; every later request presents it in an Authorization header.

login() { curl -s -X POST http://127.0.0.1:5000/api/login \
  -H "Content-Type: application/json" \
  -d "{\"username\":\"$1\",\"password\":\"$1-pw\"}" | jq -r .token; }

ALICE=$(login alice)
BOB=$(login bob)

Test 1: BOLA, Alice reads Bob's note

Note 3 belongs to Bob and contains a fake PIN. Alice requests it:

curl -s -w "\nHTTP %{http_code}\n" -H "Authorization: Bearer $ALICE" \
  http://127.0.0.1:5000/api/notes/3
{"content":"bob secret: 4821","id":3,"owner_id":2,"title":"Bob bank PIN"}

HTTP 200

The server authenticated Alice, found note 3, and returned it. At no point did it compare owner_id (Bob) to the caller (Alice).

Test 2: BFLA, Bob calls an admin function

Bob is an ordinary user. He requests the admin-only user list:

curl -s -w "\nHTTP %{http_code}\n" -H "Authorization: Bearer $BOB" \
  http://127.0.0.1:5000/api/admin/users
[{"email":"alice@example.test","id":1,"role":"user","username":"alice"},{"email":"bob@example.test","id":2,"role":"user","username":"bob"},{"email":"admin@example.test","id":3,"role":"admin","username":"admin"}]

HTTP 200

The route existed to be used by administrators, but nothing in the code says so.

Test 3: Mass assignment, Alice promotes herself

The legitimate use of this endpoint is changing an email address. Alice sends a second field:

curl -s -w "\nHTTP %{http_code}\n" -X PATCH http://127.0.0.1:5000/api/users/me \
  -H "Authorization: Bearer $ALICE" -H "Content-Type: application/json" \
  -d '{"email": "alice@example.test", "role": "admin"}'
{"email":"alice@example.test","id":1,"role":"admin","username":"alice"}

HTTP 200

The response itself is the evidence: "role":"admin". The server never decided that clients may set role; its binding code simply never decided they may not.

Test 4: GraphQL, four problems in one endpoint

First, introspection. Bob asks the server to describe its User type:

curl -s -w "\nHTTP %{http_code}\n" -X POST http://127.0.0.1:5000/graphql \
  -H "Authorization: Bearer $BOB" -H "Content-Type: application/json" \
  -d '{"query": "{ __type(name: \"User\") { fields { name } } }"}'
{"data":{"__type":{"fields":[{"name":"id"},{"name":"username"},{"name":"email"},{"name":"notes"}]}}}

HTTP 200

Second, field-level authorization. Bob reads the admin's note, and walks to the owner's email through the object graph:

curl -s -w "\nHTTP %{http_code}\n" -X POST http://127.0.0.1:5000/graphql \
  -H "Authorization: Bearer $BOB" -H "Content-Type: application/json" \
  -d '{"query": "{ note(id: 5) { content owner { username email } } }"}'
{"data":{"note":{"content":"admin only: rotate keys","owner":{"email":"admin@example.test","username":"admin"}}}}

HTTP 200

Third, aliasing. One HTTP request performs six separate lookups, which is exactly what a per-request rate limiter cannot see:

curl -s -w "\nHTTP %{http_code}\n" -X POST http://127.0.0.1:5000/graphql \
  -H "Authorization: Bearer $BOB" -H "Content-Type: application/json" \
  -d '{"query": "{ n1: note(id: 1) { title } n2: note(id: 2) { title } n3: note(id: 3) { title } n4: note(id: 4) { title } n5: note(id: 5) { title } n6: note(id: 6) { title } }"}'
{"data":{"n1":{"title":"Alice groceries"},"n2":{"title":"Alice diary"},"n3":{"title":"Bob bank PIN"},"n4":{"title":"Bob todo"},"n5":{"title":"Admin runbook"},"n6":null}}

HTTP 200

Fourth, a cyclic query. Each trip around notes → owner → notes multiplies the work, and the server accepts it at any depth. Here the response is truncated to its first 150 characters, but the server computed all of it:

curl -s -X POST http://127.0.0.1:5000/graphql \
  -H "Authorization: Bearer $BOB" -H "Content-Type: application/json" \
  -d '{"query": "{ me { notes { owner { notes { owner { notes { owner { username } } } } } } } }"}' | head -c 150; echo " ..."
{"data":{"me":{"notes":[{"owner":{"notes":[{"owner":{"notes":[{"owner":{"username":"bob"}},{"owner":{"username":"bob"}}]}},{"owner":{"notes":[{"owner":{"notes" ...

Verify, do not assume

One observation can mislead. Perhaps note 3 happened to be public, or the data was seeded oddly. A short script makes the check repeatable and gives you something you can hand to a developer. Save this as sweep.py. It signs in as Alice and checks a small, bounded range of note IDs:

"""Sweep note IDs 1-10 as Alice against the LOCAL lab API and report what leaks."""
import requests

BASE = "http://127.0.0.1:5000"
ALICE_ID = 1  # Alice's user id in the lab data

token = requests.post(f"{BASE}/api/login", json={"username": "alice", "password": "alice-pw"}).json()["token"]
headers = {"Authorization": f"Bearer {token}"}

leaked = []
for note_id in range(1, 11):  # small, bounded range: never sweep systems you do not own
    resp = requests.get(f"{BASE}/api/notes/{note_id}", headers=headers)
    if resp.status_code == 200 and resp.json()["owner_id"] != ALICE_ID:
        leaked.append(note_id)
        print(f"note {note_id}: HTTP 200, owned by user {resp.json()['owner_id']} -> LEAK")
    else:
        print(f"note {note_id}: HTTP {resp.status_code}")

print(f"\nAlice can read {len(leaked)} note(s) she does not own: {leaked}")
python sweep.py
note 1: HTTP 200
note 2: HTTP 200
note 3: HTTP 200, owned by user 2 -> LEAK
note 4: HTTP 200, owned by user 2 -> LEAK
note 5: HTTP 200, owned by user 3 -> LEAK
note 6: HTTP 404
note 7: HTTP 404
note 8: HTTP 404
note 9: HTTP 404
note 10: HTTP 404

Alice can read 3 note(s) she does not own: [3, 4, 5]

The core lesson: a 200 OK is not proof of security, and an explanation of a bug, from a person, a tool, or an AI assistant, is a hypothesis until a test confirms it. The only question that matters is should this user have been able to do that?

The fixes

The same app.py already contains the fixes, switched on by SECURE=1. Four small changes address the four root causes:

# BOLA: the ownership check (inside can_read, used by REST and GraphQL)
return (not SECURE) or note["owner_id"] == user["id"] or user["role"] == "admin"

# BFLA: deny by default on the admin route
if SECURE and user["role"] != "admin":
    return jsonify({"error": "forbidden"}), 403

# Mass assignment: only an explicit allowlist of fields is writable
allowed = {"email"} if SECURE else set(data)

# GraphQL: depth and alias limits, introspection off, per-resolver checks
rules = [NoSchemaIntrospectionCustomRule]

In plain terms: the ownership check ties access to who is asking rather than which ID was supplied, and the server answers 404 for notes the caller may not see so it does not confirm they exist. The role check refuses the admin route unless the caller is an administrator. The allowlist means role is never writable from this endpoint no matter what the client sends. And the GraphQL changes bound query depth to five levels and aliases to five per operation, switch introspection off, and make the note, notes, and email resolvers decide for themselves whether the viewer may see what they return.

One honest limitation: the depth and alias counter in this lab only walks inline selections and does not follow GraphQL fragments. A production system should rely on a maintained depth and cost-analysis library, or enforce limits at a gateway.

Re-testing the fixed version

Stop the server, restart it with SECURE=1 python app.py, log in again (tokens live in memory, so restarting invalidates them), and re-run every request above. The results:

Test Vulnerable Fixed
Alice reads Bob's note (/api/notes/3) 200, note returned 404 {"error":"not found"}
Bob calls /api/admin/users 200, all users listed 403 {"error":"forbidden"}
Alice PATCHes "role": "admin" 200, response shows "role":"admin" 200, response shows "role":"user" (role ignored)
GraphQL introspection 200, schema returned 400, "introspection has been disabled"
GraphQL note(id: 5) as Bob 200, admin's note returned 200, {"data":{"note":null}}
Six aliased lookups 200, five notes returned 400, "query too deep or too many aliases"
Cyclic query, eight levels deep 200, large nested response 400, "query too deep or too many aliases"
sweep.py 3 leaks (notes 3, 4, 5) Alice can read 0 note(s) she does not own: []

An administrator can still reach the admin route, which is the other half of a correct fix: the control blocks the wrong people without breaking the right ones.

What this lab proves

The theory sections claimed three things, and the lab shows each in miniature. First, authorization failures are logic flaws: every vulnerable response above was a perfectly valid 200 OK, which is why scanners struggle to see them. Second, tooling accelerates the mechanical work. curl, a helper function, and a short Python script made the replay and diff repeatable, which is the part of the job tools do well. Third, a human still owns the decision that matters: which user should be able to read note 3, call the admin route, or set role. No script could know that. The rule had to come from someone who understood what the application is for.


Conclusion

API security is, at its core, the discipline of enforcing who may do what to which data, consistently, at every layer of an application that has no user interface to hide behind. The shift to API-first architectures did not create new kinds of mistakes so much as remove the places where old mistakes were previously masked. Testing is the practice of asking the authorization question systematically, with two accounts, a role matrix, and a habit of comparing outcomes against rules rather than against expectations. Fixing is the practice of encoding the answer once, centrally, and testing it on every change.

As APIs multiply through partner integrations and internal services, the volume of endpoints that need an explicit rule will keep growing faster than the number of people who can review them by hand. The organizations that cope best will be the ones whose defaults refuse, whose tests assert refusals, and whose engineers treat each new route as an authorization decision that has to be made on purpose.

The takeaway: an API that works for the right user proves nothing. It is secure only if it refuses the wrong one, and that has to be tested.


Further Reading

  • OWASP API Security Top 10 (2023 edition): the reference list of API risk categories, including BOLA, BFLA, and BOPLA, with prevention guidance for each.
  • OWASP Web Security Testing Guide (WSTG): a structured testing methodology that includes authorization testing and business-logic testing.
  • PortSwigger Web Security Academy, "API testing" and "GraphQL API vulnerabilities": free, hands-on labs covering mass assignment, introspection, and alias-based brute-force bypasses.
  • OWASP GraphQL Cheat Sheet: practical defensive guidance on depth and cost limits, introspection, and authorization in resolvers.
  • OWASP Mass Assignment Cheat Sheet: explains overposting and shows how to prevent it with allowlists and data transfer objects.