fix(auth): resolve learner routes across lazy FastAPI routers

This commit is contained in:
Bingxi Zhao (Frank)
2026-10-04 16:05:11 +08:00
parent 0d8f4a4c87
commit af0777b7f5
2 changed files with 24 additions and 6 deletions

View File

@@ -671,6 +671,21 @@ def _learning_surface_for_path(
return ""
def _resolved_route_path(request: Request) -> str | None:
"""Keep include-time prefixes across FastAPI's flat and lazy routers."""
# Lazy router inclusion retains the original route in scope["route"].
# Its path omits include_router prefixes; the effective context owns the
# full matched template. Direct routes and older releases use the route.
fastapi_scope = request.scope.get("fastapi")
if isinstance(fastapi_scope, dict):
context = fastapi_scope.get("effective_route_context")
path = getattr(context, "path", None)
if isinstance(path, str):
return path
path = getattr(request.scope.get("route"), "path", None)
return path if isinstance(path, str) else None
async def require_learning_surface(
request: Request,
_: TokenPayload | None = Depends(require_auth),
@@ -679,12 +694,11 @@ async def require_learning_surface(
from deeptutor.multi_user.learning_access import assert_learning_surface
try:
route = request.scope.get("route")
assert_learning_surface(
_learning_surface_for_path(
request.url.path,
request.method,
route_path=getattr(route, "path", None),
route_path=_resolved_route_path(request),
)
)
except PermissionError as exc:

View File

@@ -13,7 +13,7 @@ Two failure modes covered:
from __future__ import annotations
from fastapi import Depends, FastAPI, Request
from fastapi import APIRouter, Depends, FastAPI, Request
from fastapi.testclient import TestClient
import pytest
@@ -556,8 +556,9 @@ def test_set_preset_checks_expected_user_id(mu_isolated_root, seed_user) -> None
@pytest.mark.parametrize("surfaces, expected", [(["reading"], 200), (["chat"], 403)])
@pytest.mark.parametrize("nested_router", [False, True])
def test_learner_proxy_list_obeys_reading_policy_over_http(
monkeypatch, mu_isolated_root, surfaces, expected
monkeypatch, mu_isolated_root, surfaces, expected, nested_router
) -> None:
from deeptutor.api.routers import auth, knowledge
from deeptutor.multi_user import learning_access
@@ -582,13 +583,16 @@ def test_learner_proxy_list_obeys_reading_policy_over_http(
monkeypatch.setattr(knowledge, "list_knowledge_bases", collection)
app = FastAPI()
app.include_router(
parent = APIRouter() if nested_router else app
parent.include_router(
knowledge.router, prefix="/api", dependencies=[Depends(auth.require_learning_surface)]
)
if nested_router:
app.include_router(parent)
client = TestClient(app)
headers = {"Authorization": "Bearer student-token"}
response = client.get("/api/knowledge-bases/list", headers=headers)
assert response.status_code == expected
assert response.status_code == expected, response.text
assert calls == ([True] if expected == 200 else [])
if expected == 200:
assert response.json() == []