Testing Protected Routes

Tests for an API's rules about who may do what sign in inside a fixture and send the token in the Authorization header, try each rule as each kind of user and once with no token, and can override get_current_user with dependency_overrides as a shortcut, knowing it skips the token check.

Journeyman · FastAPI · REST API · Updated

By

After this lesson you can

  • Test protected routes by signing in inside a fixture and sending the token in the Authorization header
  • Test each rule as each kind of user it treats differently, and once with no token
  • Override get_current_user with dependency_overrides as a shortcut in tests, and explain what such a test no longer proves

Key takeaways

  • Rules about who may do what break quietly. A route that loses its check still answers every request, so only a test that tries the forbidden request notices.
  • A fixture that signs in through POST /auth/token and gives back the Authorization header lets any test act as that user, by asking for the fixture by name and passing headers=.
  • Test each rule as each kind of user it treats differently, and once with no token, so every 200, 401 and 403 is proven.
  • app.dependency_overrides[get_current_user] hands every route a made-up user with no sign-in and no token. It's fast, but such a test no longer proves that a missing or bad token is refused.

Rules about who may do what break quietly. A teammate tidies up a route, a Depends goes missing, and every request still works: the app looks fine, and nobody notices until a member deletes a task they shouldn't. A test that tries the forbidden request, as the user who must be refused, catches it the moment it happens.

The example is Crew Board's API from Roles and Ownership: 401 or 403, tested with TestClient. As in Testing with a Real, Throwaway Database, an autouse fixture gives every test a fresh database file, here with the team (Maya the admin, Theo and Sofia the members) and their four tasks.

Signing in inside a fixture

A protected route needs a token, so the tests sign in first, through the real sign-in route. In tests/test_access.py:

import os

os.environ["JWT_SECRET"] = "test-secret-for-the-crew-board-tests-only"

import pytest
from fastapi.testclient import TestClient

from main import app

client = TestClient(app)


def sign_in(email, password):
    response = client.post("/auth/token", data={"username": email, "password": password})
    token = response.json()["access_token"]
    return {"Authorization": f"Bearer {token}"}


@pytest.fixture
def theo():
    return sign_in("theo@example.com", "practice-theo")


@pytest.fixture
def maya():
    return sign_in("maya@example.com", "practice-maya")

The tests set JWT_SECRET before they import the app, so the tokens are signed with a secret of their own. data= sends a form, the way the docs page's Authorize button does, not JSON. sign_in gives back the header that carries the token, ready to send. A test that needs Theo asks for the theo fixture by name and sends it with headers=:

def test_theo_gets_the_4_tasks(theo):
    response = client.get("/tasks", headers=theo)

    assert response.status_code == 200
    assert len(response.json()) == 4

Because the fixture signs in through POST /auth/token, every test that uses it also proves that sign-in works and that the token it hands out opens the door.

A test for each rule, as each kind of user

One test as Maya proves an admin may delete. It doesn't prove that Theo may not. A rule is proven when it's tried by each kind of user it treats differently, and once with no token at all:

Request Maya (admin) Theo (member, owns task 2) Sofia (member) No token
DELETE /tasks/3 204 403 403 401
PATCH /tasks/2 200 200 403 401

Each cell is a test. The delete rule's three kinds of answer:

def test_maya_an_admin_deletes_task_3(maya):
    response = client.delete("/tasks/3", headers=maya)

    assert response.status_code == 204


def test_theo_a_member_cant_delete_task_3(theo):
    response = client.delete("/tasks/3", headers=theo)

    assert response.status_code == 403
    assert response.json()["detail"] == "You need the admin role for that."


def test_deleting_task_3_with_no_token_answers_401():
    response = client.delete("/tasks/3")

    assert response.status_code == 401
    assert response.headers["WWW-Authenticate"] == "Bearer"

For a row of users with the same request, @pytest.mark.parametrize from Testing Errors, with a Fresh Start for Every Test runs one test per user, signing in by name:

@pytest.mark.parametrize("name, status", [("theo", 200), ("sofia", 403), ("maya", 200)])
def test_who_may_change_theos_task_2(name, status):
    headers = sign_in(f"{name}@example.com", f"practice-{name}")
    response = client.patch("/tasks/2", json={"done": True}, headers=headers)

    assert response.status_code == status

python -m pytest -v lists each test by name, and each user in square brackets:

collected 7 items

tests/test_access.py::test_theo_gets_the_4_tasks PASSED                  [ 14%]
tests/test_access.py::test_maya_an_admin_deletes_task_3 PASSED           [ 28%]
tests/test_access.py::test_theo_a_member_cant_delete_task_3 PASSED       [ 42%]
tests/test_access.py::test_deleting_task_3_with_no_token_answers_401 PASSED [ 57%]
tests/test_access.py::test_who_may_change_theos_task_2[theo-200] PASSED  [ 71%]
tests/test_access.py::test_who_may_change_theos_task_2[sofia-403] PASSED [ 85%]
tests/test_access.py::test_who_may_change_theos_task_2[maya-200] PASSED  [100%]

============================== 7 passed in 4.13s ===============================

Now the slip from the opening: someone tidies the delete route and drops dependencies=[Depends(require_role("admin"))] from its decorator. The test as Maya still passes, since admins could always delete. The other two catch it, and the end of the report says so:

FAILED tests/test_access.py::test_theo_a_member_cant_delete_task_3 - assert 2...
FAILED tests/test_access.py::test_deleting_task_3_with_no_token_answers_401
========================= 2 failed, 5 passed in 8.27s ==========================

Overriding the current user

Signing in costs time: every sign-in checks an Argon2 hash, which is slow on purpose. A file with dozens of tests about one rule can skip it. app.dependency_overrides, the dictionary Testing with a Real, Throwaway Database uses to swap get_db, can swap get_current_user too:

from dependencies import get_current_user

THEO = {"id": 2, "name": "Theo", "email": "theo@example.com", "role": "member"}


@pytest.fixture
def as_theo():
    app.dependency_overrides[get_current_user] = lambda: THEO
    yield
    del app.dependency_overrides[get_current_user]


def test_theo_cant_change_sofias_task_3(as_theo):
    response = client.patch("/tasks/3", json={"done": False})

    assert response.status_code == 403

While the fixture runs, every route that depends on get_current_user, and require_role's check too, gets THEO without a token. The line after yield removes the override, so it never leaks into the next test. The test passes, and it never sent a token.

That's the shortcut's limit. With the override in place, oauth2_scheme and jwt.decode never run, so a test that sends no token at all gets Theo anyway:

>       assert response.status_code == 401
E       assert 200 == 401
E        +  where 200 = <Response [200 OK]>.status_code

So an overridden test proves the rule (an owner, a role) and nothing about the door. Keep real sign-ins for every 401 test and for each role at least once, and use the override only where the token isn't the point.

Check yourself

2 questions to try on the lesson page.

So what

A protected route is proven by the requests it refuses as much as by the ones it serves, so a test as each kind of user, and one with no token, turns a quiet security hole into a red test.

Key terms

Related