Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 25 min · revision 2

Fixes That Stay Fixed

Fix a cross-user data leak in a small Flask service the way that lasts: write the regression test first and watch it fail, move the check into one data-access function, add a Semgrep rule that blocks the old pattern, and record guidance the team can follow and CI can enforce.

Contentsand lesson path

What you will learn

  • Deliver a fix with a regression test that fails before and passes after, and record the secure-coding guidance the team should follow.

Prerequisites: Web Application Security

01. Goal and setup

Security bugs come back. A developer copies an old route as a template, a refactor drops a check, or a new endpoint is written by someone who never saw the original bug report. A fix that only changes the vulnerable line protects you until the next change. A fix that stays fixed has three more parts: a test that proves the flaw is gone, a single place in the code where the rule lives, and an automated check that stops the old pattern from returning.

In this lab you work on a tiny order service that runs only on your machine, inside Flask's test client. It has one flaw: any signed-in user can read any order by changing the number in the URL. This is called an insecure direct object reference (IDOR), and it is a case of broken access control, the first category of the OWASP Top 10:2025. OWASP ASVS 5.0 requirement 8.2.2 asks that access to specific data items is restricted to users with permission for those items.

You need: Python 3.10 or later. The lab uses Flask 3.1.3, pytest 9.2.0 and Semgrep 1.185.0, installed into a virtual environment. Nothing listens on a network port: the tests call the app in-process.

Terminal · setup
mkdir orders-lab && cd orders-lab
python3 -m venv .venv && source .venv/bin/activate
python -m pip install "flask==3.1.3" "pytest==9.2.0" "semgrep==1.185.0"
Terminal
python -m pip show flask pytest semgrep | grep "^Version"
Expected output
Version: 3.1.3
Version: 9.2.0
Version: 1.185.0

02. Step 1: Read the vulnerable service

Two users exist, Alice and Bob, each with a fake bearer token that only works in this lab. Order 101 belongs to Alice and order 102 to Bob. Save the service as orders-lab/app.py.

Python · orders-lab/app.py
"""A tiny order service with one deliberate flaw, for a local lab only."""
from flask import Flask, abort, jsonify, request

app = Flask(__name__)
TOKENS = {"token-alice": "alice", "token-bob": "bob"}  # lab-only fake tokens
ORDERS = {
    101: {"id": 101, "owner": "alice", "item": "Dune", "total": 12.5},
    102: {"id": 102, "owner": "bob", "item": "Emma", "total": 8.0},
}


def current_user():
    user = TOKENS.get(request.headers.get("Authorization", "").removeprefix("Bearer "))
    if user is None:
        abort(401)
    return user


@app.get("/orders/<int:order_id>")
def get_order(order_id):
    current_user()
    order = ORDERS.get(order_id)  # FLAW: any signed-in user can read any order
    if order is None:
        abort(404)
    return jsonify(order)

Trace the request as a reviewer would. current_user() checks who is calling (authentication), and the route then loads the order by id. Nothing checks whether this caller may see this order (authorisation). The line marked FLAW is where the two ideas get confused: being signed in is treated as permission to read everything. From inside orders-lab, print who owns each order; step 2 uses these two ids.

Terminal
python -c "from app import ORDERS; print({k: v['owner'] for k, v in ORDERS.items()})"
Expected output
{101: 'alice', 102: 'bob'}

03. Step 2: Write the regression test first

Write the test before the fix. A regression test is a test that keeps a fixed bug from coming back. For a security bug it must reproduce the attack in the smallest safe form: here, Bob signs in and asks for Alice's order. The two other tests protect normal behaviour, so the fix cannot "work" by breaking the feature. Save this as orders-lab/test_orders.py.

Python · orders-lab/test_orders.py
import pytest

from app import app


@pytest.fixture
def client():
    return app.test_client()


def get(client, order_id, token=None):
    headers = {"Authorization": f"Bearer {token}"} if token else {}
    return client.get(f"/orders/{order_id}", headers=headers)


def test_owner_can_read_own_order(client):
    assert get(client, 101, "token-alice").status_code == 200


def test_anonymous_request_is_rejected(client):
    assert get(client, 101).status_code == 401


def test_other_users_order_is_not_found(client):
    """Regression test for the IDOR: Bob must not see Alice's order 101."""
    response = get(client, 101, "token-bob")
    assert response.status_code == 404
    assert b"Dune" not in response.data
Terminal · the sed removes the run time, which varies
python -m pytest -q -p no:cacheprovider 2>&1 | tail -n 2 | sed -E 's/ in [0-9.]+s//'
Expected output
FAILED test_orders.py::test_other_users_order_is_not_found - assert 200 == 404
1 failed, 2 passed

Red is the result you want at this point. The failure shows the test really reaches the flaw: Bob got a 200 and Alice's order. If this test had passed on vulnerable code, it would prove nothing about any fix, because it would pass whether the bug existed or not. The other two tests pass, which tells you the test setup itself is sound.

04. Step 3: Fix it in one place

Keep a copy of the vulnerable version for step 4, then fix it. The fix does not add an if inside the route. It adds one function, order_for, that is the only way to load an order, and it checks ownership there. A second route added next month gets the check for free if it uses the same function.

Terminal
cp app.py app_before.py

Now replace app.py with the fixed version:

Python · orders-lab/app.py
"""A tiny order service, for a local lab only: orders are scoped to their owner."""
from flask import Flask, abort, jsonify, request

