A permission system that the backend does not know about is not a permission system. I learned that on a university team project, an invoice-reminder app with a FastAPI backend, when an audit turned up two endpoints that skipped the approval flow we had built for them. Fixing it test-first also showed me that three tests in our suite had been passing because of the bug.

The Hole

The app has two roles, staff and admin. A few actions are sensitive: cancelling an invoice, changing an invoice amount or due date, editing a client’s legal details. Staff are not supposed to do those directly. They submit a permission request, an admin reviews it, and on approval the backend runs the real mutation as the admin.

That flow worked. The problem was that the mutation endpoints underneath it were still reachable on their own, and they only checked that you were logged in.

EndpointWhat was wrong
POST /invoices/{id}/cancelNo role check in the router or the service. A staff user could cancel any unpaid or overdue invoice by calling the URL.
PUT /invoices/{id}An earlier fix blocked staff from editing amount and due date on partially paid invoices only. Unpaid and overdue ones stayed editable.
PUT /clients/{id}Already gated at the router, but nothing tested it, so the next refactor could have removed the gate.

The UI hid the direct buttons from staff, which is why nobody noticed. Anyone with a token and curl could still call the endpoints.

First Idea: Gate the Router

The obvious fix is a require_admin dependency on the two routes. It would have closed the two holes, but I put the check in the service instead, for two reasons. First, the rule for editing an invoice depends on the payload: staff may still fix a description, but not change an amount or due date, and a route-level admin check would block all of it. Second, the approval executor does not go through the routes at all. It calls the same service methods directly, so a route dependency never sees it, and the rule would only hold for whichever callers happen to come in through HTTP.

So the check went into the service, with the caller’s role passed in as a keyword-only argument:

class InvoiceService:
    async def cancel(self, invoice_id: str, *, actor_role: str | None = None):
        if actor_role == ROLE_STAFF:
            raise PermissionError(
                "Staff cannot cancel invoices directly; "
                "submit a permission request for admin review."
            )
        ...  # existing cancel logic, unchanged

Routes pass actor_role=user.role. The approval executor passes the reviewer’s role, which is admin. Internal jobs and older unit tests pass nothing and behave as before. The router turns PermissionError into a 403.

Red First

I wrote the failing test before touching the service. This is the contract for the first hole, trimmed and with names simplified:

@pytest.mark.integration
def test_staff_cannot_edit_invoice_amount_on_unpaid(test_client, staff_token, real_db):
    client_id = _seed_client(real_db)
    invoice_id = _seed_invoice(real_db, client_id, amount=1_000_000, status="UNPAID")

    response = test_client.put(
        f"/api/invoices/{invoice_id}",
        headers={"Authorization": f"Bearer {staff_token}"},
        json={"amount": 2_000_000},
    )

    assert response.status_code == 403
    assert "permission request" in response.json()["detail"]

It failed the way a good red test should: the server answered 200 and wrote the new amount. The green commit moved two lines out of an if status == "PARTIAL" block so the amount and due-date rule applied to every status. The cancel hole got its own red and green pair.

Both tests run against a real database, not a mock. The bug lived in the gap between router auth and service logic, and a mock returns whatever you tell it to.

Three Tests Turned Red

When the second green commit landed, three tests I had not touched started failing. Their names read like happy paths:

def test_cancel_invoice_returns_200(test_client, token, real_db): ...
def test_update_invoice_amount_succeeds(test_client, token, real_db): ...
def test_cancel_invoice_marks_status_canceled(test_client, token, real_db): ...

The token fixture in that file signed in as a default user, and the default user was a staff member. Each test asserted that a staff user could cancel or edit an invoice, and for as long as the bug existed, that was true. The tests were green because the bug was the behavior.

They looked like coverage. A coverage report would have counted them. They only gave a wrong answer once I added a test that contradicted the bug.

I changed the three to sign in as an admin, which is what the names always claimed. The staff side is covered by new negative tests.

What I Do Differently Now

  • Put the role in the test name, then make the test earn it. test_admin_can_cancel_invoice and test_staff_cannot_cancel_invoice say what they claim, and test_cancel_invoice_returns_200 does not. A name is not proof, though. The staff test should assert the specific rejection message, as the one above does, because a bare 403 can also come from a bad token. And the fixture has to really hold the role the name says.
  • Write a test that contradicts the bug, even when the fix is obvious. I knew the two-line fix before I wrote the red test. Writing the test first cost about ten minutes and found the three liars, which I would not have found otherwise.
  • Keep the refactor in its own commit. After both fixes, two routes had the same except PermissionError block. I extracted a small helper that returns the 403 in a separate commit with no behavior change, so it can be reverted without touching the security fix.

Where This Falls Short

  • The default is a hole waiting for a caller. actor_role=None means “trust the caller”, which is what keeps jobs and old tests working. A new route that forgets to pass the role gets no protection, and nothing fails to tell you.
  • Three endpoints is not a whole-API audit. The fix covers the endpoints the audit listed. Any other mutation endpoint with the same gap is exactly as exposed as before.
  • A fixture that picks a role for you is a trap. That is how the three bad tests happened, and it is worth searching your own suite for fixtures like it.

The commit order on the branch was red, green, red, green, then a batch of regression tests, a chore commit fixing the three tests, and the refactor last.