Reviewing a FastAPI API whose routes declare Security() scopes, what could let a read-only reporting token still reach the write endpoints?
answer
- declared is not enforced
- which dependency the route names
- string containment vs set membership
- what the token route grants
- a test per write route
basics
~20 sDeclared scopes enforce nothing alone. Look for write routes on Depends or on Security over the scheme, a checker ignoring SecurityScopes, an any() or substring comparison, and a token route granting whatever scopes the client requests.
solid answer
~40 sStart from the fact that `Security(..., scopes=[...])` is bookkeeping. Then check, route by route: does the write route name the **checking dependency** in `Security`, or `Depends(get_current_principal)` (empty required list) or `Security(oauth2_scheme, scopes=[...])` (documented, never checked)? Does the checker read `security_scopes.scopes` at all, require **every** entry, and compare against a **set of whole names** rather than `in` on the raw scope string, where `items:write` matches `items:write-drafts`? Then the token route: FastAPI's own example copies `form_data.scopes` into the token and warns you to grant only scopes the user may hold; a route that copies them lets any client ask for `items:write`. Close it with a router-level `Security` on all write routes and tests that a read-only token gets 403.
code
python · 61 linesfrom typing import Annotated
from fastapi import APIRouter, Depends, FastAPI, HTTPException, Security, status
from fastapi.security import OAuth2PasswordBearer, SecurityScopes
from fastapi.testclient import TestClient
oauth2_scheme = OAuth2PasswordBearer(
tokenUrl="token",
scopes={"items:read": "Read items.", "items:write": "Change items."},
)
GRANTED = {"reporting-token": ["items:read"]}
def require_scopes(
security_scopes: SecurityScopes,
token: Annotated[str, Depends(oauth2_scheme)],
):
granted = set(GRANTED.get(token, [])) # a set of whole scope names, never a raw string
if not all(scope in granted for scope in security_scopes.scopes):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Not enough permissions",
headers={
"WWW-Authenticate": f'Bearer error="insufficient_scope", '
f'scope="{security_scopes.scope_str}"'
},
)
# Every route on this router needs items:write; a new route cannot forget it.
writes = APIRouter(
prefix="/items", dependencies=[Security(require_scopes, scopes=["items:write"])]
)
@writes.post("")
def create_item():
return {"created": True}
app = FastAPI()
app.include_router(writes)
def test_read_only_token_cannot_write():
client = TestClient(app)
r = client.post("/items", headers={"Authorization": "Bearer reporting-token"})
assert r.status_code == 403
def test_every_write_operation_documents_items_write():
for path, ops in app.openapi()["paths"].items():
for method, op in ops.items():
if method in {"post", "put", "patch", "delete"}:
scopes = [s for req in op.get("security", []) for s in req.values()]
assert any("items:write" in group for group in scopes), (method, path)
test_read_only_token_cannot_write()
test_every_write_operation_documents_items_write()
print("ok")go deeper
Know that a scope written in Security() does nothing unless a dependency reads SecurityScopes and raises, and check which dependency each route names.
Trace a request from route to checker to token claim, and spot Depends where Security belongs, Security on the scheme, and string containment tests.
Lead the review across routes, checker and token issuance, then lock the result in with a router-level declaration, a 403 test and a schema walk.
Make scope enforcement a structural convention, one checker and router-level requirements, so correctness does not depend on each author remembering it.
## The starting point: declared is not enforced In FastAPI, `Security(dependency, scopes=[...])` records required scopes; it never compares them with a token. Enforcement exists only where a dependency declares `security_scopes: SecurityScopes`, reads the token's granted scopes and raises. A review of an inventory API, where a reporting client holds `items:read` tokens and writes need `items:write`, is a search for every way a request can avoid that comparison or pass it wrongly. ## Holes on the route side 1. **The route uses `Depends` instead of `Security`.** `Depends(get_current_principal)` runs the checker with an empty `security_scopes.scopes`, so any valid token passes. This often appears when someone copies a read route to make a write route. 2. **`Security` points at the scheme.** `Security(oauth2_scheme, scopes=["items:write"])` puts the scope in OpenAPI, so the docs look right, but `OAuth2PasswordBearer` only returns the token string. Nothing checks the scope. 3. **`Security` points at a dependency that ignores `SecurityScopes`.** A `get_current_user` that decodes the token and loads the user, but never looks at `security_scopes`, makes every declared scope decorative. 4. **A new route on a write router forgets the declaration.** Per-route declarations rely on every author remembering them. ## Holes in the comparison - **Substring matching.** If the scope claim stays a string like `"items:read items:write-drafts"`, the test `"items:write" in claim` is true. FastAPI's example splits the claim and validates it into a `list[str]` with Pydantic; compare against a set of whole names. - **`any()` instead of `all()`.** `security_scopes.scopes` merges everything the route and its dependencies declared; every entry is a requirement. - **A missing claim defaulting to everything.** Code that treats an absent scope claim as unrestricted grants full access to tokens issued before scopes existed. ## Holes in issuance The FastAPI scopes tutorial's token route writes `" ".join(form_data.scopes)` into the token, and its documentation carries a warning: for simplicity it adds the requested scopes directly, while a real application should add only the scopes the user is actually able to have. A route that copies the client's request lets the reporting client simply ask for `items:write` and receive it. The fix is an intersection between what was requested and what that user or client is allowed, decided on the server. ## Summary table | Hole | What the review sees | Fix | |---|---|---| | `Depends` on a write route | checker reached with `[]` | `Security(checker, scopes=["items:write"])` | | `Security` on the scheme | scope in docs, no check | point `Security` at the checker | | Checker ignores `SecurityScopes` | no comparison in code | compare and raise 403 | | Substring or `any()` test | `in` on a string, `any(...)` | `all(s in granted_set for s in ...)` | | Token route copies requested scopes | `" ".join(form_data.scopes)` | grant the allowed subset only | ## Making it hard to regress - **Declare once per router.** `APIRouter(dependencies=[Security(require_scopes, scopes=["items:write"])])` applies the requirement to every route on the write router, including ones added later. - **Test the outcome, not the declaration.** A test posting with a read-only token must get 403; another must get 200 with a writing token. - **Test the schema as an inventory.** Walking `app.openapi()["paths"]` and asserting that every `post`, `put`, `patch` and `delete` operation lists `items:write` catches a route someone declared with `Depends`, because only `Security` puts the scope there. It proves the declaration, while the 403 test proves the check behind it. - **Watch test overrides.** Replacing the checker through dependency overrides in tests also removes the scope check, so keep at least one test that exercises the real checker. ## Order of the review Read the code in the order a request meets it: the router and route declarations, the checker, the token claim parsing, then the token route that minted the claim. Each layer can be correct while the next one undoes it, so a finding at any layer is worth a regression test of its own.
- Why does the token route matter when the scope checks themselves are correct?The checks compare required scopes with what the token carries. If the token route writes whatever `form_data.scopes` the client requested, the reporting client asks for `items:write` and gets a token that passes every check. The route must grant only the intersection of requested and allowed scopes, decided from the user's or client's record on the server.
- Is the OpenAPI walk enough to prove enforcement?No. It proves each write operation declares `items:write` through `Security`, which catches routes declared with `Depends`. It cannot see whether the dependency behind the declaration compares anything; `Security(oauth2_scheme, scopes=[...])` passes the walk and enforces nothing. Pair it with a behaviour test that a read-only token gets 403.
- Listing items:write in the OpenAPI docs proves the route enforces it.
- Security(oauth2_scheme, scopes=[...]) makes the scheme check the scope.
- Checking "items:write" in the raw scope string is a safe membership test.
- The token route may copy the client's requested scopes into the token.
- Depends(get_current_user) on a write route still applies the route's scopes.