app = Flask(__name__)
TOKENS = {"token-alice": "alice", "token-bob": "bob"}  # lab-only fake tokens
ORDERS = {
    101: {"id": 101, "owner": "alice", "item": "Dune", "total": 12.5},
    102: {"id": 102, "owner": "bob", "item": "Emma", "total": 8.0},
}


def current_user():
    user = TOKENS.get(request.headers.get("Authorization", "").removeprefix("Bearer "))
    if user is None:
        abort(401)
    return user


def order_for(user, order_id):
    """The only way to load an order: scoped to the user who asks."""
    order = ORDERS.get(order_id)
    if order is None or order["owner"] != user:
        abort(404)  # same answer for "missing" and "not yours"
    return order


@app.get("/orders/<int:order_id>")
def get_order(order_id):
    return jsonify(order_for(current_user(), order_id))
Terminal
python -m pytest -q -p no:cacheprovider 2>&1 | tail -n 1 | sed -E 's/ in [0-9.]+s//'
Expected output
3 passed

Green. Note the choice of 404 instead of 403 for someone else's order. A 403 says "this order exists but is not yours", which lets an attacker count how many orders exist. Returning the same answer for "missing" and "not yours" removes that signal. Both are defensible; what matters is that the rule is written down and applied the same way everywhere.

05. Step 4: Stop the old pattern in CI

Tests protect the routes that have tests. To protect future routes, make the unsafe pattern itself fail the build. Semgrep rules describe code patterns in the syntax of the language they check. This rule matches any read of ORDERS that is not inside order_for. Save it as orders-lab/order-rules.yml, and save the small report printer as orders-lab/show_findings.py.

YAML · orders-lab/order-rules.yml
rules:
  - id: orders-must-be-scoped
    languages: [python]
    severity: ERROR
    message: Load orders with order_for(), which checks the owner (bug 42)
    patterns:
      - pattern-either:
          - pattern: ORDERS.get(...)
          - pattern: ORDERS[...]
      - pattern-not-inside: |
          def order_for(...):
              ...
Python · orders-lab/show_findings.py
"""Print one line per finding from a Semgrep JSON report."""
import json
import sys

results = json.load(open(sys.argv[1]))["results"]
for r in results:
    print(f"{r['path']}:{r['start']['line']} {r['check_id'].split('.')[-1]}")
print(f"{len(results)} finding(s)")

Run it on both versions. --error makes Semgrep exit with code 1 when it finds anything, which is what fails a CI job, and --metrics=off stops it sending usage data.

Terminal
semgrep scan --metrics=off --disable-version-check --quiet --error \
  --config order-rules.yml --json -o findings.json app.py app_before.py
echo "exit=$?"
python3 show_findings.py findings.json
Expected output
exit=1
app_before.py:22 orders-must-be-scoped
1 finding(s)

The rule is the negative test for your guard rail: it flags the vulnerable copy and stays quiet on the fixed code. Delete app_before.py before you commit, or the CI job will fail on it. The rule is deliberately narrow. It knows nothing about other data, and a determined developer could still write dict.get(ORDERS, id). That is fine: its job is to catch the ordinary way this bug returns, and code review covers the rest.

06. Step 5: Record guidance people can follow

The last part of the fix is a short note in the repository that tells the next developer what to do, not only what went wrong. Good guidance is specific (it names the function to use), enforceable (it points at the rule that checks it) and small enough to read in a minute. Save it as orders-lab/SECURITY.md.

Markdown · orders-lab/SECURITY.md
## Secure-coding rules for the orders service

1. Load an order only through `order_for(user, order_id)`. It returns 404 when the
   order is missing or belongs to someone else. Direct `ORDERS` access is blocked
   in CI by the Semgrep rule `orders-must-be-scoped`.
2. Every authorisation bug gets a regression test that signs in as one user and
   asks for another user's data. The test must fail on the vulnerable code.
3. Answer "not yours" and "does not exist" the same way, so ids cannot be probed.

Background: bug 42 (Bob could read Alice's order 101), fixed on 2026-11-16.

Guidance that names a rule is only useful if the rule exists. Check that the id in SECURITY.md is the id that CI runs:

Terminal
grep -o "orders-must-be-scoped" order-rules.yml SECURITY.md
Expected output
order-rules.yml:orders-must-be-scoped
SECURITY.md:orders-must-be-scoped

Compare that with typical post-incident notes such as "be careful with order ids" or "bug fixed". Neither tells anyone what to do differently, and neither can be checked by a machine. The NIST Secure Software Development Framework (SP 800-218) asks teams to analyse the root causes of vulnerabilities and feed the lessons back into their practices; a rule plus a test plus one paragraph is a small, practical version of that.

07. Check your understanding

Practice check · 3 questions

Making fixes last

Use the files from this lab.

Q1. Before the fix, a teammate edits the regression test: Bob now asks for order 102 instead of 101, and the assertion now expects 200, "because Bob may see his own order". What does pytest report on the vulnerable app?
Q2. Next month someone adds GET /orders/<id>/invoice. Which approach gives the IDOR the least chance to return?
Q3. While refactoring, a developer writes `order = ORDERS[order_id]` inside order_for(). What does the Semgrep command in step 4 report for app.py?
Practice only: not graded, not saved, not evidence.

08. Apply it

For the skill project, take the highest-risk finding you triaged in the sample repository and fix it this way: commit a failing security test first, then the fix, then a Semgrep rule or lint setting that blocks the pattern, and a three-line entry in the repository's security guidance. In the pull request description, paste the red and the green test output.

09. Review prompt

From memory, list the four parts of a fix that stays fixed, and say what each one protects against. Explain why the regression test must fail before the fix, and why the check lives in order_for instead of in the route.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check